Ejemplo n.º 1
0
function create_graph($output, $start, $title)
{
    $options = array("--slope-mode", "--start", $start, "--title={$title}", "--vertical-label=Load 0 -> 30", "--alt-autoscale-max", "--lower-limit=0", "--lower=0", "DEF:load2mn=/usr/share/artica-postfix/ressources/databases/rrd/load.rrd:load:AVERAGE", "LINE:load2mn#00FF00:Load average", "GPRINT:load2mn:AVERAGE:Avg\\: %3.2lf", "GPRINT:load2mn:MAX:Max\\:%3.2lf");
    $ret = rrd_graph($output, $options, count($options));
    if (!$ret) {
        echo "<b>Graph error: </b>" . rrd_error() . "\n";
    }
}
Ejemplo n.º 2
0
 public static function createRRDGraph($filename, $options)
 {
     $config = json_decode(file_get_contents("config.json"), true);
     $options[] = "--watermark";
     $options[] = $config["communityName"] . " - " . date("c");
     $ret = rrd_graph($filename, $options);
     echo rrd_error();
 }
Ejemplo n.º 3
0
function create_graph($output, $start, $title)
{
    $RRDPATH = '/opt/minepeon/http/rrd/';
    $options = array("--slope-mode", "--start", $start, "--title={$title}", "--vertical-label=Hash per second", "--lower=0", "DEF:hashrate=" . $RRDPATH . "hashrate.rrd:hashrate:AVERAGE", "CDEF:realspeed=hashrate,1000,*", "LINE2:realspeed#FF0000");
    $ret = rrd_graph("/opt/minepeon/http/rrd/" . $output, $options);
    if (!$ret) {
        echo "<b>Graph error: </b>" . rrd_error() . "\n";
    }
}
Ejemplo n.º 4
0
 function execute($filename)
 {
     $return = rrd_graph($this->graphics_path . $filename, $this->options, count($this->options));
     if (!is_array($return)) {
         throw new Rrdtool_Exception("rrd_graph() ERROR: " . rrd_error());
     } else {
         return $return;
     }
 }
Ejemplo n.º 5
0
 function execute()
 {
     if (file_exists($this->db_path)) {
         return true;
     }
     $return = rrd_create($this->db_path, $this->options, count($this->options));
     if (!$return) {
         throw new Rrdtool_Exception("rrd_create() ERROR: " . rrd_error());
     } else {
         return $return;
     }
 }
Ejemplo n.º 6
0
function storagegraphWin($rrd, $graph, $from = "-2d", $descr)
{
    $database = "rrd/" . $rrd;
    $imgfile = "graphs/" . "{$graph}";
    $opts = array("--start", $from, "-v MB", "-b 1024", "--rigid", "--title", $descr, "--alt-autoscale-max", "-l 0", "--width", "335", "--height", "100", "DEF:size={$database}:size:AVERAGE", "DEF:used={$database}:used:AVERAGE", "AREA:size#80ee80:Total", "GPRINT:size:LAST:Cur\\:%8.2lf %s", "GPRINT:size:AVERAGE: Avg\\:%8.2lf %s", "GPRINT:size:MAX: Max\\:%8.2lf %s\\n", "AREA:used#ec9900:Used", "GPRINT:used:LAST: Cur\\:%8.2lf %s", "GPRINT:used:AVERAGE: Avg\\:%8.2lf %s", "GPRINT:used:MAX: Max\\:%8.2lf %s\\n", "LINE1:size#000000:");
    $ret = rrd_graph("{$imgfile}", $opts, count($opts));
    if (!is_array($ret)) {
        $err = rrd_error();
        echo "rrd_graph() ERROR: {$err}\n";
        return FALSE;
    } else {
        return $imgfile;
    }
}
Ejemplo n.º 7
0
 public function execute()
 {
     if (!file_exists($this->db_path)) {
         throw new Rrdtool_Exception("Rrdtool\\Update() ERROR: rdd file '" . $this->db_path . "' not exists");
     }
     $insert = "N";
     foreach ($this->datas as $data) {
         $insert .= ':' . $data;
     }
     $return = rrd_update($this->db_path, $insert);
     if (!$return) {
         throw new Rrdtool_Exception("rrd_update() ERROR: " . rrd_error());
     } else {
         return $return;
     }
 }
