在linux中对vbox的cpu使用率监控

目前,每天中午cpu的负载都会突然增加,通过htop命令查看到此时的vbox的cpu占用率一致蛮高的,便计划对vbox的cpu使用率进行计划性监控,最开始的想法很简单就是通过调用top命令来进行cpu使用率的监控,但监控了好几天,发现值一直为0,而htop中值是一直有变化的,正常的结果也不应该为0,可惜,我没法对htop进行重定向,便计划通过/proc/<pid>/stat文件中的数据进行监控。可是当读取/proc/<pid>/stat文件内容后发现第14,15,16,17列的值完全没有变化(用于计算cpu使用率),预估top的值没有变化也和此有关,但htop的值一直有变化,而且显示的不止一个进程,故猜想htop读取的是线程值,所以开始读取/proc/<pid>/task/<tid>/stat文件内容,发现所需列的值有发生变化,而且一秒内变化的值和htop显示的值类似(此段内容,个人没法确定正确与否),故此,读取线程cpu使用率,代码如下:

import subprocess
import time
import psutil
import os

NAME = 'vbox_cpu_info'
VERBOSE = True
#通过psutil读取VBoxHeadless进程pid
def usePsutil():
    pidList = psutil.pids()
    processToTest = "VBoxHeadless"
    for eachPid in pidList:
        try:
            eachProcess = psutil.Process(eachPid)
            processName = eachProcess.name()  
            if(processName == processToTest):
                return eachPid
        except psutil.NoSuchProcess,pid:
            print "no process found with pid=%s"%(pid)
#得到线程的cpu占用时间
def get_cpu_time():
    vboxPid = tryPsutil()
    currentDirs = os.listdir("/proc/%d/task/"%vboxPid)
    allDirs = []
    timeOfCPU = []
    for i in currentDirs:
        allDirs.append(i)
    for i in allDirs:
        fileName = "/proc/%d/task/%d/stat"%(vboxPid,int(i))
        with open(fileName, 'r') as f:
            line = f.readlines()
            line_str = ''.join(line)
            line_split = line_str.split()
            timeOfCPU.append(int(line_split[13]) + int(line_split[14]) + int(line_split[15]) + int(line_split[16]))
    return timeOfCPU
#得到线程id
def get_tid():
    vboxPid = tryPsutil()
    currentDirs = os.listdir("/proc/%d/task/"%vboxPid)
    allDirs = []
    for i in currentDirs:
        allDirs.append(i)
    return allDirs
#得到tid和cpu used
def get_stats():
    firstTime = []
    lastTime =[]
    firstTime = get_cpu_time()
    time.sleep(1)
    lastTime = get_cpu_time()
    CPUofUsed = list(map(lambda x: x[0]-x[1], zip(lastTime, firstTime)))
    tid = get_tid()
    print zip(tid,CPUofUsed)
get_stats()

若需在nagios中监控,只需修改少量代码即可,在此忽略,若想在collectd中监控,可参考:https://github.com/anryko/cpu-collectd-plugin

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章