fio2gnuplot: Keep original filename in temp. files
[fio.git] / tools / plot / fio2gnuplot.py
1 #!/usr/bin/python
2 #
3 #  Copyright (C) 2013 eNovance SAS <licensing@enovance.com>
4 #  Author: Erwan Velu  <erwan@enovance.com>
5 #
6 #  The license below covers all files distributed with fio unless otherwise
7 #  noted in the file itself.
8 #
9 #  This program is free software; you can redistribute it and/or modify
10 #  it under the terms of the GNU General Public License version 2 as
11 #  published by the Free Software Foundation.
12 #
13 #  This program is distributed in the hope that it will be useful,
14 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #  GNU General Public License for more details.
17 #
18 #  You should have received a copy of the GNU General Public License
19 #  along with this program; if not, write to the Free Software
20 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21
22 import os
23 import fnmatch
24 import sys
25 import getopt
26 import re
27 import math
28
29 def find_file(path, pattern):
30         fio_data_file=[]
31         # For all the local files
32         for file in os.listdir(path):
33             # If the file math the regexp
34             if fnmatch.fnmatch(file, pattern):
35                 # Let's consider this file
36                 fio_data_file.append(file)
37
38         return fio_data_file
39
40 def generate_gnuplot_script(fio_data_file,title,gnuplot_output_filename,mode,disk_perf):
41         f=open("mygraph",'w')
42         if len(fio_data_file) > 1:
43                 f.write("call \'graph3D.gpm\' \'%s' \'%s\' \'\' \'%s\' \'%s\'\n" % (title,gnuplot_output_filename,gnuplot_output_filename,mode))
44
45         pos=0
46         # Let's create a temporary file for each selected fio file
47         for file in fio_data_file:
48                 tmp_filename = "gnuplot_temp_file.%d" % pos
49                 png_file=file.replace('.log','')
50                 raw_filename = "%s-2Draw" % (png_file)
51                 smooth_filename = "%s-2Dsmooth" % (png_file)
52                 trend_filename = "%s-2Dtrend" % (png_file)
53                 avg  = average(disk_perf[pos])
54                 f.write("call \'graph2D.gpm\' \'%s' \'%s\' \'\' \'%s\' \'%s\' \'%s\' \'%s\' \'%f\'\n" % (title,tmp_filename,raw_filename,mode,smooth_filename,trend_filename,avg))
55                 pos = pos +1
56
57         f.close()
58
59 def generate_gnuplot_math_script(title,gnuplot_output_filename,mode,average):
60         f=open("mymath",'a')
61         f.write("call \'math.gpm\' \'%s' \'%s\' \'\' \'%s\' \'%s\' %s\n" % (title,gnuplot_output_filename,gnuplot_output_filename,mode,average))
62         f.close()
63
64 def compute_aggregated_file(fio_data_file, gnuplot_output_filename):
65         temp_files=[]
66         pos=0
67         # Let's create a temporary file for each selected fio file
68         for file in fio_data_file:
69                 tmp_filename = "gnuplot_temp_file.%d" % pos
70                 temp_files.append(open(tmp_filename,'r'))
71                 pos = pos +1
72
73         f = open(gnuplot_output_filename, "w")
74         index=0
75         # Let's add some information
76         for tempfile in temp_files:
77                     f.write("# Disk%d was coming from %s\n" % (index,fio_data_file[index]))
78                     f.write(tempfile.read())
79                     f.write("\n")
80                     tempfile.close()
81                     index = index + 1
82         f.close()
83
84 def average(s): return sum(s) * 1.0 / len(s)
85
86 def compute_temp_file(fio_data_file,disk_perf):
87         files=[]
88         temp_outfile=[]
89         blk_size=0
90         for file in fio_data_file:
91                 files.append(open(file))
92                 pos = len(files) - 1
93                 tmp_filename = "gnuplot_temp_file.%d" % pos
94                 gnuplot_file=open(tmp_filename,'w')
95                 temp_outfile.append(gnuplot_file)
96                 gnuplot_file.write("#Temporary file based on file %s\n" % file)
97                 disk_perf.append([])
98
99         shall_break = False
100         while True:
101                 current_line=[]
102                 for file in files:
103                         s=file.readline().replace(',',' ').split()
104                         if not s:
105                                 shall_break=True
106                                 break;
107                         current_line.append(s);
108
109                 if shall_break == True:
110                         break
111
112                 last_time = -1
113                 index=0
114                 perfs=[]
115                 for line in current_line:
116                         time, perf, x, block_size = line
117                         if (blk_size == 0):
118                                 blk_size=int(block_size)
119
120                         # We ignore the first 500msec as it doesn't seems to be part of the real benchmark
121                         # Time < 500 usually reports BW=0 breaking the min computing
122                         if ((int(time)) > 500):
123                                 disk_perf[index].append(int(perf))
124                                 perfs.append(perf)
125                                 index = index + 1
126
127                 # If we reach this point, it means that all the traces are coherent
128                 for p in enumerate(perfs):
129                         temp_outfile[p[0]].write("%s %.2f %s\n" % (p[0], float(float(time)/1000), p[1]))
130
131         for file in files:
132                 file.close()
133         for file in temp_outfile:
134                 file.close()
135         return blk_size
136
137 def compute_math(fio_data_file, title,gnuplot_output_filename,mode,disk_perf):
138         global_min=[]
139         global_max=[]
140         average_file=open(gnuplot_output_filename+'.average', 'w')
141         min_file=open(gnuplot_output_filename+'.min', 'w')
142         max_file=open(gnuplot_output_filename+'.max', 'w')
143         stddev_file=open(gnuplot_output_filename+'.stddev', 'w')
144         global_file=open(gnuplot_output_filename+'.global','w')
145
146         min_file.write('DiskName %s\n' % mode)
147         max_file.write('DiskName %s\n'% mode)
148         average_file.write('DiskName %s\n'% mode)
149         stddev_file.write('DiskName %s\n'% mode )
150         for disk in xrange(len(fio_data_file)):
151 #               print disk_perf[disk]
152                 min_file.write("# Disk%d was coming from %s\n" % (disk,fio_data_file[disk]))
153                 max_file.write("# Disk%d was coming from %s\n" % (disk,fio_data_file[disk]))
154                 average_file.write("# Disk%d was coming from %s\n" % (disk,fio_data_file[disk]))
155                 stddev_file.write("# Disk%d was coming from %s\n" % (disk,fio_data_file[disk]))
156                 avg  = average(disk_perf[disk])
157                 variance = map(lambda x: (x - avg)**2, disk_perf[disk])
158                 standard_deviation = math.sqrt(average(variance))
159 #               print "Disk%d [ min=%.2f max=%.2f avg=%.2f stddev=%.2f \n" % (disk,min(disk_perf[disk]),max(disk_perf[disk]),avg, standard_deviation)
160                 average_file.write('%d %d\n' % (disk, avg))
161                 stddev_file.write('%d %d\n' % (disk, standard_deviation))
162                 local_min=min(disk_perf[disk])
163                 local_max=max(disk_perf[disk])
164                 min_file.write('%d %d\n' % (disk, local_min))
165                 max_file.write('%d %d\n' % (disk, local_max))
166                 global_min.append(int(local_min))
167                 global_max.append(int(local_max))
168
169         global_disk_perf = sum(disk_perf, [])
170         avg  = average(global_disk_perf)
171         variance = map(lambda x: (x - avg)**2, global_disk_perf)
172         standard_deviation = math.sqrt(average(variance))
173
174         global_file.write('min=%.2f\n' % min(global_disk_perf))
175         global_file.write('max=%.2f\n' % max(global_disk_perf))
176         global_file.write('avg=%.2f\n' % avg)
177         global_file.write('stddev=%.2f\n' % standard_deviation)
178         global_file.write('values_count=%d\n' % len(global_disk_perf))
179         global_file.write('disks_count=%d\n' % len(fio_data_file))
180         #print "Global [ min=%.2f max=%.2f avg=%.2f stddev=%.2f \n" % (min(global_disk_perf),max(global_disk_perf),avg, standard_deviation)
181
182         average_file.close()
183         min_file.close()
184         max_file.close()
185         stddev_file.close()
186         global_file.close()
187         try:
188                 os.remove('mymath')
189         except:
190                 True
191
192         generate_gnuplot_math_script("Average values of "+title,gnuplot_output_filename+'.average',mode,int(avg))
193         generate_gnuplot_math_script("Min values of "+title,gnuplot_output_filename+'.min',mode,average(global_min))
194         generate_gnuplot_math_script("Max values of "+title,gnuplot_output_filename+'.max',mode,average(global_max))
195         generate_gnuplot_math_script("Standard Deviation of "+title,gnuplot_output_filename+'.stddev',mode,int(standard_deviation))
196
197 def parse_global_files(fio_data_file, global_search):
198         max_result=0
199         max_file=''
200         for file in fio_data_file:
201                 f=open(file)
202                 disk_count=0
203                 search_value=-1
204
205                 # Let's read the complete file
206                 while True:
207                         try:
208                                 # We do split the name from the value
209                                 name,value=f.readline().split("=")
210                         except:
211                                 f.close()
212                                 break
213                         # If we ended the file
214                         if not name:
215                                 # Let's process what we have
216                                 f.close()
217                                 break
218                         else:
219                                 # disks_count is not global_search item
220                                 # As we need it for some computation, let's save it
221                                 if name=="disks_count":
222                                         disks_count=int(value)
223
224                                 # Let's catch the searched item
225                                 if global_search in name:
226                                         search_value=float(value)
227
228                 # Let's process the avg value by estimated the global bandwidth per file
229                 # We keep the biggest in memory for reporting
230                 if global_search == "avg":
231                         if (disks_count > 0) and (search_value != -1):
232                                 result=disks_count*search_value
233                                 if (result > max_result):
234                                         max_result=result
235                                         max_file=file
236         # Let's print the avg output
237         if global_search == "avg":
238                 print "Biggest aggregated value of %s was %2.f in file %s\n" % (global_search, max_result, max_file)
239         else:
240                 print "Global search %s is not yet implemented\n" % global_search
241
242 def render_gnuplot():
243         print "Running gnuplot Rendering\n"
244         try:
245                 os.system("gnuplot mymath")
246                 os.system("gnuplot mygraph")
247         except:
248                 print "Could not run gnuplot on mymath or mygraph !\n"
249                 sys.exit(1);
250
251 def print_help():
252     print 'fio2gnuplot.py -ghbio -t <title> -o <outputfile> -p <pattern>'
253     print
254     print '-h --help                           : Print this help'
255     print '-p <pattern> or --pattern <pattern> : A pattern in regexp to select fio input files'
256     print '-b           or --bandwidth         : A predefined pattern for selecting *_bw.log files'
257     print '-i           or --iops              : A predefined pattern for selecting *_iops.log files'
258     print '-g           or --gnuplot           : Render gnuplot traces before exiting'
259     print '-o           or --outputfile <file> : The basename for gnuplot traces'
260     print '                                       - Basename is set with the pattern if defined'
261     print '-t           or --title <title>     : The title of the gnuplot traces'
262     print '                                       - Title is set with the block size detected in fio traces'
263     print '-G           or --Global <type>     : Search for <type> in .global files match by a pattern'
264     print '                                       - Available types are : min, max, avg, stddev'
265     print '                                       - The .global extension is added automatically to the pattern'
266
267 def main(argv):
268     mode='unknown'
269     pattern=''
270     pattern_set_by_user=False
271     title='No title'
272     gnuplot_output_filename='result'
273     disk_perf=[]
274     run_gnuplot=False
275     parse_global=False
276     global_search=''
277
278     try:
279             opts, args = getopt.getopt(argv[1:],"ghbio:t:p:G:")
280     except getopt.GetoptError:
281          print_help()
282          sys.exit(2)
283
284     for opt, arg in opts:
285       if opt in ("-b", "--bandwidth"):
286          pattern='*_bw.log'
287       elif opt in ("-i", "--iops"):
288          pattern='*_iops.log'
289       elif opt in ("-p", "--pattern"):
290          pattern_set_by_user=True
291          pattern=arg
292          pattern=pattern.replace('\\','')
293       elif opt in ("-o", "--outputfile"):
294          gnuplot_output_filename=arg
295       elif opt in ("-t", "--title"):
296          title=arg
297       elif opt in ("-g", "--gnuplot"):
298          run_gnuplot=True
299       elif opt in ("-G", "--Global"):
300          parse_global=True
301          global_search=arg
302       elif opt in ("-h", "--help"):
303           print_help()
304           sys.exit(1)
305
306     # Adding .global extension to the file
307     if parse_global==True:
308             if not gnuplot_output_filename.endswith('.global'):
309                 pattern = pattern+'.global'
310
311     fio_data_file=find_file('.',pattern)
312     if len(fio_data_file) == 0:
313             print "No log file found with pattern %s!" % pattern
314             sys.exit(1)
315
316     fio_data_file=sorted(fio_data_file, key=str.lower)
317     for file in fio_data_file:
318         print 'Selected %s' % file
319         if "_bw.log" in file :
320                 mode="Bandwidth (KB/sec)"
321         if "_iops.log" in file :
322                 mode="IO per Seconds (IO/sec)"
323     if (title == 'No title') and (mode != 'unknown'):
324             if "Bandwidth" in mode:
325                     title='Bandwidth benchmark with %d fio results' % len(fio_data_file)
326             if "IO" in mode:
327                     title='IO benchmark with %d fio results' % len(fio_data_file)
328
329     #We need to adjust the output filename regarding the pattern required by the user
330     if (pattern_set_by_user == True):
331             gnuplot_output_filename=pattern
332             # As we do have some regexp in the pattern, let's make this simpliest
333             # We do remove the simpliest parts of the expression to get a clear file name
334             gnuplot_output_filename=gnuplot_output_filename.replace('-*-','-')
335             gnuplot_output_filename=gnuplot_output_filename.replace('*','-')
336             gnuplot_output_filename=gnuplot_output_filename.replace('--','-')
337             gnuplot_output_filename=gnuplot_output_filename.replace('.log','')
338             # Insure that we don't have any starting or trailing dash to the filename
339             gnuplot_output_filename = gnuplot_output_filename[:-1] if gnuplot_output_filename.endswith('-') else gnuplot_output_filename
340             gnuplot_output_filename = gnuplot_output_filename[1:] if gnuplot_output_filename.startswith('-') else gnuplot_output_filename
341
342     if parse_global==True:
343         parse_global_files(fio_data_file, global_search)
344     else:
345         blk_size=compute_temp_file(fio_data_file,disk_perf)
346         title="%s @ Blocksize = %dK" % (title,blk_size/1024)
347         compute_aggregated_file(fio_data_file, gnuplot_output_filename)
348         compute_math(fio_data_file,title,gnuplot_output_filename,mode,disk_perf)
349         generate_gnuplot_script(fio_data_file,title,gnuplot_output_filename,mode,disk_perf)
350
351         if (run_gnuplot==True):
352                 render_gnuplot()
353
354     # Cleaning temporary files
355     try:
356         os.remove('gnuplot_temp_file.*')
357     except:
358         True
359
360 #Main
361 if __name__ == "__main__":
362     sys.exit(main(sys.argv))