Ejemplo n.º 8
0
 function create_image($rrd_file, $image_file, $time = '1d', $type = 'traffic')
 {
     switch ($type) {
         case 'traffic':
             $opts = array("--imgformat=PNG", "--start=-" . $time, "--end=-300", "--title=Traffic graph", "--rigid", "--base=1000", "--height=120", "--width=500", "--alt-autoscale-max", "--lower-limit=0", "--vertical-label=bits per second", "--slope-mode", "DEF:a=" . $rrd_file . ":traffic_in:AVERAGE", "DEF:b=" . $rrd_file . ":traffic_out:AVERAGE", "CDEF:cdefa=a,8,*", "CDEF:cdefe=b,8,*", "AREA:cdefa#00E600: Inbound", "GPRINT:cdefa:LAST:Current\\:%8.2lf %s", "GPRINT:cdefa:AVERAGE:Average\\:%8.2lf %s", "GPRINT:cdefa:MAX:Maximum\\:%8.2lf %s\\n", "LINE1:cdefe#002A97:Outbound", "GPRINT:cdefe:LAST:Current\\:%8.2lf %s", "GPRINT:cdefe:AVERAGE:Average\\:%8.2lf %s", "GPRINT:cdefe:MAX:Maximum\\:%8.2lf %s\\n");
             break;
     }
     $ret = rrd_graph($image_file, $opts, count($opts));
     if (!is_array($ret)) {
         $error = rrd_error();
         print $error;
         return false;
     } else {
         return true;
     }
 }
