#!/usr/bin/env python## Copyright (C) 2007 Oracle. All rights reserved.## This program is free software; you can redistribute it and/or# modify it under the terms of the GNU General Public# License v2 as published by the Free Software Foundation.# # This program is distributed in the hope that it will be useful,# but WITHOUT ANY WARRANTY; without even the implied warranty of# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU# General Public License for more details.# # You should have received a copy of the GNU General Public# License along with this program; if not, write to the# Free Software Foundation, Inc., 59 Temple Place - Suite 330,# Boston, MA 021110-1307, USA.#importsys,os,signal,time,commands,tempfile,random# numpy seems to override random() with something else. Instantiate our# own hererandgen=random.Random()randgen.seed(50)fromoptparseimportOptionParserfrommatplotlibimportrcParamsfrommatplotlib.font_managerimportfontManager,FontPropertiesimportnumpyrcParams['numerix']='numpy'rcParams['backend']='Agg'rcParams['interactive']='False'frompylabimport*classAnnoteFinder:""" callback for matplotlib to display an annotation when points are clicked on. The point which is closest to the click and within xtol and ytol is identified. Register this function like this: scatter(xdata, ydata) af = AnnoteFinder(xdata, ydata, annotes) connect('button_press_event', af) """def__init__(self,axis=None):ifaxisisNone:self.axis=gca()else:self.axis=axisself.drawnAnnotations={}self.links=[]defclear(self):forkinself.drawnAnnotations.keys():self.drawnAnnotations[k].set_visible(False)def__call__(self,event):ifevent.inaxes:ifevent.button!=1:self.clear()draw()returnclickX=event.xdataclickY=event.ydataif(self.axisisNone)or(self.axis==event.inaxes):self.drawAnnote(event.inaxes,clickX,clickY)defdrawAnnote(self,axis,x,y):""" Draw the annotation on the plot """ifself.drawnAnnotations.has_key((x,y)):markers=self.drawnAnnotations[(x,y)]markers.set_visible(notmarkers.get_visible())draw()else:t=axis.text(x,y,"(%3.2f, %3.2f)"%(x,y),bbox=dict(facecolor='red',alpha=0.8))self.drawnAnnotations[(x,y)]=tdraw()defloaddata(fh,delimiter=None,converters=None):#14413824 8192 extent back ref root 5 gen 10 owner 282 num_refs 1defiter(fh,delimiter,converters):globaltotal_dataglobaltotal_metadatafori,lineinenumerate(fh):line=line.split(' ')start=float(line[0])len=float(line[1])owner=float(line[10])root=float(line[6])ifowner<=255:total_metadata+=int(len)else:total_data+=int(len)ifstart<zoomminor(zoommax!=0andstart>zoommax):continueyieldstartyieldlenyieldowneryieldrootX=numpy.fromiter(iter(fh,delimiter,converters),dtype=float)returnXdefrun_debug_tree(device):p=os.popen('btrfs-debug-tree -e '+device)data=loaddata(p)returndatadefshapeit(X):lines=len(X)/4X.shape=(lines,4)defline_picker(line,mouseevent):ifmouseevent.xdataisNone:returnFalse,dict()print"%d%d\n",mouseevent.xdata,mouseevent.ydatareturnFalse,dict()defxycalc(byte):byte=byte/bytes_per_cellyval=floor(byte/num_cells)xval=byte%num_cellsreturn(xval,yval+1)# record the color used for each root the first time we find itroot_colors={}# there are lots of good colormaps to choose from# http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps#meta_cmap=get_cmap("gist_ncar")data_done=Falsedefplotone(a,xvals,yvals,owner,root,lines,labels):globaldata_doneadd_label=Falseifowner:ifoptions.meta_only:returncolor="blue"label="Data"ifnotdata_done:add_label=Truedata_done=Trueelse:ifoptions.data_only:returnifrootnotinroot_colors:color=meta_cmap(randgen.random())label="Meta %d"%int(root)root_colors[root]=(color,label)add_label=Trueelse:color,label=root_colors[root]plotlines=a.plot(xvals,yvals,'s',color=color,mfc=color,mec=color,markersize=.23,label=label)ifadd_label:lines+=plotlineslabels.append(label)print"add label %s"%labeldefparse_zoom():defparse_num(s):mult=1c=s.lower()[-1]ifc=='t':mult=1024*1024*1024*1024elifc=='g':mult=1024*1024*1024elifc=='m':mult=1024*1024elifc=='k':mult=1024else:c=Noneifc:num=int(s[:-1])*multelse:num=int(s)returnnumifnotoptions.zoom:return(0,0)vals=options.zoom.split(':')iflen(vals)!=2:sys.stderr.write("warning: unable to parse zoom %s\n"%options.zoom)return(0,0)zoommin=parse_num(vals[0])zoommax=parse_num(vals[1])return(zoommin,zoommax)usage="usage: %prog [options]"parser=OptionParser(usage=usage)parser.add_option("-d","--device",help="Btrfs device",default="")parser.add_option("-i","--input-file",help="debug-tree data",default="")parser.add_option("-o","--output",help="Output file",default="blocks.png")parser.add_option("-z","--zoom",help="Zoom",default=None)parser.add_option("","--data-only",help="Only print data blocks",default=False,action="store_true")parser.add_option("","--meta-only",help="Only print metadata blocks",default=False,action="store_true")(options,args)=parser.parse_args()ifnotoptions.deviceandnotoptions.input_file:parser.print_help()sys.exit(1)zoommin,zoommax=parse_zoom()total_data=0total_metadata=0ifoptions.device:data=run_debug_tree(options.device)elifoptions.input_file:data=loaddata(file(options.input_file))shapeit(data)# try to drop out the least common data points by creating# a historgram of the sectors seen.sectors=data[:,0]sizes=data[:,1]datalen=len(data)sectormax=numpy.max(sectors)sectormin=0num_cells=800total_cells=num_cells*num_cellsbyte_range=sectormax-sectorminbytes_per_cell=byte_range/total_cellsf=figure(figsize=(8,6))# Throughput goes at the botooma=subplot(1,1,1)subplots_adjust(right=0.7)datai=0xvals=[]yvals=[]last_owner=0last_root=0lines=[]labels=[]whiledatai<datalen:row=data[datai]datai+=1byte=row[0]size=row[1]owner=row[2]root=row[3]ifowner<=255:owner=0else:owner=1iflen(xvals)and(owner!=last_ownerorlast_root!=root):plotone(a,xvals,yvals,last_owner,last_root,lines,labels)xvals=[]yvals=[]cell=0whilecell<size:xy=xycalc(byte)byte+=bytes_per_cellcell+=bytes_per_cellifxy:xvals.append(xy[0])yvals.append(xy[1])last_owner=ownerlast_root=rootifxvals:plotone(a,xvals,yvals,last_owner,last_root,lines,labels)# make sure the final second goes on the x axesticks=[]a.set_xticks(ticks)ticks=a.get_yticks()first_tick=ticks[1]*bytes_per_cell*num_cellsiffirst_tick>1024*1024*1024*1024:scale=1024*1024*1024*1024;scalestr="TB"eliffirst_tick>1024*1024*1024:scale=1024*1024*1024;scalestr="GB"eliffirst_tick>1024*1024:scale=1024*1024;scalestr="MB"eliffirst_tick>1024:scale=1024;scalestr="KB"else:scalestr="Bytes"scale=1ylabels=[str(int((x*bytes_per_cell*num_cells)/scale))forxinticks]a.set_yticklabels(ylabels)a.set_ylabel('Disk offset (%s)'%scalestr)a.set_xlim(0,num_cells)a.set_title('Blocks')a.legend(lines,labels,loc=(1.05,0.8),shadow=True,pad=0.1,numpoints=1,handletextsep=0.005,labelsep=0.01,markerscale=10,prop=FontProperties(size='x-small'))iftotal_data==0:percent_meta=100else:percent_meta=(float(total_metadata)/float(total_data))*100print"Total metadata bytes %d data %d ratio %.3f"%(total_metadata,total_data,percent_meta)print"saving graph to %s"%options.outputsavefig(options.output,orientation='landscape')show()