今天將介紹讀取 /proc/loadavg 的內容,並將資料寫入
rrd file的Python程式.
我們看一下 /proc/loadavg 的內容
0.91 0.64 0.50 1/416 4044
所謂load 就是Job 還在Run Queue裡面尚未執行,或是等待IO,數值越大代表系統越多工作
等待;前三個欄位分別是 1分鐘,5分鐘,15分鐘的負荷平均值,
第四個欄位代表 正在執行的processes與休眠的processes.用 / 分隔.
第五個是剛執行的 process 的 pid.
接著就是 Python 程式碼
#!/usr/bin/env python
# ---------------------------------
# Python RRDTool
# Update LoadAvg and Processes RRD
# ---------------------------------
import rrdtool
import time
def get_loads():
""" get system avg. load and process status"""
loads_dict = {}
loads_list = ('load1', 'load5', 'load15', 'runproc', 'slpproc')
with open('/proc/loadavg', 'r') as loads:
sysloads = loads.readline()
sysloads = sysloads.split()
load1 = float(sysloads[0])
load5 = float(sysloads[1])
load15 = float(sysloads[2])
procs = sysloads[3]
runproc , slpproc = procs.split('/')
runproc = int(runproc)
slpproc = int(slpproc)
loads_dict = dict(zip(loads_list, (load1, load5, load15, runproc, slpproc)))
return loads_dict
#
def update_loads_rrd(rrdfile):
""" update loads rrd file """
loads_dict = get_loads()
load1 = loads_dict['load1']
load5 = loads_dict['load5']
load15 = loads_dict['load15']
runproc = loads_dict['runproc']
slpproc = loads_dict['slpproc']
totproc = runproc + slpproc
rrdtool.update(rrdfile, 'N:' + `load1` + ':' + `load5` + ':' + \
`load15` + ':' + `totproc` + ':' + `slpproc` + \
':' + `runproc`)
#
if __name__ == '__main__':
while 1:
update_loads_rrd('sysload.rrd')
time.sleep(60)
放到背景執行,會每分鐘update資料.