Ejemplo n.º 9
0
function callsgraphSNOM($rrd, $graph, $from, $to, $width, $height, $title, $vertical)
{
    global $config;
    $database = $config['rrd_dir'] . '/' . $rrd;
    $imgfile = 'graphs/' . "{$graph}";
    $optsa = array('--start', $from, '--end', $to, '--width', $width, '--height', $height, '--vertical-label', $vertical, '--alt-autoscale-max', '-l 0', '-E', '--title', $title, "DEF:call={$database}:CALLS:AVERAGE", 'CDEF:calls=call,360,*', 'LINE1.25:calls#FF9900:Calls', 'GPRINT:calls:LAST:Cu\\: %2.0lf/min', 'GPRINT:calls:AVERAGE:Av\\: %2.0lf/min', "GPRINT:calls:MAX:Mx\\: %2.0lf/min\\n");
    if ($width <= '300') {
        $optsb = array('--font', 'LEGEND:7:' . $config['mono_font'] . '', '--font', 'AXIS:6:' . $config['mono_font'] . '', '--font-render-mode', 'normal');
    }
    $opts = array_merge($config['rrdgraph_defaults'], $optsa, $optsb);
    $ret = rrd_graph("{$imgfile}", $opts, count($opts));
    if (!is_array($ret)) {
        $err = rrd_error();
        echo "rrd_graph() ERROR: {$err}\n";
        return false;
    } else {
        return $imgfile;
    }
}
Ejemplo n.º 10
0
function callsgraphSNOM($rrd, $graph, $from, $to, $width, $height, $title, $vertical)
{
    global $config;
    $database = $config['rrd_dir'] . "/" . $rrd;
    $imgfile = "graphs/" . "{$graph}";
    $optsa = array("--start", $from, "--end", $to, "--width", $width, "--height", $height, "--vertical-label", $vertical, "--alt-autoscale-max", "-l 0", "-E", "--title", $title, "DEF:call={$database}:CALLS:AVERAGE", "CDEF:calls=call,360,*", "LINE1.25:calls#FF9900:Calls", "GPRINT:calls:LAST:Cu\\: %2.0lf/min", "GPRINT:calls:AVERAGE:Av\\: %2.0lf/min", "GPRINT:calls:MAX:Mx\\: %2.0lf/min\\n");
    if ($width <= "300") {
        $optsb = array("--font", "LEGEND:7:" . $config['mono_font'] . "", "--font", "AXIS:6:" . $config['mono_font'] . "", "--font-render-mode", "normal");
    }
    $opts = array_merge($config['rrdgraph_defaults'], $optsa, $optsb);
    $ret = rrd_graph("{$imgfile}", $opts, count($opts));
    if (!is_array($ret)) {
        $err = rrd_error();
        echo "rrd_graph() ERROR: {$err}\n";
        return FALSE;
    } else {
        return $imgfile;
    }
}
Ejemplo n.º 11
0
function memgraphHP($rrd, $graph, $from, $to, $width, $height, $title, $vertical)
{
    global $config, $installdir;
    $database = "rrd/" . $rrd;
    $memrrd = $database;
    $opts = array("--start", "{$from}", "--alt-autoscale-max", "--width", "{$width}", "--height", "{$height}", "-l", "0", "-E", "-b", "1024", "DEF:TOTAL={$memrrd}:TOTAL:AVERAGE", "DEF:FREE={$memrrd}:FREE:AVERAGE", "DEF:USED={$memrrd}:USED:AVERAGE", "AREA:USED#ee9900:Used", "AREA:FREE#FAFDCE:Free:STACK", "LINE1.5:TOTAL#cc0000:");
    if ($width <= "300") {
        $optsb = array("--font", "LEGEND:7:" . $config['mono_font'] . "", "--font", "AXIS:6:" . $config['mono_font'] . "", "--font-render-mode", "normal");
    }
    $opts = array_merge($config['rrdgraph_defaults'], ${$opts}, $optsb);
    $ret = rrd_graph("{$graph}", $opts, count($opts));
    if (!is_array($ret)) {
        $err = rrd_error();
        #echo "rrd_graph() ERROR: $err\n";
        return FALSE;
    } else {
        return $graph;
    }
}
Ejemplo n.º 12
0
 function drawCurrentVsActualTempGraph($period, $peerId)
 {
     $options = $this->tempGraphOptions;
     $options[] = "--title=Actual Temp vs. Configured Temp on Peer " . $peerId . " (" . $period . ")";
     $options[] = "--vertical-label=°C";
     $options[] = "--start";
     $options[] = $this->graphPeriods[$period];
     $options[] = "--upper-limit=30";
     $i = 0;
     $this->colorIndex = 0;
     foreach ($this->devices as $device) {
         if ($device["type"] == "valve" && intval($device["peerId"]) == intval($peerId)) {
             $rrdPath = $this->rrdBasePath . "valves/peer_" . $device["peerId"] . ".rrd";
             if (isset($device["tempSensor"]) && file_exists($rrdPath)) {
                 $options[] = "DEF:temp" . $i . "=" . $rrdPath . ":temp:LAST";
                 $options[] = "LINE2:temp" . $i . $this->getColor() . ": Actual Temperature";
                 $options[] = "GPRINT:temp" . $i . ":LAST:%2.1lf°C";
                 $options[] = "DEF:configuredTemp" . $i . "=" . $rrdPath . ":configuredTemp:LAST";
                 $options[] = "LINE2:configuredTemp" . $i . $this->getColor() . ": Configured Temperature";
                 $options[] = "GPRINT:configuredTemp" . $i . ":LAST:%2.1lf°C";
                 $options[] = "COMMENT:\\n";
                 $i++;
             }
         }
     }
     if ($i == 0) {
         $options[] = "ERROR: Device " . $peerId . " not found or not a valve!";
     }
     if (!rrd_graph($this->rrdBasePath . "output/" . $peerId . "_CurrentVsActual_" . $period . ".gif", $options)) {
         echo "RRD ERROR: " . rrd_error() . "\n";
         print_r($options);
     }
 }
