allow to magically find files if they're named <conf_id>.rrd
[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;
31df2e13 6 var $basename = null;
b7878f4d 7
099bd59f 8 var $config_all = null;
a039a75c 9 var $config_raw = null;
10 var $config_graph = null;
11 var $config_page = null;
12
b7878f4d 13 var $rrd_fields = array();
14 var $rra_base = array();
15 var $rrd_step = 300;
16 var $rra_add_max = true;
17
18 var $status = 'unused';
19
ebe03325 20 function rrdstat($rrdconfig, $conf_id = null) {
b7878f4d 21 // ***** init RRD stat module *****
ebe03325 22 $this->set_def($rrdconfig, $conf_id);
b7878f4d 23
b1776944 24 if (($this->status == 'unused') && !is_null($this->rrd_file)) {
2a386f5a 25 if (!is_writeable($this->rrd_file)) {
26 if (!file_exists($this->rrd_file)) {
86ff8b91 27 if (@touch($this->rrd_file)) { $this->create(); }
2a386f5a 28 else { trigger_error('RRD file can not be created', E_USER_WARNING); }
29 }
30 else {
31 if (is_readable($this->rrd_file)) { $this->status = 'readonly'; }
32 else { trigger_error('RRD file is not readable', E_USER_WARNING); }
33 }
b7878f4d 34 }
35 else {
2a386f5a 36 $this->status = 'ok';
b7878f4d 37 }
38 }
b7878f4d 39 }
40
ebe03325 41 function set_def($rrdconfig, $conf_id = null) {
42 if (is_array($rrdconfig)) {
b7878f4d 43 // we have an array in the format we like to have
ebe03325 44 $complete_conf =& $rrdconfig;
b7878f4d 45 }
46 else {
47 // we have something else (XML data?), try to generate the iinfo aray from it
ebe03325 48 $complete_conf =& $rrdconfig;
49 }
50
51 if (!is_null($conf_id)) {
52 $iinfo = isset($complete_conf[$conf_id])?$complete_conf[$conf_id]:array();
e1727e7f 53 if (isset($complete_conf['*'])) {
54 $iinfo = (array)$iinfo + (array)$complete_conf['*'];
55 if (isset($complete_conf['*']['graph'])) { $iinfo['graph'] = (array)$iinfo['graph'] + (array)$complete_conf['*']['graph']; }
56 if (isset($complete_conf['*']['page'])) { $iinfo['page'] = (array)$iinfo['page'] + (array)$complete_conf['*']['page']; }
57 }
ebe03325 58 }
59 else {
60 $iinfo = $complete_conf;
b7878f4d 61 }
62
b1776944 63 if (isset($iinfo['graph-only']) && $iinfo['graph-only'] && !is_null($conf_id)) {
64 $this->basename = $conf_id;
65 $this->status = 'graphonly';
66 }
099bd59f 67 elseif (isset($iinfo['file'])) {
b1776944 68 $this->rrd_file = $iinfo['file'];
69 $this->basename = (substr($this->rrd_file, -4) == '.rrd')?substr($this->rrd_file, 0, -4):$this->rrd_file;
70 }
abe8eac1 71 elseif (!is_null($conf_id) && file_exists($conf_id.'.rrd')) {
72 $this->rrd_file = $conf_id.'.rrd';
73 $this->basename = $conf_id;
74 }
b7878f4d 75 else {
099bd59f 76 $this->basename = !is_null($conf_id)?$conf_id:'xxx.unknown';
77 }
78
abe8eac1 79 if (!is_null($this->rrd_file)) {
099bd59f 80 // fields (data sources, DS)
81 // name - DS name
82 // type - one of COUNTER, GAUGE, DERIVE, ABSOLUTE
83 // heartbeat - if no sample recieved for that time, store UNKNOWN
84 // min - U (unconstrained) or minimum value
85 // max - U (unconstrained) or maximum value
86 // update - this string will be fed into eval() for updating this field
87 if (isset($iinfo['fields']) && is_array($iinfo['fields'])) {
88 $this->rrd_fields = $iinfo['fields'];
89 }
90 else {
91 $this->rrd_fields[] = array('name' => 'ds0', 'type' => 'COUNTER', 'heartbeat' => 600, 'min' => 'U', 'max' => 'U');
92 $this->rrd_fields[] = array('name' => 'ds1', 'type' => 'COUNTER', 'heartbeat' => 600, 'min' => 'U', 'max' => 'U');
93 }
b7878f4d 94
95
099bd59f 96 // MRTG-style RRD "database", see http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/tut/rrdtutorial.en.html
97 //
98 // archives (RRAs):
99 // 600 samples of 5 minutes (2 days and 2 hours)
100 // 700 samples of 30 minutes (2 days and 2 hours, plus 12.5 days)
101 // 775 samples of 2 hours (above + 50 days)
102 // 797 samples of 1 day (above + 732 days, rounded up to 797)
b7878f4d 103
099bd59f 104 $this->rrd_step = isset($iinfo['rrd_step'])?$iinfo['rrd_step']:300;
b7878f4d 105
099bd59f 106 if (isset($iinfo['rra_base']) && is_array($iinfo['rra_base'])) {
107 $this->rra_base = $iinfo['rra_base'];
108 }
109 else {
110 $this->rra_base[] = array('step' => 1, 'rows' => 600);
111 $this->rra_base[] = array('step' => 6, 'rows' => 700);
112 $this->rra_base[] = array('step' => 24, 'rows' => 775);
113 $this->rra_base[] = array('step' => 288, 'rows' => 797);
114 }
b7878f4d 115
099bd59f 116 $this->rra_add_max = isset($iinfo['rra_add_max'])?$iinfo['rra_add_max']:true;
117 }
a039a75c 118
119 if (isset($iinfo['graph'])) { $this->config_graph = $iinfo['graph']; }
120 if (isset($iinfo['page'])) { $this->config_page = $iinfo['page']; }
121 $this->config_raw = $iinfo;
099bd59f 122 $this->config_all = $complete_conf;
b7878f4d 123 }
124
125 function create() {
126 // create RRD file
127
128 // compose create command
129 $create_cmd = 'rrdtool create '.$this->rrd_file.' --step '.$this->rrd_step;
130 foreach ($this->rrd_fields as $ds) {
131 if (!isset($ds['type'])) { $ds['type'] = 'COUNTER'; }
132 if (!isset($ds['heartbeat'])) { $ds['heartbeat'] = 2*$this->rrd_step; }
133 if (!isset($ds['min'])) { $ds['min'] = 'U'; }
134 if (!isset($ds['max'])) { $ds['max'] = 'U'; }
135 $create_cmd .= ' DS:'.$ds['name'].':'.$ds['type'].':'.$ds['heartbeat'].':'.$ds['min'].':'.$ds['max'];
136 }
137 foreach ($this->rra_base as $rra) {
138 if (!isset($rra['cf'])) { $rra['cf'] = 'AVERAGE'; }
139 if (!isset($rra['xff'])) { $rra['xff'] = 0.5; }
140 if (!isset($rra['step'])) { $rra['step'] = 1; }
141 if (!isset($rra['rows'])) { $rra['rows'] = 600; }
142 $create_cmd .= ' RRA:'.$rra['cf'].':'.$rra['xff'].':'.$rra['step'].':'.$rra['rows'];
143 }
144 if ($this->rra_add_max) {
145 foreach ($this->rra_base as $rra) {
146 if (!isset($rra['cf'])) {
147 // only rows that have no CF set will be looked at here
148 $rra['cf'] = 'MAX';
149 if (!isset($rra['xff'])) { $rra['xff'] = 0.5; }
150 if (!isset($rra['step'])) { $rra['step'] = 1; }
151 if (!isset($rra['rows'])) { $rra['rows'] = 600; }
152 $create_cmd .= ' RRA:'.$rra['cf'].':'.$rra['xff'].':'.$rra['step'].':'.$rra['rows'];
153 }
154 }
155 }
b61757c1 156 $return = `$create_cmd 2>&1`;
157 if (strpos($return, 'ERROR') !== false) {
158 trigger_error($this->rrd_file.' - rrd create error: '.$return, E_USER_WARNING);
159 }
b7878f4d 160 else { $this->status = 'ok'; }
161 }
162
163 function update($upArray = null) {
164 // feed new data into RRD
165 if ($this->status != 'ok') { trigger_error('Cannot update non-writeable file', E_USER_WARNING); return 1; }
166 $upvals = array();
de093632 167 if (isset($this->config_raw['update'])) {
168 $evalcode = $this->config_raw['update'];
169 if (!is_null($evalcode)) {
170 ob_start();
171 eval($evalcode);
25b93a4d 172 $ret = ob_get_contents();
173 if (strlen($ret)) { $upvals = explode("\n", $ret); }
de093632 174 ob_end_clean();
175 }
099bd59f 176 $walkfunc = create_function('&$val,$key', '$val = is_numeric(trim($val))?trim($val):"U";');
68424dd3 177 array_walk($upvals, $walkfunc);
de093632 178 }
179 else {
180 foreach ($this->rrd_fields as $ds) {
181 if (is_array($upArray) && isset($upArray[$ds['name']])) { $val = $upArray[$ds['name']]; }
182 elseif (isset($ds['update'])) {
183 $val = null; $evalcode = null;
184 if (substr($ds['update'], 0, 4) == 'val:') {
185 $evalcode = 'print(trim('.substr($ds['update'], 4).'));';
c5db3bd5 186 }
de093632 187 elseif (substr($ds['update'], 0, 8) == 'snmp-if:') {
188 $snmphost = 'localhost'; $snmpcomm = 'public';
189 list($nix, $ifname, $valtype) = explode(':', $ds['update'], 3);
190 $iflist = explode("\n", `snmpwalk -v2c -c $snmpcomm $snmphost interfaces.ifTable.ifEntry.ifDescr`);
191 $ifnr = null;
192 foreach ($iflist as $ifdesc) {
193 if (preg_match('/ifDescr\.(\d+) = STRING: '.$ifname.'/', $ifdesc, $regs)) { $ifnr = $regs[1]; }
194 }
195 $oid = null;
196 if ($valtype == 'in') { $oid = '1.3.6.1.2.1.2.2.1.10.'.$ifnr; }
197 elseif ($valtype == 'out') { $oid = '1.3.6.1.2.1.2.2.1.16.'.$ifnr; }
198 if (!is_null($ifnr) && !is_null($oid)) {
199 $evalcode = 'print(trim(substr(strrchr(`snmpget -v2c -c '.$snmpcomm.' '.$snmphost.' '.$oid.'`,":"),1)));';
200 }
201 }
202 else { $evalcode = $ds['update']; }
203 if (!is_null($evalcode)) {
204 ob_start();
205 eval($evalcode);
206 $val = ob_get_contents();
207 ob_end_clean();
c5db3bd5 208 }
209 }
de093632 210 else { $val = null; }
211 $upvals[] = is_null($val)?'U':$val;
c5db3bd5 212 }
b7878f4d 213 }
25b93a4d 214 $return = null;
215 if (count($upvals)) {
216 $update_cmd = 'rrdtool update '.$this->rrd_file.' N:'.implode(':', $upvals);
217 $return = `$update_cmd 2>&1`;
218 }
b61757c1 219
220 if (strpos($return, 'ERROR') !== false) {
221 trigger_error($this->rrd_file.' - rrd update error: '.$return, E_USER_WARNING);
222 $success = false;
223 }
224 else { $success = true; }
b7878f4d 225 return ($return_var == 0);
226 }
227
a039a75c 228 function fetch($cf = 'AVERAGE', $resolution = null, $start = null, $end = null) {
229 // fetch data from a RRD
230 if (!in_array($this->status, array('ok','readonly'))) { trigger_error('Error: rrd status is '.$this->status, E_USER_WARNING); return false; }
231
232 if (!in_array($cf, array('AVERAGE','MIN','MAX','LAST'))) { $cf = 'AVERAGE'; }
233 if (!is_numeric($resolution)) { $resolution = $this->rrd_step; }
234 if (!is_numeric($end)) { $end = $this->last_update(); }
235 elseif ($end < 0) { $end += $this->last_update(); }
236 $end = intval($end/$resolution)*$resolution;
237 if (!is_numeric($start)) { $start = $end; }
238 elseif ($start < 0) { $start += $end; }
239 $start = intval($start/$resolution)*$resolution;
240
241 $fetch_cmd = 'rrdtool fetch '.$this->rrd_file.' '.$cf.' --resolution '.$resolution.' --start '.$start.' --end '.$end;
242 $return = `$fetch_cmd 2>&1`;
243
244 if (strpos($return, 'ERROR') !== false) {
b61757c1 245 trigger_error($this->rrd_file.' - rrd fetch error: '.$return, E_USER_WARNING);
a039a75c 246 $fresult = false;
247 }
248 else {
249 $fresult = array();
250 $rows = explode("\n", $return);
251 $fields = preg_split('/\s+/', array_shift($rows));
252 if (array_shift($fields) == 'timestamp') {
253 $fresult[0] = $fields;
254 foreach ($rows as $row) {
255 if (strlen(trim($row))) {
256 $rvals = preg_split('/\s+/', $row);
257 $rtime = array_shift($rvals);
258 $rv_array = array();
259 foreach ($rvals as $key=>$rval) {
260 $rv_array[$fields[$key]] = ($rval=='nan')?null:floatval($rval);
261 }
262 $fresult[$rtime] = $rv_array;
263 }
264 }
265 }
266 }
267 return $fresult;
268 }
b7878f4d 269
f5e899df 270 function last_update() {
271 // fetch time of last update in this RRD file
272 static $last_update;
273 if (!isset($last_update) && in_array($this->status, array('ok','readonly'))) {
274 $last_cmd = 'rrdtool last '.$this->rrd_file;
275 $return = trim(`$last_cmd 2>&1`);
276 $last_update = is_numeric($return)?$return:null;
277 }
278 return isset($last_update)?$last_update:null;
279 }
280
2c30ff69 281 function graph($timeframe = 'day', $sub = null, $extra = null) {
a039a75c 282 // create a RRD graph
283 static $gColors;
b7878f4d 284 if (!isset($gColors)) {
285 $gColors = array('#00CC00','#0000FF','#000000','#FF0000','#00FF00','#FFFF00','#FF00FF','#00FFFF','#808080','#800000','#008000','#000080','#808000','#800080','#008080','#C0C0C0');
286 }
287
b1776944 288 if (!in_array($this->status, array('ok','readonly','graphonly'))) { trigger_error('Error: rrd status is '.$this->status, E_USER_WARNING); return false; }
a039a75c 289
290 // assemble configuration
e1727e7f 291 $gconf = (array)$extra;
2c30ff69 292 if (!is_null($sub) && is_array($this->config_raw['graph.'.$sub])) {
e1727e7f 293 $gconf = $gconf + $this->config_raw['graph.'.$sub];
a039a75c 294 }
e1727e7f 295 $gconf = $gconf + (array)$this->config_graph;
a039a75c 296
297 if (isset($gconf['format']) && ($gconf['format'] == 'SVG')) {
298 $format = $gconf['format']; $fmt_ext = '.svg';
299 }
300 elseif (isset($gconf['format']) && ($gconf['format'] == 'EPS')) {
301 $format = $gconf['format']; $fmt_ext = '.eps';
302 }
303 elseif (isset($gconf['format']) && ($gconf['format'] == 'PDF')) {
304 $format = $gconf['format']; $fmt_ext = '.pdf';
305 }
306 else {
307 $format = 'PNG'; $fmt_ext = '.png';
308 }
309
310 if (isset($gconf['filename'])) { $fname = $gconf['filename']; }
31df2e13 311 else { $fname = $this->basename.(is_null($sub)?'':'-%s').'-%t%f'; }
2c30ff69 312 $fname = str_replace('%s', strval($sub), $fname);
a039a75c 313 $fname = str_replace('%t', $timeframe, $fname);
314 $fname = str_replace('%f', $fmt_ext, $fname);
315 if (substr($fname, -strlen($fmt_ext)) != $fmt_ext) { $fname .= $fmt_ext; }
ebe03325 316 if (isset($gconf['path'])) { $fname = $gconf['path'].'/'.$fname; }
317 $fname = str_replace('//', '/', $fname);
b7878f4d 318
abe8eac1 319 $graphrows = array(); $specialrows = array(); $gC = 0;
4ba56977 320 $gDefs = ''; $gGraphs = ''; $addSpecial = '';
321
322 if ($timeframe == 'day') {
a039a75c 323 $duration = isset($gconf['duration'])?$gconf['duration']:30*3600; // 30 hours
324 $slice = isset($gconf['slice'])?$gconf['slice']:300; // 5 minutes
4ba56977 325 // vertical lines at day borders
326 $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d')).'#FF0000';
327 $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' -1 day').'#FF0000';
a039a75c 328 if (!isset($gconf['grid_x'])) { $gconf['grid_x'] = 'HOUR:1:HOUR:6:HOUR:2:0:%-H'; }
4ba56977 329 }
330 elseif ($timeframe == 'week') {
a039a75c 331 $duration = isset($gconf['duration'])?$gconf['duration']:8*86400; // 8 days
332 $slice = isset($gconf['slice'])?$gconf['slice']:1800; // 30 minutes
4ba56977 333 // vertical lines at week borders
334 $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' '.(-date('w')+1).' day').'#FF0000';
335 $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' '.(-date('w')-6).' day').'#FF0000';
336 }
337 elseif ($timeframe == 'month') {
a039a75c 338 $duration = isset($gconf['duration'])?$gconf['duration']:36*86400; // 36 days
339 $slice = isset($gconf['slice'])?$gconf['slice']:7200; // 2 hours
4ba56977 340 // vertical lines at month borders
341 $addSpecial .= ' VRULE:'.strtotime(date('Y-m-01')).'#FF0000';
342 $addSpecial .= ' VRULE:'.strtotime(date('Y-m-01').' -1 month').'#FF0000';
343 }
344 elseif ($timeframe == 'year') {
a039a75c 345 $duration = isset($gconf['duration'])?$gconf['duration']:396*86400; // 365+31 days
346 $slice = isset($gconf['slice'])?$gconf['slice']:86400; // 1 day
4ba56977 347 // vertical lines at month borders
dfe923be 348 $addSpecial .= ' VRULE:'.strtotime(date('Y-01-01 12:00:00')).'#FF0000';
349 $addSpecial .= ' VRULE:'.strtotime(date('Y-01-01 12:00:00').' -1 year').'#FF0000';
4ba56977 350 }
351 else {
a039a75c 352 $duration = isset($gconf['duration'])?$gconf['duration']:$this->rrd_step*500; // 500 steps
353 $slice = isset($gconf['slice'])?$gconf['slice']:$this->rrd_step; // whatever our step is
4ba56977 354 }
355
a039a75c 356 if (isset($gconf['rows']) && count($gconf['rows'])) {
357 foreach ($gconf['rows'] as $erow) {
b7878f4d 358 if (isset($erow['name']) && strlen($erow['name'])) {
a039a75c 359 if (!isset($erow['scale']) && isset($gconf['scale'])) { $erow['scale'] = $gconf['scale']; }
b7878f4d 360 $grow = array();
361 $grow['dType'] = isset($erow['dType'])?$erow['dType']:'DEF';
5f42eda6 362 $grow['name'] = $erow['name'].(isset($erow['scale'])?'_tmp':'');
16cc643c 363 if ($grow['dType'] == 'DEF') {
364 $grow['dsname'] = isset($erow['dsname'])?$erow['dsname']:$erow['name'];
b1776944 365 if (isset($erow['dsfile'])) { $grow['dsfile'] = $erow['dsfile']; }
16cc643c 366 $grow['cf'] = isset($erow['cf'])?$erow['cf']:'AVERAGE';
367 }
368 else {
369 $grow['rpn_expr'] = isset($erow['rpn_expr'])?$erow['rpn_expr']:'0';
370 }
5f42eda6 371 if (isset($erow['scale'])) {
372 $graphrows[] = $grow;
373 $grow = array();
374 $grow['dType'] = 'CDEF';
375 $grow['name'] = $erow['name'];
376 $grow['rpn_expr'] = $erow['name'].'_tmp,'.$erow['scale'].',*';
377 }
b7878f4d 378 $grow['gType'] = isset($erow['gType'])?$erow['gType']:'LINE1';
379 $grow['color'] = isset($erow['color'])?$erow['color']:$gColors[$gC++];
380 if ($gC >= count($gColors)) { $gC = 0; }
4ba56977 381 if (isset($erow['legend'])) {
382 $grow['legend'] = $erow['legend'];
a039a75c 383 if (!isset($gconf['show_legend'])) { $gconf['show_legend'] = true; }
4ba56977 384 }
b7878f4d 385 if (isset($erow['stack'])) { $grow['stack'] = ($erow['stack'] == true); }
fe34d2fe 386 if (isset($erow['desc'])) { $grow['desc'] = $erow['desc']; }
b7878f4d 387 $graphrows[] = $grow;
388 }
389 }
390 }
391 else {
e920ca68 392 foreach ($this->rrd_fields as $key=>$ds) {
b7878f4d 393 $grow = array();
394 $grow['dType'] = 'DEF';
a039a75c 395 $grow['name'] = $ds['name'].(isset($gconf['scale'])?'_tmp':'');
b7878f4d 396 $grow['dsname'] = $ds['name'];
397 $grow['cf'] = 'AVERAGE';
a039a75c 398 if (isset($gconf['scale'])) {
5f42eda6 399 $graphrows[] = $grow;
400 $grow = array();
401 $grow['dType'] = 'CDEF';
402 $grow['name'] = $ds['name'];
a039a75c 403 $grow['rpn_expr'] = $ds['name'].'_tmp,'.$gconf['scale'].',*';
5f42eda6 404 }
e920ca68 405 $grow['gType'] = ((count($this->rrd_fields)==2) && ($key==0))?'AREA':'LINE1';
b7878f4d 406 $grow['color'] = $gColors[$gC++]; if ($gC >= count($gColors)) { $gC = 0; }
75124b94 407 if (isset($ds['legend'])) {
408 $grow['legend'] = $ds['legend'];
409 if (!isset($gconf['show_legend'])) { $gconf['show_legend'] = true; }
410 }
b7878f4d 411 $graphrows[] = $grow;
412 }
413 }
414
16cc643c 415 if (isset($gconf['special']) && count($gconf['special'])) {
416 foreach ($gconf['special'] as $crow) {
417 $srow = array();
418 $srow['sType'] = isset($crow['sType'])?$crow['sType']:'COMMENT';
419 if ($grow['sType'] != 'COMMENT') {
420 // XXX: use line below and remove cf var once we have rrdtol 1.2
421 // $srow['name'] = $crow['name'].(isset($crow['cf'])?'_'.$crow['cf']:'');
422 $srow['name'] = $crow['name'];
423 $srow['cf'] = isset($crow['cf'])?$crow['cf']:'AVERAGE';
424 if (isset($crow['cf'])) {
425 // XXX: use line below once we have rrdtol 1.2
426 // $graphrows[] = array('dType'=>'VDEF', 'name'=>$srow['name'].'_'.$crow['cf'], 'rpn_expr'=>$srow['name'].','.$crow['cf']);
427 }
428 elseif (isset($crow['rpn_expr'])) {
429 // XXX: does only work with rrdtool 1.2
430 $graphrows[] = array('dType'=>'VDEF', 'name'=>$srow['name'], 'rpn_expr'=>$crow['rpn_expr']);
431 }
432 }
433 $srow['text'] = isset($crow['text'])?$crow['text']:'';
434 $specialrows[] = $srow;
435 }
436 }
437 else {
438 foreach ($graphrows as $grow) {
439 if (isset($grow['gType']) && strlen($grow['gType'])) {
fe34d2fe 440 $textprefix = isset($grow['desc'])?$grow['desc']:(isset($grow['legend'])?$grow['legend']:$grow['name']);
16cc643c 441 // XXX: use lines below once we have rrdtol 1.2
442 // $graphrows[] = array('dType'=>'VDEF', 'name'=>$grow['name'].'_last', 'rpn_expr'=>$grow['name'].',LAST');
443 // $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'].'_last', 'text'=>'%3.2lf%s');
444 $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'MAX', 'text'=>$textprefix.'|Maximum|%.2lf%s');
445 $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'AVERAGE', 'text'=>$textprefix.'|Average|%.2lf%s');
446 $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'LAST', 'text'=>$textprefix.'|Current|%.2lf%s');
447 }
448 }
449 }
450
a039a75c 451 $endtime = isset($gconf['time_end'])?$gconf['time_end']:(is_numeric($this->last_update())?$this->last_update():time());
452 $gOpts = ' --start '.($endtime-$duration).' --end '.$endtime.' --step '.$slice;
453 if (isset($gconf['label_top'])) { $gOpts .= ' --title '.$this->text_quote($gconf['label_top']); }
454 if (isset($gconf['label_y'])) { $gOpts .= ' --vertical-label '.$this->text_quote($gconf['label_y']); }
455 if (isset($gconf['width'])) { $gOpts .= ' --width '.$gconf['width']; }
456 if (isset($gconf['height'])) { $gOpts .= ' --height '.$gconf['height'];
457 if (($gconf['height'] <= 32) && isset($gconf['thumb']) && ($gconf['thumb'])) { $gOpts .= ' --only-graph'; }
4ba56977 458 }
a039a75c 459 if (!isset($gconf['show_legend']) || (!$gconf['show_legend'])) { $gOpts .= ' --no-legend'; }
460 if (isset($gconf['min_y'])) { $gOpts .= ' --lower-limit '.$gconf['min_y']; }
461 if (isset($gconf['max_y'])) { $gOpts .= ' --upper-limit '.$gconf['max_y']; }
462 if (isset($gconf['fix_scale_y']) && $gconf['fix_scale_y']) { $gOpts .= ' --rigid'; }
463 if (isset($gconf['grid_x'])) { $gOpts .= ' --x-grid '.$gconf['grid_x']; }
464 if (isset($gconf['grid_y'])) { $gOpts .= ' --y-grid '.$gconf['grid_y']; }
465 if (isset($gconf['units_exponent'])) { $gOpts .= ' --units-exponent '.$gconf['units_exponent']; }
466 if (isset($gconf['units_length'])) { $gOpts .= ' --units-length '.$gconf['units_length']; }
467 if (!isset($gconf['force_recreate']) || (!$gconf['force_recreate'])) { $gOpts .= ' --lazy'; }
468 if (isset($gconf['force_color']) && is_array($gconf['force_color'])) {
469 foreach ($gconf['force_color'] as $ctag=>$cval) { $gOpts .= ' --color '.$ctag.$cval; }
4ba56977 470 }
a039a75c 471 if (isset($gconf['force_font']) && is_array($gconf['force_font'])) {
472 foreach ($gconf['force_font'] as $ctag=>$cval) { $gOpts .= ' --font '.$ctag.$cval; }
4ba56977 473 }
a039a75c 474 if (isset($gconf['units_binary']) && $gconf['units_binary']) { $gOpts .= ' --base 1024'; }
4ba56977 475
b7878f4d 476 foreach ($graphrows as $grow) {
4ba56977 477 if (isset($grow['dType']) && strlen($grow['dType'])) {
478 $gDefs .= ' '.$grow['dType'].':'.$grow['name'].'=';
b1776944 479 if ($grow['dType'] == 'DEF') {
480 $gDefs .= isset($grow['dsfile'])?$grow['dsfile']:$this->rrd_file;
481 $gDefs .= ':'.$grow['dsname'].':'.$grow['cf'];
482 }
483 else { $gDefs .= $grow['rpn_expr']; }
4ba56977 484 }
485 if (isset($grow['gType']) && strlen($grow['gType'])) {
16cc643c 486 // XXX: change from STACK type to STACK flag once we have rrdtool 1.2
4ba56977 487 if (isset($grow['stack']) && $grow['stack']) { $grow['gType'] = 'STACK'; }
488 $gGraphs .= ' '.$grow['gType'].':'.$grow['name'].$grow['color'];
489 if (isset($grow['legend'])) { $gGraphs .= ':'.$this->text_quote($grow['legend']); }
16cc643c 490 // XXX: remove above STACK if-command and uncomment the one below once we have rrdtool 1.2
4ba56977 491 //if (isset($grow['stack']) && $grow['stack']) { $gGraphs .= ':STACK'; }
492 }
b7878f4d 493 }
494
16cc643c 495 foreach ($specialrows as $srow) {
496 $addSpecial .= ' '.$srow['sType'];
497 // XXX: eliminate cf once we have rrdtool 1.2
498 // $addSpecial .= ($grow['sType']!='COMMENT')?':'.$grow['name']:'');
499 $addSpecial .= (($srow['sType']!='COMMENT')?':'.$srow['name'].':'.$srow['cf']:'');
500 $addSpecial .= ':'.$this->text_quote($srow['text']);
501 }
502
5f42eda6 503 $graph_cmd = 'rrdtool graph '.str_replace('*', '\*', $fname.$gOpts.$gDefs.$gGraphs.$addSpecial);
b7878f4d 504 $return = `$graph_cmd 2>&1`;
505
b7878f4d 506 if (strpos($return, 'ERROR') !== false) {
b61757c1 507 trigger_error($this->rrd_file.' - rrd graph error: '.$return, E_USER_WARNING);
16cc643c 508 $return = $graph_cmd."\n\n".$return;
b7878f4d 509 }
ebe03325 510 $return = 'file:'.$fname."\n".$return;
a039a75c 511 return $return;
b7878f4d 512 }
513
f5e899df 514 function graph_plus($timeframe = 'day', $sub = null, $extra = null) {
515 // create a RRD graph and return meta info as a ready-to-use array
516 $gmeta = array('filename'=>null);
517 $ret = $this->graph($timeframe, $sub, $extra);
518 if (strpos($ret, "\n\n") !== false) { $gmeta['graph_cmd'] = substr($ret, 0, strpos($ret, "\n\n")); $ret = substr($ret, strpos($ret, "\n\n")+2); }
519 else { $gmeta['graph_cmd'] = null; }
520 $grout = explode("\n", $ret);
521 foreach ($grout as $gline) {
522 if (preg_match('/^file:(.+)$/', $gline, $regs)) {
523 $gmeta['filename'] = $regs[1];
524 }
525 elseif (preg_match('/^(\d+)x(\d+)$/', $gline, $regs)) {
526 $gmeta['width'] = $regs[1]; $gmeta['height'] = $regs[2];
527 }
528 elseif (preg_match('/^([^\|]+)\|([^|]+)\|([^\|]*)$/', $gline, $regs)) {
529 $gmeta['data'][$regs[1]][$regs[2]] = $regs[3];
530 }
531 elseif (preg_match('/^([^\|]+)\|([^\|]*)$/', $gline, $regs)) {
532 $gmeta['var'][$regs[1]] = $regs[2];
533 }
534 elseif (strlen(trim($gline))) {
535 $gmeta['info'][] = $gline;
536 }
537 }
538 if (is_null($gmeta['filename'])) {
539 $gmeta['filename'] = $this->basename.(!is_null($sub)?'-'.$sub:'').'-'.$timeframe.'.png';
540 }
541 return $gmeta;
542 }
543
099bd59f 544 function page($sub = null, $page_extras = null, $graph_extras = null) {
545 // create a (HTML) page and return it in a string
546
547 // assemble configuration
548 $pconf = (array)$page_extras;
549 if (!is_null($sub) && is_array($this->config_raw['page.'.$sub])) {
550 $pconf = $pconf + $this->config_raw['page.'.$sub];
551 }
552 $pconf = $pconf + (array)$this->config_page;
553
554 $return = null;
555 switch ($pconf['type']) {
556 case 'index':
557 $return = $this->page_index($pconf);
558 break;
559 case 'overview':
560 $return = $this->page_overview($pconf, $graph_extras);
561 break;
562 case 'simple':
563 default:
564 $return = $this->page_simple($pconf, $graph_extras);
565 break;
566 }
567 return $return;
568 }
569
2c30ff69 570 function simple_html($sub = null, $page_extras = null, $graph_extras = null) {
b7878f4d 571 // create a simple (MRTG-like) HTML page and return it in a string
099bd59f 572 // XXX: this is here temporarily for compat only, it's preferred to use page()!
a039a75c 573
574 // assemble configuration
e1727e7f 575 $pconf = (array)$page_extras;
2c30ff69 576 if (!is_null($sub) && is_array($this->config_raw['page.'.$sub])) {
e1727e7f 577 $pconf = $pconf + $this->config_raw['page.'.$sub];
a039a75c 578 }
e1727e7f 579 $pconf = $pconf + (array)$this->config_page;
a039a75c 580
099bd59f 581 return $this->page_simple($pconf, $graph_extras);
582 }
583
584 function page_index($pconf) {
585 // create a bare, very simple index list HTML page and return it in a string
586
f5e899df 587 $ptitle = isset($pconf['title_page'])?$pconf['title_page']:'RRD statistics index';
099bd59f 588
589 $out = '<html><head>';
590 $out .= '<title>'.$ptitle.'</title>';
591 $out .= '<style>';
592 if (isset($pconf['style_base'])) { $out .= $pconf['style_base']; }
593 else {
594 $out .= 'h1 { font-weight: bold; font-size: 1.5em; }';
595 $out .= '.footer { font-size: 0.75em; margin: 0.5em 0; }';
596 $out .= 'li.scanfile { font-style: italic; }';
597 }
598 if (isset($pconf['style'])) { $out .= $pconf['style']; }
599 $out .= '</style>';
600 $out .= '</head>';
601 $out .= '<body>';
602
603 $out .= '<h1>'.$ptitle.'</h1>';
f5e899df 604 if (isset($pconf['text_intro']) && strlen($pconf['text_intro'])) {
605 $out .= '<p class="intro">'.$pconf['text_intro'].'</p>';
099bd59f 606 }
f5e899df 607 elseif (!isset($pconf['text_intro'])) {
608 $out .= '<p class="intro">The following RRD stats are available:</p>';
099bd59f 609 }
f5e899df 610
611 $stats = $this->h_page_statsArray($pconf);
612
613 $out .= '<ul class="indexlist">';
099bd59f 614 foreach ($stats as $stat) {
615 $out .= '<li'.(isset($stat['class'])?' class="'.$stat['class'].'"':'').'>';
616 $surl = '?stat='.$stat['name'];
617 $out .= '<a href="'.$surl.'">'.$stat['name'].'</a>';
618 if (isset($stat['sub']) && count($stat['sub'])) {
619 $sprt = array();
620 foreach ($stat['sub'] as $ssub) { $sprt[] = '<a href="'.$surl.'&sub='.$ssub.'">'.$ssub.'</a>'; }
621 $out .= ' <span="subs">('.implode(', ', $sprt).')</span>';
622 }
623 $out .= '</li>';
624 }
625 $out .= '</ul>';
626
f5e899df 627 $out .= $this->h_page_footer();
099bd59f 628 $out .= '</body></html>';
099bd59f 629 return $out;
630 }
631
632 function page_overview($pconf, $graph_extras = null) {
633 // create an overview HTML page (including graphs) and return it in a string
634
f5e899df 635 $ptitle = isset($pconf['title_page'])?$pconf['title_page']:'RRD statistics overview';
636
637 $out = '<html><head>';
638 $out .= '<title>'.$ptitle.'</title>';
639 $out .= '<style>';
640 if (isset($pconf['style_base'])) { $out .= $pconf['style_base']; }
641 else {
642 $out .= 'h1 { font-weight: bold; font-size: 1.5em; }';
643 $out .= 'h2 { font-weight: bold; font-size: 1em; margin: 0.5em 0; }';
644 $out .= '.footer { font-size: 0.75em; margin: 0.5em 0; }';
645 $out .= 'img.rrdgraph { border: none; }';
646 }
647 if (isset($pconf['style'])) { $out .= $pconf['style']; }
648 $out .= '</style>';
649 $out .= '</head>';
650 $out .= '<body>';
651
652 $out .= '<h1>'.$ptitle.'</h1>';
653 if (isset($pconf['text_intro'])) { $out .= '<p class="intro">'.$pconf['text_intro'].'</p>'; }
654
655 $stats = $this->h_page_statsArray($pconf);
656
657 $num_rows = is_numeric($pconf['num_rows'])?$pconf['num_rows']:2;
658 $num_cols = ceil(count($stats)/$num_rows);
659
660 $out .= '<table class="overview">';
661 for ($col = 0; $col < $num_cols; $col++) {
662 $out .= '<tr>';
663 for ($row = 0; $row < $num_rows; $row++) {
664 $idx = $col * $num_rows + $row;
665 $out .= '<td>';
666 if ($idx < count($stats)) {
667 list($sname, $s_psub) = explode('|', $stats[$idx]['name'], 2);
668 $s_psname = 'page'.(isset($s_psub)?'.'.$s_psub:'');
669 $g_sub = $this->config_all[$sname][$s_psname]['graph_sub'];
670
671 if (isset($this->config_all[$sname][$s_psname]['title_page'])) {
672 $s_ptitle = $this->config_all[$sname][$s_psname]['title_page'];
673 }
674 elseif (isset($this->config_all[$sname]['page']['title_page'])) {
675 $s_ptitle = $this->config_all[$sname]['page']['title_page'];
676 }
677 else {
678 $s_ptitle = $sname.(isset($s_psub)?' ('.$s_psub.')':'').' statistics';
679 }
680 if (!isset($pconf['hide_titles']) || !$pconf['hide_titles']) {
681 $out .= '<h2>'.$s_ptitle.'</h2>';
682 }
683
684 $s_rrd = new rrdstat($this->config_all, $sname);
685 if (in_array($s_rrd->status, array('ok','readonly','graphonly'))) {
686 $tframe = isset($pconf['graph_timeframe'])?$pconf['graph_timeframe']:'day';
687 $gmeta = $s_rrd->graph_plus($tframe, $g_sub);
688 if (isset($pconf['graph_url'])) {
689 $gURL = $pconf['graph_url'];
690 $fname = str_replace('%f', basename($gmeta['filename']), $gURL);
691 $fname = str_replace('%p', $gmeta['filename'], $gURL);
692 if (substr($gURL, -1) == '/') { $gURL .= $gmeta['filename']; }
693 }
694 else {
695 $gURL = $gmeta['filename'];
696 }
697 $out .= '<a href="?stat='.$sname.(isset($s_psub)?'&sub='.$s_psub:'').'"';
698 $out .= '<img src="'.$gURL.'"';
699 $out .= ' alt="'.$s_rrd->basename.(!is_null($g_sub)?' - '.$g_sub:'').' - '.$tframe.'" class="rrdgraph"';
700 $out .= ' style="width:'.$gmeta['width'].'px;height:'.$gmeta['height'].'px;">';
701 $out .= '</a>';
702 }
703 else {
704 $out .= 'RRD error: status is "'.$s_rrd->status.'"';
705 }
706 }
707 else {
708 $out .= '&nbsp;';
709 }
710 $out .= '</td>';
711 }
712 $out .= '</tr>';
713 }
714 $out .= '</table>';
715
716 $out .= $this->h_page_footer();
717 $out .= '</body></html>';
718 return $out;
099bd59f 719 }
720
721 function page_simple($pconf, $graph_extras = null) {
722 // create a simple (MRTG-like) HTML page and return it in a string
723
31df2e13 724 $ptitle = isset($pconf['title_page'])?$pconf['title_page']:$this->basename.' - RRD statistics';
16cc643c 725 $gtitle = array();
2c30ff69 726 $gtitle['day'] = isset($pconf['title_day'])?$pconf['title_day']:'Day overview (scaling 5 minutes)';
727 $gtitle['week'] = isset($pconf['title_week'])?$pconf['title_week']:'Week overview (scaling 30 minutes)';
728 $gtitle['month'] = isset($pconf['title_month'])?$pconf['title_month']:'Month overview (scaling 2 hours)';
729 $gtitle['year'] = isset($pconf['title_year'])?$pconf['title_year']:'Year overview (scaling 1 day)';
b7878f4d 730
16cc643c 731 $out = '<html><head>';
732 $out .= '<title>'.$ptitle.'</title>';
733 $out .= '<style>';
734 if (isset($pconf['style_base'])) { $out .= $pconf['style_base']; }
735 else {
736 $out .= 'h1 { font-weight: bold; font-size: 1.5em; }';
737 $out .= 'h2 { font-weight: bold; font-size: 1em; }';
738 $out .= '.gdata, .gvar, .ginfo { font-size: 0.75em; margin: 0.5em 0; }';
739 $out .= 'table.gdata { border: 1px solid gray; border-collapse: collapse; }';
740 $out .= 'table.gdata td, table.gdata th { border: 1px solid gray; padding: 0.1em 0.2em; }';
c5db3bd5 741 $out .= '.footer { font-size: 0.75em; margin: 0.5em 0; }';
16cc643c 742 }
743 if (isset($pconf['style'])) { $out .= $pconf['style']; }
744 $out .= '</style>';
745 $out .= '</head>';
746 $out .= '<body>';
747
748 $out .= '<h1>'.$ptitle.'</h1>';
2c30ff69 749 if (!isset($pconf['show_update']) || $pconf['show_update']) {
86ff8b91 750 $out .= '<p class="last_up">Last Update: '.(is_null($this->last_update())?'unknown':date('Y-m-d H:i:s', $this->last_update())).'</p>';
2c30ff69 751 }
4ba56977 752
f5e899df 753 $g_sub = isset($pconf['graph_sub'])?$pconf['graph_sub']:null;
b1776944 754 if (in_array($this->status, array('ok','readonly','graphonly'))) {
b7878f4d 755 foreach (array('day','week','month','year') as $tframe) {
f5e899df 756 $gmeta = $this->graph_plus($tframe, $g_sub, $graph_extras);
253ead9f 757 if (isset($pconf['graph_url'])) {
758 $gURL = $pconf['graph_url'];
f5e899df 759 $fname = str_replace('%f', basename($gmeta['filename']), $gURL);
760 $fname = str_replace('%p', $gmeta['filename'], $gURL);
761 if (substr($gURL, -1) == '/') { $gURL .= $gmeta['filename']; }
253ead9f 762 }
763 else {
f5e899df 764 $gURL = $gmeta['filename'];
253ead9f 765 }
16cc643c 766 $out .= '<div class="'.$tframe.'">';
b25db622 767// $out .= '<p>'.nl2br($ret).'</p>';
16cc643c 768 $out .= '<h2>'.$gtitle[$tframe].'</h2>';
253ead9f 769 $out .= '<img src="'.$gURL.'"';
31df2e13 770 $out .= ' alt="'.$this->basename.(!is_null($g_sub)?' - '.$g_sub:'').' - '.$tframe.'" class="rrdgraph"';
16cc643c 771 $out .= ' style="width:'.$gmeta['width'].'px;height:'.$gmeta['height'].'px;">';
772 if (isset($gmeta['data']) && count($gmeta['data'])) {
773 $out .= '<table class="gdata">';
774 foreach ($gmeta['data'] as $field=>$gdata) {
775 $out .= '<tr><th>'.$field.'</th>';
776 foreach ($gdata as $gkey=>$gval) {
777 $out .= '<td><span class="gkey">'.$gkey.': </span>'.$gval.'</td>';
778 }
779 $out .= '</tr>';
780 }
781 $out .= '</table>';
782 }
783 if (isset($gmeta['var']) && count($gmeta['var'])) {
784 foreach ($gmeta['var'] as $gkey=>$gval) {
785 $out .= '<p class="gvar"><span class="gkey">'.$gkey.': </span>'.$gval.'</p>';
786 }
787 }
788 if (isset($gmeta['info']) && count($gmeta['info'])) {
789 foreach ($gmeta['info'] as $gval) {
790 $out .= '<p class="ginfo">'.$gval.'</p>';
791 }
792 }
f5e899df 793 $out .= '</div>';
b7878f4d 794 }
795 }
796 else {
797 $out .= 'RRD error: status is "'.$this->status.'"';
798 }
c5db3bd5 799
f5e899df 800 $out .= $this->h_page_footer();
16cc643c 801 $out .= '</body></html>';
b7878f4d 802 return $out;
803 }
804
f5e899df 805 function h_page_statsArray($pconf) {
806 // return array of stats to list on a page
807 $stats = array();
808 $snames = array(); $s_exclude = array(); $sfiles = array();
809 if (isset($pconf['index_ids'])) {
810 foreach (explode(',', $pconf['index_ids']) as $iid) {
811 if ($iid{0} == '-') { $s_exclude[] = substr($iid, 1); }
812 else { $snames[] = $iid; }
813 }
4ba56977 814 }
f5e899df 815 if (!isset($pconf['scan_config']) || $pconf['scan_config']) {
816 foreach ($this->config_all as $iname=>$rinfo) {
817 if (($iname != '*') && !(isset($rinfo['hidden']) && $rinfo['hidden']) &&
818 !(in_array($iname, $snames)) && !(in_array($iname, $s_exclude))) {
819 $snames[] = $iname;
820 }
821 }
822 }
823 foreach ($snames as $iname) {
824 $newstat = array('name'=>$iname);
825 $sfiles[] = isset($this->config_all[$iname]['file'])?$this->config_all[$iname]['file']:$iname.'.rrd';
826 if (is_array($this->config_all[$iname])) {
827 foreach ($this->config_all[$iname] as $key=>$val) {
828 if (substr($key, 0, 5) == 'page.') { $newstat['sub'][] = substr($key, 5); }
829 }
830 }
831 $stats[] = $newstat;
832 }
833 if (isset($pconf['scan_files']) && $pconf['scan_files']) {
834 $rrdfiles = glob('*.rrd');
835 foreach ($rrdfiles as $rrdfile) {
836 $iname = (substr($rrdfile, -4) == '.rrd')?substr($rrdfile, 0, -4):$rrdfile;
837 if (!in_array($rrdfile, $sfiles) && !(in_array($iname, $s_exclude))) {
838 $stats[] = array('name'=>$iname, 'class'=>'scanfile');
839 }
840 }
841 }
842 return $stats;
843 }
844
845 function h_page_footer() {
846 // return generic page footer
847 $out = '<p class="footer">';
848 $out .= 'Statistics created by <a href="http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/">RRDtool</a>';
849 $out .= ' using a library created by <a href="http://www.kairo.at/">KaiRo.at</a>.';
850 $out .= '</p>';
851 return $out;
4ba56977 852 }
853
b7878f4d 854 function text_quote($text) { return '"'.str_replace('"', '\"', str_replace(':', '\:', $text)).'"'; }
855}
856?>