基於JRobin的CPU使用率監控

 

基於JRobin的CPU使用率監控

 

作者:終南   <[email protected]>

 

JRobin是一個很強大的存儲和用圖形展示基於時間序列數據的工具。只要有合適的需求,能夠提供提供滿足這些需求的數據,JRobin就能合理地存儲這些數據,並且生成非常漂亮的圖形。

 

在基於JRobin的應用中,最主要的工具並不在於JRobin,而是如何設計應用和使用Java代碼採用相應的手段獲取感興趣的數據。在文章“基於JRobin的網絡監控管理”,通過在Java中執行外部命令來獲取Ping的響應時間。本文的應用旨在對計算機CPU的使用率進行監視,因爲如何在Windows和Linux上獲取CPU的使用率就成爲了關鍵要解決的問題。

 

1、在Windows上獲取CPU使用率:

WMI提供了在Windows上獲取計算機各種有用信息的接口,尤其可以利用WMI來獲取計算機性能有關的數據。可以用通過Win32_Processor對象來獲取CPU的使用率,該對象LoadPercentage屬性保存了相應CPU的負載情況。在本例中,將計算機上各個CPU使用率進行簡單平均,既是該計算機CPU的使用率。

腳本如下:

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!//" & strComputer & "/root/cimv2")

Set colItems = objWMIService.ExecQuery("Select * from Win32_Processor ",,48)
load = 0
n = 0
For Each objItem in colItems
   load = load + objItem.LoadPercentage
   n = n + 1
Next
Wscript.Echo (load/n)

該最後腳本輸出CPU平均使用率,Java程序可以執行該腳本獲取標準輸出,得到CPU平均使用率。

 

2、在Linux上獲取CPU使用率:

Linux操作系統的/proc文件系統提供了與系統和進程有關的信息。通過訪問/proc/stat就可以獲取CPU的使用情況。其bash腳本如下:

user=`cat /proc/stat | head -n 1 | awk '{print $2}'`
nice=`cat /proc/stat | head -n 1 | awk '{print $3}'`
system=`cat /proc/stat | head -n 1 | awk '{print $4}'`
idle=`cat /proc/stat | head -n 1 | awk '{print $5}'`
iowait=`cat /proc/stat | head -n 1 | awk '{print $6}'`
irq=`cat /proc/stat | head -n 1 | awk '{print $7}'`
softirq=`cat /proc/stat | head -n 1 | awk '{print $8}'`
let used=$user+$nice+$system+$iowait+$irq+$softirq
let total=$used+$idle
echo $used $total

該腳本最後輸出自機器啓動以來,CPU總共使用的時間和總共運行時間。要想獲取CPU使用率,還需要作進行一步處理。處理步驟如下:

(1)運行腳本,得到相應數據:1000 10000

(2)sleep 60秒

(3)運行腳本,得到相應數據:7000 70000

(4)那麼在這段時間內,CPU的使用率就等於:(7000 - 1000)/(70000 - 10000)= 10%。

(5)定時運行腳本,就可以得到每個時段CPU的使用率。

 

3、與獲取Ping響應時間代碼的異同:

這兩個程序實現的功能基本類似,就是獲取數據,利用JRobin保存和畫圖。其中利用JRobin保存和畫圖的功能除了保存的數據源、顯示的文本信息不同以外,其他都是相同的。他們最大的不同在於獲取和處理數據的方式。

在WIndows下,Ping程序利用Ping命令來獲取數據,而CPU監視程序則使用VBScript利用WMI接口通過CScript.EXE執行腳本來實現。

在Linux下,不能直接獲取CPU使用率信息,需要在下一次獲取到CPU使用信息時,對數據進行進一步出來才能得到。

 

4、看看成果:

aeff889bbebf3bacc8eaf40e.jpg

 

5、事例代碼:

import java.awt.Color;
import java.awt.Font;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Logger;

import org.jrobin.core.RrdDb;
import org.jrobin.core.RrdDef;
import org.jrobin.core.Sample;
import org.jrobin.graph.RrdGraph;
import org.jrobin.graph.RrdGraphDef;