Ejemplo n.º 13
0
 /**
  * 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;
 }
Ejemplo n.º 14
0
function asSBGraph($img, $end, $span)
{
    global $rate, $maxi, $libdir, $msgs, $show_graph_period;
    global $as_version, $rrdstep, $host, $as_pkg;
    /*
     * Work out the beginning and the end, based on the span
     */
    $limits = getlimits($end, $span);
    $end = $limits["end"];
    $start = $limits["start"];
    $length = $end - $start;
    $timetext = $limits["description"];
    $start_period = strftime("%A %B %d %H:%M:%S (GMT%z)", $start);
    $end_period = strftime("%A %B %d %H:%M:%S (GMT%z)", $end);
    $startdate = strftime("%c", $start);
    $enddate = strftime("%c", $end);
    $nowdate = strftime("%c", time());
    $hostname = on_host($host);
    if ($rate == 60) {
        $rate = 60;
        $ratemsg = "min";
    } else {
        $rate = 3600;
        $ratemsg = "hour";
    }
    $arrcol = array("Passed SPAM" => "6a5aff", "Blocked SPAM" => "fa5aff", "Blocked CLEAN" => "7ffa00", "Passed BANNED" => "cc9900", "Blocked BANNED" => "ffdd00", "Passed INFECTED" => "9900aa", "Blocked INFECTED" => "ff3a3d", "Passed BAD-HEADER" => "3f40cc", "Blocked BAD-HEADER" => "594e61");
    /*
     * It is a two-step process to build the final graph. The average over
     * a specific time period seems to be impossible to get without actually
     * building a graph. Ie, rrd fetch will not calculate the values we
     * need - we would have to sum and average manually.
     *
     * However the PRINT function of a graph will return what we want
     * in an array. So first of all build a graph that PRINTs the average
     * of every virus over the selected time period.
     */
    $opts = array();
    $opts[] = "--start={$start}";
    $opts[] = "--end={$end}";
    foreach ($msgs as $id => $name) {
        foreach ($arrcol as $matchname => $rest) {
            if ($name == $matchname) {
                $opts[] = "DEF:v{$id}={$libdir}/{$id}.rrd:hits:AVERAGE";
                $opts[] = "CDEF:gv{$id}=v{$id},UN,0,v{$id},IF";
                $opts[] = "CDEF:gvt{$id}=gv{$id},{$length},*";
                $opts[] = "PRINT:gvt{$id}:AVERAGE:%.0lf";
            }
        }
    }
    $ret = pre_graph($img, $opts, count($opts));
    $infected = 0;
    if (!is_array($ret)) {
        $msg = rrd_error();
        asErr("rrd_graph(): {$msg}");
        return false;
    }
    /*
     * All results from PRINT commands are in the array $ret["calcpr"][..]
     */
    $maxi = 0;
    $i = 0;
    $bcount = array();
    foreach ($msgs as $id => $name) {
        foreach ($arrcol as $matchname => $rest) {
            if ($name == $matchname) {
                /*
                 * We don't have enough resolution in the rrds
                 * to calculate the correct counts at low averages,
                 * so we just don't display them
                 */
                if ($ret["calcpr"][$i] != 0) {
                    $bcount[$id] = $ret["calcpr"][$i];
                    $maxi = max($maxi, strlen($msgs[$id]));
                }
                $i++;
            }
        }
    }
    $maxi++;
    aslog("Maxi: {$maxi}");
    /*
     */
    if (count($bcount) >= 1) {
        arsort($bcount);
        aslog($bcount, 0, '$bcount');
    } else {
        aslog("bcount is an empty array");
    }
    /*
     * Now that we have the counts of each virus over the time period
     * we can build the actual graph
     */
    $opts = array();
    $opts[] = "--start={$start}";
    $opts[] = "--end={$end}";
    $opts[] = "--imgformat=PNG";
    $opts[] = "--title=Spam/Header Detection {$hostname}({$timetext} to {$enddate})";
    $opts[] = "--width=580";
    $opts[] = "--vertical-label=non-virus/{$ratemsg}";
    /*
     * The tricky part, building rrd rows but ordering the elements by
     * columns...
     */
    $width = calc_maxi($maxi);
    $total = count($bcount);
    $depth = ceil($total / $width);
    $mod = $total % $width;
    if ($total > 0) {
        $keyarray = array_keys($bcount);
        for ($d = 1; $d <= $depth; $d++) {
            for ($col = 1; $col <= $width; $col++) {
                if ($col == 1) {
                    $index = $d;
                } elseif ($d != $depth || $mod == 0 || $mod >= $col) {
                    if ($mod == 0 || $col - $mod < 2) {
                        $index = ($col - 1) * $depth + $d;
                    } else {
                        $index = $mod * $depth + ($col - $mod - 1) * ($depth - 1) + $d;
                    }
                } else {
                    continue;
                }
                $id = $keyarray[$index - 1];
                foreach ($arrcol as $matchname => $color) {
                    if ($msgs[$id] == $matchname) {
                        $usecolor = $color;
                    }
                }
                if ($d == 1 && $col == 1) {
                    addopts($opts, "AREA", $id, $bcount, $msgs[$id], $usecolor);
                } else {
                    addopts($opts, "STACK", $id, $bcount, $msgs[$id], $usecolor);
                }
            }
            $opts[] = "COMMENT:\\n";
        }
    }
    $opts[] = "COMMENT:\\n";
    if ($show_graph_period) {
        $opts[] = graph_date($start_period, $end_period);
    }
    $opts[] = "COMMENT:{$as_pkg} v{$as_version}\\r";
    $ret = pre_graph($img, $opts, count($opts));
    if (!is_array($ret)) {
        $err = rrd_error();
        asErr("rrd_graph(): {$err}");
        return false;
    }
    if ($ret['ysize'] < 190) {
        return "<br><center>NO SPAM/HEADER DATA TO GRAPH</center><br>";
    }
    return "<img src=\"{$img}\" alt=\"[image: {$timetext}]\">";
}
Ejemplo n.º 15
0
 public function fillHardwareRRDData()
 {
     if (!$this->checkHardwareRRDFile()) {
         $this->createHardwareRRDFile();
     }
     $data = array();
     $data[] = time();
     $hardwareDS = RRD::getDSFromRRDFile($this->rrdHardwareFile);
     $tmphardware = array();
     foreach ($this->nodeHardware as $key => $value) {
         $hardKey = $this->hardwareMapper->addNameToMapping($key);
         if (!in_array($hardKey, $hardwareDS)) {
             $hardwareDS[] = $key;
             RRD::addDS2RRDFile($this->rrdHardwareFile, $hardKey, "GAUGE", 600, 0, "U");
         }
         $tmphardware[$hardKey] = $value;
     }
     foreach ($hardwareDS as $hard) {
         //echo $firm."\n";
         $data[] = $tmphardware[$hard];
     }
     $string = implode(":", $data);
     $ret = rrd_update($this->rrdHardwareFile, array($string));
     echo rrd_error();
 }
