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