public class CPUMonitor {

public static String[] execute(String[] commands) {
   String[] strs = null;
   File scriptFile = null;
   try {
    List<String> cmdList = new ArrayList<String>();
    String osName = System.getProperty("os.name");
    if (osName.indexOf("Windows") > -1) {
     scriptFile = File.createTempFile("monitor", ".vbs");
     cmdList.add("CMD.EXE");
     cmdList.add("/C");
     cmdList.add("CSCRIPT.EXE");
     cmdList.add("//NoLogo");
    } else {
     scriptFile = File.createTempFile("monitor", ".sh");
     cmdList.add("/bin/bash");
    }
    String fileName = scriptFile.getCanonicalPath();
    PrintWriter writer = new PrintWriter(scriptFile);
    for (int i = 0; i < commands.length; i++) {
     writer.println(commands[i]);
    }
    writer.flush();
    writer.close();
    cmdList.add(fileName);

    writer.flush();
    writer.close();
    cmdList.add(fileName);

    ProcessBuilder pb = new ProcessBuilder(cmdList);
    Process p = pb.start();

    p.waitFor();

    String line = null;
    BufferedReader stdout = new BufferedReader(new InputStreamReader(p
      .getInputStream()));
    List<String> stdoutList = new ArrayList<String>();
    while ((line = stdout.readLine()) != null) {
     stdoutList.add(line);
    }

    BufferedReader stderr = new BufferedReader(new InputStreamReader(p
      .getErrorStream()));
    List<String> stderrList = new ArrayList<String>();
    while ((line = stderr.readLine()) != null) {
     stderrList.add(line);
    }

    strs = stdoutList.toArray(new String[0]);
   } catch (Exception e) {
    e.printStackTrace();
   } finally {
    if (scriptFile != null)
     scriptFile.delete();
   }

   return strs;
}

private String dataFormat = "%3f";
private Logger logger = Logger.getLogger(this.getClass().getName());
private String monitorName = "cpu";
private String dataDir = ".";
private int step = 10;
private String rrdPath = "";
private Timer timer = new Timer();
private long timeStart = 0;
protected int width = 600;
protected int height = 150;

public CPUMonitor(String dataDir, int step) {
   this.dataDir = dataDir;
   this.step = step;
   this.rrdPath = this.dataDir + File.separator + monitorName + ".rrd";
}

public String generateGraph() {
   long timeCur = org.jrobin.core.Util.getTimestamp();
   return generateGraph(timeStart, timeCur);
}

public String generateGraph(long start, long end) {
   RrdDb rrdDb = null;
   try {
    Color[] colors = new Color[] { Color.GREEN, Color.BLUE,
      Color.MAGENTA, Color.YELLOW, Color.RED, Color.CYAN,
      Color.ORANGE, Color.PINK, Color.BLACK };
    String graphPath = this.dataDir + File.separator + monitorName
      + ".png";

    // create graph
    logger.info("Creating graph");
    RrdGraphDef gDef = new RrdGraphDef();
    gDef.setWidth(width);
    gDef.setHeight(height);
    gDef.setFilename(graphPath);
    gDef.setStartTime(start);
    gDef.setEndTime(end);

    gDef.setTitle("CPU Usage");
    gDef.setVerticalLabel("%");

    String[] dsNames = null;

    rrdDb = new RrdDb(rrdPath);
    dsNames = rrdDb.getDsNames();

    for (int i = 0; i < dsNames.length; i++) {
     String dsName = dsNames[i];
     String legend = dsName;
     if (legend == null || legend.equals(""))
      legend = dsName;
     gDef.datasource(dsName, rrdPath, dsName, "AVERAGE");
     gDef.line(dsName, colors[i % colors.length], legend, 2);

     gDef.gprint(dsName, "MIN", dataFormat + " Min");
     gDef.gprint(dsName, "AVERAGE", dataFormat + " Avg");
     gDef.gprint(dsName, "MAX", dataFormat + " Max");
     gDef.gprint(dsName, "LAST", dataFormat + " Last//r");

     gDef.print(dsName, "MIN", "min" + dsName + " = %.3f");
     gDef.print(dsName, "AVERAGE", "avg" + dsName + " = %.3f");
     gDef.print(dsName, "MAX", "max" + dsName + " = %.3f");
     gDef.print(dsName, "LAST", "last" + dsName + " = %.3f");
    }

    gDef.setImageInfo("<img src='%s' width='%d' height = '%d'>");
    gDef.setPoolUsed(false);
    gDef.setImageFormat("png");

    gDef.setSmallFont(new Font("Monospaced", Font.PLAIN, 11));
    gDef.setLargeFont(new Font("SansSerif", Font.BOLD, 14));
    // gDef.setAltYMrtg(true);

    // create graph finally
    RrdGraph graph = new RrdGraph(gDef);

    // logger.info(graph.getRrdGraphInfo().dump());
    logger.info("Graph created");

    return graph.getRrdGraphInfo().getFilename();
   } catch (Exception e) {
    logger.warning("Error in generating graph: " + e.getMessage());
   } finally {
    if (rrdDb != null)
     try {
      rrdDb.close();
     } catch (IOException e) {
      e.printStackTrace();
     }
   }
   return null;
}

private long lastUsed = 0;
private long lastTotal = 0;

private double getCPUUsage(String[] strs) {
   double value = Double.NaN;
   String osName = System.getProperty("os.name");
   if (osName.indexOf("Windows") > -1) {
    String strValue = strs[0];
    value = Double.parseDouble(strValue);
   } else {
    String strValue = strs[0];
    String[] values = strValue.split(" ");
    if (values.length == 2) {
     long used = Long.parseLong(values[0]);
     long total = Long.parseLong(values[1]);

     if (lastUsed > 0 && lastTotal > 0) {
      long deltaUsed = used - lastUsed;
      long deltaTotal = total - lastTotal;
      if (deltaTotal > 0) {
       value = ((long) (((deltaUsed * 100) / deltaTotal) * 10)) / 10;
      }
     }

     lastUsed = used;
     lastTotal = total;
    }

   }
   return value;
}

/**
* Return a HashMap which contains the current value of each data source.
*
* @return the current value of each data source.
*/
public double getValue(String dsName) {
   String[] commands = new String[0];
   String osName = System.getProperty("os.name");
   if (osName.indexOf("Windows") > -1) {
    commands = new String[] {
      "strComputer = /"./"",
      "Set objWMIService = GetObject(/"winmgmts:/" _",
      "   & /"{impersonationLevel=impersonate}!/////" & strComputer & /"
//root//cimv2/")",
      "Set colItems = objWMIService.ExecQuery(/"Select * from Win32_Processor /",,48)",
      "load = 0", "n = 0", "For Each objItem in colItems",
      " load = load + objItem.LoadPercentage", " n = n + 1",
      "Next", "Wscript.Echo (load/n)" };
   } else {
    commands = new String[] {
      "user=`cat /proc/stat | head -n 1 | awk '{print $2}'`",
      "nice=`cat /proc/stat | head -n 1 | awk '{print $3}'`",
      "system=`cat /proc/stat | head -n 1 | awk '{print $4}'`",
      "idle=`cat /proc/stat | head -n 1 | awk '{print $5}'`",
      "iowait=`cat /proc/stat | head -n 1 | awk '{print $6}'`",
      "irq=`cat /proc/stat | head -n 1 | awk '{print $7}'`",
      "softirq=`cat /proc/stat | head -n 1 | awk '{print $8}'`",
      "let used=$user+$nice+$system+$iowait+$irq+$softirq",
      "let total=$used+$idle", "echo /"$used $total/"" };
   }
   return getCPUUsage(execute(commands));
}

/**
* Initialization.
*/
public void initialize() throws Exception {
   RrdDb rrdDb = null;
   try {
    rrdDb = new RrdDb(rrdPath);
   } catch (Exception e) {
   }

   if (rrdDb == null) {
    logger.info("RRD data is not located in " + rrdPath
      + ", create a new one");

    RrdDef rrdDef = new RrdDef(rrdPath, timeStart - 1, step);

    rrdDef.addDatasource("cpu", "GAUGE", 2 * step, 0, Double.NaN);
    rrdDef.addArchive("AVERAGE", 0.5, 1, 24 * 3600 / step);
    rrdDef.addArchive("AVERAGE", 0.5, 300 / step, 7 * 288);

    logger.info("Estimated file size: " + rrdDef.getEstimatedSize());
    rrdDb = new RrdDb(rrdDef);
    logger.info("RRD file created.");
   }

   logger.info(monitorName + " RRD Db Defs: " + rrdDb.getRrdDef().dump());
   if (rrdDb != null)
    rrdDb.close();
}

/**
* Start monitor.
*
* @return true if succeed, else false.
*/
public boolean start() {
   logger.info("start to monitor " + monitorName);

   try {
    timeStart = org.jrobin.core.Util.getTimestamp();
    initialize();
    timer.scheduleAtFixedRate(new TimerTask() {
     public void run() {
      try {
       updateData();
      } catch (Exception e) {
       e.printStackTrace();
       logger.severe("Timer running error: " + e.getMessage());
      }
     }
    }, 0, step * 1000);
    return true;
   } catch (Exception e) {
    e.printStackTrace();
   }
   return false;
}

/**
* Stop monitor.
*/
public void stop() {
   timer.cancel();
}

private void updateData() throws Exception {
   RrdDb rrdDb = null;
   try {
    logger.info("update rrd data for " + monitorName);

    rrdDb = new RrdDb(rrdPath);
    String[] dsNames = rrdDb.getDsNames();

    long lastUpdateTime = rrdDb.getLastUpdateTime();
    long t = org.jrobin.core.Util.getTimestamp();
    if (t > lastUpdateTime) {
     rrdDb.setInfo("T=" + t);
     Sample sample = rrdDb.createSample();
     sample.setTime(t);
     for (int i = 0; i < dsNames.length; i++) {
      String dsName = dsNames[i];
      Double value = getValue(dsName);
      logger.fine(dsName + " = " + value);
      if (value == null)
       value = Double.NaN;
      sample.setValue(dsName, value);
     }
     sample.update();
    } else {
     logger.warning("Bad sample time " + t + "("
       + new Date(t * 1000L) + ")" + new Date()
       + ", the last update time was " + lastUpdateTime + "("
       + new Date(lastUpdateTime * 1000L) + ") - "
       + monitorName);
    }
   } finally {
    if (rrdDb != null)
     try {
      rrdDb.close();
     } catch (IOException e) {
      e.printStackTrace();
     }
   }
}

public static void main(String[] args) {
   CPUMonitor p = new CPUMonitor(".", 10);
   p.start();

   try {
    Thread.sleep(10 * 60 * 1000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }

   p.stop();
   p.generateGraph();
}
}

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