Ejemplo n.º 16
0
if (!file_exists($cfgfile)) {
    echo "Copy config.php.dist to config.php and adjust it\n";
    exit(1);
}
require $cfgfile;
if (!function_exists('rrd_lastupdate')) {
    echo "rrd PHP extension is missing\n";
    exit(2);
}
if (!is_array($filetemplate)) {
    $filetemplate = array_combine(array_keys($names), array_fill(0, count($names), $filetemplate));
}
$data = array();
foreach ($names as $id => $name) {
    $data[$id]['name'] = $name;
    foreach (array('humidity', 'temperature') as $item) {
        $lu = rrd_lastupdate(str_replace(array('{item}', '{id}'), array($item, $id), $filetemplate[$id]));
        if ($lu === false) {
            throw new Exception(rrd_error());
        }
        $data[$id][$item] = reset($lu['data']);
    }
}
foreach (glob(__DIR__ . '/templates/*.php') as $tplfile) {
    $outfile = $outdir . basename($tplfile, '.php');
    ob_start();
    include $tplfile;
    $content = ob_get_contents();
    ob_end_clean();
    file_put_contents($outfile, $content);
}
Ejemplo n.º 17
0
 public function update($arr, $time = false)
 {
     // Mimics the internal methods of the extension
     $ds_names = '';
     $ds_vals = '';
     if (!$time) {
         $time = 'N';
     }
     $ds_count = count($arr);
     foreach ($arr as $k => $v) {
         if (strlen($ds_names) > 0) {
             $ds_names .= ':';
         } else {
             $ds_names .= '--template=';
         }
         $ds_names .= $k;
         if (strlen($ds_vals) == 0) {
             $ds_vals .= $time;
         }
         $ds_vals .= ':';
         $ds_vals .= $v;
     }
     $ret = rrd_update($this->path, array($ds_names, $ds_vals));
     if (!$ret) {
         $this->error = rrd_error();
     }
     return $ret;
 }
