public function getSpecificValues($metricId) { $rrdFile = $this->rrdPath . '/' . $metricId . '.rrd'; if (file_exists($rrdFile)) { $values = rrd_fetch($rrdFile, array("AVERAGE", "--resolution", "300", "--start", "now", "--end", "start-1h")); } else { throw new \Exception("rrd file " . $rrdFile . " doesn't exist"); } return $values; }
public function get($datasource, $end = 'now', $start = 'end-1h', $resolution = 3600, $cf = 'AVERAGE') { // if ($end == 'now-best') { // $end = (int)(time() / $resolution) * $resolution; // } $data = rrd_fetch($this->rrd_file, array($cf, '--resolution', $resolution, '--start', $start, '--end', $end)); if (!isset($data['data']) || !isset($data['data'][$datasource]) || empty($data['data'][$datasource])) { return NAN; } $func = $this->_cf_func($cf); if ($func) { return $func($data['data'][$datasource]); } else { return $data['data'][$datasource][0]; } }
function find_limits($nodes, $metricname) { global $conf, $metrics, $clustername, $rrd_dir, $start, $end, $rrd_options; if (!count($metrics)) { return array(0, 0); } $firsthost = key($metrics); if (array_key_exists($metricname, $metrics[$firsthost])) { if ($metrics[$firsthost][$metricname]['TYPE'] == "string" or $metrics[$firsthost][$metricname]['SLOPE'] == "zero") { return array(0, 0); } } else { return array(0, 0); } $max = 0; $min = 0; if ($conf['graph_engine'] == "graphite") { $target = $conf['graphite_prefix'] . $clustername . ".[a-zA-Z0-9]*." . $metricname . ".sum"; $raw_highestMax = file_get_contents($conf['graphite_url_base'] . "?target=highestMax(" . $target . ",1)&from=" . $start . "&until=" . $end . "&format=json"); $highestMax = json_decode($raw_highestMax, TRUE); $highestMaxDatapoints = $highestMax[0]['datapoints']; $maxdatapoints = array(); foreach ($highestMaxDatapoints as $datapoint) { array_push($maxdatapoints, $datapoint[0]); } $max = max($maxdatapoints); } else { foreach ($nodes as $host => $value) { $out = array(); $rrd_dir = "{$conf['rrds']}/{$clustername}/{$host}"; $rrd_file = "{$rrd_dir}/{$metricname}.rrd"; if (file_exists($rrd_file)) { if (extension_loaded('rrd')) { $values = rrd_fetch($rrd_file, array("--start", $start, "--end", $end, "AVERAGE")); $values = array_filter(array_values($values['data']['sum']), 'is_finite'); $thismax = max($values); $thismin = min($values); } else { $command = $conf['rrdtool'] . " graph /dev/null {$rrd_options} " . "--start {$start} --end {$end} " . "DEF:limits='{$rrd_dir}/{$metricname}.rrd':'sum':AVERAGE " . "PRINT:limits:MAX:%.2lf " . "PRINT:limits:MIN:%.2lf"; exec($command, $out); if (isset($out[1])) { $thismax = $out[1]; } else { $thismax = NULL; } if (!is_numeric($thismax)) { continue; } $thismin = $out[2]; if (!is_numeric($thismin)) { continue; } } if ($max < $thismax) { $max = $thismax; } if ($min > $thismin) { $min = $thismin; } #echo "$host: $thismin - $thismax (now $value)<br>\n"; } } } return array($min, $max); }
function wmrrd_read_from_php_rrd($rrdfile, $cf, $start, $end, $dsnames, &$data, &$map, &$data_time, &$item) { // not yet implemented - use php-rrdtool to read rrd data. Should be quicker if (1 == 0 && extension_loaded('RRDTool')) { // for the php-rrdtool module, we use an array instead... $rrdparams = array("AVERAGE", "--start", $start, "--end", $end); $rrdreturn = rrd_fetch($rrdfile, $rrdparams, count($rrdparams)); print_r($rrdreturn); // XXX - figure out what to do with the results here $now = $rrdreturn['start']; $n = 0; do { $now += $rrdreturn['step']; print "{$now} - "; for ($i = 0; $i < $rrdreturn['ds_cnt']; $i++) { print $rrdreturn['ds_namv'][$i] . ' = ' . $rrdreturn['data'][$n++] . " "; } print "\n"; } while ($now <= $rrdreturn['end']); } }
#!/usr/local/eyou/toolmail/opt/bin/php <?php $path = '/usr/local/eyou/toolmail/data/rrds/esop.eyou.net/dev/'; $rrd_file = 'load_fifteen.rrd'; $rrd_file = 'net_rx_bytes__lo.rrd'; $opt = ['AVERAGE', '-r', '600', '-s', '-1h']; var_dump($opt); $ret = rrd_fetch($path . $rrd_file, $opt); var_export($ret); exit; function _d($d) { return date('Y-m-d H:i:s', $d); } $ret['start'] = _d($ret['start']); $ret['end'] = _d($ret['end']); $arr = []; foreach ($ret['data']['sum'] as $k => $v) { $arr[_d($k)] = $v; } $ret['data']['sum'] = $arr; print_r($ret);
/** * Fetch data from RRD Database * */ function Fetch($CF, $resolution = false, $start=false, $end=false) { $args = array($CF); if ($start) { $args[] = "--start"; $args[] = $start; } print_r($args); print $this->DBPath; $ret = rrd_fetch($this->DBPath, $args, count($args)); var_dump($ret); return $ret; }
function getData($rrd, $type, $start, $end) { // centre around the start point $s = intval($start - ($end - $start) / 2); $e = $s + ($end - $start); $r = $e - $s; // ensure start and end is divisable by the resolution $s = intval($s / $r) * $r; if ($e % $r != 0) { $e = intval(ceil($e / $r)) * $r; } $opts = [$type, "--start", $s, "--end", $e, "--resolution", $r]; $dss = rrd_fetch($rrd, $opts); // consolodate the values we find $data = []; $data['in'] = 0; $data['out'] = 0; if ($dss && isset($dss['data']['ds0'])) { switch ($type) { case 'AVERAGE': foreach ($dss['data']['ds0'] as $ds) { $data['in'] += !is_nan($ds) ? $ds : 0; } foreach ($dss['data']['ds1'] as $ds) { $data['out'] += !is_nan($ds) ? $ds : 0; } $data['in'] /= count($dss['data']['ds0']); $data['out'] /= count($dss['data']['ds1']); return array_map('intval', $data); break; case 'MAX': foreach ($dss['data']['ds0'] as $ds) { if ($data['in'] < $ds) { $data['in'] = $ds; } } foreach ($dss['data']['ds1'] as $ds) { if ($data['out'] < $ds) { $data['out'] = $ds; } } return array_map('intval', $data); break; } } return false; }
function find_limits($nodes, $metricname) { global $conf, $metrics, $clustername, $rrd_dir, $start, $end, $rrd_options; if (!count($metrics)) { return array(0, 0); } $firsthost = key($metrics); if (array_key_exists($metricname, $metrics[$firsthost])) { if ($metrics[$firsthost][$metricname]['TYPE'] == "string" or $metrics[$firsthost][$metricname]['SLOPE'] == "zero") { return array(0, 0); } } else { return array(0, 0); } $max = 0; $min = 0; foreach ($nodes as $host => $value) { $out = array(); $rrd_dir = "{$conf['rrds']}/{$clustername}/{$host}"; $rrd_file = "{$rrd_dir}/{$metricname}.rrd"; if (file_exists($rrd_file)) { if (extension_loaded('rrd')) { $values = rrd_fetch($rrd_file, array("--start", $start, "--end", $end, "AVERAGE")); $values = array_filter(array_values($values['data']['sum']), 'is_finite'); $thismax = max($values); $thismin = min($values); } else { $command = $conf['rrdtool'] . " graph /dev/null {$rrd_options} " . "--start {$start} --end {$end} " . "DEF:limits='{$rrd_dir}/{$metricname}.rrd':'sum':AVERAGE " . "PRINT:limits:MAX:%.2lf " . "PRINT:limits:MIN:%.2lf"; exec($command, $out); if (isset($out[1])) { $thismax = $out[1]; } else { $thismax = NULL; } if (!is_numeric($thismax)) { continue; } $thismin = $out[2]; if (!is_numeric($thismin)) { continue; } } if ($max < $thismax) { $max = $thismax; } if ($min > $thismin) { $min = $thismin; } #echo "$host: $thismin - $thismax (now $value)<br>\n"; } } return array($min, $max); }
<?php date_default_timezone_set('America/Chicago'); //Get old data: $json = file_get_contents('./archive/almanac_current.json'); $archiveobj = json_decode(trim($json), true); $json = file_get_contents('./archive/astronomy_current.json'); $astroobj = json_decode(trim($json), true); $sunrise = $astroobj['sun_phase']['sunrise']['hour'] . ":" . $astroobj['sun_phase']['sunrise']['minute']; $sunset = $astroobj['sun_phase']['sunset']['hour'] . ":" . $astroobj['sun_phase']['sunset']['minute']; $sunset = Date('g:i', strtotime($sunset)); // Get Data #//rrdtool fetch /usr/local/wun/wundergrounddata.rrd AVERAGE -r 300 -s -10min -e -5min $result = rrd_fetch("./wundergrounddata.rrd", array("AVERAGE", "--resolution", "300", "--start", "-10min", "--end", "-5min")); //$a = print_r($result); //print "<pre>T: ". print_r($result['data']['temperature'], true); $data = array(); $data['temperature'] = 0; $data['humidity'] = 0; $data['winddir'] = 0; $data['windspeed'] = 0; $data['pressure'] = 0; $data['rain'] = 0; foreach ($data as $key => $value) { foreach ($result['data'][$key] as $otherkey => $value) { if (strcmp($value, "NAN") != 0) { $data[$key] = $value; } } } print rrd_error();
/** * getPerformanceChartData * * @param args array containing parameters * device_id id of device to get history for * start start date/time * stop date/time * metric metric to return rrd data for * @throws none * @return array containing result and possible error messages */ public function ajax_getPerformanceChartData($args) { $result = 'success'; $error = ''; $data = array(); try { $rrd_info = $this->getRRDInfo($args['device_id'], $args['metric']); $sd = date_parse_from_format('D M d Y H:i:s \\G\\M\\TO \\(T\\)', $args['start']); $ed = date_parse_from_format('D M d Y H:i:s \\G\\M\\TO \\(T\\)', $args['stop']); $start = sprintf("--start=%ld", mktime(0, 0, 0, $sd['month'], $sd['day'], $sd['year'])); $end = sprintf("--end=%ld", mktime(0, 0, 0, $ed['month'], $ed['day'], $ed['year'])); if (extension_loaded('RRDTool') && function_exists('rrd_fetch')) { $ret = rrd_fetch($rrd_info['rrd_file'], array("AVERAGE", $start, $end), 3); if (!is_array($ret)) { $result = 'failure'; $error = rrd_error(); } else { // parse response and return useful pieces $data['start'] = $ret['start']; $data['end'] = $ret['end']; $data['step'] = $ret['step']; $data['title'] = $rrd_info['title']; foreach ($ret['data'] as $k => $v) { if ($v == 'NAN') { $v = 0; } $data['data'][$k] = round($v, 5); } $data['info'] = $rrd_info['datas']; } } else { // just run cli and parse the output $rrdtool = $this->getConfigValue('web.rrdtool'); if ($rrdtool) { $cmd = $rrdtool . ' fetch ' . $rrf_info['rrd_file'] . ' AVERAGE ' . $start . ' ' . $end; $pfh = popen($cmd, "r"); // read off first two header lines fread($pfh, 1024); fread($pfh, 1024); $data['data'] = array(); while (!feof($pfh)) { /* and read data */ $line = fread($pfh, 1024); if (preg_match('/^(\\d+):\\s+([^\\s+])\\s+([^\\s+])\\s+([^\\s+])\\s+([^\\s+])/', $line, $matches)) { $v = $matches[2]; if ($v == '-nan') { $v = 0; } $data['data'][$matches[1]] = round($v, 5); } else { $result = 'failure'; $error = 'rrdtool unexpected output: ' . $line; } } $keys = sort(array_keys($data['data']), SORT_NUMERIC); $data['start'] = min(array_keys($data['data'])); $data['end'] = max(array_keys($data['data'])); $data['step'] = $keys[0] - $keys[1]; $data['title'] = $rrd_info['title']; $data['info'] = $rrd_info['datas']; pclose($pfh); } else { $result = 'failure'; $error = 'web.rrdtool is not defined'; } } } catch (Exception $e) { return array('result' => 'failure', 'error' => $e->getMessage()); } return array('result' => $result, 'error' => $error, 'data' => $data); }
/** * renderUserWidget * * @param entry dashboardUserWidget object * @throws PDOException * @return none */ public function renderUserWidget(dashboardUserWidget $entry) { global $panoptes_current_user; try { $rtn = array(); $rtn['type'] = 'js'; // make sure rrd extension is loaded if (!extension_loaded('RRDTool') && function_exists('rrd_fetch')) { // throw error for now // could just run cli though $rtn['error'] = 'php rrd extension missing'; return $rtn; } require_once dirname(realpath(__FILE__)) . '/../panoptes.php'; require_once dirname(realpath(__FILE__)) . '/../userEntry.php'; require_once dirname(realpath(__FILE__)) . '/../userPrefs.php'; $pan = new panoptes(); // load user prefs for chart theme $user = new userEntry(); $user->db = $this->db; $user->getByName($panoptes_current_user); $userPrefs = new userPrefs($this->db); $userPrefs->db = $this->db; $theme = $userPrefs->getPref($user->id, 'general', 'general_prefs_chart_theme'); if (is_null($theme)) { $theme = $pan->config()->getConfigValue('web.default_chart_theme'); } // draw rrd graph from params field of widget render last 30 minutes $start = sprintf("--start=%d", time() - 1800); $prms = $entry->params; $data = array(); $rrd_params = array(); $devices = array(); $count = 0; $max_y = 0; foreach ($prms as $a) { preg_match('/^(\\d+):(.*)/', $a, $matches); $dev = $pan->getDevice($matches[1]); $short_name = preg_replace('/([^\\.]+)\\..*/', '\\1', $dev->name); array_push($devices, $short_name); $rrd_info = $pan->getRRDInfo($matches[1], $matches[2], false, $count); $ret = rrd_fetch($rrd_info['rrd_file'], array("AVERAGE", $start), 2); if (!is_array($ret)) { $rtn['error'] = rrd_error(); return $rtn; } else { // parse response and load data for this device into array $data['_']['step'] = $ret['step']; $data['_']['start'] = $ret['start']; $data['_']['end'] = $ret['end']; $data[$short_name] = array(); foreach ($ret['data'] as $k => $v) { if ($v == 'NAN') { $v = 0; } $v = round($v, 5); // keep track of max value for y-axis if ($v > $max_y) { $max_y = $v; } $data[$short_name][] = array('x' => $data['_']['start'] + $k * $data['_']['step'], 'y' => $v, 'tooltip' => $v); } $data['_'][$short_name]['info'] = $rrd_info['datas']; } $count++; } // make title out of device names $devices = array_unique($devices); if (count($devices) > 1) { $last = array_pop($devices); $first = implode(',', $devices); $title = $first . ' & ' . $last; } else { $title = $devices[0]; } // select a font size that will fit number of characters within 200px // div on most user screens // assume avg is 90 px/inch // 200px = 2.22 in // 72 pts/in // pts avail = 72 / 2.22 = 32 $font_width = round(32 / strlen($title)); // send back code to draw chart $ret = "var dv = document.createElement('div'); dv.id = '" . $entry->id . "' + '_perf_div'; dv.style.height = '175px'; dv.style.width = '200px'; node.appendChild(dv); var chrt = new dojox.charting.Chart2D('" . $entry->id . "_perf_div', { title: '" . $title . "', titleGap: 5, titleFont: 'normal normal bold " . $font_width . "pt Helvetica' }); chrt.setTheme(dojox.charting.themes." . $theme . "); chrt.addPlot('default', { type: 'Lines', markers: true }); f = new dojox.charting.action2d.Tooltip(chrt, 'default'); chrt.addAxis('x', { natural: true, htmlLabels: true, labelFunc: function(value) { var v = value; var dt = new Date(); dt.setTime(v.replace(/\\,/g,'') * 1000); var h = dt.getHours(); h = (h < 10 ? '0' + h : h); var m = dt.getMinutes(); m = (m < 10 ? '0' + m : m); return(h + ':' + m); }, microTicks: false, min: " . $data['_']['start'] . ", max: " . $data['_']['end'] . ", minorTickSpan: " . $data['_']['step'] . " }); chrt.addAxis('y', { vertical: true, min: 0, max: " . $max_y . ", includeZero: true, title: '" . $rrd_info['datas'][0]['vlabel'] . "', font: 'normal normal bold 8pt Helvetica', titleGap: 5 });"; // go through each requested rrd and add series to chart foreach ($data as $k => $v) { if ($k != '_') { $ret .= " var foo = " . json_encode($v) . "; chrt.addSeries('" . $data['_'][$k]['info'][0]['label'] . "', foo);"; } } $ret .= " f = new dojox.charting.action2d.Tooltip(chrt, 'default'); chrt.render(); var w_lg_dv = document.createElement('div'); w_lg_dv.id = '" . $entry->id . "_legend_div'; w_lg_dv.style.height = '25px'; w_lg_dv.style.width = '200px'; node.appendChild(w_lg_dv); f = new dojox.charting.widget.Legend({ chart: chrt }, '" . $entry->id . "_legend_div');"; $rtn['value'] = $ret; } catch (PDOException $e) { throw $e; } return $rtn; }
function Fetch($gid, $fetch_opts) { $file = $this::GidToFilename($gid, $this); $return = rrd_fetch($file, $fetch_opts); //, count($fetch_opts)); return $return; }
if (!is_dir(RRD3_PATH)) { die("error opening RRD3_PATH: " . RRD3_PATH . "\n"); } while (1) { if ($dh = opendir(RRD3_PATH)) { while (($file = readdir($dh)) !== false) { if (!is_file(RRD3_PATH . $file)) { continue; } if (preg_match(RRD3_FILE_FILTER, $file)) { continue; } $site = strtr($file, array('_moodle' => '', '.rrd' => '')); echo "+ {$file}\n"; $options = array("AVERAGE", "--start", RRD3_DOMAIN, "--end", "now"); if ($data = rrd_fetch(RRD3_PATH . $file, $options)) { foreach ($data['data'] as $name => $values) { if (!isset($labels[$name])) { continue; } array_walk($values, function (&$n) { if (is_nan($n)) { $n = 0.0; } }); $data['data'][$name] = array(); echo " -{$name}\n"; foreach ($values as $key => $value) { $data['data'][$name][$key * 1000] = $value; } $send = new stdClass();