今天將介紹使用RRDTool來繪製系統負荷的Python程式.
程式碼如下:
#!/usr/bin/env python
# ---------------------------
# Python RRDTool
# LoadAvg Data
# Create Image from rrd file
# ---------------------------
import rrdtool
import datetime
def load_graph(rrdfile, load, period):
timenow = datetime.datetime.now()
disptime = datetime.datetime.strftime(timenow, '%Y-%m-%d %H-%M-%S')
if period == 'yesterday':
start = 'end-1d'
end = '00:00'
if period == 'today':
start = '00:00'
end = '23:59'
title = '%s_avg_%s' % (load, period)
filename = title + '.png'
def_load = 'DEF:%s=%s:%s:AVERAGE' % (load, rrdfile, load)
if load == 'load1':
graph_cmd = 'AREA:%s#8985BF: 1 min average' % load
if load == 'load5':
graph_cmd = 'AREA:%s#F4888B: 5 min average' % load
if load == 'load15':
graph_cmd = 'AREA:%s#EAEF66: 15 min average' % load
last_print = 'GPRINT:%s' % load
last_print = last_print + ':LAST: Current\\: %4.2lf'
avg_print = 'GPRINT:%s:' % load
avg_print = avg_print + 'AVERAGE: Average\\: %4.2lf'
min_print = 'GPRINT:%s' % load
min_print = min_print + ':MIN: Min\\: %4.2lf'
max_print = 'GPRINT:%s' % load
max_print = max_print + ':MAX: Max\\: %4.2lf\\n'
# -------------------
rrdtool.graph(
filename,
'--start', start,
'--end', end,
'--title', title,
'-a', 'PNG',
'-W', 'Hitomitanaka for ITHelp',
'--slope-mode',
'--vertical-label=Load Average',
'--rigid',
'--upper-limit', '3',
'--lower-limit', '0',
'--width', '500',
'--height', '150',
'--x-grid', 'HOUR:1:HOUR:2:HOUR:2:0:%H',
'--alt-y-grid',
'--color', 'BACK#000000',
'--color', 'CANVAS#000000',
'--color', 'FONT#FFF978',
'--font=LEGEND:7',
'--font', 'TITLE:8:',
'--font', 'UNIT:7:',
'--font', 'WATERMARK:9',
# ---------------------------------
def_load,
graph_cmd,
last_print,
avg_print,
min_print,
max_print,
'COMMENT:\t\t\t\tUpdate Time %s' % disptime)
#
def draw_loads(period):
load_graph('sysload.rrd', 'load1', period)
load_graph('sysload.rrd', 'load5', period)
load_graph('sysload.rrd', 'load15', period)
if __name__ == '__main__':
draw_loads('today')
匯製的圖形如下:
一分鐘平均負荷:
五分鐘平均負荷:
十五分鐘平均負荷:
除了匯製 時間-數值 圖形以外,底下還有例出 現在值,平均值,最大值,最小值,
方便對系統負荷有一個整體的概觀.