Ejemplo n.º 18
0
 /**
  * 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);
 }
Ejemplo n.º 19
0
 public function save()
 {
     $options = ['--start' => $this->getStart()->getTimestamp(), '--step' => $this->getStep()];
     foreach ($this->getDataSources() as $dataSource) {
         $options[] = sprintf('DS:%s', $dataSource);
     }
     foreach ($this->getArchives() as $archive) {
         $options[] = sprintf('RRA:%s', $archive);
     }
     $status = rrd_create($this->getFileName(), $this->convertOptions($options));
     if (!$status) {
         throw new RuntimeException(rrd_error());
     }
 }
Ejemplo n.º 20
0
<?php

#date_default_timezone_set("America/Los_Angeles");
$fname = "/home/pi/temperature.rrd";
$opts = array("-s", "300", "DS:temp:GAUGE:600:U:U", "RRA:MAX:0.5:1:600", "RRA:MAX:0.5:6:700", "RRA:MAX:0.5:24:775", "RRA:MAX:0.5:288:797");
if (file_exists($fname)) {
    $datenow = date('U');
    $temp = exec('sudo python /home/pi/readtemp.py');
    $updatevalue = array($datenow . ":" . $temp);
    $ret = rrd_update($fname, $updatevalue);
    if ($ret == 0) {
        $err = rrd_error();
        echo "ERROR occurred: {$err}\n";
    } else {
        echo "Temperature " . $temp . " logged at " . $datenow;
    }
} else {
    $ret = rrd_create($fname, $opts);
    if ($ret == 0) {
        $err = rrd_error();
        echo "Create error: {$err}\n";
    } else {
        echo "Tempearture database created";
    }
}
?>
  
Ejemplo n.º 21
0
$in = $name[0];
$COMMUNITY = $name[1];
$IP = $name[2];
$PORT = $name[3];
$now = time();
$path = dirname(__FILE__);
$device = "{$COMMUNITY}" . "_" . "{$IP}" . "_" . "{$PORT}";
echo "<br>Graphs for the device with IP {$IP}, COMMUNITY {$COMMUNITY} and PORT {$PORT}<br>";
$a = array("-1d:Daily", "-1w:Weekly", "-1m:Monthly", "-1y:Yearly");
foreach ($a as $x) {
    $b = explode(':', $x);
    $span = $b[0];
    $name = $b[1];
    $rrdgraph = array("--slope-mode", "--start", "{$span}", "--end", $now, "--vertical-label", "Bytes per second");
    $color = str_pad(dechex(mt_rand(0, 0xffffff)), 6, '0', STR_PAD_LEFT);
    array_push($rrdgraph, "DEF:input{$in}={$device}.rrd:input{$in}:AVERAGE", "LINE:input{$in}#{$color}:Input{$in}", "GPRINT:input{$in}:LAST:Current Input = %6.2lf %SBps");
    $color = str_pad(dechex(mt_rand(0, 0xffffff)), 6, '0', STR_PAD_LEFT);
    array_push($rrdgraph, "DEF:output{$in}={$device}.rrd:output{$in}:AVERAGE", "LINE:output{$in}#{$color}:Output{$in}", "GPRINT:output{$in}:LAST:Current Output = %6.2lf %SBps");
    $ret = rrd_graph("{$path}/{$device}{$span}.png", $rrdgraph);
    echo rrd_error();
    echo "<br> {$name} Graph";
    echo "<br><img src='view.php?name={$device}{$span}'/><br>";
}
?>
        </center>
        
        </table>
        </div>
        </body>
</html>        
Ejemplo n.º 22
0
function tool_graphs_build_rrd($fname, $period = 0)
{
    $rrdperiod = '-' . $period;
    $rrdfile = RRD_PATH . $fname;
    $webimage = GFX_PATH . $fname . '_' . $period . '.gif';
    $opts = array("--start", $rrdperiod, "DEF:val=" . $rrdfile . ":var:AVERAGE", "LINE2:val#0000FF");
    $ret = rrd_graph($webimage, $opts, count($opts));
    if (is_array($ret)) {
        return array('status' => true, 'img' => $webimage);
    }
    $err = rrd_error();
    return array('status' => false, 'error' => "Error: rrd_graph() -- {$err}");
}
Ejemplo n.º 23
0
         $recData = array();
         foreach ($values as $bytes) {
             array_push($recData, PhpType::bytes2signedInt($bytes));
         }
     }
     // Get signed integer from INT interpretation
     $t = time();
     $wert1 = array_merge((array) $t, (array) $recData);
     // zeit und daten zusammenfügen
     $wert2 = implode(":", $wert1);
     // ausgabe für rrd vorbereiten
     $wert3 = array($wert2);
     $ret = rrd_update($filename, $wert3);
     // rrd updaten
     if (!$ret) {
         $rrd_error = rrd_error();
         System_Daemon::info('{appName} Graph error %s', $rrd_error);
         //echo "<b>Graph error, </b>".rrd_error()."\n";
     }
 } else {
     // wenn das rrd file noch nicht vorhanden ist neues anlagen
     $options = array("--step", "5", "--start", "-30 days");
     $zaehler = $start + $anzahl;
     //echo("Start: ".$start."Ende: ".$zaehler."");
     for ($i = $start; $i < $zaehler; $i++) {
         // anzahl der trends Name ist aus Datenbanck IWx
         array_push($options, "DS:" . $art . $i . ":GAUGE:5:U:U");
     }
     array_push($options, "RRA:AVERAGE:0.5:1:17280");
     array_push($options, "RRA:AVERAGE:0.5:12:86400");
     array_push($options, "RRA:AVERAGE:0.5:720:8760");
Ejemplo n.º 24
0
 private function createRRDFile()
 {
     $options = array("--step", "60", "DS:memoryUsage:GAUGE:600:0:100", "DS:clients:GAUGE:600:0:U", "DS:rootfsUsage:GAUGE:600:0:100", "DS:loadavg:GAUGE:600:0:U", "DS:trafMgmtRxBy:COUNTER:600:0:U", "DS:trafMgmtRxPa:COUNTER:600:0:U", "DS:trafMgmtTxBy:COUNTER:600:0:U", "DS:trafMgmtTxPa:COUNTER:600:0:U", "DS:trafRxBy:COUNTER:600:0:U", "DS:trafRxPa:COUNTER:600:0:U", "DS:trafTxBy:COUNTER:600:0:U", "DS:trafTxPa:COUNTER:600:0:U", "DS:trafForwardBy:COUNTER:600:0:U", "DS:trafForwardPa:COUNTER:600:0:U", "RRA:AVERAGE:0.5:1:10080", "RRA:AVERAGE:0.5:60:8760", "RRA:AVERAGE:0.5:1440:5256");
     $ret = rrd_create($this->getRRDFileName(), $options);
     echo rrd_error();
 }
Ejemplo n.º 25
0
 public function build($action, $settings)
 {
     global $config, $_theme, $argv;
     if (!$settings) {
         error('This theme is not currently installed.');
     }
     $this->boards = explode(' ', $settings['boards']);
     $this->spans = array('hour', 'day', 'week', 'month', 'year');
     // exclude boards from the "combined" graph
     $this->combined_exclude = array();
     if ($action == 'cron') {
         if (!file_exists($settings['path'])) {
             mkdir($settings['path']);
         }
         if (!file_exists($settings['images'])) {
             mkdir($settings['images']);
         }
         foreach ($this->boards as &$board) {
             $file = $settings['path'] . '/' . $board . '.rrd';
             if (!file_exists($file)) {
                 // Create graph
                 if (!rrd_create($file, array('-s 60', 'DS:posts:COUNTER:86400:0:10000', 'RRA:AVERAGE:0:1:60', 'RRA:AVERAGE:0:1:1440', 'RRA:AVERAGE:0:30:10080', 'RRA:AVERAGE:0:120:43829', 'RRA:AVERAGE:0:1440:525948', 'RRA:AVERAGE:0:2880:1051897', 'RRA:MAX:0:1:60', 'RRA:MAX:0:1:1440', 'RRA:MAX:0:30:10080', 'RRA:MAX:0:120:43829', 'RRA:MAX:0:1440:525948', 'RRA:MAX:0:2880:1051897'))) {
                     error('RRDtool failed: ' . htmlentities(rrd_error()));
                 }
             }
             // debug just the graphing (not updating) with the --debug switch
             if (!isset($argv[1]) || $argv[1] != '--debug') {
                 // Update graph
                 $query = query(sprintf("SELECT MAX(`id`) AS `count` FROM `posts_%s`", $board));
                 $count = $query->fetch();
                 $count = $count['count'];
                 if (!rrd_update($file, array('-t', 'posts', 'N:' . $count))) {
                     error('RRDtool failed: ' . htmlentities(rrd_error()));
                 }
             }
             foreach ($this->spans as &$span) {
                 // Graph graph
                 if (!rrd_graph($settings['images'] . '/' . $board . '-' . $span . '.png', array('-s -1' . $span, '-t Posts on ' . sprintf($config['board_abbreviation'], $board) . ' this ' . $span, '--lazy', '-l 0', '-h', $settings['height'], '-w', $settings['width'], '-a', 'PNG', '-R', 'mono', '-W', 'Powered by Tinyboard', '-E', '-X', '0', '-Y', '-v posts/' . $settings['rate'], 'DEF:posts-second=' . $file . ':posts:AVERAGE', 'CDEF:posts-minute=posts-second,60,*', 'CDEF:posts-hour=posts-minute,60,*', 'CDEF:posts-day=posts-hour,24,*', 'CDEF:posts-week=posts-day,7,*', 'CDEF:posts-month=posts-day,28,*', 'CDEF:posts-year=posts-day,365,*', 'DEF:posts=' . $file . ':posts:AVERAGE', 'LINE2:posts-' . $settings['rate'] . '#663300:Posts', 'GPRINT:posts-' . $settings['rate'] . ':MAX:Max\\: %5.2lf', 'GPRINT:posts-' . $settings['rate'] . ':AVERAGE:Average\\: %5.2lf', 'GPRINT:posts-' . $settings['rate'] . ':LAST:Current\\: %5.2lf posts/' . $settings['rate'], 'HRULE:0#000000'))) {
                     error('RRDtool failed: ' . htmlentities(rrd_error()));
                 }
             }
         }
         // combined graph
         foreach ($this->spans as &$span) {
             $options = array('-s -1' . $span, '-t Posts this ' . $span, '--lazy', '-l 0', '-h', $settings['height'], '-w', $settings['width'], '-a', 'PNG', '-R', 'mono', '-W', 'Powered by Tinyboard', '-E', '-X', '0', '-Y', '-v posts/' . $settings['rate']);
             $red = 0;
             $green = 0;
             $blue = 0;
             $c = 0;
             $cc = 0;
             $c = 1;
             $cc = 0;
             $red = 2;
             foreach ($this->boards as &$board) {
                 if (in_array($board, $this->combined_exclude)) {
                     continue;
                 }
                 $color = str_pad(dechex($red * 85), 2, '0', STR_PAD_LEFT) . str_pad(dechex($green * 85), 2, '0', STR_PAD_LEFT) . str_pad(dechex($blue * 85), 2, '0', STR_PAD_LEFT);
                 $options[] = 'DEF:posts' . $board . '-second=' . $settings['path'] . '/' . $board . '.rrd' . ':posts:AVERAGE';
                 $options[] = 'CDEF:posts' . $board . '-minute=posts' . $board . '-second,60,*';
                 $options[] = 'CDEF:posts' . $board . '-hour=posts' . $board . '-minute,60,*';
                 $options[] = 'CDEF:posts' . $board . '-day=posts' . $board . '-hour,24,*';
                 $options[] = 'CDEF:posts' . $board . '-week=posts' . $board . '-day,7,*';
                 $options[] = 'CDEF:posts' . $board . '-month=posts' . $board . '-day,28,*';
                 $options[] = 'CDEF:posts' . $board . '-year=posts' . $board . '-day,365,*';
                 $options[] = 'LINE2:posts' . $board . '-' . $settings['rate'] . '#' . $color . ':' . sprintf($config['board_abbreviation'], $board);
                 // Randomize colors using this horrible undocumented algorithm I threw together while debugging
                 if ($c == 0) {
                     $red++;
                 } elseif ($c == 1) {
                     $green++;
                 } elseif ($c == 2) {
                     $blue++;
                 } elseif ($c == 3) {
                     $green--;
                 } elseif ($c == 4) {
                     $red--;
                 }
                 $cc++;
                 if ($cc > 2) {
                     $c++;
                     $cc = 0;
                 }
                 if ($c > 4) {
                     $c = 0;
                 }
                 if ($red > 3) {
                     $red = 0;
                 }
                 if ($green > 3) {
                     $green = 0;
                 }
                 if ($blue > 3) {
                     $blue = 0;
                 }
             }
             $options[] = 'HRULE:0#000000';
             if (!rrd_graph($settings['images'] . '/combined-' . $span . '.png', $options)) {
                 error('RRDtool failed: ' . htmlentities(rrd_error()));
             }
         }
     }
 }
Ejemplo n.º 26
0
		/**
		 * Update data in RRD
		 *
		 * @param array $data
		 * @param integer $timestamp UNIX TimeStamp
		 * @return bool
		 */
		function Update($data, $timestamp = "N")
		{
			$arg = "{$timestamp}";
			foreach ($data as $val)
				$arg .= ":{$val}";
			
			if(rrd_update($this->DBPath, $arg))
				return true;
			else 
				Core::RaiseError(_("Cannot update RRD: ".rrd_error()));
		}
Ejemplo n.º 27
0
//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();
include 'includes/top.inc';
print_Head($sunrise, $sunset, $data['temperature']);
?>
<script type="text/javascript">
 function changeImage(element) {
   document.getElementById('imageReplace').src = element; 
 }
</script>

<script type="text/javascript">
 function changeImage2(element) {
   document.getElementById('imageReplace2').src = element; 
 }
</script>