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