RRDtool在python里面的绘图函数是rrdtool.graph(),函数的各个参数代表什么意义就不讲了,主要讲思路,后面贴上绘图函 数的代码就会明白了。在成千上万的监控图的海洋里怎样用最短和最通用的方法将这些图片绘出了是个问题。我目前由于水平的限制能够想到的解决问题的方法是这 样的。

1、所有的图形都有有限的item,将相同数目item的图片用同一个函数来绘制。

2、一些特别的图形如内存堆栈图(stack),可以在该函数中写个判断语句单独配置相应的绘图参数。

3、关于item的颜色和绘制方式(LINE1,LINE2,AREA),需要特别照顾的图形可以在DrawDef这张表中定义,其它的图形的item就采用自动默认就好。

4、成千上万的item绘图时怎样真确的找到rrd文件中对应的DS,取得正确的数据。这个一开始就设计好了,每台主机的所有rrd文件放在一个文 件夹里,文件夹以主机id命名,每个rrd文件以图形id命名并带上.rrd的后缀,每个rrd文件的DS用itemid命名。这样做就能正确的找到数据 源了。

解决了这些逻辑上的麻烦后,就可以堆绘图代码了。

首先根据GET请求的hostid和type找到要进行绘图的rrd文件

rrdtooldraw02

处理这个GET请求的views的函数是这样的:

 1def zabbixdraw(request):
 2    dir = r"/opt/rrd/"
 3    pngdir = r"/opt/www/diewu/static/images/rrdpng/"
 4    #value = request.GET
 5    hostid = request.GET['hostid']
 6    type = request.GET['type']
 7    sql = "select hostid, graphid, graphname, hostname from zabbixapp_drawtree where hostid="+hostid+" and type="+type+" and draw='1'"
 8    graphs = DrawTree.objects.getclass(sql)
 9    pngs = []
10    gdatas = []
11    strtime = str(int(time.time()- 86400))
12    for graph in graphs:
13        hostid = graph[0]
14        graphid = graph[1]
15        graphname = graph[2]
16        hostname = graph[3]
17        rpath = dir + hostid + r"/" + graphid + r".rrd"
18        ############################################
19        if not os.path.exists(pngdir + hostid + r"/"):
20            os.makedirs(pngdir + hostid + r"/")
21        pngname = pngdir + hostid + r"/" + graphid + r".png"
22        sql = "select itemid,itemname,units from zabbixapp_drawgraphs where graphid="+graphid
23        pitem = DrawGraphs.objects.getdata(sql)
24        #####取自定义颜色和绘制方法
25        sql = "select cols from zabbixapp_drawdef where graphid="+graphid
26        cols = DrawDef.objects.getdata(sql)
27        if cols:
28            cols = (cols[0][0].split(":"),)
29        sql = "select types from zabbixapp_drawdef where graphid="+graphid
30        itypes = DrawDef.objects.getdata(sql)
31        if itypes:
32            itypes = (itypes[0][0].split(":"),)
33        gdata = {'pname':pngname, 'gname':graphname, 'rrdpath':rpath, 'pitem':pitem, 'graphid':graphid,
34            'cols':cols, 'itypes':itypes, 'host':hostname, 'stime':strtime, 'flag':'Daily'}
35        gdatas.append(gdata)
36        pngs.append({'pngpath':str(pngname).replace(r"/opt/www/diewu", ''), 'graphid':graphid})
37    drawrrd.drawmain(gdatas)
38    #value = gdatas
39    #avg = {'privatetitle': 'Zabbix监控数据展示', 'STATIC_URL': '/static', 'value':value, 'pngs':pngs}
40    avg = {'privatetitle': 'Zabbix监控数据展示', 'STATIC_URL': '/static', 'pngs':pngs}
41    return render_to_response('zabbixapp/zabbixdraw.html', avg)

其中自定义的绘图函数drawrrd.drawmain()函数主要是用来遍历需要绘制的图形,根据图形数据提供的item个数,再调用相应的绘图函数绘制出对应的png图形。

贴上真正的绘图函数,绘制一个item图形的和绘制2个item的图形的函数。

 1#!/usr/bin/env python
 2#coding=utf-8
 3import rrdtool
 4def dItem01(data):
 5    pngname = str(data['pname'])
 6    start = data['stime']
 7    graphname = str(data['gname'] + " (" + data['graphid'] + ") " + data['host'] + "(" + data['flag'] + ")")
 8    DEF = str(r"DEF:a="+data['rrdpath']+r':'+data['pitem'][0][0]+r":AVERAGE")
 9    if data['cols'] or data['itypes']:
10        if not data['cols']:
11            dtype = str(data['itypes'][0][0]+r":a#EAAF00FF:"+data['pitem'][0][1])
12        elif not data['itypes']:
13            dtype = str(r"AREA:a"+data['cols'][0][0]+r":"+data['pitem'][0][1])
14        else:
15            dtype = str(data['itypes'][0][0]+r":a"+data['cols'][0][0]+r":"+data['pitem'][0][1])
16    else:
17        dtype = str(r"AREA:a#EAAF00FF:"+data['pitem'][0][1])
18    unit = str(data['pitem'][0][2])
19    if not unit:
20        unit = ' '
21    max = 'GPRINT:a:MAX:Max\:%.2lf %s'
22    min = 'GPRINT:a:MIN:Min\:%.2lf %s'
23    avg = 'GPRINT:a:AVERAGE:Avg\:%.2lf %s'
24    now = 'GPRINT:a:LAST:Now\:%.2lf %s'
25    rrdtool.graph(pngname, '-w', '600', '-h', '144', '-l', '0', '-s', start,
26                '-t', graphname, '-v', unit, DEF, 'COMMENT: \\n', dtype, now, avg, min, max, 'COMMENT: \\n')
27###################################################################################################################
28def dItem02(data):
29    pngname = str(data['pname'])
30    start = data['stime']
31    graphname = str(data['gname'] + " (" + data['graphid'] + ") " + data['host'] + "(" + data['flag'] + ")")
32    DEFa = str(r"DEF:a="+data['rrdpath']+r':'+data['pitem'][0][0]+r":AVERAGE")
33    DEFb = str(r"DEF:b="+data['rrdpath']+r':'+data['pitem'][1][0]+r":AVERAGE")
34    unit = str(data['pitem'][0][2])
35    if not unit:
36        unit = ' '
37    if data['cols'] or data['itypes']:
38        if not data['cols']:
39            dtypea = str(data['itypes'][0][0]+r":a#00CF00FF:"+data['pitem'][0][1])
40            dtypeb = str(data['itypes'][0][1]+r":b#002A97FF:"+data['pitem'][1][1])
41        elif not data['itypes']:
42            dtypea = str(r"AREA:a"+data['cols'][0][0]+r":"+data['pitem'][0][1])
43            dtypeb = str(r"LINE1:b"+data['cols'][0][1]+r":"+data['pitem'][1][1])
44        else:
45            dtypea = str(data['itypes'][0][0]+r":a"+data['cols'][0][0]+r":"+data['pitem'][0][1])
46            dtypeb = str(data['itypes'][0][1]+r":b"+data['cols'][0][1]+r":"+data['pitem'][1][1])
47    else:
48        dtypea = str(r"AREA:a#00CF00FF:"+data['pitem'][0][1])
49        dtypeb = str(r"LINE1:b#002A97FF:"+data['pitem'][1][1])
50    maxa = 'GPRINT:a:MAX:Max\:%.2lf %s'
51    mina = 'GPRINT:a:MIN:Min\:%.2lf %s'
52    avga = 'GPRINT:a:AVERAGE:Avg\:%.2lf %s'
53    nowa = 'GPRINT:a:LAST:Now\:%.2lf %s'
54    maxb = 'GPRINT:b:MAX:Max\:%.2lf %s'
55    minb = 'GPRINT:b:MIN:Min\:%.2lf %s'
56    avgb = 'GPRINT:b:AVERAGE:Avg\:%.2lf %s'
57    nowb = 'GPRINT:b:LAST:Now\:%.2lf %s'
58    rrdtool.graph(pngname, '-w', '600', '-h', '144', '-l', '0', '-s', start,
59                '-t', graphname, '-v', unit, DEFa, DEFb, 'COMMENT: \\n', dtypea, nowa, avga, mina, maxa, 'COMMENT: \\n',
60                dtypeb, nowb, avgb, minb, maxb, 'COMMENT: \\n')

如果有24个item的图形需要绘图,貌似我是想不到更好的方法了,只得慢慢细心的堆代码了。如果想到更优秀的方法,请告诉我一下。谢谢!