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