add RRD statistics class
[php-utility-classes.git] / include / classes / rrdstat.php-class
1 <?php
2 // ************ RRD status class **************
3 class rrdstat {
4
5   var $rrd_file = 'sample.rrd';
6
7   var $rrd_fields = array();
8   var $rra_base = array();
9   var $rrd_step = 300;
10   var $rra_add_max = true;
11
12   var $status = 'unused';
13
14   function rrdstat($init_info = null) {
15     // ***** init RRD stat module *****
16     $this->set_def($init_info);
17
18     if (!is_writeable($this->rrd_file)) {
19       if (!file_exists($this->rrd_file)) {
20         if (touch($this->rrd_file)) { $this->create(); }
21         else { trigger_error('RRD file can not be created', E_USER_WARNING); }
22       }
23       else {
24         if (is_readable($this->rrd_file)) { $this->status = 'readonly'; }
25         else { trigger_error('RRD file is not readable', E_USER_WARNING); }
26       }
27     }
28     else {
29       $this->status = 'ok';
30     }
31   }
32
33   function set_def($init_info = null) {
34     if (is_array($init_info) && isset($init_info['file'])) {
35       // we have an array in the format we like to have
36       $iinfo =& $init_info;
37     }
38     else {
39       // we have something else (XML data?), try to generate the iinfo aray from it
40       $iinfo =& $init_info;
41     }
42
43     if (!isset($iinfo['file'])) { return false; }
44
45     $this->rrd_file = $iinfo['file'];
46
47     // fields (data sources, DS)
48     //  name - DS name
49     //  type - one of COUNTER, GAUGE, DERIVE, ABSOLUTE
50     //  heartbeat - if no sample recieved for that time, store UNKNOWN
51     //  min - U (unconstrained) or minimum value
52     //  max - U (unconstrained) or maximum value
53     //  update - this string will be fed into eval() for updating this field
54     if (isset($iinfo['fields']) && is_array($iinfo['fields'])) {
55       $this->rrd_fields = $iinfo['fields'];
56     }
57     else {
58       $this->rrd_fields[] = array('name' => 'ds0', 'type' => 'COUNTER', 'heartbeat' => 600, 'min' => 'U', 'max' => 'U');
59       $this->rrd_fields[] = array('name' => 'ds1', 'type' => 'COUNTER', 'heartbeat' => 600, 'min' => 'U', 'max' => 'U');
60     }
61
62
63     // MRTG-style RRD "database", see http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/tut/rrdtutorial.en.html
64     //
65     // archives (RRAs):
66     // 600 samples of 5 minutes  (2 days and 2 hours)
67     // 700 samples of 30 minutes (2 days and 2 hours, plus 12.5 days)
68     // 775 samples of 2 hours    (above + 50 days)
69     // 797 samples of 1 day      (above + 732 days, rounded up to 797)
70
71     $this->rrd_step = isset($iinfo['rrd_step'])?$iinfo['rrd_step']:300;
72
73     if (isset($iinfo['rra_base']) && is_array($iinfo['rra_base'])) {
74       $this->rra_base = $iinfo['rra_base'];
75     }
76     else {
77       $this->rra_base[] = array('step' => 1, 'rows' => 600);
78       $this->rra_base[] = array('step' => 6, 'rows' => 700);
79       $this->rra_base[] = array('step' => 24, 'rows' => 775);
80       $this->rra_base[] = array('step' => 288, 'rows' => 797);
81     }
82
83     $this->rra_add_max = isset($iinfo['rra_add_max'])?$iinfo['rra_add_max']:true;
84   }
85
86   function create() {
87     // create RRD file
88
89     // compose create command
90     $create_cmd = 'rrdtool create '.$this->rrd_file.' --step '.$this->rrd_step;
91     foreach ($this->rrd_fields as $ds) {
92       if (!isset($ds['type'])) { $ds['type'] = 'COUNTER'; }
93       if (!isset($ds['heartbeat'])) { $ds['heartbeat'] = 2*$this->rrd_step; }
94       if (!isset($ds['min'])) { $ds['min'] = 'U'; }
95       if (!isset($ds['max'])) { $ds['max'] = 'U'; }
96       $create_cmd .= ' DS:'.$ds['name'].':'.$ds['type'].':'.$ds['heartbeat'].':'.$ds['min'].':'.$ds['max'];
97     }
98     foreach ($this->rra_base as $rra) {
99       if (!isset($rra['cf'])) { $rra['cf'] = 'AVERAGE'; }
100       if (!isset($rra['xff'])) { $rra['xff'] = 0.5; }
101       if (!isset($rra['step'])) { $rra['step'] = 1; }
102       if (!isset($rra['rows'])) { $rra['rows'] = 600; }
103       $create_cmd .= ' RRA:'.$rra['cf'].':'.$rra['xff'].':'.$rra['step'].':'.$rra['rows'];
104     }
105     if ($this->rra_add_max) {
106       foreach ($this->rra_base as $rra) {
107         if (!isset($rra['cf'])) {
108           // only rows that have no CF set will be looked at here
109           $rra['cf'] = 'MAX';
110           if (!isset($rra['xff'])) { $rra['xff'] = 0.5; }
111           if (!isset($rra['step'])) { $rra['step'] = 1; }
112           if (!isset($rra['rows'])) { $rra['rows'] = 600; }
113           $create_cmd .= ' RRA:'.$rra['cf'].':'.$rra['xff'].':'.$rra['step'].':'.$rra['rows'];
114         }
115       }
116     }
117     $output = array(); $return_var = null;
118     exec($create_cmd, $output, $return_var);
119     if ($return_var) { trigger_error('rrd create returned with value '.$return_var, E_USER_WARNING); }
120     else { $this->status = 'ok'; }
121   }
122
123   function update($upArray = null) {
124     // feed new data into RRD
125     if ($this->status != 'ok') { trigger_error('Cannot update non-writeable file', E_USER_WARNING); return 1; }
126     $upvals = array();
127     foreach($this->rrd_fields as $ds) {
128       if (is_array($upArray) && isset($upArray[$ds['name']])) { $val = $upArray[$ds['name']]; }
129       elseif (isset($ds['update'])) { $val = eval($ds['update']); }
130       else { $val = null; }
131       $upvals[] = $val;
132     }
133     $update_cmd = 'rrdtool update '.$this->rrd_file.' N:'.implode(':', $upvals);
134     $output = array(); $return_var = null;
135     exec($update_cmd, $output, $return_var);
136     if ($return_var) { trigger_error('rrd update returned with value '.$return_var, E_USER_WARNING); }
137   return ($return_var == 0);
138   }
139
140   function graph($filename, $timeframe, $extra = null) {
141     // create an RRD graph
142     static $gColors;
143
144     if (!isset($gColors)) {
145       $gColors = array('#00CC00','#0000FF','#000000','#FF0000','#00FF00','#FFFF00','#FF00FF','#00FFFF','#808080','#800000','#008000','#000080','#808000','#800080','#008080','#C0C0C0');
146     }
147
148     if (is_null($filename) || !strlen($filename)) { $filename = str_replace('.rrd', '-%tf.png', $this->rrd_file); }
149     $fname = str_replace('%tf', $timeframe, $filename);
150     if (substr($fname, -4) != '.png') { $fname .= '.png'; }
151
152     // [-s|--start time] [-e|--end time] [-S|--step seconds]
153     if ($timeframe == 'day') { $timeinfo = '--start -86400'; }
154     elseif ($timeframe == 'week') { $timeinfo = '--start -604800'; }
155     elseif ($timeframe == 'month') { $timeinfo = '--start -2678400'; }
156     elseif ($timeframe == 'year') { $timeinfo = '--start -31622400'; }
157     else { $timeinfo = '--start -'.$this->rrd_step*500; }
158
159     $graphrows = array(); $gC = 0;
160     if (isset($extra['rows']) && count($extra['rows'])) {
161       foreach ($extra['rows'] as $erow) {
162         if (isset($erow['name']) && strlen($erow['name'])) {
163           $grow = array();
164           $grow['dType'] = isset($erow['dType'])?$erow['dType']:'DEF';
165           $grow['name'] = $erow['name'];
166           $grow['dsname'] = isset($erow['dsname'])?$erow['dsname']:$erow['name'];
167           $grow['cf'] = isset($erow['cf'])?$erow['cf']:'AVERAGE';
168           $grow['gType'] = isset($erow['gType'])?$erow['gType']:'LINE1';
169           $grow['color'] = isset($erow['color'])?$erow['color']:$gColors[$gC++];
170           if ($gC >= count($gColors)) { $gC = 0; }
171           if (isset($erow['legend'])) { $grow['legend'] = $erow['legend']; }
172           if (isset($erow['stack'])) { $grow['stack'] = ($erow['stack'] == true); }
173           $graphrows[] = $grow;
174         }
175       }
176     }
177     else {
178       foreach ($this->rrd_fields as $ds) {
179         $grow = array();
180         $grow['dType'] = 'DEF';
181         $grow['name'] = $ds['name'];
182         $grow['dsname'] = $ds['name'];
183         $grow['cf'] = 'AVERAGE';
184         $grow['gType'] = ($ds['name']=='ds0')?'AREA':'LINE1';
185         $grow['color'] = $gColors[$gC++]; if ($gC >= count($gColors)) { $gC = 0; }
186         $graphrows[] = $grow;
187       }
188     }
189
190     $gDefs = ''; $gGraphs = '';
191     foreach ($graphrows as $grow) {
192       $gDefs .= ' '.$grow['dType'].':'.$grow['name'].'='.$this->rrd_file.':'.$grow['dsname'].':'.$grow['cf'];
193       // XXX: current rrdtools version doesn't support STACK flag, only STACK type
194       if (isset($grow['stack']) && $grow['stack']) { $grow['gType'] = 'STACK'; }
195       $gGraphs .= ' '.$grow['gType'].':'.$grow['name'].$grow['color'];
196       if (isset($grow['legend'])) { $gGraphs .= ':'.$this->text_quote($grow['legend']); }
197       // XXX: when STACK flag is supported, remove above STACK if-command and uncomment the one below
198       //if (isset($grow['stack']) && $grow['stack']) { $gGraphs .= ':STACK'; }
199     }
200
201     $graph_cmd = 'rrdtool graph '.$fname.' '.$timeinfo.$gDefs.$gGraphs;
202     $return = `$graph_cmd 2>&1`;
203
204     $retval = 0;
205     if (strpos($return, 'ERROR') !== false) {
206       trigger_error('rrd graph error: '.$return, E_USER_WARNING);
207       $retval = 1;
208     }
209   return $retval;
210   }
211
212   function simple_html($page_extras = null, $graph_extras = null) {
213     // create a simple (MRTG-like) HTML page and return it in a string
214     $basename = str_replace('.rrd', '', $this->rrd_file);
215     $out = '<html><head><title>'.$basename.' - RRD statistics</title></head><body>';
216
217     if (in_array($this->status, array('ok','readonly'))) {
218       foreach (array('day','week','month','year') as $tframe) {
219         $this->graph(null, $tframe, $graph_extras);
220         $out .= '<p><img src="'.$basename.'-'.$tframe.'.png"></p>';
221       }
222     }
223     else {
224       $out .= 'RRD error: status is "'.$this->status.'"';
225     }
226
227     $ou .= '</body></html>';
228   return $out;
229   }
230
231   function text_quote($text) { return '"'.str_replace('"', '\"', str_replace(':', '\:', $text)).'"'; }
232 }
233 ?>