make it possible to centralize configuration on init, make graph options simpler
[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 $config_raw = null;
8   var $config_graph = null;
9   var $config_page = null;
10
11   var $rrd_fields = array();
12   var $rra_base = array();
13   var $rrd_step = 300;
14   var $rra_add_max = true;
15
16   var $status = 'unused';
17
18   function rrdstat($init_info = null) {
19     // ***** init RRD stat module *****
20     $this->set_def($init_info);
21
22     if (!is_writeable($this->rrd_file)) {
23       if (!file_exists($this->rrd_file)) {
24         if (touch($this->rrd_file)) { $this->create(); }
25         else { trigger_error('RRD file can not be created', E_USER_WARNING); }
26       }
27       else {
28         if (is_readable($this->rrd_file)) { $this->status = 'readonly'; }
29         else { trigger_error('RRD file is not readable', E_USER_WARNING); }
30       }
31     }
32     else {
33       $this->status = 'ok';
34     }
35   }
36
37   function set_def($init_info = null) {
38     if (is_array($init_info) && isset($init_info['file'])) {
39       // we have an array in the format we like to have
40       $iinfo =& $init_info;
41     }
42     else {
43       // we have something else (XML data?), try to generate the iinfo aray from it
44       $iinfo =& $init_info;
45     }
46
47     if (!isset($iinfo['file'])) { return false; }
48
49     $this->rrd_file = $iinfo['file'];
50
51     // fields (data sources, DS)
52     //  name - DS name
53     //  type - one of COUNTER, GAUGE, DERIVE, ABSOLUTE
54     //  heartbeat - if no sample recieved for that time, store UNKNOWN
55     //  min - U (unconstrained) or minimum value
56     //  max - U (unconstrained) or maximum value
57     //  update - this string will be fed into eval() for updating this field
58     if (isset($iinfo['fields']) && is_array($iinfo['fields'])) {
59       $this->rrd_fields = $iinfo['fields'];
60     }
61     else {
62       $this->rrd_fields[] = array('name' => 'ds0', 'type' => 'COUNTER', 'heartbeat' => 600, 'min' => 'U', 'max' => 'U');
63       $this->rrd_fields[] = array('name' => 'ds1', 'type' => 'COUNTER', 'heartbeat' => 600, 'min' => 'U', 'max' => 'U');
64     }
65
66
67     // MRTG-style RRD "database", see http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/tut/rrdtutorial.en.html
68     //
69     // archives (RRAs):
70     // 600 samples of 5 minutes  (2 days and 2 hours)
71     // 700 samples of 30 minutes (2 days and 2 hours, plus 12.5 days)
72     // 775 samples of 2 hours    (above + 50 days)
73     // 797 samples of 1 day      (above + 732 days, rounded up to 797)
74
75     $this->rrd_step = isset($iinfo['rrd_step'])?$iinfo['rrd_step']:300;
76
77     if (isset($iinfo['rra_base']) && is_array($iinfo['rra_base'])) {
78       $this->rra_base = $iinfo['rra_base'];
79     }
80     else {
81       $this->rra_base[] = array('step' => 1, 'rows' => 600);
82       $this->rra_base[] = array('step' => 6, 'rows' => 700);
83       $this->rra_base[] = array('step' => 24, 'rows' => 775);
84       $this->rra_base[] = array('step' => 288, 'rows' => 797);
85     }
86
87     $this->rra_add_max = isset($iinfo['rra_add_max'])?$iinfo['rra_add_max']:true;
88
89     if (isset($iinfo['graph'])) { $this->config_graph = $iinfo['graph']; }
90     if (isset($iinfo['page'])) { $this->config_page = $iinfo['page']; }
91     $this->config_raw = $iinfo;
92   }
93
94   function create() {
95     // create RRD file
96
97     // compose create command
98     $create_cmd = 'rrdtool create '.$this->rrd_file.' --step '.$this->rrd_step;
99     foreach ($this->rrd_fields as $ds) {
100       if (!isset($ds['type'])) { $ds['type'] = 'COUNTER'; }
101       if (!isset($ds['heartbeat'])) { $ds['heartbeat'] = 2*$this->rrd_step; }
102       if (!isset($ds['min'])) { $ds['min'] = 'U'; }
103       if (!isset($ds['max'])) { $ds['max'] = 'U'; }
104       $create_cmd .= ' DS:'.$ds['name'].':'.$ds['type'].':'.$ds['heartbeat'].':'.$ds['min'].':'.$ds['max'];
105     }
106     foreach ($this->rra_base as $rra) {
107       if (!isset($rra['cf'])) { $rra['cf'] = 'AVERAGE'; }
108       if (!isset($rra['xff'])) { $rra['xff'] = 0.5; }
109       if (!isset($rra['step'])) { $rra['step'] = 1; }
110       if (!isset($rra['rows'])) { $rra['rows'] = 600; }
111       $create_cmd .= ' RRA:'.$rra['cf'].':'.$rra['xff'].':'.$rra['step'].':'.$rra['rows'];
112     }
113     if ($this->rra_add_max) {
114       foreach ($this->rra_base as $rra) {
115         if (!isset($rra['cf'])) {
116           // only rows that have no CF set will be looked at here
117           $rra['cf'] = 'MAX';
118           if (!isset($rra['xff'])) { $rra['xff'] = 0.5; }
119           if (!isset($rra['step'])) { $rra['step'] = 1; }
120           if (!isset($rra['rows'])) { $rra['rows'] = 600; }
121           $create_cmd .= ' RRA:'.$rra['cf'].':'.$rra['xff'].':'.$rra['step'].':'.$rra['rows'];
122         }
123       }
124     }
125     $output = array(); $return_var = null;
126     exec($create_cmd, $output, $return_var);
127     if ($return_var) { trigger_error('rrd create returned with value '.$return_var, E_USER_WARNING); }
128     else { $this->status = 'ok'; }
129   }
130
131   function update($upArray = null) {
132     // feed new data into RRD
133     if ($this->status != 'ok') { trigger_error('Cannot update non-writeable file', E_USER_WARNING); return 1; }
134     $upvals = array();
135     foreach($this->rrd_fields as $ds) {
136       if (is_array($upArray) && isset($upArray[$ds['name']])) { $val = $upArray[$ds['name']]; }
137       elseif (isset($ds['update'])) { $val = eval($ds['update']); }
138       else { $val = null; }
139       $upvals[] = $val;
140     }
141     $update_cmd = 'rrdtool update '.$this->rrd_file.' N:'.implode(':', $upvals);
142     $output = array(); $return_var = null;
143     exec($update_cmd, $output, $return_var);
144     if ($return_var) { trigger_error('rrd update returned with value '.$return_var, E_USER_WARNING); }
145   return ($return_var == 0);
146   }
147
148   function fetch($cf = 'AVERAGE', $resolution = null, $start = null, $end = null) {
149     // fetch data from a RRD
150     if (!in_array($this->status, array('ok','readonly'))) { trigger_error('Error: rrd status is '.$this->status, E_USER_WARNING); return false; }
151
152     if (!in_array($cf, array('AVERAGE','MIN','MAX','LAST'))) { $cf = 'AVERAGE'; }
153     if (!is_numeric($resolution)) { $resolution = $this->rrd_step; }
154     if (!is_numeric($end)) { $end = $this->last_update(); }
155     elseif ($end < 0) { $end += $this->last_update(); }
156     $end = intval($end/$resolution)*$resolution;
157     if (!is_numeric($start)) { $start = $end; }
158     elseif ($start < 0) { $start += $end; }
159     $start = intval($start/$resolution)*$resolution;
160
161     $fetch_cmd = 'rrdtool fetch '.$this->rrd_file.' '.$cf.' --resolution '.$resolution.' --start '.$start.' --end '.$end;
162     $return = `$fetch_cmd 2>&1`;
163
164     if (strpos($return, 'ERROR') !== false) {
165       trigger_error('rrd fetch error: '.$return, E_USER_WARNING);
166       $fresult = false;
167     }
168     else {
169       $fresult = array();
170       $rows = explode("\n", $return);
171       $fields = preg_split('/\s+/', array_shift($rows));
172       if (array_shift($fields) == 'timestamp') {
173         $fresult[0] = $fields;
174         foreach ($rows as $row) {
175           if (strlen(trim($row))) {
176             $rvals = preg_split('/\s+/', $row);
177             $rtime = array_shift($rvals);
178             $rv_array = array();
179             foreach ($rvals as $key=>$rval) {
180               $rv_array[$fields[$key]] = ($rval=='nan')?null:floatval($rval);
181             }
182             $fresult[$rtime] = $rv_array;
183           }
184         }
185       }
186     }
187   return $fresult;
188   }
189
190   function graph($timeframe = 'day', $special = null, $extra = null) {
191     // create a RRD graph
192     static $gColors;
193     if (!isset($gColors)) {
194       $gColors = array('#00CC00','#0000FF','#000000','#FF0000','#00FF00','#FFFF00','#FF00FF','#00FFFF','#808080','#800000','#008000','#000080','#808000','#800080','#008080','#C0C0C0');
195     }
196
197     if (!in_array($this->status, array('ok','readonly'))) { trigger_error('Error: rrd status is '.$this->status, E_USER_WARNING); return false; }
198
199     // assemble configuration
200     $gconf = $this->config_graph;
201     if (!is_null($special) && is_array($this->config_raw['graph'][$special])) {
202       if (is_array($gconf)) { $gconf = array_merge($gconf, $this->config_raw['graph'][$special]); }
203       else { $gconf = $this->config_raw['graph'][$special]; }
204     }
205     if (is_array($extra)) {
206       if (is_array($gconf)) { $gconf = array_merge($gconf, $extra); }
207       else { $gconf = $extra; }
208     }
209
210     if (isset($gconf['format']) && ($gconf['format'] == 'SVG')) {
211       $format = $gconf['format']; $fmt_ext = '.svg';
212     }
213     elseif (isset($gconf['format']) && ($gconf['format'] == 'EPS')) {
214       $format = $gconf['format']; $fmt_ext = '.eps';
215     }
216     elseif (isset($gconf['format']) && ($gconf['format'] == 'PDF')) {
217       $format = $gconf['format']; $fmt_ext = '.pdf';
218     }
219     else {
220       $format = 'PNG'; $fmt_ext = '.png';
221     }
222
223     if (isset($gconf['filename'])) { $fname = $gconf['filename']; }
224     else { $fname = str_replace('.rrd', '-%t%f', $this->rrd_file); }
225     $fname = str_replace('%t', $timeframe, $fname);
226     $fname = str_replace('%f', $fmt_ext, $fname);
227     if (substr($fname, -strlen($fmt_ext)) != $fmt_ext) { $fname .= $fmt_ext; }
228
229     $graphrows = array(); $gC = 0;
230     $gDefs = ''; $gGraphs = ''; $addSpecial = '';
231
232     if ($timeframe == 'day') {
233       $duration = isset($gconf['duration'])?$gconf['duration']:30*3600; // 30 hours
234       $slice = isset($gconf['slice'])?$gconf['slice']:300; // 5 minutes
235       // vertical lines at day borders
236       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d')).'#FF0000';
237       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' -1 day').'#FF0000';
238       if (!isset($gconf['grid_x'])) { $gconf['grid_x'] = 'HOUR:1:HOUR:6:HOUR:2:0:%-H'; }
239     }
240     elseif ($timeframe == 'week') {
241       $duration = isset($gconf['duration'])?$gconf['duration']:8*86400; // 8 days
242       $slice = isset($gconf['slice'])?$gconf['slice']:1800; // 30 minutes
243       // vertical lines at week borders
244       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' '.(-date('w')+1).' day').'#FF0000';
245       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' '.(-date('w')-6).' day').'#FF0000';
246     }
247     elseif ($timeframe == 'month') {
248       $duration = isset($gconf['duration'])?$gconf['duration']:36*86400; // 36 days
249       $slice = isset($gconf['slice'])?$gconf['slice']:7200; // 2 hours
250       // vertical lines at month borders
251       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-01')).'#FF0000';
252       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-01').' -1 month').'#FF0000';
253     }
254     elseif ($timeframe == 'year') {
255       $duration = isset($gconf['duration'])?$gconf['duration']:396*86400; // 365+31 days
256       $slice = isset($gconf['slice'])?$gconf['slice']:86400; // 1 day
257       // vertical lines at month borders
258       $addSpecial .= ' VRULE:'.strtotime(date('Y-01-01')).'#FF0000';
259       $addSpecial .= ' VRULE:'.strtotime(date('Y-01-01').' -1 year').'#FF0000';
260     }
261     else {
262       $duration = isset($gconf['duration'])?$gconf['duration']:$this->rrd_step*500; // 500 steps
263       $slice = isset($gconf['slice'])?$gconf['slice']:$this->rrd_step; // whatever our step is
264     }
265
266     if (isset($gconf['rows']) && count($gconf['rows'])) {
267       foreach ($gconf['rows'] as $erow) {
268         if (isset($erow['name']) && strlen($erow['name'])) {
269           if (!isset($erow['scale']) && isset($gconf['scale'])) { $erow['scale'] = $gconf['scale']; }
270           $grow = array();
271           $grow['dType'] = isset($erow['dType'])?$erow['dType']:'DEF';
272           $grow['name'] = $erow['name'].(isset($erow['scale'])?'_tmp':'');
273           $grow['dsname'] = isset($erow['dsname'])?$erow['dsname']:$erow['name'];
274           $grow['cf'] = isset($erow['cf'])?$erow['cf']:'AVERAGE';
275           if (isset($erow['rpn_expr'])) { $grow['rpn_expr'] = $erow['rpn_expr']; }
276           if (isset($erow['scale'])) {
277             $graphrows[] = $grow;
278             $grow = array();
279             $grow['dType'] = 'CDEF';
280             $grow['name'] = $erow['name'];
281             $grow['rpn_expr'] = $erow['name'].'_tmp,'.$erow['scale'].',*';
282           }
283           $grow['gType'] = isset($erow['gType'])?$erow['gType']:'LINE1';
284           $grow['color'] = isset($erow['color'])?$erow['color']:$gColors[$gC++];
285           if ($gC >= count($gColors)) { $gC = 0; }
286           if (isset($erow['legend'])) {
287             $grow['legend'] = $erow['legend'];
288             if (!isset($gconf['show_legend'])) { $gconf['show_legend'] = true; }
289           }
290           if (isset($erow['stack'])) { $grow['stack'] = ($erow['stack'] == true); }
291           $graphrows[] = $grow;
292         }
293       }
294     }
295     else {
296       foreach ($this->rrd_fields as $ds) {
297         $grow = array();
298         $grow['dType'] = 'DEF';
299         $grow['name'] = $ds['name'].(isset($gconf['scale'])?'_tmp':'');
300         $grow['dsname'] = $ds['name'];
301         $grow['cf'] = 'AVERAGE';
302         if (isset($gconf['scale'])) {
303           $graphrows[] = $grow;
304           $grow = array();
305           $grow['dType'] = 'CDEF';
306           $grow['name'] = $ds['name'];
307           $grow['rpn_expr'] = $ds['name'].'_tmp,'.$gconf['scale'].',*';
308         }
309         $grow['gType'] = ($ds['name']=='ds0')?'AREA':'LINE1';
310         $grow['color'] = $gColors[$gC++]; if ($gC >= count($gColors)) { $gC = 0; }
311         $graphrows[] = $grow;
312       }
313     }
314
315     $endtime = isset($gconf['time_end'])?$gconf['time_end']:(is_numeric($this->last_update())?$this->last_update():time());
316     $gOpts = ' --start '.($endtime-$duration).' --end '.$endtime.' --step '.$slice;
317     if (isset($gconf['label_top'])) { $gOpts .= ' --title '.$this->text_quote($gconf['label_top']); }
318     if (isset($gconf['label_y'])) { $gOpts .= ' --vertical-label '.$this->text_quote($gconf['label_y']); }
319     if (isset($gconf['width'])) { $gOpts .= ' --width '.$gconf['width']; }
320     if (isset($gconf['height'])) { $gOpts .= ' --height '.$gconf['height'];
321       if (($gconf['height'] <= 32) && isset($gconf['thumb']) && ($gconf['thumb'])) { $gOpts .= ' --only-graph'; }
322     }
323     if (!isset($gconf['show_legend']) || (!$gconf['show_legend'])) { $gOpts .= ' --no-legend'; }
324     if (isset($gconf['min_y'])) { $gOpts .= ' --lower-limit '.$gconf['min_y']; }
325     if (isset($gconf['max_y'])) { $gOpts .= ' --upper-limit '.$gconf['max_y']; }
326     if (isset($gconf['fix_scale_y']) && $gconf['fix_scale_y']) { $gOpts .= ' --rigid'; }
327     if (isset($gconf['grid_x'])) { $gOpts .= ' --x-grid '.$gconf['grid_x']; }
328     if (isset($gconf['grid_y'])) { $gOpts .= ' --y-grid '.$gconf['grid_y']; }
329     if (isset($gconf['units_exponent'])) { $gOpts .= ' --units-exponent '.$gconf['units_exponent']; }
330     if (isset($gconf['units_length'])) { $gOpts .= ' --units-length '.$gconf['units_length']; }
331     if (!isset($gconf['force_recreate']) || (!$gconf['force_recreate'])) { $gOpts .= ' --lazy'; }
332     if (isset($gconf['force_color']) && is_array($gconf['force_color'])) {
333       foreach ($gconf['force_color'] as $ctag=>$cval) { $gOpts .= ' --color '.$ctag.$cval; }
334     }
335     if (isset($gconf['force_font']) && is_array($gconf['force_font'])) {
336       foreach ($gconf['force_font'] as $ctag=>$cval) { $gOpts .= ' --font '.$ctag.$cval; }
337     }
338     if (isset($gconf['units_binary']) && $gconf['units_binary']) { $gOpts .= ' --base 1024'; }
339
340     foreach ($graphrows as $grow) {
341       if (isset($grow['dType']) && strlen($grow['dType'])) {
342         $gDefs .= ' '.$grow['dType'].':'.$grow['name'].'=';
343         $gDefs .= ($grow['dType']=='DEF')?$this->rrd_file.':'.$grow['dsname'].':'.$grow['cf']:$grow['rpn_expr'];
344       }
345       if (isset($grow['gType']) && strlen($grow['gType'])) {
346         // XXX: current rrdtools version doesn't support STACK flag, only STACK type
347         if (isset($grow['stack']) && $grow['stack']) { $grow['gType'] = 'STACK'; }
348         $gGraphs .= ' '.$grow['gType'].':'.$grow['name'].$grow['color'];
349         if (isset($grow['legend'])) { $gGraphs .= ':'.$this->text_quote($grow['legend']); }
350         // XXX: when STACK flag is supported, remove above STACK if-command and uncomment the one below
351         //if (isset($grow['stack']) && $grow['stack']) { $gGraphs .= ':STACK'; }
352       }
353     }
354
355     $graph_cmd = 'rrdtool graph '.str_replace('*', '\*', $fname.$gOpts.$gDefs.$gGraphs.$addSpecial);
356     $return = `$graph_cmd 2>&1`;
357
358     if (strpos($return, 'ERROR') !== false) {
359       trigger_error('rrd graph error: '.$return, E_USER_WARNING);
360       $return = $graph_cmd."\n\n".$return;
361     }
362   return $return;
363   }
364
365   function simple_html($page_extras = null, $graph_extras = null) {
366     // create a simple (MRTG-like) HTML page and return it in a string
367     $basename = str_replace('.rrd', '', $this->rrd_file);
368
369     // assemble configuration
370     $pconf = $this->config_page;
371     if (is_array($page_extras)) {
372       if (is_array($pconf)) { $pconf = array_merge($pconf, $page_extras); }
373       else { $pconf = $page_extras; }
374     }
375
376     $out = '<html><head><title>'.$basename.' - RRD statistics</title></head><body>';
377
378     $out .= '<p>Last Update: '.date('Y-m-d H:i:s', $this->last_update()).'</p>';
379
380     if (in_array($this->status, array('ok','readonly'))) {
381       foreach (array('day','week','month','year') as $tframe) {
382         $ret = $this->graph($tframe, null, $graph_extras);
383         $out .= '<p>'.nl2br($ret).'</p>';
384         $out .= '<p><img src="'.$basename.'-'.$tframe.'.png"></p>';
385       }
386     }
387     else {
388       $out .= 'RRD error: status is "'.$this->status.'"';
389     }
390
391     $ou .= '</body></html>';
392   return $out;
393   }
394
395   function last_update() {
396     // fetch time of last update in this RRD file
397     static $last_update;
398     if (!isset($last_update) && in_array($this->status, array('ok','readonly'))) {
399       $last_cmd = 'rrdtool last '.$this->rrd_file;
400       $return = trim(`$last_cmd 2>&1`);
401       $last_update = is_numeric($return)?$return:null;
402     }
403   return isset($last_update)?$last_update:null;
404   }
405
406   function text_quote($text) { return '"'.str_replace('"', '\"', str_replace(':', '\:', $text)).'"'; }
407 }
408 ?>