better assembling of used config based on defaults
[php-utility-classes.git] / include / classes / rrdstat.php-class
... / ...
CommitLineData
1<?php
2// ************ RRD status class **************
3class rrdstat {
4
5 var $rrd_file = null;
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($rrdconfig, $conf_id = null) {
19 // ***** init RRD stat module *****
20 $this->set_def($rrdconfig, $conf_id);
21
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 }
32 }
33 else {
34 $this->status = 'ok';
35 }
36 }
37 }
38
39 function set_def($rrdconfig, $conf_id = null) {
40 if (is_array($rrdconfig)) {
41 // we have an array in the format we like to have
42 $complete_conf =& $rrdconfig;
43 }
44 else {
45 // we have something else (XML data?), try to generate the iinfo aray from it
46 $complete_conf =& $rrdconfig;
47 }
48
49 if (!is_null($conf_id)) {
50 $iinfo = isset($complete_conf[$conf_id])?$complete_conf[$conf_id]:array();
51 if (isset($complete_conf['*'])) {
52 $iinfo = (array)$iinfo + (array)$complete_conf['*'];
53 if (isset($complete_conf['*']['graph'])) { $iinfo['graph'] = (array)$iinfo['graph'] + (array)$complete_conf['*']['graph']; }
54 if (isset($complete_conf['*']['page'])) { $iinfo['page'] = (array)$iinfo['page'] + (array)$complete_conf['*']['page']; }
55 }
56 }
57 else {
58 $iinfo = $complete_conf;
59 }
60
61 if (!isset($iinfo['file'])) { return false; }
62
63 $this->rrd_file = $iinfo['file'];
64
65 // fields (data sources, DS)
66 // name - DS name
67 // type - one of COUNTER, GAUGE, DERIVE, ABSOLUTE
68 // heartbeat - if no sample recieved for that time, store UNKNOWN
69 // min - U (unconstrained) or minimum value
70 // max - U (unconstrained) or maximum value
71 // update - this string will be fed into eval() for updating this field
72 if (isset($iinfo['fields']) && is_array($iinfo['fields'])) {
73 $this->rrd_fields = $iinfo['fields'];
74 }
75 else {
76 $this->rrd_fields[] = array('name' => 'ds0', 'type' => 'COUNTER', 'heartbeat' => 600, 'min' => 'U', 'max' => 'U');
77 $this->rrd_fields[] = array('name' => 'ds1', 'type' => 'COUNTER', 'heartbeat' => 600, 'min' => 'U', 'max' => 'U');
78 }
79
80
81 // MRTG-style RRD "database", see http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/tut/rrdtutorial.en.html
82 //
83 // archives (RRAs):
84 // 600 samples of 5 minutes (2 days and 2 hours)
85 // 700 samples of 30 minutes (2 days and 2 hours, plus 12.5 days)
86 // 775 samples of 2 hours (above + 50 days)
87 // 797 samples of 1 day (above + 732 days, rounded up to 797)
88
89 $this->rrd_step = isset($iinfo['rrd_step'])?$iinfo['rrd_step']:300;
90
91 if (isset($iinfo['rra_base']) && is_array($iinfo['rra_base'])) {
92 $this->rra_base = $iinfo['rra_base'];
93 }
94 else {
95 $this->rra_base[] = array('step' => 1, 'rows' => 600);
96 $this->rra_base[] = array('step' => 6, 'rows' => 700);
97 $this->rra_base[] = array('step' => 24, 'rows' => 775);
98 $this->rra_base[] = array('step' => 288, 'rows' => 797);
99 }
100
101 $this->rra_add_max = isset($iinfo['rra_add_max'])?$iinfo['rra_add_max']:true;
102
103 if (isset($iinfo['graph'])) { $this->config_graph = $iinfo['graph']; }
104 if (isset($iinfo['page'])) { $this->config_page = $iinfo['page']; }
105 $this->config_raw = $iinfo;
106 }
107
108 function create() {
109 // create RRD file
110
111 // compose create command
112 $create_cmd = 'rrdtool create '.$this->rrd_file.' --step '.$this->rrd_step;
113 foreach ($this->rrd_fields as $ds) {
114 if (!isset($ds['type'])) { $ds['type'] = 'COUNTER'; }
115 if (!isset($ds['heartbeat'])) { $ds['heartbeat'] = 2*$this->rrd_step; }
116 if (!isset($ds['min'])) { $ds['min'] = 'U'; }
117 if (!isset($ds['max'])) { $ds['max'] = 'U'; }
118 $create_cmd .= ' DS:'.$ds['name'].':'.$ds['type'].':'.$ds['heartbeat'].':'.$ds['min'].':'.$ds['max'];
119 }
120 foreach ($this->rra_base as $rra) {
121 if (!isset($rra['cf'])) { $rra['cf'] = 'AVERAGE'; }
122 if (!isset($rra['xff'])) { $rra['xff'] = 0.5; }
123 if (!isset($rra['step'])) { $rra['step'] = 1; }
124 if (!isset($rra['rows'])) { $rra['rows'] = 600; }
125 $create_cmd .= ' RRA:'.$rra['cf'].':'.$rra['xff'].':'.$rra['step'].':'.$rra['rows'];
126 }
127 if ($this->rra_add_max) {
128 foreach ($this->rra_base as $rra) {
129 if (!isset($rra['cf'])) {
130 // only rows that have no CF set will be looked at here
131 $rra['cf'] = 'MAX';
132 if (!isset($rra['xff'])) { $rra['xff'] = 0.5; }
133 if (!isset($rra['step'])) { $rra['step'] = 1; }
134 if (!isset($rra['rows'])) { $rra['rows'] = 600; }
135 $create_cmd .= ' RRA:'.$rra['cf'].':'.$rra['xff'].':'.$rra['step'].':'.$rra['rows'];
136 }
137 }
138 }
139 $output = array(); $return_var = null;
140 exec($create_cmd, $output, $return_var);
141 if ($return_var) { trigger_error('rrd create returned with value '.$return_var, E_USER_WARNING); }
142 else { $this->status = 'ok'; }
143 }
144
145 function update($upArray = null) {
146 // feed new data into RRD
147 if ($this->status != 'ok') { trigger_error('Cannot update non-writeable file', E_USER_WARNING); return 1; }
148 $upvals = array();
149 foreach($this->rrd_fields as $ds) {
150 if (is_array($upArray) && isset($upArray[$ds['name']])) { $val = $upArray[$ds['name']]; }
151 elseif (isset($ds['update'])) {
152 $val = null; $evalcode = null;
153 if (substr($ds['update'], 0, 4) == 'val:') {
154 $evalcode = 'print(trim('.substr($ds['update'], 4).'));';
155 }
156 elseif (substr($ds['update'], 0, 8) == 'snmp-if:') {
157 $snmphost = 'localhost'; $snmpcomm = 'public';
158 list($nix, $ifname, $valtype) = explode(':', $ds['update'], 3);
159 $iflist = explode("\n", `snmpwalk -v2c -c $snmpcomm $snmphost interfaces.ifTable.ifEntry.ifDescr`);
160 $ifnr = null;
161 foreach ($iflist as $ifdesc) {
162 if (preg_match('/ifDescr\.(\d+) = STRING: '.$ifname.'/', $ifdesc, $regs)) { $ifnr = $regs[1]; }
163 }
164 $oid = null;
165 if ($valtype == 'in') { $oid = '1.3.6.1.2.1.2.2.1.10.'.$ifnr; }
166 elseif ($valtype == 'out') { $oid = '1.3.6.1.2.1.2.2.1.16.'.$ifnr; }
167 if (!is_null($ifnr) && !is_null($oid)) {
168 $evalcode = 'print(trim(substr(strrchr(`snmpget -v2c -c '.$snmpcomm.' '.$snmphost.' '.$oid.'`,":"),1)));';
169 }
170 }
171 else { $evalcode = $ds['update']; }
172 if (!is_null($evalcode)) {
173 ob_start();
174 eval($evalcode);
175 $val = ob_get_contents();
176 ob_end_clean();
177 }
178 }
179 else { $val = null; }
180 $upvals[] = is_null($val)?'U':$val;
181 }
182 $update_cmd = 'rrdtool update '.$this->rrd_file.' N:'.implode(':', $upvals);
183 $output = array(); $return_var = null;
184 exec($update_cmd, $output, $return_var);
185 if ($return_var) { trigger_error('rrd update returned with value '.$return_var, E_USER_WARNING); }
186 return ($return_var == 0);
187 }
188
189 function fetch($cf = 'AVERAGE', $resolution = null, $start = null, $end = null) {
190 // fetch data from a RRD
191 if (!in_array($this->status, array('ok','readonly'))) { trigger_error('Error: rrd status is '.$this->status, E_USER_WARNING); return false; }
192
193 if (!in_array($cf, array('AVERAGE','MIN','MAX','LAST'))) { $cf = 'AVERAGE'; }
194 if (!is_numeric($resolution)) { $resolution = $this->rrd_step; }
195 if (!is_numeric($end)) { $end = $this->last_update(); }
196 elseif ($end < 0) { $end += $this->last_update(); }
197 $end = intval($end/$resolution)*$resolution;
198 if (!is_numeric($start)) { $start = $end; }
199 elseif ($start < 0) { $start += $end; }
200 $start = intval($start/$resolution)*$resolution;
201
202 $fetch_cmd = 'rrdtool fetch '.$this->rrd_file.' '.$cf.' --resolution '.$resolution.' --start '.$start.' --end '.$end;
203 $return = `$fetch_cmd 2>&1`;
204
205 if (strpos($return, 'ERROR') !== false) {
206 trigger_error('rrd fetch error: '.$return, E_USER_WARNING);
207 $fresult = false;
208 }
209 else {
210 $fresult = array();
211 $rows = explode("\n", $return);
212 $fields = preg_split('/\s+/', array_shift($rows));
213 if (array_shift($fields) == 'timestamp') {
214 $fresult[0] = $fields;
215 foreach ($rows as $row) {
216 if (strlen(trim($row))) {
217 $rvals = preg_split('/\s+/', $row);
218 $rtime = array_shift($rvals);
219 $rv_array = array();
220 foreach ($rvals as $key=>$rval) {
221 $rv_array[$fields[$key]] = ($rval=='nan')?null:floatval($rval);
222 }
223 $fresult[$rtime] = $rv_array;
224 }
225 }
226 }
227 }
228 return $fresult;
229 }
230
231 function graph($timeframe = 'day', $sub = null, $extra = null) {
232 // create a RRD graph
233 static $gColors;
234 if (!isset($gColors)) {
235 $gColors = array('#00CC00','#0000FF','#000000','#FF0000','#00FF00','#FFFF00','#FF00FF','#00FFFF','#808080','#800000','#008000','#000080','#808000','#800080','#008080','#C0C0C0');
236 }
237
238 if (!in_array($this->status, array('ok','readonly'))) { trigger_error('Error: rrd status is '.$this->status, E_USER_WARNING); return false; }
239
240 // assemble configuration
241 $gconf = (array)$extra;
242 if (!is_null($sub) && is_array($this->config_raw['graph.'.$sub])) {
243 $gconf = $gconf + $this->config_raw['graph.'.$sub];
244 }
245 $gconf = $gconf + (array)$this->config_graph;
246
247 if (isset($gconf['format']) && ($gconf['format'] == 'SVG')) {
248 $format = $gconf['format']; $fmt_ext = '.svg';
249 }
250 elseif (isset($gconf['format']) && ($gconf['format'] == 'EPS')) {
251 $format = $gconf['format']; $fmt_ext = '.eps';
252 }
253 elseif (isset($gconf['format']) && ($gconf['format'] == 'PDF')) {
254 $format = $gconf['format']; $fmt_ext = '.pdf';
255 }
256 else {
257 $format = 'PNG'; $fmt_ext = '.png';
258 }
259
260 if (isset($gconf['filename'])) { $fname = $gconf['filename']; }
261 else { $fname = str_replace('.rrd', (is_null($sub)?'':'-%s').'-%t%f', $this->rrd_file); }
262 $fname = str_replace('%s', strval($sub), $fname);
263 $fname = str_replace('%t', $timeframe, $fname);
264 $fname = str_replace('%f', $fmt_ext, $fname);
265 if (substr($fname, -strlen($fmt_ext)) != $fmt_ext) { $fname .= $fmt_ext; }
266 if (isset($gconf['path'])) { $fname = $gconf['path'].'/'.$fname; }
267 $fname = str_replace('//', '/', $fname);
268
269 $graphrows = array(); $gC = 0;
270 $gDefs = ''; $gGraphs = ''; $addSpecial = '';
271
272 if ($timeframe == 'day') {
273 $duration = isset($gconf['duration'])?$gconf['duration']:30*3600; // 30 hours
274 $slice = isset($gconf['slice'])?$gconf['slice']:300; // 5 minutes
275 // vertical lines at day borders
276 $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d')).'#FF0000';
277 $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' -1 day').'#FF0000';
278 if (!isset($gconf['grid_x'])) { $gconf['grid_x'] = 'HOUR:1:HOUR:6:HOUR:2:0:%-H'; }
279 }
280 elseif ($timeframe == 'week') {
281 $duration = isset($gconf['duration'])?$gconf['duration']:8*86400; // 8 days
282 $slice = isset($gconf['slice'])?$gconf['slice']:1800; // 30 minutes
283 // vertical lines at week borders
284 $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' '.(-date('w')+1).' day').'#FF0000';
285 $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' '.(-date('w')-6).' day').'#FF0000';
286 }
287 elseif ($timeframe == 'month') {
288 $duration = isset($gconf['duration'])?$gconf['duration']:36*86400; // 36 days
289 $slice = isset($gconf['slice'])?$gconf['slice']:7200; // 2 hours
290 // vertical lines at month borders
291 $addSpecial .= ' VRULE:'.strtotime(date('Y-m-01')).'#FF0000';
292 $addSpecial .= ' VRULE:'.strtotime(date('Y-m-01').' -1 month').'#FF0000';
293 }
294 elseif ($timeframe == 'year') {
295 $duration = isset($gconf['duration'])?$gconf['duration']:396*86400; // 365+31 days
296 $slice = isset($gconf['slice'])?$gconf['slice']:86400; // 1 day
297 // vertical lines at month borders
298 $addSpecial .= ' VRULE:'.strtotime(date('Y-01-01')).'#FF0000';
299 $addSpecial .= ' VRULE:'.strtotime(date('Y-01-01').' -1 year').'#FF0000';
300 }
301 else {
302 $duration = isset($gconf['duration'])?$gconf['duration']:$this->rrd_step*500; // 500 steps
303 $slice = isset($gconf['slice'])?$gconf['slice']:$this->rrd_step; // whatever our step is
304 }
305
306 if (isset($gconf['rows']) && count($gconf['rows'])) {
307 foreach ($gconf['rows'] as $erow) {
308 if (isset($erow['name']) && strlen($erow['name'])) {
309 if (!isset($erow['scale']) && isset($gconf['scale'])) { $erow['scale'] = $gconf['scale']; }
310 $grow = array();
311 $grow['dType'] = isset($erow['dType'])?$erow['dType']:'DEF';
312 $grow['name'] = $erow['name'].(isset($erow['scale'])?'_tmp':'');
313 if ($grow['dType'] == 'DEF') {
314 $grow['dsname'] = isset($erow['dsname'])?$erow['dsname']:$erow['name'];
315 $grow['cf'] = isset($erow['cf'])?$erow['cf']:'AVERAGE';
316 }
317 else {
318 $grow['rpn_expr'] = isset($erow['rpn_expr'])?$erow['rpn_expr']:'0';
319 }
320 if (isset($erow['scale'])) {
321 $graphrows[] = $grow;
322 $grow = array();
323 $grow['dType'] = 'CDEF';
324 $grow['name'] = $erow['name'];
325 $grow['rpn_expr'] = $erow['name'].'_tmp,'.$erow['scale'].',*';
326 }
327 $grow['gType'] = isset($erow['gType'])?$erow['gType']:'LINE1';
328 $grow['color'] = isset($erow['color'])?$erow['color']:$gColors[$gC++];
329 if ($gC >= count($gColors)) { $gC = 0; }
330 if (isset($erow['legend'])) {
331 $grow['legend'] = $erow['legend'];
332 if (!isset($gconf['show_legend'])) { $gconf['show_legend'] = true; }
333 }
334 if (isset($erow['stack'])) { $grow['stack'] = ($erow['stack'] == true); }
335 $graphrows[] = $grow;
336 }
337 }
338 }
339 else {
340 foreach ($this->rrd_fields as $key=>$ds) {
341 $grow = array();
342 $grow['dType'] = 'DEF';
343 $grow['name'] = $ds['name'].(isset($gconf['scale'])?'_tmp':'');
344 $grow['dsname'] = $ds['name'];
345 $grow['cf'] = 'AVERAGE';
346 if (isset($gconf['scale'])) {
347 $graphrows[] = $grow;
348 $grow = array();
349 $grow['dType'] = 'CDEF';
350 $grow['name'] = $ds['name'];
351 $grow['rpn_expr'] = $ds['name'].'_tmp,'.$gconf['scale'].',*';
352 }
353 $grow['gType'] = ((count($this->rrd_fields)==2) && ($key==0))?'AREA':'LINE1';
354 $grow['color'] = $gColors[$gC++]; if ($gC >= count($gColors)) { $gC = 0; }
355 $graphrows[] = $grow;
356 }
357 }
358
359 if (isset($gconf['special']) && count($gconf['special'])) {
360 foreach ($gconf['special'] as $crow) {
361 $srow = array();
362 $srow['sType'] = isset($crow['sType'])?$crow['sType']:'COMMENT';
363 if ($grow['sType'] != 'COMMENT') {
364 // XXX: use line below and remove cf var once we have rrdtol 1.2
365 // $srow['name'] = $crow['name'].(isset($crow['cf'])?'_'.$crow['cf']:'');
366 $srow['name'] = $crow['name'];
367 $srow['cf'] = isset($crow['cf'])?$crow['cf']:'AVERAGE';
368 if (isset($crow['cf'])) {
369 // XXX: use line below once we have rrdtol 1.2
370 // $graphrows[] = array('dType'=>'VDEF', 'name'=>$srow['name'].'_'.$crow['cf'], 'rpn_expr'=>$srow['name'].','.$crow['cf']);
371 }
372 elseif (isset($crow['rpn_expr'])) {
373 // XXX: does only work with rrdtool 1.2
374 $graphrows[] = array('dType'=>'VDEF', 'name'=>$srow['name'], 'rpn_expr'=>$crow['rpn_expr']);
375 }
376 }
377 $srow['text'] = isset($crow['text'])?$crow['text']:'';
378 $specialrows[] = $srow;
379 }
380 }
381 else {
382 foreach ($graphrows as $grow) {
383 if (isset($grow['gType']) && strlen($grow['gType'])) {
384 $textprefix = isset($grow['legend'])?$grow['legend']:$grow['name'];
385 // XXX: use lines below once we have rrdtol 1.2
386 // $graphrows[] = array('dType'=>'VDEF', 'name'=>$grow['name'].'_last', 'rpn_expr'=>$grow['name'].',LAST');
387 // $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'].'_last', 'text'=>'%3.2lf%s');
388 $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'MAX', 'text'=>$textprefix.'|Maximum|%.2lf%s');
389 $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'AVERAGE', 'text'=>$textprefix.'|Average|%.2lf%s');
390 $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'LAST', 'text'=>$textprefix.'|Current|%.2lf%s');
391 }
392 }
393 }
394
395 $endtime = isset($gconf['time_end'])?$gconf['time_end']:(is_numeric($this->last_update())?$this->last_update():time());
396 $gOpts = ' --start '.($endtime-$duration).' --end '.$endtime.' --step '.$slice;
397 if (isset($gconf['label_top'])) { $gOpts .= ' --title '.$this->text_quote($gconf['label_top']); }
398 if (isset($gconf['label_y'])) { $gOpts .= ' --vertical-label '.$this->text_quote($gconf['label_y']); }
399 if (isset($gconf['width'])) { $gOpts .= ' --width '.$gconf['width']; }
400 if (isset($gconf['height'])) { $gOpts .= ' --height '.$gconf['height'];
401 if (($gconf['height'] <= 32) && isset($gconf['thumb']) && ($gconf['thumb'])) { $gOpts .= ' --only-graph'; }
402 }
403 if (!isset($gconf['show_legend']) || (!$gconf['show_legend'])) { $gOpts .= ' --no-legend'; }
404 if (isset($gconf['min_y'])) { $gOpts .= ' --lower-limit '.$gconf['min_y']; }
405 if (isset($gconf['max_y'])) { $gOpts .= ' --upper-limit '.$gconf['max_y']; }
406 if (isset($gconf['fix_scale_y']) && $gconf['fix_scale_y']) { $gOpts .= ' --rigid'; }
407 if (isset($gconf['grid_x'])) { $gOpts .= ' --x-grid '.$gconf['grid_x']; }
408 if (isset($gconf['grid_y'])) { $gOpts .= ' --y-grid '.$gconf['grid_y']; }
409 if (isset($gconf['units_exponent'])) { $gOpts .= ' --units-exponent '.$gconf['units_exponent']; }
410 if (isset($gconf['units_length'])) { $gOpts .= ' --units-length '.$gconf['units_length']; }
411 if (!isset($gconf['force_recreate']) || (!$gconf['force_recreate'])) { $gOpts .= ' --lazy'; }
412 if (isset($gconf['force_color']) && is_array($gconf['force_color'])) {
413 foreach ($gconf['force_color'] as $ctag=>$cval) { $gOpts .= ' --color '.$ctag.$cval; }
414 }
415 if (isset($gconf['force_font']) && is_array($gconf['force_font'])) {
416 foreach ($gconf['force_font'] as $ctag=>$cval) { $gOpts .= ' --font '.$ctag.$cval; }
417 }
418 if (isset($gconf['units_binary']) && $gconf['units_binary']) { $gOpts .= ' --base 1024'; }
419
420 foreach ($graphrows as $grow) {
421 if (isset($grow['dType']) && strlen($grow['dType'])) {
422 $gDefs .= ' '.$grow['dType'].':'.$grow['name'].'=';
423 $gDefs .= ($grow['dType']=='DEF')?$this->rrd_file.':'.$grow['dsname'].':'.$grow['cf']:$grow['rpn_expr'];
424 }
425 if (isset($grow['gType']) && strlen($grow['gType'])) {
426 // XXX: change from STACK type to STACK flag once we have rrdtool 1.2
427 if (isset($grow['stack']) && $grow['stack']) { $grow['gType'] = 'STACK'; }
428 $gGraphs .= ' '.$grow['gType'].':'.$grow['name'].$grow['color'];
429 if (isset($grow['legend'])) { $gGraphs .= ':'.$this->text_quote($grow['legend']); }
430 // XXX: remove above STACK if-command and uncomment the one below once we have rrdtool 1.2
431 //if (isset($grow['stack']) && $grow['stack']) { $gGraphs .= ':STACK'; }
432 }
433 }
434
435 foreach ($specialrows as $srow) {
436 $addSpecial .= ' '.$srow['sType'];
437 // XXX: eliminate cf once we have rrdtool 1.2
438 // $addSpecial .= ($grow['sType']!='COMMENT')?':'.$grow['name']:'');
439 $addSpecial .= (($srow['sType']!='COMMENT')?':'.$srow['name'].':'.$srow['cf']:'');
440 $addSpecial .= ':'.$this->text_quote($srow['text']);
441 }
442
443 $graph_cmd = 'rrdtool graph '.str_replace('*', '\*', $fname.$gOpts.$gDefs.$gGraphs.$addSpecial);
444 $return = `$graph_cmd 2>&1`;
445
446 if (strpos($return, 'ERROR') !== false) {
447 trigger_error('rrd graph error: '.$return, E_USER_WARNING);
448 $return = $graph_cmd."\n\n".$return;
449 }
450 $return = 'file:'.$fname."\n".$return;
451 return $return;
452 }
453
454 function simple_html($sub = null, $page_extras = null, $graph_extras = null) {
455 // create a simple (MRTG-like) HTML page and return it in a string
456 $basename = str_replace('.rrd', '', $this->rrd_file);
457
458 // assemble configuration
459 $pconf = (array)$page_extras;
460 if (!is_null($sub) && is_array($this->config_raw['page.'.$sub])) {
461 $pconf = $pconf + $this->config_raw['page.'.$sub];
462 }
463 $pconf = $pconf + (array)$this->config_page;
464
465 $ptitle = isset($pconf['title_page'])?$pconf['title_page']:$basename.' - RRD statistics';
466 $gtitle = array();
467 $gtitle['day'] = isset($pconf['title_day'])?$pconf['title_day']:'Day overview (scaling 5 minutes)';
468 $gtitle['week'] = isset($pconf['title_week'])?$pconf['title_week']:'Week overview (scaling 30 minutes)';
469 $gtitle['month'] = isset($pconf['title_month'])?$pconf['title_month']:'Month overview (scaling 2 hours)';
470 $gtitle['year'] = isset($pconf['title_year'])?$pconf['title_year']:'Year overview (scaling 1 day)';
471
472 $out = '<html><head>';
473 $out .= '<title>'.$ptitle.'</title>';
474 $out .= '<style>';
475 if (isset($pconf['style_base'])) { $out .= $pconf['style_base']; }
476 else {
477 $out .= 'h1 { font-weight: bold; font-size: 1.5em; }';
478 $out .= 'h2 { font-weight: bold; font-size: 1em; }';
479 $out .= '.gdata, .gvar, .ginfo { font-size: 0.75em; margin: 0.5em 0; }';
480 $out .= 'table.gdata { border: 1px solid gray; border-collapse: collapse; }';
481 $out .= 'table.gdata td, table.gdata th { border: 1px solid gray; padding: 0.1em 0.2em; }';
482 $out .= '.footer { font-size: 0.75em; margin: 0.5em 0; }';
483 }
484 if (isset($pconf['style'])) { $out .= $pconf['style']; }
485 $out .= '</style>';
486 $out .= '</head>';
487 $out .= '<body>';
488
489 $out .= '<h1>'.$ptitle.'</h1>';
490 if (!isset($pconf['show_update']) || $pconf['show_update']) {
491 $out .= '<p class="last_up">Last Update: '.date('Y-m-d H:i:s', $this->last_update()).'</p>';
492 }
493
494 if (in_array($this->status, array('ok','readonly'))) {
495 $g_sub = isset($pconf['graph_sub'])?$pconf['graph_sub']:null;
496 foreach (array('day','week','month','year') as $tframe) {
497 $ret = $this->graph($tframe, $g_sub, $graph_extras);
498 if (strpos($ret, "\n\n") !== false) { $graph_cmd = substr($ret, 0, strpos($ret, "\n\n")); $ret = substr($ret, strpos($ret, "\n\n")+2); }
499 else { $graph_cmd = null; }
500 $grout = explode("\n",$ret);
501 $gfilename = null;
502 $gmeta = array();
503 foreach ($grout as $gline) {
504 if (preg_match('/^file:(.+)$/', $gline, $regs)) {
505 $gfilename = $regs[1];
506 }
507 elseif (preg_match('/^(\d+)x(\d+)$/', $gline, $regs)) {
508 $gmeta['width'] = $regs[1]; $gmeta['height'] = $regs[2];
509 }
510 elseif (preg_match('/^([^\|]+)\|([^|]+)\|([^\|]*)$/', $gline, $regs)) {
511 $gmeta['data'][$regs[1]][$regs[2]] = $regs[3];
512 }
513 elseif (preg_match('/^([^\|]+)\|([^\|]*)$/', $gline, $regs)) {
514 $gmeta['var'][$regs[1]] = $regs[2];
515 }
516 elseif (strlen(trim($gline))) {
517 $gmeta['info'][] = $gline;
518 }
519 }
520 $out .= '<div class="'.$tframe.'">';
521// $out .= '<p>'.nl2br($ret).'</p>';
522 $out .= '<h2>'.$gtitle[$tframe].'</h2>';
523 $out .= '<img src="'.(!is_null($gfilename)?$gfilename:$basename.(!is_null($g_sub)?'-'.$g_sub:'').'-'.$tframe.'.png').'"';
524 $out .= ' alt="'.$basename.(!is_null($g_sub)?' - '.$g_sub:'').' - '.$tframe.'" class="rrdgraph"';
525 $out .= ' style="width:'.$gmeta['width'].'px;height:'.$gmeta['height'].'px;">';
526 if (isset($gmeta['data']) && count($gmeta['data'])) {
527 $out .= '<table class="gdata">';
528 foreach ($gmeta['data'] as $field=>$gdata) {
529 $out .= '<tr><th>'.$field.'</th>';
530 foreach ($gdata as $gkey=>$gval) {
531 $out .= '<td><span class="gkey">'.$gkey.': </span>'.$gval.'</td>';
532 }
533 $out .= '</tr>';
534 }
535 $out .= '</table>';
536 }
537 if (isset($gmeta['var']) && count($gmeta['var'])) {
538 foreach ($gmeta['var'] as $gkey=>$gval) {
539 $out .= '<p class="gvar"><span class="gkey">'.$gkey.': </span>'.$gval.'</p>';
540 }
541 }
542 if (isset($gmeta['info']) && count($gmeta['info'])) {
543 foreach ($gmeta['info'] as $gval) {
544 $out .= '<p class="ginfo">'.$gval.'</p>';
545 }
546 }
547 }
548 }
549 else {
550 $out .= 'RRD error: status is "'.$this->status.'"';
551 }
552 $out .= '</div>';
553
554 $out .= '<p class="footer">';
555 $out .= 'Statistics created by <a href="http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/">RRDtool</a>';
556 $out .= ' using a library created by <a href="http://www.kairo.at/">KaiRo.at</a>.';
557 $out .= '</p>';
558
559 $out .= '</body></html>';
560 return $out;
561 }
562
563 function last_update() {
564 // fetch time of last update in this RRD file
565 static $last_update;
566 if (!isset($last_update) && in_array($this->status, array('ok','readonly'))) {
567 $last_cmd = 'rrdtool last '.$this->rrd_file;
568 $return = trim(`$last_cmd 2>&1`);
569 $last_update = is_numeric($return)?$return:null;
570 }
571 return isset($last_update)?$last_update:null;
572 }
573
574 function text_quote($text) { return '"'.str_replace('"', '\"', str_replace(':', '\:', $text)).'"'; }
575}
576?>