e749c515edae593cc901c1000384731f9d0cbec7
[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 import shutil
29
30 def find_file(path, pattern):
31         fio_data_file=[]
32         # For all the local files
33         for file in os.listdir(path):
34             # If the file math the regexp
35             if fnmatch.fnmatch(file, pattern):
36                 # Let's consider this file
37                 fio_data_file.append(file)
38
39         return fio_data_file
40
41 def generate_gnuplot_script(fio_data_file,title,gnuplot_output_filename,gnuplot_output_dir,mode,disk_perf,gpm_dir):
42         filename=gnuplot_output_dir+'mygraph'
43         f=open(filename,'w')
44
45         # Plotting 3D or comparing graphs doesn't have a meaning unless if there is at least 2 traces
46         if len(fio_data_file) > 1:
47                 f.write("call \'%s/graph3D.gpm\' \'%s' \'%s\' \'\' \'%s\' \'%s\'\n" % (gpm_dir,title,gnuplot_output_filename,gnuplot_output_filename,mode))
48
49                 # Setting up the compare files that will be plot later
50                 compare=open(gnuplot_output_dir + 'compare.gnuplot','w')
51                 compare.write('''
52 set title '%s'
53 set terminal png size 1280,1024
54 set ytics axis out auto
55 set key top left reverse
56 set xlabel "Time (Seconds)"
57 set ylabel '%s'
58 set xrange [0:]
59 set yrange [0:]
60 '''% (title,mode))
61                 compare.close()
62                 #Copying the common file for all kind of graph (raw/smooth/trend)
63                 compare_raw_filename="compare-%s-2Draw" % (gnuplot_output_filename)
64                 compare_smooth_filename="compare-%s-2Dsmooth" % (gnuplot_output_filename)
65                 compare_trend_filename="compare-%s-2Dtrend" % (gnuplot_output_filename)
66                 shutil.copy(gnuplot_output_dir+'compare.gnuplot',gnuplot_output_dir+compare_raw_filename+".gnuplot")
67                 shutil.copy(gnuplot_output_dir+'compare.gnuplot',gnuplot_output_dir+compare_smooth_filename+".gnuplot")
68                 shutil.copy(gnuplot_output_dir+'compare.gnuplot',gnuplot_output_dir+compare_trend_filename+".gnuplot")
69
70                 #Setting up a different output filename for each kind of graph
71                 compare_raw=open(gnuplot_output_dir+compare_raw_filename + ".gnuplot",'a')
72                 compare_raw.write("set output '%s.png'\n" % compare_raw_filename)
73                 compare_smooth=open(gnuplot_output_dir+compare_smooth_filename+".gnuplot",'a')
74                 compare_smooth.write("set output '%s.png'\n" % compare_smooth_filename)
75                 compare_trend=open(gnuplot_output_dir+compare_trend_filename+".gnuplot",'a')
76                 compare_trend.write("set output '%s.png'\n" % compare_trend_filename)
77
78         pos=0
79         # Let's create a temporary file for each selected fio file
80         for file in fio_data_file:
81                 tmp_filename = "gnuplot_temp_file.%d" % pos
82
83                 # Plotting comparing graphs doesn't have a meaning unless if there is at least 2 traces
84                 if len(fio_data_file) > 1:
85                         # Adding the plot instruction for each kind of comparing graphs
86                         if pos ==0 :
87                                 compare_raw.write("plot '%s' using 2:3 with linespoints title '%s'" % (tmp_filename,fio_data_file[pos]))
88                                 compare_smooth.write("plot '%s' using 2:3 smooth csplines title '%s'" % (tmp_filename,fio_data_file[pos]))
89                                 compare_trend.write("plot '%s' using 2:3 smooth bezier title '%s'" % (tmp_filename,fio_data_file[pos]))
90                         else:
91                                 compare_raw.write(",\\\n'%s' using 2:3 with linespoints title '%s'" % (tmp_filename,fio_data_file[pos]))
92                                 compare_smooth.write(",\\\n'%s' using 2:3 smooth csplines title '%s'" % (tmp_filename,fio_data_file[pos]))
93                                 compare_trend.write(",\\\n'%s' using 2:3 smooth bezier title '%s'" % (tmp_filename,fio_data_file[pos]))
94
95                 png_file=file.replace('.log','')
96                 raw_filename = "%s-2Draw" % (png_file)
97                 smooth_filename = "%s-2Dsmooth" % (png_file)
98                 trend_filename = "%s-2Dtrend" % (png_file)
99                 avg  = average(disk_perf[pos])
100                 f.write("call \'%s/graph2D.gpm\' \'%s' \'%s\' \'\' \'%s\' \'%s\' \'%s\' \'%s\' \'%f\'\n" % (gpm_dir,title,tmp_filename,raw_filename,mode,smooth_filename,trend_filename,avg))
101                 pos = pos +1
102
103         # Plotting comparing graphs doesn't have a meaning unless if there is at least 2 traces
104         if len(fio_data_file) > 1:
105                 os.remove(gnuplot_output_dir+"compare.gnuplot")
106                 compare_raw.close()
107                 compare_smooth.close()
108                 compare_trend.close()
109         f.close()
110
111 def generate_gnuplot_math_script(title,gnuplot_output_filename,mode,average,gnuplot_output_dir,gpm_dir):
112         filename=gnuplot_output_dir+'mymath';
113         f=open(filename,'a')
114         f.write("call \'%s/math.gpm\' \'%s' \'%s\' \'\' \'%s\' \'%s\' %s\n" % (gpm_dir,title,gnuplot_output_filename,gnuplot_output_filename,mode,average))
115         f.close()
116
117 def compute_aggregated_file(fio_data_file, gnuplot_output_filename, gnuplot_output_dir):
118         temp_files=[]
119         pos=0
120
121         # Let's create a temporary file for each selected fio file
122         for file in fio_data_file:
123                 tmp_filename = "%sgnuplot_temp_file.%d" % (gnuplot_output_dir, pos)
124                 temp_files.append(open(tmp_filename,'r'))
125                 pos = pos +1
126
127         f = open(gnuplot_output_dir+gnuplot_output_filename, "w")
128         index=0
129         # Let's add some information
130         for tempfile in temp_files:
131                     f.write("# Disk%d was coming from %s\n" % (index,fio_data_file[index]))
132                     f.write(tempfile.read())
133                     f.write("\n")
134                     tempfile.close()
135                     index = index + 1
136         f.close()
137
138 def average(s): return sum(s) * 1.0 / len(s)
139
140 def compute_temp_file(fio_data_file,disk_perf,gnuplot_output_dir):
141         files=[]
142         temp_outfile=[]
143         blk_size=0
144         for file in fio_data_file:
145                 files.append(open(file))
146                 pos = len(files) - 1
147                 tmp_filename = "%sgnuplot_temp_file.%d" % (gnuplot_output_dir,pos)
148                 gnuplot_file=open(tmp_filename,'w')
149                 temp_outfile.append(gnuplot_file)
150                 gnuplot_file.write("#Temporary file based on file %s\n" % file)
151                 disk_perf.append([])
152
153         shall_break = False
154         while True:
155                 current_line=[]
156                 nb_empty_files=0
157                 nb_files=len(files)
158                 for file in files:
159                         s=file.readline().replace(',',' ').split()
160                         if not s:
161                                 nb_empty_files+=1
162                                 s="-1, 0, 0, 0'".replace(',',' ').split()
163
164                         if (nb_empty_files == nb_files):
165                                 shall_break=True
166                                 break;
167
168                         current_line.append(s);
169
170                 if shall_break == True:
171                         break
172
173                 last_time = -1
174                 index=0
175                 perfs=[]
176                 for line in current_line:
177                         time, perf, x, block_size = line
178                         if (blk_size == 0):
179                                 blk_size=int(block_size)
180
181                         # We ignore the first 500msec as it doesn't seems to be part of the real benchmark
182                         # Time < 500 usually reports BW=0 breaking the min computing
183                         if (((int(time)) > 500) or (int(time)==-1)):
184                                 disk_perf[index].append(int(perf))
185                                 perfs.append("%s %s"% (time, perf))
186                                 index = index + 1
187
188                 # If we reach this point, it means that all the traces are coherent
189                 for p in enumerate(perfs):
190                         perf_time,perf = p[1].split()
191                         if (perf_time != "-1"):
192                                 temp_outfile[p[0]].write("%s %.2f %s\n" % (p[0], float(float(perf_time)/1000), perf))
193
194
195         for file in files:
196                 file.close()
197         for file in temp_outfile:
198                 file.close()
199         return blk_size
200
201 def compute_math(fio_data_file, title,gnuplot_output_filename,gnuplot_output_dir,mode,disk_perf,gpm_dir):
202         global_min=[]
203         global_max=[]
204         average_file=open(gnuplot_output_dir+gnuplot_output_filename+'.average', 'w')
205         min_file=open(gnuplot_output_dir+gnuplot_output_filename+'.min', 'w')
206         max_file=open(gnuplot_output_dir+gnuplot_output_filename+'.max', 'w')
207         stddev_file=open(gnuplot_output_dir+gnuplot_output_filename+'.stddev', 'w')
208         global_file=open(gnuplot_output_dir+gnuplot_output_filename+'.global','w')
209
210         min_file.write('DiskName %s\n' % mode)
211         max_file.write('DiskName %s\n'% mode)
212         average_file.write('DiskName %s\n'% mode)
213         stddev_file.write('DiskName %s\n'% mode )
214         for disk in xrange(len(fio_data_file)):
215 #               print disk_perf[disk]
216                 min_file.write("# Disk%d was coming from %s\n" % (disk,fio_data_file[disk]))
217                 max_file.write("# Disk%d was coming from %s\n" % (disk,fio_data_file[disk]))
218                 average_file.write("# Disk%d was coming from %s\n" % (disk,fio_data_file[disk]))
219                 stddev_file.write("# Disk%d was coming from %s\n" % (disk,fio_data_file[disk]))
220                 avg  = average(disk_perf[disk])
221                 variance = map(lambda x: (x - avg)**2, disk_perf[disk])
222                 standard_deviation = math.sqrt(average(variance))
223 #               print "Disk%d [ min=%.2f max=%.2f avg=%.2f stddev=%.2f \n" % (disk,min(disk_perf[disk]),max(disk_perf[disk]),avg, standard_deviation)
224                 average_file.write('%d %d\n' % (disk, avg))
225                 stddev_file.write('%d %d\n' % (disk, standard_deviation))
226                 local_min=min(disk_perf[disk])
227                 local_max=max(disk_perf[disk])
228                 min_file.write('%d %d\n' % (disk, local_min))
229                 max_file.write('%d %d\n' % (disk, local_max))
230                 global_min.append(int(local_min))
231                 global_max.append(int(local_max))
232
233         global_disk_perf = sum(disk_perf, [])
234         avg  = average(global_disk_perf)
235         variance = map(lambda x: (x - avg)**2, global_disk_perf)
236         standard_deviation = math.sqrt(average(variance))
237
238         global_file.write('min=%.2f\n' % min(global_disk_perf))
239         global_file.write('max=%.2f\n' % max(global_disk_perf))
240         global_file.write('avg=%.2f\n' % avg)
241         global_file.write('stddev=%.2f\n' % standard_deviation)
242         global_file.write('values_count=%d\n' % len(global_disk_perf))
243         global_file.write('disks_count=%d\n' % len(fio_data_file))
244         #print "Global [ min=%.2f max=%.2f avg=%.2f stddev=%.2f \n" % (min(global_disk_perf),max(global_disk_perf),avg, standard_deviation)
245
246         average_file.close()
247         min_file.close()
248         max_file.close()
249         stddev_file.close()
250         global_file.close()
251         try:
252                 os.remove(gnuplot_output_dir+'mymath')
253         except:
254                 True
255
256         generate_gnuplot_math_script("Average values of "+title,gnuplot_output_filename+'.average',mode,int(avg),gnuplot_output_dir,gpm_dir)
257         generate_gnuplot_math_script("Min values of "+title,gnuplot_output_filename+'.min',mode,average(global_min),gnuplot_output_dir,gpm_dir)
258         generate_gnuplot_math_script("Max values of "+title,gnuplot_output_filename+'.max',mode,average(global_max),gnuplot_output_dir,gpm_dir)
259         generate_gnuplot_math_script("Standard Deviation of "+title,gnuplot_output_filename+'.stddev',mode,int(standard_deviation),gnuplot_output_dir,gpm_dir)
260
261 def parse_global_files(fio_data_file, global_search):
262         max_result=0
263         max_file=''
264         for file in fio_data_file:
265                 f=open(file)
266                 disk_count=0
267                 search_value=-1
268
269                 # Let's read the complete file
270                 while True:
271                         try:
272                                 # We do split the name from the value
273                                 name,value=f.readline().split("=")
274                         except:
275                                 f.close()
276                                 break
277                         # If we ended the file
278                         if not name:
279                                 # Let's process what we have
280                                 f.close()
281                                 break
282                         else:
283                                 # disks_count is not global_search item
284                                 # As we need it for some computation, let's save it
285                                 if name=="disks_count":
286                                         disks_count=int(value)
287
288                                 # Let's catch the searched item
289                                 if global_search in name:
290                                         search_value=float(value)
291
292                 # Let's process the avg value by estimated the global bandwidth per file
293                 # We keep the biggest in memory for reporting
294                 if global_search == "avg":
295                         if (disks_count > 0) and (search_value != -1):
296                                 result=disks_count*search_value
297                                 if (result > max_result):
298                                         max_result=result
299                                         max_file=file
300         # Let's print the avg output
301         if global_search == "avg":
302                 print "Biggest aggregated value of %s was %2.f in file %s\n" % (global_search, max_result, max_file)
303         else:
304                 print "Global search %s is not yet implemented\n" % global_search
305
306 def render_gnuplot(fio_data_file, gnuplot_output_dir):
307         print "Running gnuplot Rendering"
308         try:
309                 # Let's render all the compared files if some
310                 if len(fio_data_file) > 1:
311                         print " |-> Rendering comparing traces"
312                         os.system("cd %s; for i in *.gnuplot; do gnuplot $i; done" % gnuplot_output_dir)
313                 print " |-> Rendering math traces"
314                 os.system("cd %s; gnuplot mymath" % gnuplot_output_dir)
315                 print " |-> Rendering 2D & 3D traces"
316                 os.system("cd %s; gnuplot mygraph" % gnuplot_output_dir)
317         except:
318                 print "Could not run gnuplot on mymath or mygraph !\n"
319                 sys.exit(1);
320
321 def print_help():
322     print 'fio2gnuplot.py -ghbio -t <title> -o <outputfile> -p <pattern>'
323     print
324     print '-h --help                           : Print this help'
325     print '-p <pattern> or --pattern <pattern> : A pattern in regexp to select fio input files'
326     print '-b           or --bandwidth         : A predefined pattern for selecting *_bw.log files'
327     print '-i           or --iops              : A predefined pattern for selecting *_iops.log files'
328     print '-g           or --gnuplot           : Render gnuplot traces before exiting'
329     print '-o           or --outputfile <file> : The basename for gnuplot traces'
330     print '                                       - Basename is set with the pattern if defined'
331     print '-d           or --outputdir <dir>   : The directory where gnuplot shall render files'
332     print '-t           or --title <title>     : The title of the gnuplot traces'
333     print '                                       - Title is set with the block size detected in fio traces'
334     print '-G           or --Global <type>     : Search for <type> in .global files match by a pattern'
335     print '                                       - Available types are : min, max, avg, stddev'
336     print '                                       - The .global extension is added automatically to the pattern'
337
338 def main(argv):
339     mode='unknown'
340     pattern=''
341     pattern_set_by_user=False
342     title='No title'
343     gnuplot_output_filename='result'
344     gnuplot_output_dir='./'
345     gpm_dir="/usr/share/fio/"
346     disk_perf=[]
347     run_gnuplot=False
348     parse_global=False
349     global_search=''
350
351     if not os.path.isfile(gpm_dir+'math.gpm'):
352             gpm_dir="/usr/local/share/fio/"
353             if not os.path.isfile(gpm_dir+'math.gpm'):
354                     print "Looks like fio didn't got installed properly as no gpm files found in '/usr/share/fio' or '/usr/local/share/fio'\n"
355                     sys.exit(3)
356
357     try:
358             opts, args = getopt.getopt(argv[1:],"ghbio:d:t:p:G:")
359     except getopt.GetoptError:
360          print_help()
361          sys.exit(2)
362
363     for opt, arg in opts:
364       if opt in ("-b", "--bandwidth"):
365          pattern='*_bw.log'
366       elif opt in ("-i", "--iops"):
367          pattern='*_iops.log'
368       elif opt in ("-p", "--pattern"):
369          pattern_set_by_user=True
370          pattern=arg
371          pattern=pattern.replace('\\','')
372       elif opt in ("-o", "--outputfile"):
373          gnuplot_output_filename=arg
374       elif opt in ("-d", "--outputdir"):
375          gnuplot_output_dir=arg
376          if not gnuplot_output_dir.endswith('/'):
377                 gnuplot_output_dir=gnuplot_output_dir+'/'
378          if not os.path.exists(gnuplot_output_dir):
379                 os.makedirs(gnuplot_output_dir)
380       elif opt in ("-t", "--title"):
381          title=arg
382       elif opt in ("-g", "--gnuplot"):
383          run_gnuplot=True
384       elif opt in ("-G", "--Global"):
385          parse_global=True
386          global_search=arg
387       elif opt in ("-h", "--help"):
388           print_help()
389           sys.exit(1)
390
391     # Adding .global extension to the file
392     if parse_global==True:
393             if not gnuplot_output_filename.endswith('.global'):
394                 pattern = pattern+'.global'
395
396     fio_data_file=find_file('.',pattern)
397     if len(fio_data_file) == 0:
398             print "No log file found with pattern %s!" % pattern
399             sys.exit(1)
400     else:
401             print "%d files Selected with pattern '%s'" % (len(fio_data_file), pattern)
402
403     fio_data_file=sorted(fio_data_file, key=str.lower)
404     for file in fio_data_file:
405         print ' |-> %s' % file
406         if "_bw.log" in file :
407                 mode="Bandwidth (KB/sec)"
408         if "_iops.log" in file :
409                 mode="IO per Seconds (IO/sec)"
410     if (title == 'No title') and (mode != 'unknown'):
411             if "Bandwidth" in mode:
412                     title='Bandwidth benchmark with %d fio results' % len(fio_data_file)
413             if "IO" in mode:
414                     title='IO benchmark with %d fio results' % len(fio_data_file)
415
416     print
417     #We need to adjust the output filename regarding the pattern required by the user
418     if (pattern_set_by_user == True):
419             gnuplot_output_filename=pattern
420             # As we do have some regexp in the pattern, let's make this simpliest
421             # We do remove the simpliest parts of the expression to get a clear file name
422             gnuplot_output_filename=gnuplot_output_filename.replace('-*-','-')
423             gnuplot_output_filename=gnuplot_output_filename.replace('*','-')
424             gnuplot_output_filename=gnuplot_output_filename.replace('--','-')
425             gnuplot_output_filename=gnuplot_output_filename.replace('.log','')
426             # Insure that we don't have any starting or trailing dash to the filename
427             gnuplot_output_filename = gnuplot_output_filename[:-1] if gnuplot_output_filename.endswith('-') else gnuplot_output_filename
428             gnuplot_output_filename = gnuplot_output_filename[1:] if gnuplot_output_filename.startswith('-') else gnuplot_output_filename
429
430     if parse_global==True:
431         parse_global_files(fio_data_file, global_search)
432     else:
433         blk_size=compute_temp_file(fio_data_file,disk_perf,gnuplot_output_dir)
434         title="%s @ Blocksize = %dK" % (title,blk_size/1024)
435         compute_aggregated_file(fio_data_file, gnuplot_output_filename, gnuplot_output_dir)
436         compute_math(fio_data_file,title,gnuplot_output_filename,gnuplot_output_dir,mode,disk_perf,gpm_dir)
437         generate_gnuplot_script(fio_data_file,title,gnuplot_output_filename,gnuplot_output_dir,mode,disk_perf,gpm_dir)
438
439         if (run_gnuplot==True):
440                 render_gnuplot(fio_data_file, gnuplot_output_dir)
441
442     # Cleaning temporary files
443     try:
444         os.remove('gnuplot_temp_file.*')
445     except:
446         True
447
448 #Main
449 if __name__ == "__main__":
450     sys.exit(main(sys.argv))