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