一直很想了解nagios中的pnp是如何工做的,正好看到這幾天cu上有人問rrdtool如何圖像。這幾天特意的翻了翻rrd的資料,補習了下。結合perl的一些模塊,獲取所須要的數據,最後調用rrdtools繪製圖像。好了,廢話很少說了,開始講解實現過程。html
3、代碼ios
- #!/usr/bin/perl
- use strict;
- use warnings;
- use RRD::Simple qw(:all);
- use YAML;
- use Sys::Statistics::Linux;
- my $rrdfile = '/home/mcshell/tmp/myfile.rrd';
- my $rrdfile_tmp = '/home/mcshell/tmp/myfile_tmp.rrd';
- my $rrd = RRD::Simple->new( file => "$rrdfile" );
- my $rrd_tmp = RRD::Simple->new( file => "$rrdfile_tmp"); #創建一個臨時rrd用於計算5分鐘內變化的差值
- unless(-e $rrdfile){
- $rrd->create( #若是沒有rrd則進行創建一個rrd
- bytesIn => "GAUGE", #定義數值源類型
- bytesOut => "GAUGE",
- );
- $rrd_tmp->create(
- bytesIn => "GAUGE",
- bytesOut => "GAUGE",
- );
- }
- my ($now_input,$now_output,$input,$output);
- my $lxs = Sys::Statistics::Linux->new( #這裏進行獲取網卡的流量(這個模塊能夠獲取多個系統參數,如cpu,process,磁盤IO)
- #能夠根據這些能夠繪製這種圖形。
- netstats => {
- init => 1,
- initfile => '/tmp/netstats.yml', #數據存入yml文件
- },
- );
- my $stat = $lxs->get;
- my $config = YAML::LoadFile('/tmp/netstats.yml');#解析yml文件
- $now_input = $config->{eth0}->{rxbyt};
- $now_output = $config->{eth0}->{txbyt};
- my $info = $rrd->info("$rrdfile_tmp"); #獲取tmp的數據
- my $before_input_5=$info->{ds}->{bytesIn}->{last_ds}; #獲取5分鐘以前的數據
- my $before_output_5=$info->{ds}->{bytesOut}->{last_ds};
- if ($before_input_5 eq 'U' || $before_output_5 eq 'U'){
- $before_input_5 = $now_input;
- $before_output_5 = $now_output;
- }
- $input = $now_input - $before_input_5; #5分鐘變化的數據
- $output = $now_output - $before_output_5;
- $rrd->update(
- bytesIn => "$input",
- bytesOut => "$output",
- );
- $rrd_tmp->update(
- bytesIn => "$now_input",
- bytesOut => "$now_output",
- );
- my $starttime = time; #獲取當前unix時間戳
- my $endtime = $starttime - 7200; #2個小時以前的unix時間戳
- my %rtn = $rrd->graph( #這裏是定義每週,每個月,每一年的圖形。
- timestamp => "both",
- periods => [ qw{ weekly monthly annual} ], #定義所需的週期文件
- title => "Network Interface eth0",
- vertical_label => "Bytes/sec",
- line_thickness => 2, #畫線的像素
- extended_legend => 1, #打開詳細信息
- );
- %rtn = $rrd->graph( #這裏是定義一個2小時的圖形,去掉下面的end,start爲一天的圖
- destination => "/var/www/html",
- timestamp => "both",
- periods => [ qw{ daily } ],
- title => "Network Interface eth0",
- vertical_label => "Bytes/sec",
- line_thickness => 2,
- extended_legend => 2,
- end => $starttime,
- start =>$endtime,
- "COMMENT: " => "",
- #此處的COMMENT是有空格的,尼瑪真是一個一個空格來對齊下面的格式,靠O__O"…
- "GPRINT:bytesOut:AVERAGE: bytesOut平均值%8.2lf%s"=> "",
- "COMMENT: " => "",
- "GPRINT:bytesIn:AVERAGE: bytesIn平均值%8.2lf%s"=> "",
- );
- my $lastUpdated = $rrd->last;
- print "myfile.rrd was last updated at " .
- scalar(localtime($lastUpdated)) . "\n";
在crontab中加入每五分鐘運行一次。web
4、驗證圖像sql