linux下的用于性能监控出图的工具很多,像rrdtool、cacti(这个也是基于rrdtool的)、pnp4nagios、smoking、rrdtool等。不过前两天在看一个技术站点时又看到了另一个强大的绘图工具gnuplot(跨平台,不仅仅只linux) —— 其不但能绘制系统性能图、还可以很简单的绘制科学计算图、二维图、三维图、立方图等。项目主页为:http://www.gnuplot.info/ 。
一、安装
目前的最新版为4.6.5,这里不再列出源码包的方式进行安装,因为常用的linux系统源里都有该包:
//centos/redhat等rpm包安装 yum -y install gnuplot //ubuntu/debian等 apt安装 sudo apt-get install gnuplot
二、使用及示例
gnuplot有两种绘图方式,一种是交互式,一种是直接配置好相关参数直接运行。(这点和python相似)
交互式方式的如果想直接将图形展示,需要x11终端支持。这里不再具体示例,有兴趣的可以参看gnuplot中文手册参看示例或官方示例。下面以结合第二种方式为例,展示一个完整的示例:
例1、gnuplot绘制CPU使用图
sar获取 cpu信息并输出到文件
sar -u 1 10 | head -n -2 | tail -11 | grep . > /var/www/html/monitor.data
文件内容格式如下:
#cat monitor.data 06:24:52 CPU %user %nice %system %iowait %steal %idle 06:24:53 all 0.00 0.00 1.00 1.00 0.00 98.00 06:24:54 all 0.00 0.00 1.01 0.00 0.00 98.99 06:24:55 all 5.00 0.00 2.00 0.00 0.00 93.00 06:24:56 all 1.00 0.00 2.00 6.00 0.00 91.00 06:24:57 all 0.00 0.00 1.02 2.04 0.00 96.94 06:24:58 all 31.68 0.00 9.90 0.00 0.00 58.42 06:24:59 all 76.77 0.00 23.23 0.00 0.00 0.00 06:25:00 all 73.00 0.00 27.00 0.00 0.00 0.00 06:25:01 all 76.00 0.00 24.00 0.00 0.00 0.00
编辑monitor.conf配置文件,以备gnuplot读取执行:
# cat monitor.conf set term png set xdata time set style data lines set output 'cpu.png' set timefmt '%H:%M:%S' set format x '%H:%M:%S' set xlabel 'TIME' set ylabel 'CPU' plot 'monitor.data' using 1:3 title "%user", 'monitor.data' using 1:5 title "%sys", 'monitor.data' using 1:8 title "%idle"
具体输出的图形如下:
可以写一个脚本每隔一分钟执行一次:
# cat checkcpu.sh #!/bin/sh sar -u 1 10 | head -n -2 | tail -11 | grep . > /var/www/html/monitor.data && gnuplot /var/www/html/monitor.conf [root@oracle html]# chmod +x checkcpu.sh
可以再配合一个简单的html页面,每一秒钟刷新一次,html内容如下:
<html> <body> <tablewidth="600"border="0"cellpadding="3"cellspacing="0"> <tr> <td><strong><center>CPU Monitor</center></strong></td> </tr> </table> <br> <p><imgsrc="cpu.png"width="600"height="380"></p> </body> <scriptlanguage="JavaScript"> function refresh(){ window.location.reload(); } setTimeout('refresh()',1000); </script> </html>
例2、gnuplot绘制负载图
[root@localhost~]# cat /opt/cpuload.gnuplot #!/bin/bash uptime | awk '{print $1,$(NF-2),$(NF-1),$(NF) }' | tr -d ',' >>/opt/mydata gnuplot <<EOF set terminal png tiny font '/usr/share/fonts/liberation/LiberationSans-Regular.ttf' set output '/var/www/html/loadavg.png' set xdata time set timefmt '%H:%M:%S' set xlabel 'TIME' set format x '%H:%M' set xtics rotate set ylabel 'load average' plot '/opt/mydata' u 1:2 t '1-min' with lines, '/opt/mydata' u 1:3 t '5-min' with lines,'/opt/mydata' u 1:4 t '15-min' with lines EOF #chmod +x /opt/cpuload.gnuplot
同样,可以利用html展示:
[root@localhost ~]# cat /var/www/html/gnuplot.html <html> <h1>Performance Charts</h1> <a href="/loadavg.png">LOAD Acerage</a> </html>
以上脚本也可以利用crontab进行绘图。
当然如果想自制监控平台的话,还可以配合php、mysql等进行入库与图形展示。这里也只是列了两个小示例,gnuplot的使用场景不止这些。
利用apache做压力测试时,也可以用其配合,直接的以图形展示。这里有csdn上的一个示例。
同样,利用tpcc-mysql做mysql性能测试时,也可以利用gnuplot进行绘制性能图。这里有chinaunix上的一个示例。