Пример #1
0
     $error_rate = isset($error_codes[$error_db['error_code']]['rate']) && $error_codes[$error_db['error_code']]['rate'] < $error_db['error_rate'];
     if ($error_both) {
         $error_exceeded = $error_count && $error_rate;
     } else {
         $error_exceeded = $error_count || $error_rate;
     }
     if ($error_exceeded) {
         $error_class = 'danger';
         $error_class2 = 'error';
     } else {
         $error_class = $error_class2 = 'warning';
     }
     $text_class = count(explode(' ', $error_db['oid'])) > 3 ? '' : 'text-nowrap';
     echo '<tr width="100%" class="' . $error_class2 . '"><td style="width: 50%;" class="' . $text_class . '"><strong><i class="glyphicon glyphicon-exclamation-sign"></i>&nbsp;' . $error_db['oid'] . '</strong></td>' . PHP_EOL;
     $timediff = $GLOBALS['config']['time']['now'] - $error_db['updated'];
     echo '<td style="width: 100px; white-space: nowrap; text-align: right;">' . generate_tooltip_link('', formatUptime($timediff, "short-3") . ' ago', format_unixtime($error_db['updated'])) . '</td>' . PHP_EOL;
     echo '<td style="width: 80px; white-space: nowrap;"><span class="text-' . $error_class . '">' . $error_codes[$error_db['error_code']]['reason'] . '</span></td>' . PHP_EOL;
     echo '<td style="width: 40px; text-align: right;"><span class="label">' . $error_db['error_count'] . '</span></td>' . PHP_EOL;
     echo '<td style="width: 80px; text-align: right;"><span class="label">' . round($error_db['error_rate'], 2) . '/poll</span></td>' . PHP_EOL;
     echo '<td>' . PHP_EOL;
     $form = array('type' => 'simple');
     // Elements
     $form['row'][0]['mib'] = array('type' => 'hidden', 'value' => $mib);
     $form['row'][0]['toggle_oid'] = array('type' => 'hidden', 'value' => $error_db['oid']);
     $form['row'][0]['submit'] = array('type' => 'submit', 'name' => '', 'class' => 'btn-mini btn-' . $error_class, 'icon' => $btn_icon, 'right' => TRUE, 'readonly' => $readonly, 'disabled' => TRUE, 'value' => 'toggle_oid');
     print_form($form);
     unset($form);
     echo '</td>' . PHP_EOL;
     echo '</td></tr>' . PHP_EOL;
 }
 echo '  </table>
Пример #2
0
 /**
  * @dataProvider providerFormatUnixtime
  */
 public function testFormatUnixtime($value, $format, $result)
 {
     // override local timezone settings or these tests may fail
     date_default_timezone_set('UTC');
     $this->assertSame($result, format_unixtime($value, $format));
 }
Пример #3
0
        }
        if (count($m_disabled)) {
            print_message('Disabled poller modules:');
            print_message('  ' . implode("\n  ", $m_disabled));
        }
        exit;
    }
}
if (!isset($options['q'])) {
    print_cli_banner();
    $latest['version'] = get_obs_attrib('latest_ver');
    $latest['revision'] = get_obs_attrib('latest_rev');
    $latest['date'] = get_obs_attrib('latest_rev_date');
    if ($latest['revision'] > OBSERVIUM_REV) {
        print_message("%GThere is a newer revision of Observium available!%n", 'color');
        print_message("%GVersion %r" . $latest['version'] . "%G (" . format_unixtime(datetime_to_unixtime($latest['date']), 'jS F Y') . ") is %r" . ($latest['revision'] - OBSERVIUM_REV) . "%G revisions ahead.%n\n", 'color');
    }
    //  print_message("%g".OBSERVIUM_PRODUCT." ".OBSERVIUM_VERSION."\n%WPoller%n\n", 'color');
    if (OBS_DEBUG) {
        print_versions();
    }
}
if ($options['h'] == "odd") {
    $options['n'] = "1";
    $options['i'] = "2";
} elseif ($options['h'] == "even") {
    $options['n'] = "0";
    $options['i'] = "2";
} elseif ($options['h'] == "all") {
    $where = " ";
    $doing = "all";
Пример #4
0
function poll_status($device)
{
    global $config, $agent_sensors, $ipmi_sensors, $graphs, $oid_cache;
    $sql = "SELECT * FROM `status`";
    $sql .= " LEFT JOIN `status-state` USING(`status_id`)";
    $sql .= " WHERE `device_id` = ?";
    foreach (dbFetchRows($sql, array($device['device_id'])) as $status_db) {
        //print_cli_heading("Status: ".$status_db['status_descr']. "(".$status_db['poller_type'].")", 3);
        print_debug("Checking (" . $status_db['poller_type'] . ") " . $status_db['status_descr'] . " ");
        // $status_poll = $status_db;    // Cache non-humanized status array for use as new status state
        if ($status_db['poller_type'] == "snmp") {
            // Check if a specific poller file exists for this status, else collect via SNMP.
            $file = $config['install_dir'] . "/includes/polling/status/" . $status_db['status_type'] . ".inc.php";
            if (is_file($file)) {
                include $file;
            } else {
                // Take value from $oid_cache if we have it, else snmp_get it
                if (is_numeric($oid_cache[$status_db['status_oid']])) {
                    print_debug("value taken from oid_cache");
                    $status_value = $oid_cache[$status_db['status_oid']];
                } else {
                    $status_value = snmp_get($device, $status_db['status_oid'], "-OUqnv", "SNMPv2-MIB");
                }
                $status_value = snmp_fix_numeric($status_value);
            }
        } else {
            if ($status_db['poller_type'] == "agent") {
                if (isset($agent_sensors['state'])) {
                    $status_value = $agent_sensors['state'][$status_db['status_type']][$status_db['status_index']]['current'];
                } else {
                    print_warning("No agent status data available.");
                    continue;
                }
            } else {
                if ($status_db['poller_type'] == "ipmi") {
                    if (isset($ipmi_sensors['state'])) {
                        $status_value = $ipmi_sensors['state'][$status_db['status_type']][$status_db['status_index']]['current'];
                    } else {
                        print_warning("No IPMI status data available.");
                        continue;
                    }
                } else {
                    print_warning("Unknown status poller type.");
                    continue;
                }
            }
        }
        $status_polled_time = time();
        // Store polled time for current status
        // Write new value and humanize (for alert checks)
        $state_array = get_state_array($status_db['status_type'], $status_value, $status_db['poller_type']);
        $status_poll['status_value'] = $state_array['value'];
        $status_poll['status_name'] = $state_array['name'];
        if ($status_db['status_ignore'] || $status_db['status_disable']) {
            $status_poll['status_event'] = 'ignore';
        } else {
            $status_poll['status_event'] = $state_array['event'];
        }
        // If last change never set, use current time
        if (empty($status_db['status_last_change'])) {
            $status_db['status_last_change'] = $status_polled_time;
        }
        if ($status_poll['status_event'] != $status_db['status_event']) {
            // Status event changed, log and set status_last_change
            $status_poll['status_last_change'] = $status_polled_time;
            if ($status_poll['status_event'] == 'ignore') {
                print_message("[%ystatus Ignored%n]", 'color');
            } else {
                if ($status_db['status_event'] != '') {
                    // If old state not empty and new state not equals to new state
                    $msg = 'Status ';
                    switch ($status_poll['status_event']) {
                        case 'alert':
                            // New state alerted
                            $msg .= "Alert: " . $device['hostname'] . " " . $status_db['status_descr'] . " entered ALERT state: " . $status_poll['status_name'] . " (previous: " . $status_db['status_name'] . ")";
                            log_event($msg, $device, 'status', $status_db['status_id'], 'warning');
                            break;
                        case 'warning':
                            // New state warned
                            $msg .= "Warning: " . $device['hostname'] . " " . $status_db['status_descr'] . " entered WARNING state: " . $status_poll['status_name'] . " (previous: " . $status_db['status_name'] . ")";
                            log_event($msg, $device, 'status', $status_db['status_id']);
                            break;
                        case 'ok':
                            // New state ok
                            $msg .= "Ok: " . $device['hostname'] . " " . $status_db['status_descr'] . " entered OK state: " . $status_poll['status_name'] . " (previous: " . $status_db['status_name'] . ")";
                            log_event($msg, $device, 'status', $status_db['status_id'], 'warning');
                            break;
                    }
                }
            }
        } else {
            // If status not changed, leave old last_change
            $status_poll['status_last_change'] = $status_db['status_last_change'];
        }
        if (OBS_DEBUG > 1) {
            print_vars($status_poll);
        }
        // Send statistics array via AMQP/JSON if AMQP is enabled globally and for the ports module
        if ($config['amqp']['enable'] == TRUE && $config['amqp']['modules']['status']) {
            $json_data = array('value' => $status_value);
            messagebus_send(array('attribs' => array('t' => time(), 'device' => $device['hostname'], 'device_id' => $device['device_id'], 'e_type' => 'status', 'e_type' => $status_db['status_type'], 'e_index' => $status_db['status_index']), 'data' => $json_data));
        }
        // Update StatsD/Carbon
        if ($config['statsd']['enable'] == TRUE) {
            StatsD::gauge(str_replace(".", "_", $device['hostname']) . '.' . 'status' . '.' . $status_db['status_class'] . '.' . $status_db['status_type'] . '.' . $status_db['status_index'], $status_value);
        }
        // Update RRD - FIXME - can't convert to NG because filename is dynamic! new function should return index instead of filename.
        $rrd_file = get_status_rrd($device, $status_db);
        rrdtool_create($device, $rrd_file, "DS:status:GAUGE:600:-20000:U");
        rrdtool_update($device, $rrd_file, "N:{$status_value}");
        // Enable graph
        $graphs[$sensor_db['status']] = TRUE;
        // Check alerts
        $metrics = array();
        $metrics['status_value'] = $status_value;
        $metrics['status_name'] = $status_poll['status_name'];
        $metrics['status_name_uptime'] = $status_polled_time - $status_poll['status_last_change'];
        $metrics['status_event'] = $status_poll['status_event'];
        //print_cli_data("Event (State)", $status_poll['status_event'] ." (".$status_poll['status_name'].")", 3);
        $GLOBALS['table_rows'][] = array($status_db['status_descr'], $status_db['status_type'], $status_db['status_index'], $status_db['poller_type'], $status_poll['status_name'], $status_poll['status_event'], format_unixtime($status_poll['status_last_change']));
        check_entity('status', $status_db, $metrics);
        // Update SQL State
        if (is_numeric($status_db['status_polled'])) {
            dbUpdate(array('status_value' => $status_value, 'status_name' => $status_poll['status_name'], 'status_event' => $status_poll['status_event'], 'status_last_change' => $status_poll['status_last_change'], 'status_polled' => $status_polled_time), 'status-state', '`status_id` = ?', array($status_db['status_id']));
        } else {
            dbInsert(array('status_id' => $status_db['status_id'], 'status_value' => $status_value, 'status_name' => $status_poll['status_name'], 'status_event' => $status_poll['status_event'], 'status_last_change' => $status_poll['status_last_change'], 'status_polled' => $status_polled_time), 'status-state');
        }
    }
}
Пример #5
0
            if ($config['housekeeping']['rrd']['invalid'] && file_exists($file)) {
                if (!file_exists($config['file'])) {
                    print_debug("Magic 'file' binary not found in configured path!");
                } else {
                    $filetype = $this_data = trim(external_exec($config['file'] . " -b " . $file));
                    if (substr($filetype, 0, 10) != "RRDTool DB") {
                        print_debug("Invalid file type for {$file} ({$filetype}) - deleting");
                        logfile("housekeeping.log", "File {$file} has invalid type: {$filetype} - deleting");
                        unlink($file);
                        $count_notvalid++;
                    }
                }
            }
        }
    }
    if ($prompt && $cutoff) {
        if ($count_notmodified) {
            print_message("Deleted {$count_notmodified} not modified RRD files older than " . format_unixtime($cutoff));
        } else {
            print_message("No RRD files found last modified before " . format_unixtime($cutoff));
        }
    }
    if ($prompt && $config['housekeeping']['rrd']['invalid']) {
        if ($count_notvalid) {
            print_message("Deleted {$count_notvalid} invalid RRD files");
        } else {
            print_message("No invalid RRD files found");
        }
    }
}
// EOF
Пример #6
0
function generate_status_row($status, $vars)
{
    global $config;
    $table_cols = 7;
    humanize_status($status);
    $alert = $status['state_event'] == 'alert' ? 'oicon-exclamation-red' : '';
    // FIXME - make this "four graphs in popup" a function/include and "small graph" a function.
    // FIXME - DUPLICATED IN device/overview/status
    $graph_array = array();
    $graph_array['to'] = $config['time']['now'];
    $graph_array['id'] = $status['status_id'];
    $graph_array['type'] = "status_graph";
    $graph_array['legend'] = "no";
    $graph_array['width'] = 80;
    $graph_array['height'] = 20;
    $graph_array['bg'] = 'ffffff00';
    $graph_array['from'] = $config['time']['day'];
    $status_misc = '<span class="label">' . $status['entPhysicalClass'] . '</span>';
    $row .= '<tr class="' . $status['row_class'] . '">
        <td class="state-marker"></td>';
    if ($vars['page'] != "device" && $vars['popup'] != TRUE) {
        $row .= '<td class="entity">' . generate_device_link($status) . '</td>';
        $table_cols++;
    }
    if ($status['status_event'] && $status['status_name']) {
        $mini_graph = generate_graph_tag($graph_array);
    } else {
        // Do not show "Draw Error" minigraph
        $mini_graph = '';
    }
    $row .= '<td class="entity">' . generate_entity_link('status', $status) . '</td>';
    if ($vars['tab'] != "overview") {
        $row .= '<td><span class="label">' . $status['entPhysicalClass'] . '</span></td>';
        $table_cols++;
    }
    $row .= '<td style="width: 90px; text-align: right;">' . generate_entity_link('status', $status, $mini_graph, NULL, FALSE) . '</td>';
    if ($vars['tab'] != "overview") {
        $row .= '<td style="white-space: nowrap">' . generate_tooltip_link(NULL, formatUptime($config['time']['now'] - $status['status_last_change'], 'short-2') . ' ago', format_unixtime($status['status_last_change'])) . '</td>
        <td style="text-align: right;"><strong><span class="' . $status['state_class'] . '">' . $status['status_event'] . '</span></strong></td>';
        $table_cols++;
        $table_cols++;
    }
    $row .= '<td style="width: 80px; text-align: right;"><strong><span class="' . $status['state_class'] . '">' . $status['status_name'] . '</span></strong></td>
        </tr>' . PHP_EOL;
    if ($vars['view'] == "graphs") {
        $vars['graph'] = "status";
    }
    if ($vars['graph'] || $vars['id'] == $status['status_id']) {
        // If id set in vars, display only specific graphs
        $row .= '<tr class="' . $status['row_class'] . '">
      <td class="state-marker"></td>
      <td colspan="' . $table_cols . '">';
        unset($graph_array['height'], $graph_array['width'], $graph_array['legend']);
        $graph_array['to'] = $config['time']['now'];
        $graph_array['id'] = $status['status_id'];
        $graph_array['type'] = "status_graph";
        $row .= generate_graph_row($graph_array, TRUE);
        $row .= '</td></tr>';
    }
    # endif graphs
    return $row;
}
Пример #7
0
$data = snmp_get_multi($device, $oids, "-OQUst", "SNMPv2-MIB:CISCO-CONFIG-MAN-MIB", mib_dirs(array("cisco")));
$config_age = $data[0];
foreach ($config_age as $key => $val) {
    $config_age[$key] = $val / 100;
}
$RunningLastChanged = $config_age['sysUpTime'] - $config_age['ccmHistoryRunningLastChanged'];
$RunningLastChangedTS = time() - $RunningLastChanged;
$RunningLastSaved = $config_age['sysUpTime'] - $config_age['ccmHistoryRunningLastSaved'];
$RunningLastSavedTS = time() - $RunningLastSaved;
$StartupLastChanged = $config_age['sysUpTime'] - $config_age['ccmHistoryStartupLastChanged'];
$StartupLastChangedTS = time() - $StartupLastChanged;
$sysUptimeTS = time() - $config_age['sysUpTime'];
echo 'sysUptime : ' . format_unixtime($sysUptimeTS) . ' | ' . formatUptime($config_age['sysUpTime']) . PHP_EOL;
echo 'Running   : ' . format_unixtime($RunningLastChangedTS) . ' | ' . formatUptime($RunningLastChanged) . PHP_EOL;
echo 'Saved     : ' . format_unixtime($RunningLastSavedTS) . ' | ' . formatUptime($RunningLastSaved) . PHP_EOL;
echo 'Startup   : ' . format_unixtime($StartupLastChangedTS) . ' | ' . formatUptime($StartupLastChanged) . PHP_EOL;
# 7200 and IOS-XE (ASR1k)
if (preg_match('/^Cisco IOS Software, .+? Software \\([^\\-]+-([^\\-]+)-\\w\\),.+?Version ([^, ]+)/', $poll_device['sysDescr'], $regexp_result)) {
    $features = $regexp_result[1];
    $version = $regexp_result[2];
} elseif (preg_match('/Cisco Internetwork Operating System Software\\s+IOS \\(tm\\) [^ ]+ Software \\([^\\-]+-([^\\-]+)-\\w\\),.+?Version ([^, ]+)/', $poll_device['sysDescr'], $regexp_result)) {
    $features = $regexp_result[1];
    $version = $regexp_result[2];
} elseif (is_array($entPhysical)) {
    if ($entPhysical['entPhysicalContainedIn'] === '0') {
        if (!empty($entPhysical['entPhysicalSoftwareRev'])) {
            $version = $entPhysical['entPhysicalSoftwareRev'];
        }
        if (!empty($entPhysical['entPhysicalModelName'])) {
            $hardware = $entPhysical['entPhysicalModelName'];
        } else {
Пример #8
0
function generate_sensor_row($sensor, $vars)
{
    global $config;
    humanize_sensor($sensor);
    $table_cols = 4;
    $graph_array = array();
    $graph_array['to'] = $config['time']['now'];
    $graph_array['id'] = $sensor['sensor_id'];
    $graph_array['type'] = "sensor_graph";
    $graph_array['width'] = 80;
    $graph_array['height'] = 20;
    $graph_array['bg'] = 'ffffff00';
    $graph_array['from'] = $config['time']['day'];
    if ($sensor['sensor_event'] && is_numeric($sensor['sensor_value'])) {
        $mini_graph = generate_graph_tag($graph_array);
    } else {
        // Do not show "Draw Error" minigraph
        $mini_graph = '';
    }
    $row = '
      <tr class="' . $sensor['row_class'] . '">
        <td class="state-marker"></td>';
    if ($vars['page'] != "device" && $vars['popup'] != TRUE) {
        $row .= '        <td class="entity">' . generate_device_link($sensor) . '</td>' . PHP_EOL;
        $table_cols++;
    }
    if ($vars['entity_icon'] == TRUE) {
        $row .= '        <td width="20px"><i class="' . $config['sensor_types'][$sensor['sensor_class']]['icon'] . '"></i></td>';
    }
    $row .= '        <td class="entity">' . generate_entity_link("sensor", $sensor) . '</td>';
    if ($vars['show_class']) {
        $row .= '        <td>' . nicecase($sensor['sensor_class']) . '</td>' . PHP_EOL;
        $table_cols++;
    }
    if ($vars['tab'] != 'overview') {
        $row .= '        <td><span class="label ' . ($sensor['sensor_custom_limit'] ? 'label-warning' : '') . '">' . $sensor['sensor_thresholds'] . '</span></td>' . PHP_EOL;
        $table_cols++;
    }
    $row .= '        <td style="width: 90px; text-align: right;">' . generate_entity_link('sensor', $sensor, $mini_graph, NULL, FALSE) . '</td>';
    if ($vars['tab'] != 'overview') {
        $row .= '        <td style="white-space: nowrap">' . generate_tooltip_link(NULL, formatUptime($config['time']['now'] - $sensor['sensor_last_change'], 'short-2') . ' ago', format_unixtime($sensor['sensor_last_change'])) . '</td>';
        $table_cols++;
        $row .= '        <td style="text-align: right;"><strong><span class="' . $sensor['state_class'] . '">' . $sensor['sensor_event'] . '</span></strong></td>';
        $table_cols++;
    }
    $row .= '        <td style="width: 80px; text-align: right;"><strong><span class="' . $sensor['state_class'] . '">' . $sensor['human_value'] . $sensor['sensor_symbol'] . '</span></strong>
        </tr>' . PHP_EOL;
    if ($vars['view'] == "graphs" || $vars['id'] == $sensor['sensor_id']) {
        $vars['graph'] = "graph";
    }
    if ($vars['graph']) {
        $row .= '
      <tr class="' . $sensor['row_class'] . '">
        <td class="state-marker"></td>
        <td colspan="' . $table_cols . '">';
        $graph_array = array();
        $graph_array['to'] = $config['time']['now'];
        $graph_array['id'] = $sensor['sensor_id'];
        $graph_array['type'] = 'sensor_' . $vars['graph'];
        $row .= generate_graph_row($graph_array, TRUE);
        $row .= '</td></tr>';
    }
    # endif graphs
    return $row;
}
Пример #9
0
   foreach (json_decode($tunnel['tunnel_endpoint'], TRUE) as $entry) {
       $tunnel_endpoint[] = 'Local: ' . generate_popup_link('ip', $entry['local']) . ', Remote: ' . generate_popup_link('ip', $entry['remote']);
   }
   $tunnel_endpoint = implode('<br />', $tunnel_endpoint);
   $timediff = $GLOBALS['config']['time']['now'] - $tunnel['tunnel_added'];
   echo '<tr class="' . $tunnel['row_class'] . '">
 <td class="state-marker"></td>
 <td>' . generate_popup_link('ip', $tunnel['local_addr']) . '</td>
 <td><b>&#187;</b></td>
 <td>' . generate_popup_link('ip', $tunnel['peer_addr']) . '</td>
 <td>' . $tunnel['tunnel_name'] . '</td>
 <td><span>' . $tunnel_endpoint . '</span></td>
 <td><span>' . generate_tooltip_link(NULL, formatUptime($tunnel['tunnel_lifetime'], 'short-3'), $tunnel['tunnel_lifetime'] . ' sec') . '</span></td>
 <td><span class="label ' . $tunnel['ike_label_class'] . '">' . $tunnel['tunnel_ike_alive'] . '</span></td>
 <td><span>' . generate_tooltip_link(NULL, formatUptime($tunnel['tunnel_ike_lifetime'], 'short-3'), $tunnel['tunnel_ike_lifetime'] . ' sec') . '</span></td>
 <td><span>' . generate_tooltip_link(NULL, formatUptime($timediff, "short-3") . ' ago', format_unixtime($tunnel['tunnel_added'])) . '</span></td>
 </tr>';
   switch ($vars['graph']) {
       case 'bits':
       case 'pkts':
           $graph_array['type'] = 'ipsectunnel_' . $vars['graph'];
           $graph_array['id'] = $tunnel['tunnel_id'];
   }
   if ($vars['graph'] == 'bits' || $vars['graph'] == 'pkts') {
       $tunnel['graph'] = 1;
   }
   if ($tunnel['graph']) {
       $graph_array['to'] = $config['time']['now'];
       echo '<tr class="' . $tunnel['row_class'] . '">';
       echo '<td colspan="10">';
       print_graph_row($graph_array);
Пример #10
0
function get_http_request($request, $context = array(), $rate_limit = FALSE)
{
    global $config;
    $ok = TRUE;
    if (defined('OBS_HTTP_REQUEST') && OBS_HTTP_REQUEST === FALSE) {
        print_debug("HTTP requests skipped since previous request exit with timeout");
        $ok = FALSE;
        $GLOBALS['response_headers'] = array('code' => '408', 'status' => 'Request Timeout');
    } else {
        if (!ini_get('allow_url_fopen')) {
            print_debug('HTTP requests disabled, since PHP config option "allow_url_fopen" set to off. Please enable this option in your PHP config.');
            $ok = FALSE;
            $GLOBALS['response_headers'] = array('code' => '501', 'status' => 'Not Implemented');
        } else {
            if (preg_match('/^https/i', $request) && !check_extension_exists('openssl')) {
                // Check if Secure requests allowed, but ssl extensin not exist
                print_debug(__FUNCTION__ . '() wants to connect with https but https is not enabled on this server. Please check your PHP settings, the openssl extension must exist and be enabled.');
                logfile(__FUNCTION__ . '() wants to connect with https but https is not enabled on this server. Please check your PHP settings, the openssl extension must exist and be enabled.');
                $ok = FALSE;
                $GLOBALS['response_headers'] = array('code' => '501', 'status' => 'HTTPS Method Not Implemented');
            }
        }
    }
    if ($ok && $rate_limit && is_numeric($rate_limit) && $rate_limit >= 0) {
        // Check limit rates to this domain (per/day)
        if (preg_match('/^https?:\\/\\/([\\w\\.]+[\\w\\-\\.]*(:\\d+)?)/i', $request, $matches)) {
            $date = format_unixtime($config['time']['now'], 'Y-m-d');
            $domain = $matches[0];
            // base domain (with http(s)): https://test-me.com/ -> https://test-me.com
            $rate_db = json_decode(get_obs_attrib('http_rate_' . $domain), TRUE);
            //print_vars($date); print_vars($rate_db);
            if (is_array($rate_db) && isset($rate_db[$date])) {
                $rate_count = $rate_db[$date];
            } else {
                $rate_count = 0;
            }
            $rate_count++;
            set_obs_attrib('http_rate_' . $domain, json_encode(array($date => $rate_count)));
            if ($rate_count > $rate_limit) {
                print_debug("HTTP requests skipped because the rate limit {$rate_limit}/day for domain '{$domain}' is exceeded (count: {$rate_count})");
                $GLOBALS['response_headers'] = array('code' => '429', 'status' => 'Too Many Requests');
                $ok = FALSE;
            } else {
                if (OBS_DEBUG > 1) {
                    print_debug("HTTP rate count for domain '{$domain}': {$rate_count} ({$rate_limit}/day)");
                }
            }
        } else {
            $rate_limit = FALSE;
        }
    }
    if (OBS_DEBUG > 0) {
        $debug_request = $request;
        if (OBS_DEBUG < 2 && strpos($request, 'update.observium.org')) {
            $debug_request = preg_replace('/&stats=.+/', '&stats=***', $debug_request);
        }
        $debug_msg = PHP_EOL . 'REQUEST[%y' . $debug_request . '%n]';
    }
    if (!$ok) {
        if (OBS_DEBUG > 0) {
            print_message($debug_msg . PHP_EOL . 'REQUEST STATUS[' . $GLOBALS['response_headers']['code'] . ' ' . $GLOBALS['response_headers']['status'] . ']', 'console');
        }
        return FALSE;
    }
    $response = '';
    if (!is_array($context)) {
        $context = array();
    }
    // Fix context if not array passed
    $opts = array('http' => $context);
    $opts['http']['timeout'] = '15';
    // User agent (required for some type of queries, ie geocoding)
    if (!isset($opts['http']['header'])) {
        $opts['http']['header'] = '';
    }
    // Avoid 'undefined index' when concatting below
    $opts['http']['header'] .= 'User-Agent: ' . OBSERVIUM_PRODUCT . '/' . OBSERVIUM_VERSION . '\\r\\n';
    if (isset($config['http_proxy']) && $config['http_proxy']) {
        $opts['http']['proxy'] = 'tcp://' . $config['http_proxy'];
        $opts['http']['request_fulluri'] = TRUE;
    }
    // Basic proxy auth
    if (isset($config['proxy_user']) && $config['proxy_user'] && isset($config['proxy_password'])) {
        $auth = base64_encode($config['proxy_user'] . ':' . $config['proxy_password']);
        $opts['http']['header'] .= 'Proxy-Authorization: Basic ' . $auth . '\\r\\n';
    }
    $start = utime();
    $context = stream_context_create($opts);
    $response = file_get_contents($request, FALSE, $context);
    $runtime = utime() - $start;
    // Parse response headers
    $head = array();
    foreach ($http_response_header as $k => $v) {
        $t = explode(':', $v, 2);
        if (isset($t[1])) {
            $head[trim($t[0])] = trim($t[1]);
        } else {
            if (preg_match("!HTTP/([\\d\\.]+)\\s+(\\d+)(.*)!", $v, $matches)) {
                $head['http'] = $matches[1];
                $head['code'] = intval($matches[2]);
                $head['status'] = trim($matches[3]);
            } else {
                $head[] = $v;
            }
        }
    }
    $GLOBALS['response_headers'] = $head;
    if (OBS_DEBUG > 0) {
        if (OBS_DEBUG < 2 && strpos($request, 'update.observium.org')) {
            $request = preg_replace('/&stats=.+/', '&stats=***', $request);
        }
        print_message($debug_msg . PHP_EOL . 'REQUEST STATUS[' . $head['code'] . ' ' . $head['status'] . ']' . PHP_EOL . 'REQUEST RUNTIME[' . ($runtime > 3 ? '%r' : '%g') . round($runtime, 4) . 's%n]', 'console');
        if (OBS_DEBUG > 1) {
            print_message("RESPONSE[\n" . $response . "\n]", 'console', FALSE);
            print_vars($http_response_header);
            print_vars($opts);
        }
    }
    // Set OBS_HTTP_REQUEST for skip all other requests
    if (!defined('OBS_HTTP_REQUEST')) {
        if ($response === FALSE && empty($http_response_header)) {
            $GLOBALS['response_headers'] = array('code' => '408', 'status' => 'Request Timeout');
            // Timeout error, only if not received responce headers
            define('OBS_HTTP_REQUEST', FALSE);
            print_debug(__FUNCTION__ . '() exit with timeout. Access to outside localnet is blocked by firewall or network problems. Check proxy settings.');
            logfile(__FUNCTION__ . '() exit with timeout. Access to outside localnet is blocked by firewall or network problems. Check proxy settings.');
        } else {
            define('OBS_HTTP_REQUEST', TRUE);
        }
    }
    // FIXME. what if first request fine, but second broken?
    //else if ($response === FALSE)
    //{
    //  if (function_exists('runkit_constant_redefine')) { runkit_constant_redefine('OBS_HTTP_REQUEST', FALSE); }
    //}
    return $response;
}
Пример #11
0
function generate_pseudowire_row($pw, $vars)
{
    global $config;
    humanize_pseudowire($pw);
    $table_cols = 11;
    $graph_array = array();
    $graph_array['to'] = $config['time']['now'];
    $graph_array['id'] = $pw['pseudowire_id'];
    $graph_array['type'] = $pw['graph'];
    $graph_array['legend'] = "no";
    $graph_array['width'] = 80;
    $graph_array['height'] = 20;
    $graph_array['bg'] = 'ffffff00';
    $graph_array['from'] = $config['time']['day'];
    if ($pw['event'] && $pw['pwOperStatus']) {
        $mini_graph = generate_graph_tag($graph_array);
    } else {
        // Do not show "Draw Error" minigraph
        $mini_graph = '';
    }
    $out = '<tr class="' . $pw['row_class'] . '"><td class="state-marker"></td>';
    $out .= '<td class="entity" style="text-align: right;">' . generate_entity_link('pseudowire', $pw, NULL, NULL, TRUE, TRUE) . '</td>';
    $out .= '<td>' . nicecase($pw['pwType']) . '/' . nicecase($pw['pwPsnType']) . '</td>';
    if ($vars['page'] != "device" && $vars['popup'] != TRUE) {
        $out .= '<td class="entity">' . generate_device_link($pw, NULL, array('tab' => 'pseudowires')) . '</td>';
        $table_cols++;
    }
    $out .= '<td class="entity">' . generate_entity_link('port', $pw['port_id']) . '</td>';
    $out .= '<td><span class="text-success"><i class="glyphicon glyphicon-arrow-right"></i></span></td>';
    if ($pw['peer_port_id']) {
        $out .= '<td class="entity">' . generate_entity_link('device', $pw['peer_device_id']) . '</td>';
        $out .= '<td class="entity">' . generate_entity_link('port', $pw['peer_port_id']) . '</td>';
    } else {
        $out .= '<td class="entity">' . generate_popup_link('ip', $pw['peer_addr']) . '</td>';
        $out .= '<td>' . $pw['pwRemoteIfString'] . '</td>';
    }
    $out .= '<td>' . generate_entity_link('pseudowire', $pw, $mini_graph, NULL, FALSE) . '</td>';
    $out .= '<td style="white-space: nowrap">' . generate_tooltip_link(NULL, formatUptime($config['time']['now'] - $pw['last_change'], 'short-2') . ' ago', format_unixtime($pw['last_change'])) . '</td>';
    $out .= '<td style="text-align: right;"><strong><span class="' . $pw['pw_class'] . '">' . $pw['event'] . '</span></strong></td>';
    $out .= '<td style="text-align: right;"><strong><span class="' . $pw['pw_class'] . '">' . $pw['pwOperStatus'] . '</span></strong></td>';
    $out .= '<td>' . formatUptime($pw['pwUptime'], 'short-2') . '</td>';
    $out .= '</tr>';
    if ($vars['graph'] || $vars['view'] == "graphs" || $vars['id'] == $pw['pseudowire_id']) {
        // If id set in vars, display only specific graphs
        $graph_array = array();
        $graph_array['type'] = $vars['graph'] ? $vars['graph'] : $pw['graph'];
        $graph_array['id'] = $pw['pseudowire_id'];
        $out .= '<tr class="' . $pw['row_class'] . '">';
        $out .= '  <td class="state-marker"></td>';
        $out .= '  <td colspan="' . $table_cols . '">';
        $out .= generate_graph_row($graph_array, TRUE);
        $out .= '  </td>';
        $out .= '</tr>';
    }
    return $out;
}
Пример #12
0
            case "finishtime":
                $perlArgs[] = sprintf($finishArg, $value);
                break;
            case "ipaddress":
                $perlArgs[] = sprintf($IPArg, $value);
                break;
        }
    }
    return sprintf($perlCommand, implode(' && ', $perlArgs));
}
/* Start Page Logic */
if (trim($_GET['acctid']) != '') {
    $session = DatabaseFunctions::getInstance()->getRadiusSessionDetails($_GET['acctid']);
    // Build up components for perl matching command
    $conditions['starttime'] = escapeshellcmd(format_unixtime($session['AcctStartTime']));
    $finishTime = escapeshellcmd(format_unixtime($session['AcctStopTime']));
    if ($finishTime != "0.0.0 0:00:00" && $finishTime != '') {
        $conditions['finishtime'] = $finishTime;
    }
    $conditions['ipaddress'] = escapeshellcmd($session['FramedIPAddress']);
    /* We use a perl command as it's faster and easier to code the
     * matching logic than trying to process the entire log file in PHP */
    $perlCommand = buildPerlCommand($conditions);
    $username = $session['Username'];
    $command = "gunzip -fc /var/log/squid3/access.log*  | {$perlCommand} ";
} else {
    $error = "Invalid Acctid";
    $templateEngine->assign("error", $error);
}
if ($command) {
    $logLines = array();
Пример #13
0
if (is_device_mib($device, 'CISCO-CONFIG-MAN-MIB')) {
    // Check Cisco configuration age
    $oids = 'sysUpTime.0 ccmHistoryRunningLastChanged.0 ccmHistoryRunningLastSaved.0 ccmHistoryStartupLastChanged.0';
    $data = snmp_get_multi($device, $oids, '-OQUst', 'SNMPv2-MIB:CISCO-CONFIG-MAN-MIB');
    $config_age = $data[0];
    foreach ($config_age as $key => $val) {
        $config_age[$key] = $val / 100;
    }
    $RunningLastChanged = $config_age['sysUpTime'] - $config_age['ccmHistoryRunningLastChanged'];
    $RunningLastChangedTS = time() - $RunningLastChanged;
    $RunningLastSaved = $config_age['sysUpTime'] - $config_age['ccmHistoryRunningLastSaved'];
    $RunningLastSavedTS = time() - $RunningLastSaved;
    $StartupLastChanged = $config_age['sysUpTime'] - $config_age['ccmHistoryStartupLastChanged'];
    $StartupLastChangedTS = time() - $StartupLastChanged;
    $sysUptimeTS = time() - $config_age['sysUpTime'];
    $os_additional_info['Cisco configuration ages'] = array('sysUptime' => format_unixtime($sysUptimeTS) . ' | ' . formatUptime($config_age['sysUpTime']), 'Running' => format_unixtime($RunningLastChangedTS) . ' | ' . formatUptime($RunningLastChanged), 'Saved' => format_unixtime($RunningLastSavedTS) . ' | ' . formatUptime($RunningLastSaved), 'Startup' => format_unixtime($StartupLastChangedTS) . ' | ' . formatUptime($StartupLastChanged));
}
$sysDescr = preg_replace('/\\s+/', ' ', $poll_device['sysDescr']);
// Replace all spaces and newline to single space
// Generic IOS/IOS-XE/IES/IOS-XR sysDescr
if (preg_match('/^Cisco IOS Software, .+? Software \\([^\\-]+-([\\w\\d]+)-\\w\\),.+?Version ([^, ]+)/', $sysDescr, $matches)) {
    //Cisco IOS Software, Catalyst 4500 L3 Switch Software (cat4500e-ENTSERVICESK9-M), Version 15.2(1)E3, RELEASE SOFTWARE (fc1) Technical Support: http://www.cisco.com/techsupport Copyright (c) 1986-2014 by Cisco Systems, Inc. Compiled Mon 05-May-14 07:56 b
    //Cisco IOS Software, IOS-XE Software (PPC_LINUX_IOSD-IPBASEK9-M), Version 15.2(2)S, RELEASE SOFTWARE (fc1) Technical Support: http://www.cisco.com/techsupport Copyright (c) 1986-2012 by Cisco Systems, Inc. Compiled Mon 26-Mar-12 15:23 by mcpre
    //Cisco IOS Software, IES Software (IES-LANBASEK9-M), Version 12.2(52)SE1, RELEASE SOFTWARE (fc1) Technical Support: http://www.cisco.com/techsupport Copyright (c) 1986-2010 by Cisco Systems, Inc. Compiled Tue 09-Feb-10 03:17 by prod_rel_team
    $features = $matches[1];
    $version = $matches[2];
} else {
    if (preg_match('/^Cisco Internetwork Operating System Software IOS \\(tm\\) [^ ]+ Software \\([^\\-]+-([\\w\\d]+)-\\w\\),.+?Version ([^, ]+)/', $sysDescr, $matches)) {
        //Cisco Internetwork Operating System Software IOS (tm) 7200 Software (UBR7200-IK8SU2-M), Version 12.3(17b)BC8, RELEASE SOFTWARE (fc1) Technical Support: http://www.cisco.com/techsupport Copyright (c) 1986-2007 by cisco Systems, Inc. Compiled Fri 29-Ju
        //Cisco Internetwork Operating System Software IOS (tm) C1700 Software (C1700-Y-M), Version 12.2(4)YA2, EARLY DEPLOYMENT RELEASE SOFTWARE (fc1) Synched to technology version 12.2(5.4)T TAC Support: http://www.cisco.com/tac Copyright (c) 1986-2002 by ci
        $features = $matches[1];
Пример #14
0
                        if ($geo_db[$k] == $value) {
                            unset($update_geo[$k]);
                        }
                    }
                    if ($update_geo) {
                        dbUpdate($update_geo, 'devices_locations', '`location_id` = ?', array($geo_db['location_id']));
                        if ($geo_msg) {
                            log_event($geo_msg, $device, 'device', $device['device_id']);
                        }
                    }
                    // else not changed
                } else {
                    $update_geo['device_id'] = $device['device_id'];
                    dbInsert($update_geo, 'devices_locations');
                    if ($geo_msg) {
                        log_event($geo_msg, $device, 'device', $device['device_id']);
                    }
                }
            }
        } else {
            if (is_numeric($geo_db['location_id'])) {
                $update_geo = array('location_updated' => format_unixtime($config['time']['now'], 'Y-m-d G:i:s'));
                // Increase updated time
                dbUpdate($update_geo, 'devices_locations', '`location_id` = ?', array($geo_db['location_id']));
            }
        }
        # end if $update_geo
    }
}
unset($geo_detect, $geo_db, $update_geo);
// EOF
Пример #15
0
 * @package    observium
 * @subpackage housekeeping
 * @author     Adam Armstrong <*****@*****.**>
 * @copyright  (C) 2006-2013 Adam Armstrong, (C) 2013-2016 Observium Limited
 *
 */
$cutoff = age_to_unixtime($config['housekeeping']['deleted_ports']['age']);
if ($cutoff) {
    $where = "`deleted` = 1 AND UNIX_TIMESTAMP(`ifLastChange`) < {$cutoff}";
    $ports = dbFetchRows("SELECT `port_id` FROM `ports` WHERE {$where}");
    $count = count($ports);
    if ($count) {
        if ($prompt) {
            $answer = print_prompt("{$count} ports marked as deleted before " . format_unixtime($cutoff) . " will be deleted");
        }
        if ($answer) {
            foreach ($ports as $entry) {
                delete_port($entry['port_id']);
            }
            print_debug("Deleted ports housekeeping: deleted {$count} entries");
            logfile("housekeeping.log", "Deleted ports: deleted {$count} entries older than " . format_unixtime($cutoff));
        }
    } else {
        if ($prompt) {
            print_message("No ports found marked as deleted before " . format_unixtime($cutoff));
        }
    }
} else {
    print_message("Deleted ports housekeeping disabled in configuration.");
}
// EOF
Пример #16
0
    print_error_permission();
    return;
}
?>

<div class="row">
  <div class="col-md-12">

<?php 
$box_args = array('title' => 'Duration', 'header-border' => TRUE, 'padding' => TRUE);
$box_args['header-controls'] = array('controls' => array('perf' => array('text' => 'Performance Data', 'anchor' => TRUE, 'url' => generate_url(array('page' => 'device', 'device' => $device['device_id'], 'tab' => 'perf')))));
echo generate_box_open($box_args);
$ptime = dbFetchRow('SELECT * FROM `devices_perftimes` WHERE `operation` = "poll" AND `device_id` = ? ORDER BY `start` DESC LIMIT 1', array($device['device_id']));
echo "Last Polled: <b>" . format_unixtime($ptime['start']) . '</b> (took ' . $ptime['duration'] . 's) - <a href="' . generate_url(array('page' => 'device', 'device' => $device['device_id'], 'tab' => 'perf')) . '">Details</a>';
$dtime = dbFetchRow('SELECT * FROM `devices_perftimes` WHERE `operation` = "discover" AND `device_id` = ? ORDER BY `start` DESC LIMIT 1', array($device['device_id']));
echo "<p>Last discovered: <b>" . format_unixtime($dtime['start']) . '</b> (took ' . $dtime['duration'] . 's) - <a href="' . generate_url(array('page' => 'device', 'device' => $device['device_id'], 'tab' => 'perf')) . '">Details</a></p>';
echo generate_box_close();
$box_args = array('title' => 'RANCID', 'header-border' => TRUE, 'padding' => TRUE);
$box_args['header-controls'] = array('controls' => array('perf' => array('text' => 'Show Config', 'anchor' => TRUE, 'url' => generate_url(array('page' => 'device', 'device' => $device['device_id'], 'tab' => 'showconfig')))));
echo generate_box_open($box_args);
if (count($config['rancid_configs'])) {
    $device_config_file = get_rancid_filename($device['hostname'], 1);
    echo '<p />';
    if ($device_config_file) {
        print_success("Configuration file for device was found; will be displayed to users with level 7 or higher.");
    } else {
        print_warning("Configuration file for device was not found.");
    }
} else {
    print_warning("No RANCID directories configured.");
}
Пример #17
0
        <div class="title">
          <i class="oicon-blocks"></i> Discovery Times
        </div>
        <div class="content">
          <table class="table table-hover table-striped table-bordered table-condensed table-rounded">
            <thead>
              <tr>
                <th>Time</th>
                <th>Duration</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
<?php 
$times = dbFetchRows('SELECT * FROM `devices_perftimes` WHERE `operation` = "discover" AND `device_id` = ? ORDER BY `start` DESC LIMIT 100', array($device['device_id']));
foreach ($times as $time) {
    echo '    <tr>
      <td>' . format_unixtime($time['start']) . '</td>
      <td>' . $time['duration'] . 's</td>
      <td></td>
    </tr>';
}
?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
<?php 
// EOF
Пример #18
0
## Bypass Frequency
$oid = ".1.3.6.1.2.1.33.1.5.1.0";
# UPS-MIB:upsBypassFrequency.0
$value = snmp_get($device, $oid, "-Oqv");
if (is_numeric($value)) {
    discover_sensor($valid['sensor'], 'frequency', $device, $oid, "upsBypassFrequency", 'ups-mib', "Bypass", $scale, $value);
}
//UPS-MIB::upsTestId.0 = OID: UPS-MIB::upsTestNoTestsInitiated
//UPS-MIB::upsTestSpinLock.0 = INTEGER: 1
//UPS-MIB::upsTestResultsSummary.0 = INTEGER: noTestsInitiated(6)
//UPS-MIB::upsTestResultsDetail.0 = STRING: No test initiated.
//UPS-MIB::upsTestStartTime.0 = Timeticks: (0) 0:00:00.00
//UPS-MIB::upsTestElapsedTime.0 = INTEGER: 0
$ups_array = snmpwalk_cache_multi_oid($device, "upsTest", array(), "UPS-MIB");
if (isset($ups_array[0]['upsTestResultsSummary']) && $ups_array[0]['upsTestResultsSummary'] != 'noTestsInitiated') {
    $descr = "Diagnostics Results";
    $oid = ".1.3.6.1.2.1.33.1.7.3.0";
    $value = $ups_array[0]['upsTestResultsSummary'];
    $test_starttime = timeticks_to_sec($ups_array[0]['upsTestStartTime']);
    if ($test_starttime) {
        $test_sysUpime = timeticks_to_sec(snmp_get($device, "sysUpTime.0", "-OQUs", "SNMPv2-MIB"));
        if ($test_sysUpime) {
            $test_starttime = time() + $test_starttime - $test_sysUpime;
            // Unixtime of start test
            $descr .= ' (last ' . format_unixtime($test_starttime) . ')';
        }
    }
    discover_status($device, $oid, "upsTestResultsSummary.0", 'ups-mib-test-state', $descr, $value, array('entPhysicalClass' => 'other'));
}
unset($ups_array);
// EOF
Пример #19
0
function get_geolocation($address, $geo_db = array(), $dns_only = FALSE)
{
    global $config;
    $ok = FALSE;
    $location = array('location' => $address);
    // Init location array
    $location['location_geoapi'] = strtolower(trim($config['geocoding']['api']));
    if (!isset($config['geo_api'][$location['location_geoapi']])) {
        // Use default if unknown api
        $location['location_geoapi'] = 'openstreetmap';
    }
    $api_params =& $config['geo_api'][$location['location_geoapi']];
    // Link to api specific params
    $params = $api_params['params'];
    // Init base request params
    // GEO API KEY and rate limits
    $ratelimit = FALSE;
    if (strlen($config['geocoding']['api_key']) && isset($api_params['request_params']['key'])) {
        $param = $api_params['request_params']['key'];
        $params[$param] = escape_html($config['geocoding']['api_key']);
        // KEYs is never used special characters
        if (isset($api_params['ratelimit_key'])) {
            $ratelimit = $api_params['ratelimit_key'];
        }
    } else {
        if (isset($api_params['ratelimit'])) {
            $ratelimit = $api_params['ratelimit'];
        }
    }
    if (isset($api_params['request_params']['id'])) {
        $params[$api_params['request_params']['id']] = OBSERVIUM_PRODUCT . '-' . substr(get_unique_id(), 0, 8);
    }
    if (isset($api_params['request_params']['uuid'])) {
        $params[$api_params['request_params']['uuid']] = get_unique_id();
    }
    if (isset($config['geocoding']['enable']) && $config['geocoding']['enable']) {
        $reverse = FALSE;
        // by default forward geocoding
        $debug_msg = "Geocoding ENABLED, try detect device coordinates:" . PHP_EOL;
        // If device coordinates set manually, use Reverse Geocoding.
        if ($geo_db['location_manual']) {
            $location['location_lat'] = $geo_db['location_lat'];
            $location['location_lon'] = $geo_db['location_lon'];
            $reverse = TRUE;
            $debug_msg .= '  MANUAL coordinates - SET' . PHP_EOL;
        } else {
            if ($config['geocoding']['dns']) {
                /**
                 * Ack! dns_get_record not only cannot retrieve LOC records, but it also actively filters them when using
                 * DNS_ANY as query type (which, admittedly would not be all that reliable as per the manual).
                 *
                 * Example LOC:
                 *   "20 31 55.893 N 4 57 38.269 E 45.00m 10m 100m 10m"
                 *
                 * From Wikipedia: d1 [m1 [s1]] {"N"|"S"}  d2 [m2 [s2]] {"E"|"W"}
                 *
                 * Parsing this is something for Net_DNS2 as it has the code for it.
                 */
                if ($geo_db['hostname']) {
                    //include_once('Net/DNS2.php');
                    //include_once('Net/DNS2/RR/LOC.php');
                    $resolver = new Net_DNS2_Resolver();
                    try {
                        $response = $resolver->query($geo_db['hostname'], 'LOC', 'IN');
                    } catch (Net_DNS2_Exception $e) {
                        print_debug('  ' . $e->getMessage() . ' (' . $geo_db['hostname'] . ')');
                    }
                } else {
                    $response = FALSE;
                    print_debug("  DNS LOC enabled, but device hostname empty.");
                }
                if ($response) {
                    if (OBS_DEBUG > 1) {
                        var_dump($response->answer);
                    }
                    foreach ($response->answer as $answer) {
                        if (is_numeric($answer->latitude) && is_numeric($answer->longitude)) {
                            $location['location_lat'] = $answer->latitude;
                            $location['location_lon'] = $answer->longitude;
                            $reverse = TRUE;
                            break;
                        } else {
                            if (is_numeric($answer->degree_latitude) && is_numeric($answer->degree_longitude)) {
                                $ns_multiplier = $answer->ns_hem == 'N' ? 1 : -1;
                                $ew_multiplier = $answer->ew_hem == 'E' ? 1 : -1;
                                $location['location_lat'] = round($answer->degree_latitude + $answer->min_latitude / 60 + $answer->sec_latitude / 3600, 7) * $ns_multiplier;
                                $location['location_lon'] = round($answer->degree_longitude + $answer->min_longitude / 60 + $answer->sec_longitude / 3600, 7) * $ew_multiplier;
                                $reverse = TRUE;
                                break;
                            }
                        }
                    }
                    if (isset($location['location_lat'])) {
                        $debug_msg .= '  DNS LOC records - FOUND' . PHP_EOL;
                    } else {
                        $debug_msg .= '  DNS LOC records - NOT FOUND' . PHP_EOL;
                        if ($dns_only) {
                            // If we check only DNS LOC records but it not found, exit
                            print_debug($debug_msg);
                            return FALSE;
                        }
                    }
                }
            }
        }
        if ($reverse || !preg_match('/^<?(unknown|none)>?$/i', $address)) {
            /**
             * If location string contains coordinates use Reverse Geocoding.
             * Valid strings:
             *   Some location [33.234, -56.22]
             *   Some location (33.234 -56.22)
             *   Some location [33.234;-56.22]
             *   33.234,-56.22
             */
            $pattern = '/(?:^|[\\[(])\\s*(?<lat>[+-]?\\d+(?:\\.\\d+)*)\\s*[,; ]\\s*(?<lon>[+-]?\\d+(?:\\.\\d+)*)\\s*(?:[\\])]|$)/';
            if (!$reverse && preg_match($pattern, $address, $matches)) {
                if ($matches['lat'] >= -90 && $matches['lat'] <= 90 && $matches['lon'] >= -180 && $matches['lon'] <= 180) {
                    $location['location_lat'] = $matches['lat'];
                    $location['location_lon'] = $matches['lon'];
                    $reverse = TRUE;
                }
            }
            if ($reverse) {
                $debug_msg .= '  by REVERSE query (API: ' . strtoupper($config['geocoding']['api']) . ', LAT: ' . $location['location_lat'] . ', LON: ' . $location['location_lon'] . ') - ';
                $url = $api_params['reverse_url'];
                if (isset($api_params['reverse_params'])) {
                    // Additional params for reverse query
                    $params = array_merge($params, $api_params['reverse_params']);
                }
                if (!is_numeric($location['location_lat']) || !is_numeric($location['location_lat'])) {
                    // Do nothing for empty, skip requests for empty coordinates
                } else {
                    if (isset($api_params['request_params']['lat']) && isset($api_params['request_params']['lon'])) {
                        $ok = TRUE;
                        $param = $api_params['request_params']['lat'];
                        $params[$param] = $location['location_lat'];
                        $param = $api_params['request_params']['lon'];
                        $params[$param] = $location['location_lon'];
                    } else {
                        if (isset($api_params['request_params']['latlon'])) {
                            $ok = TRUE;
                            $param = $api_params['request_params']['latlon'];
                            $params[$param] = $location['location_lat'] . ',' . $location['location_lon'];
                        }
                    }
                }
            } else {
                $debug_msg .= '  by PARSING sysLocation (API: ' . strtoupper($config['geocoding']['api']) . ') - ';
                $url = $api_params['direct_url'];
                if (isset($api_params['direct_params'])) {
                    // Additional params for reverse query
                    $params = array_merge($params, $api_params['direct_params']);
                }
                if ($address != '') {
                    $ok = TRUE;
                    $param = $api_params['request_params']['address'];
                    $params[$param] = urlencode($address);
                    //$request = $url . urlencode($address);
                }
            }
            if (OBS_DEBUG > 1) {
                print_vars($api_params);
                print_vars($params);
            }
            if ($ok) {
                // Build request query
                $request = build_request_url($url, $params, $api_params['method']);
                // First request
                $mapresponse = get_http_request($request, NULL, $ratelimit);
                switch ($GLOBALS['response_headers']['code'][0]) {
                    case '4':
                        // 4xx (timeout, rate limit, forbidden)
                    // 4xx (timeout, rate limit, forbidden)
                    case '5':
                        // 5xx (server error)
                        $geo_status = strtoupper($GLOBALS['response_headers']['status']);
                        $debug_msg .= $geo_status . PHP_EOL;
                        if (OBS_DEBUG < 2) {
                            // Hide API KEY from output
                            $request = str_replace($api_params['request_params']['key'] . '=' . escape_html($config['geocoding']['api_key']), $api_params['request_params']['key'] . '=' . '***', $request);
                        }
                        $debug_msg .= '  GEO API REQUEST: ' . $request;
                        print_debug($debug_msg);
                        // Return old array with new status (for later recheck)
                        unset($geo_db['hostname'], $geo_db['location_updated']);
                        $location['location_status'] = $debug_msg;
                        $location['location_updated'] = format_unixtime($config['time']['now'], 'Y-m-d G:i:s');
                        //print_vars($location);
                        //print_vars($geo_db);
                        return array_merge($geo_db, $location);
                }
                $data = json_decode($mapresponse, TRUE);
                //print_vars($data);
                $geo_status = 'NOT FOUND';
                $api_specific = is_file($config['install_dir'] . '/includes/geolocation/' . $location['location_geoapi'] . '.inc.php');
                if ($api_specific) {
                    // API specific parser
                    require_once $config['install_dir'] . '/includes/geolocation/' . $location['location_geoapi'] . '.inc.php';
                    if ($data === FALSE) {
                        // Return old array with new status (for later recheck)
                        unset($geo_db['hostname'], $geo_db['location_updated']);
                        //$location['location_status']  = $debug_msg;
                        $location['location_updated'] = format_unixtime($config['time']['now'], 'Y-m-d G:i:s');
                        //print_vars($location);
                        //print_vars($geo_db);
                        return array_merge($geo_db, $location);
                    }
                } else {
                    if (!isset($location['location_lat'])) {
                        $data = $data[0];
                        if (!count($data) && strpos($address, ',')) {
                            // We seem to have hit a snag geocoding. It might be that the first element of the address is a business name.
                            // Lets drop the first element and see if we get anything better! This works more often than one might expect.
                            list(, $address_new) = explode(',', $address, 2);
                            //$request_new = $url.urlencode($address);
                            $param = $api_params['request_params']['address'];
                            $params[$param] = urlencode($address_new);
                            $request_new = build_request_url($url, $params, $api_params['method']);
                            $mapresponse = get_http_request($request_new, NULL, $ratelimit);
                            $data_new = json_decode($mapresponse, TRUE);
                            if (count($data_new[0])) {
                                // We only want the first entry in the returned data.
                                $data = $data_new[0];
                                $request = $request_new;
                            }
                        }
                    }
                }
                if (OBS_DEBUG > 1 && count($data)) {
                    var_dump($data);
                }
            } else {
                $geo_status = 'NOT REQUESTED';
            }
        }
    }
    if (!$api_specific) {
        // Nominatum
        if (!$reverse) {
            // If using reverse queries, do not change lat/lon
            $location['location_lat'] = $data['lat'];
            $location['location_lon'] = $data['lon'];
        }
        foreach (array('town', 'city', 'hamlet', 'village') as $param) {
            if (isset($data['address'][$param])) {
                $location['location_city'] = $data['address'][$param];
                break;
            }
        }
        $location['location_state'] = $data['address']['state'];
        $location['location_county'] = isset($data['address']['county']) ? $data['address']['county'] : $data['address']['state_district'];
        $location['location_country'] = $data['address']['country_code'];
    }
    // Use defaults if empty values
    if (!strlen($location['location_lat']) || !strlen($location['location_lon'])) {
        // Reset to empty coordinates
        $location['location_lat'] = array('NULL');
        $location['location_lon'] = array('NULL');
        //$location['location_lat'] = $config['geocoding']['default']['lat'];
        //$location['location_lon'] = $config['geocoding']['default']['lon'];
        //if (is_numeric($config['geocoding']['default']['lat']) && is_numeric($config['geocoding']['default']['lon']))
        //{
        //  $location['location_manual']     = 1; // Set manual key for ability reset from WUI
        //}
    } else {
        // Always round lat/lon same as DB precision (DECIMAL(10,7))
        $location['location_lat'] = round($location['location_lat'], 7);
        $location['location_lon'] = round($location['location_lon'], 7);
    }
    foreach (array('city', 'county', 'state') as $entry) {
        // Remove duplicate County/State words
        $param = 'location_' . $entry;
        $location[$param] = strlen($location[$param]) ? str_ireplace(' ' . $entry, '', $location[$param]) : 'Unknown';
    }
    if (strlen($location['location_country'])) {
        $location['location_country'] = strtolower($location['location_country']);
        $geo_status = 'FOUND';
    } else {
        $location['location_country'] = 'Unknown';
    }
    // Print some debug informations
    $debug_msg .= $geo_status . PHP_EOL;
    if (OBS_DEBUG < 2) {
        // Hide API KEY from output
        $request = str_replace($api_params['request_params']['key'] . '=' . escape_html($config['geocoding']['api_key']), $api_params['request_params']['key'] . '=' . '***', $request);
    }
    $debug_msg .= '  GEO API REQUEST: ' . $request;
    if ($geo_status == 'FOUND') {
        $debug_msg .= PHP_EOL . '  GEO LOCATION: ';
        $debug_msg .= country_from_code($location['location_country']) . ' (Country), ' . $location['location_state'] . ' (State), ';
        $debug_msg .= $location['location_county'] . ' (County), ' . $location['location_city'] . ' (City)';
        $debug_msg .= PHP_EOL . '  GEO COORDINATES: ';
        $debug_msg .= $location['location_lat'] . ' (Latitude), ' . $location['location_lon'] . ' (Longitude)';
    } else {
        $debug_msg .= PHP_EOL . '  QUERY DATE: ' . date('r');
        // This is requered for increase data in DB
    }
    print_debug($debug_msg);
    $location['location_status'] = $debug_msg;
    return $location;
}
                 // Additional data for Jitter
                 $sla_poll = snmpwalk_cache_multi_oid($device, "rttMonLatestJitterOperEntry", $sla_poll, "CISCO-RTTMON-MIB", mib_dirs('cisco'));
                 break;
             case 'icmpjitter':
                 // Additional data for ICMP jitter
                 $sla_poll = snmpwalk_cache_multi_oid($device, "rttMonLatestIcmpJitterOperEntry", $sla_poll, "CISCO-RTTMON-ICMP-MIB", mib_dirs('cisco'));
                 break;
         }
     }
     $uptime = timeticks_to_sec($poll_device['sysUpTime']);
     $uptime_offset = time() - intval($uptime) / 100;
     /// WARNING. System timezone BOMB
     // Convert timestamps
     foreach ($sla_poll as &$sla) {
         $sla['UnixTime'] = intval(timeticks_to_sec($sla['rttMonLatestRttOperTime']) / 100 + $uptime_offset);
         $sla['TimeStr'] = format_unixtime($sla['UnixTime']);
     }
     unset($sla);
 }
 foreach ($sla_db as $sla) {
     echo "SLA " . $sla['sla_index'] . ": " . $sla['rtt_type'] . " " . $sla['sla_owner'] . " " . $sla['sla_tag'] . "... ";
     $rrd_filename = "sla-" . $sla['sla_index'] . ".rrd";
     $rrd_ds = "DS:rtt:GAUGE:600:0:300000";
     if (isset($sla_poll[$sla['sla_index']])) {
         $entry = $sla_poll[$sla['sla_index']];
         //if ($sla['sla_index'] == '99') { $entry['rttMonLatestRttOperSense'] = 'ok'; } // DEBUG
         echo $entry['rttMonLatestRttOperCompletionTime'] . 'ms at ' . $entry['TimeStr'] . ', Sense code - "' . $entry['rttMonLatestRttOperSense'] . '"';
         $sla_state = array('rtt_value' => $entry['rttMonLatestRttOperCompletionTime'], 'rtt_sense' => $entry['rttMonLatestRttOperSense'], 'rtt_unixtime' => $entry['UnixTime']);
         $rrd_value = $sla_state['rtt_value'];
         if ($sla['rtt_sense'] && $sla['rtt_sense'] != $sla_state['rtt_sense']) {
             // SLA sense changed, log
Пример #21
0
 // Example how to read usefull info from this debug by grep:
 // grep -B 1 -A 6 'ID:\ 520' /tmp/port_debug_spikes.txt
 if ($config['debug_port']['spikes'] && $this_port['ifSpeed'] > "0" && ($port['stats']['ifInBits_rate'] > $this_port['ifSpeed'] || $port['stats']['ifOutBits_rate'] > $this_port['ifSpeed'] || isset($port['stats']['ifInOctets_negative_rate']) || isset($port['stats']['ifOutOctets_negative_rate']))) {
     if (!$port['port_64bit']) {
         $hc_prefix = '';
     }
     print_warning("Spike above ifSpeed or negative rate detected! See debug info here: ");
     $debug_file = "/tmp/port_debug_spikes.txt";
     $debug_format = "| %20s | %20s | %20s |\n";
     $debug_msg = sprintf("+%'-68s+\n", '');
     $debug_msg .= sprintf("|%67s |\n", $device['hostname'] . " " . $debug_port['ifDescr'] . " (ID: " . $port['port_id'] . ") " . formatRates($debug_port['ifSpeed']) . " " . ($port['port_64bit'] ? 'Counter64' : 'Counter32'));
     $debug_msg .= sprintf("+%'-68s+\n", '');
     $debug_msg .= sprintf("| %-20s | %-20s | %-20s |\n", 'Polled time', 'if' . $hc_prefix . 'OutOctets', 'if' . $hc_prefix . 'InOctets');
     $debug_msg .= sprintf($debug_format, '(prev) ' . $port['poll_time'], $port['ifOutOctets'], $port['ifInOctets']);
     $debug_msg .= sprintf($debug_format, '(now)  ' . $polled, $this_port['ifOutOctets'], $this_port['ifInOctets']);
     $debug_msg .= sprintf($debug_format, format_unixtime($polled), formatRates($port['stats']['ifOutBits_rate'] * 8), formatRates($port['stats']['ifInBits_rate']));
     $debug_msg .= sprintf("%'+70s\n", '');
     $debug_msg .= sprintf("| %-67s|\n", 'Port dump:');
     // Added full original port variable dump
     foreach ($debug_port as $debug_key => $debug_var) {
         $debug_msg .= sprintf("|  %-66s|\n", "'{$debug_key}' => '{$debug_var}',");
     }
     $debug_msg .= sprintf("+%'-68s+\n\n", '');
     file_put_contents($debug_file, $debug_msg, FILE_APPEND);
 }
 // Put States into alert array
 foreach (array('ifOperStatus', 'ifAdminStatus', 'ifMtu', 'ifDuplex') as $oid) {
     if (isset($this_port[$oid])) {
         $port['alert_array'][$oid] = $this_port[$oid];
     }
 }
Пример #22
0
        include $config['html_dir'] . "/includes/navbar.inc.php";
    }
}
?>

  <div class="container">

<?php 
if ($_SESSION['authenticated']) {
    if ($_SESSION['userlevel'] > 7) {
        $latest['version'] = get_obs_attrib('latest_ver');
        $latest['revision'] = get_obs_attrib('latest_rev');
        $latest['date'] = get_obs_attrib('latest_rev_date');
        if ($latest['revision'] > OBSERVIUM_REV + $config['version_check_revs']) {
            $notifications[] = array('text' => '<h4>There is a newer revision of Observium available!</h4> Version ' . $latest['version'] . ' (' . format_unixtime(datetime_to_unixtime($latest['date']), 'jS F Y') . ') is ' . ($latest['revision'] - OBSERVIUM_REV) . ' revisions ahead.', 'severity' => 'warning');
            $alerts[] = array('text' => '<h4>There is a newer revision of Observium available!</h4> Version ' . $latest['version'] . ' (' . format_unixtime(datetime_to_unixtime($latest['date']), 'jS F Y') . ') is ' . ($latest['revision'] - OBSERVIUM_REV) . ' revisions ahead.', 'severity' => 'warning');
        }
        // Warn about lack of mcrypt unless told not to.
        if ($config['login_remember_me'] || isset($_SESSION['mcrypt_required'])) {
            check_extension_exists('mcrypt', 'This extension required for use by the "remember me" feature. Please install the php5-mcrypt package on Ubuntu/Debian or the php-mcrypt package on RHEL/CentOS. Alternatively, you can disable this feature by setting $config[\'login_remember_me\'] = FALSE; in your config.');
        }
        // Warning about web_url config, only for ssl
        if (is_ssl() && preg_match('/^http:/', $config['web_url'])) {
            $notifications[] = array('text' => 'Setting \'web_url\' for "External Web URL" not set or incorrect, please update on ' . generate_link('Global Settings Edit', array('page' => 'settings', 'section' => 'wui')) . ' page.', 'severity' => 'warning');
        }
        // Warning about need DB schema update
        $db_version = get_db_version();
        $db_version = sprintf("%03d", $db_version + 1);
        if (is_file($config['install_dir'] . "/update/{$db_version}.sql") || is_file($config['install_dir'] . "/update/{$db_version}.php")) {
            $notifications[] = array('text' => 'Your database schema is old and needs updating. Run from server console:
                  <pre style="padding: 3px" class="small">' . $config['install_dir'] . '/discovery.php -u</pre>', 'severity' => 'alert');
Пример #23
0
        if ($prompt) {
            $answer = print_prompt("{$count} eventlog entries older than " . format_unixtime($cutoff) . " will be deleted");
        }
        if ($answer) {
            $rows = dbDelete('eventlog', $where);
            if ($rows === FALSE) {
                // Use LIMIT with big tables
                print_debug("Event log table is too big, using LIMIT to delete entries");
                $rows = 0;
                $i = 1000;
                while ($i && $rows < $count) {
                    $iter = dbDelete('eventlog', $where . ' LIMIT 1000000');
                    if ($iter === FALSE) {
                        break;
                    }
                    $rows += $iter;
                    $i--;
                }
            }
            print_debug("Event log housekeeping: deleted {$rows} entries");
            logfile("housekeeping.log", "Event log: deleted {$rows} entries older than " . format_unixtime($cutoff));
        }
    } else {
        if ($prompt) {
            print_message("No event log entries found older than " . format_unixtime($cutoff));
        }
    }
} else {
    print_message("Event log housekeeping is disabled in configuration or less than 24h.");
}
// EOF
Пример #24
0
 * @package    observium
 * @subpackage housekeeping
 * @author     Adam Armstrong <*****@*****.**>
 * @copyright  (C) 2006-2014 Adam Armstrong
 *
 */
$cutoff = age_to_unixtime($config['housekeeping']['deleted_ports']['age']);
if ($cutoff) {
    $where = "`deleted` = 1 AND UNIX_TIMESTAMP(`ifLastChange`) < {$cutoff}";
    $ports = dbFetchRows("SELECT `port_id` FROM `ports` WHERE {$where}");
    $count = count($ports);
    if ($count) {
        if ($prompt) {
            $answer = print_prompt("{$count} ports marked as 'DELETED' older than " . format_unixtime($cutoff) . " will be deleted");
        }
        if ($answer) {
            foreach ($ports as $entry) {
                delete_port($entry['port_id']);
            }
            print_debug("Deleted ports housekeeping: deleted {$count} entries");
            logfile("housekeeping.log", "Deleted ports: deleted {$count} entries older than " . format_unixtime($cutoff));
        }
    } else {
        if ($prompt) {
            print_message("No deleted ports found older than " . format_unixtime($cutoff));
        }
    }
} else {
    print_message("Deleted ports housekeeping disabled in configuration.");
}
// EOF
Пример #25
0
function generate_sla_row($sla, $vars)
{
    global $config;
    humanize_sla($sla);
    $table_cols = "8";
    $graph_array = array();
    $graph_array['to'] = $config['time']['now'];
    $graph_array['id'] = $sla['sla_id'];
    $graph_array['type'] = $sla['graph_type'];
    $graph_array['legend'] = "no";
    $graph_array['width'] = 80;
    $graph_array['height'] = 20;
    $graph_array['bg'] = 'ffffff00';
    $graph_array['from'] = $config['time']['day'];
    if ($sla['rtt_event'] && $sla['rtt_sense']) {
        $mini_graph = generate_graph_tag($graph_array);
    } else {
        // Do not show "Draw Error" minigraph
        $mini_graph = '';
    }
    $out = '<tr class="' . $sla['row_class'] . '"><td class="state-marker"></td>';
    if ($vars['page'] != "device" && $vars['popup'] != TRUE) {
        $out .= '<td class="entity">' . generate_device_link($sla) . '</td>';
        $table_cols++;
    }
    $out .= '<td class="entity">' . generate_entity_link('sla', $sla) . '</td>';
    $out .= '<td>' . $sla['sla_owner'] . '</td>';
    $out .= '<td>' . $sla['rtt_label'] . '</td>';
    $out .= '<td>' . generate_entity_link('sla', $sla, $mini_graph, NULL, FALSE) . '</td>';
    $out .= '<td style="white-space: nowrap">' . generate_tooltip_link(NULL, formatUptime($config['time']['now'] - $sla['rtt_last_change'], 'short-2') . ' ago', format_unixtime($sla['rtt_last_change'])) . '</td>';
    $out .= '<td style="text-align: right;"><strong><span class="' . $sla['rtt_class'] . '">' . $sla['rtt_event'] . '</span></strong></td>';
    $out .= '<td style="text-align: right;"><strong><span class="' . $sla['rtt_class'] . '">' . $sla['rtt_sense'] . '</span></strong></td>';
    $out .= '<td><span class="' . $sla['sla_class'] . '">' . $sla['human_value'] . $sla['human_unit'] . '</span></td>';
    $out .= '</tr>';
    if ($vars['graph'] || $vars['view'] == "graphs" || $vars['id'] == $sla['sla_id']) {
        // If id set in vars, display only specific graphs
        $graph_array = array();
        $graph_array['type'] = $sla['graph_type'];
        $graph_array['id'] = $sla['sla_id'];
        $out .= '<tr class="' . $sla['row_class'] . '">';
        $out .= '  <td class="state-marker"></td>';
        $out .= '  <td colspan="' . $table_cols . '">';
        $out .= generate_graph_row($graph_array, TRUE);
        $out .= '  </td>';
        $out .= '</tr>';
    }
    return $out;
}
Пример #26
0
/**
 * Display alert_table entries.
 *
 * @param array $vars
 * @return none
 *
 */
function print_alert_table($vars)
{
    global $alert_rules;
    global $config;
    // This should be set outside, but do it here if it isn't
    if (!is_array($alert_rules)) {
        $alert_rules = cache_alert_rules();
    }
    /// WARN HERE
    if (isset($vars['device']) && !isset($vars['device_id'])) {
        $vars['device_id'] = $vars['device'];
    }
    if (isset($vars['entity']) && !isset($vars['entity_id'])) {
        $vars['entity_id'] = $vars['entity'];
    }
    // Short? (no pagination, small out)
    $short = isset($vars['short']) && $vars['short'];
    list($query, $param, $query_count) = build_alert_table_query($vars);
    // Fetch alerts
    $count = dbFetchCell($query_count, $param);
    $alerts = dbFetchRows($query, $param);
    // Set which columns we're going to show.
    // We hide the columns that have been given as search options via $vars
    $list = array('device_id' => FALSE, 'entity_id' => FALSE, 'entity_type' => FALSE, 'alert_test_id' => FALSE);
    foreach ($list as $argument => $nope) {
        if (!isset($vars[$argument]) || empty($vars[$argument]) || $vars[$argument] == "all") {
            $list[$argument] = TRUE;
        }
    }
    if ($vars['format'] != "condensed") {
        $list['checked'] = TRUE;
        $list['changed'] = TRUE;
        $list['alerted'] = TRUE;
    }
    if ($vars['short'] == TRUE) {
        $list['checked'] = FALSE;
        $list['alerted'] = FALSE;
    }
    // Hide device if we know entity_id
    if (isset($vars['entity_id'])) {
        $list['device_id'] = FALSE;
    }
    // Hide entity_type if we know the alert_test_id
    if (isset($vars['alert_test_id']) || TRUE) {
        $list['entity_type'] = FALSE;
    }
    // Hide entity types in favour of icons to save space
    if ($vars['pagination'] && !$short) {
        $pagination_html = pagination($vars, $count);
        echo $pagination_html;
    }
    echo generate_box_open($vars['header']);
    echo '<table class="table table-condensed  table-striped  table-hover">';
    if ($vars['no_header'] == FALSE) {
        echo '
  <thead>
    <tr>
      <th class="state-marker"></th>
      <th style="width: 1px;"></th>';
        if ($list['device_id']) {
            echo '      <th style="width: 15%">Device</th>';
        }
        if ($list['entity_type']) {
            echo '      <th style="width: 10%">Type</th>';
        }
        if ($list['entity_id']) {
            echo '      <th style="">Entity</th>';
        }
        if ($list['alert_test_id']) {
            echo '      <th style="min-width: 15%;">Alert</th>';
        }
        echo '
      <th style="width: 100px;">Status</th>';
        if ($list['checked']) {
            echo '      <th style="width: 95px;">Checked</th>';
        }
        if ($list['changed']) {
            echo '      <th style="width: 95px;">Changed</th>';
        }
        if ($list['alerted']) {
            echo '      <th style="width: 95px;">Alerted</th>';
        }
        echo '    <th style="width: 45px;"></th>
    </tr>
  </thead>';
    }
    echo '<tbody>' . PHP_EOL;
    foreach ($alerts as $alert) {
        // Process the alert entry, generating colours and classes from the data
        humanize_alert_entry($alert);
        // Get the entity array using the cache
        $entity = get_entity_by_id_cache($alert['entity_type'], $alert['entity_id']);
        // Get the device array using the cache
        $device = device_by_id_cache($alert['device_id']);
        // Get the entity_name.
        ### FIXME - This is probably duplicated effort from above. We should pass it $entity
        $entity_name = entity_name($alert['entity_type'], $entity);
        // Set the alert_rule from the prebuilt cache array
        $alert_rule = $alert_rules[$alert['alert_test_id']];
        echo '<tr class="' . $alert['html_row_class'] . '" style="cursor: pointer;" onclick="openLink(\'' . generate_url(array('page' => 'device', 'device' => $device['device_id'], 'tab' => 'alert', 'alert_entry' => $alert['alert_table_id'])) . '\')">';
        echo '<td class="state-marker"></td>';
        echo '<td style="width: 1px;"></td>';
        // If we know the device, don't show the device
        if ($list['device_id']) {
            echo '<td><span class="entity-title">' . generate_device_link($device) . '</span></td>';
        }
        // If we're showing all entity types, print the entity type here
        if ($list['entity_type']) {
            echo '<td>' . nicecase($alert['entity_type']) . '</td>';
        }
        // Print a link to the entity
        if ($list['entity_id']) {
            echo '<td><span class="entity-title"><i class="' . $config['entities'][$alert['entity_type']]['icon'] . '"></i> ' . generate_entity_link($alert['entity_type'], $alert['entity_id']) . '</span></td>';
        }
        // Print link to the alert rule page
        if ($list['alert_test_id']) {
            echo '<td class="entity"><a href="', generate_url(array('page' => 'alert_check', 'alert_test_id' => $alert_rule['alert_test_id'])), '">', escape_html($alert_rule['alert_name']), '</a></td>';
        }
        echo '<td>';
        echo '<span class="label label-' . ($alert['html_row_class'] != 'up' ? $alert['html_row_class'] : 'success') . '">' . generate_tooltip_link('', $alert['status'], '<div class="small" style="max-width: 500px;"><strong>' . $alert['last_message'] . '</strong></div>', $alert['alert_class']) . '</span>';
        echo '</td>';
        // echo('<td class="'.$alert['class'].'">'.$alert['last_message'].'</td>');
        if ($list['checked']) {
            echo '<td>' . generate_tooltip_link('', $alert['checked'], format_unixtime($alert['last_checked'], 'r')) . '</td>';
        }
        if ($list['changed']) {
            echo '<td>' . generate_tooltip_link('', $alert['changed'], format_unixtime($alert['last_changed'], 'r')) . '</td>';
        }
        if ($list['alerted']) {
            echo '<td>' . generate_tooltip_link('', $alert['alerted'], format_unixtime($alert['last_alerted'], 'r')) . '</td>';
        }
        echo '<td>';
        // This stuff should go in an external entity popup in the future.
        $state = json_decode($alert['state'], true);
        $alert['state_popup'] = '';
        if (count($state['failed'])) {
            $alert['state_popup'] .= generate_box_open(array('title' => 'Failed Tests'));
            //'<h4>Failed Tests</h4>';
            $alert['state_popup'] .= '<table style="min-width: 400px;" class="table   table-striped table-condensed">';
            $alert['state_popup'] .= '<thead><tr><th>Metric</th><th>Cond</th><th>Value</th><th>Measured</th></tr></thead>';
            foreach ($state['failed'] as $test) {
                $alert['state_popup'] .= '<tr><td><strong>' . $test['metric'] . '</strong></td><td>' . $test['condition'] . '</td><td>' . $test['value'] . '</td><td><i class="red">' . $state['metrics'][$test['metric']] . '</i></td></tr>';
            }
            $alert['state_popup'] .= '</table>';
            $alert['state_popup'] .= generate_box_close();
        }
        $alert['state_popup'] .= generate_entity_popup_graphs($alert, array('entity_type' => 'alert_entry'));
        // Print (i) icon with popup of state.
        echo overlib_link("", '<i class="icon-info-sign text-primary"></i>', $alert['state_popup'], NULL);
        echo '&nbsp;&nbsp;<a href="' . generate_url(array('page' => 'device', 'device' => $device['device_id'], 'tab' => 'alert', 'alert_entry' => $alert['alert_table_id'])) . '"><i class="icon-cog text-muted"></i></a>';
        echo '</td>';
        echo '</tr>';
    }
    echo '  </tbody>' . PHP_EOL;
    echo '</table>' . PHP_EOL;
    echo generate_box_close();
    if ($vars['pagination'] && !$short) {
        echo $pagination_html;
    }
}
<div class="row">
  <div class="col-md-12">
    <div class="well info_box">
      <div class="title"><a href="<?php 
    echo generate_url(array('page' => 'device', 'device' => $device['device_id'], 'tab' => 'perf'));
    ?>
">
        <i class="oicon-clock"></i> 持续时间</a></div>
      <div class="content">

<?php 
    $ptime = dbFetchRow('SELECT * FROM `devices_perftimes` WHERE `operation` = "poll" AND `device_id` = ? ORDER BY `start` DESC LIMIT 1', array($device['device_id']));
    echo "最后一次轮询: <b>" . format_unixtime($ptime['start']) . '</b> (took ' . $ptime['duration'] . 's) - <a href="' . generate_url(array('page' => 'device', 'device' => $device['device_id'], 'tab' => 'perf')) . '">详情</a><p />';
    $dtime = dbFetchRow('SELECT * FROM `devices_perftimes` WHERE `operation` = "discover" AND `device_id` = ? ORDER BY `start` DESC LIMIT 1', array($device['device_id']));
    echo "最后一次发现: <b>" . format_unixtime($dtime['start']) . '</b> (took ' . $dtime['duration'] . 's) - <a href="' . generate_url(array('page' => 'device', 'device' => $device['device_id'], 'tab' => 'perf')) . '">详情</a><p />';
    ?>

      </div>
    </div>

    <div class="well info_box">
      <div class="title"><a href="<?php 
    echo generate_url(array('page' => 'device', 'device' => $device['device_id'], 'tab' => 'showconfig'));
    ?>
">
        <i class="oicon-blocks"></i> RANCID</a></div>
      <div class="content">
<?php 
    if (count($config['rancid_configs'])) {
        $device_config_file = get_rancid_filename($device['hostname'], 1);
Пример #28
0
/**
 * Display alert_table entries.
 *
 * @param array $vars
 * @return none
 *
 */
function print_alert_table($vars)
{
    global $alert_rules;
    global $config;
    // This should be set outside, but do it here if it isn't
    if (!is_array($alert_rules)) {
        $alert_rules = cache_alert_rules();
    }
    /// WARN HERE
    if (isset($vars['device']) && !isset($vars['device_id'])) {
        $vars['device_id'] = $vars['device'];
    }
    if (isset($vars['entity']) && !isset($vars['entity_id'])) {
        $vars['entity_id'] = $vars['entity'];
    }
    // Short? (no pagination, small out)
    $short = isset($vars['short']) && $vars['short'];
    list($query, $param, $query_count) = build_alert_table_query($vars);
    // Fetch alerts
    $count = dbFetchCell($query_count, $param);
    $alerts = dbFetchRows($query, $param);
    // Set which columns we're going to show.
    // We hide the columns that have been given as search options via $vars
    $list = array('device_id' => FALSE, 'entity_id' => FALSE, 'entity_type' => FALSE, 'alert_test_id' => FALSE);
    foreach ($list as $argument => $nope) {
        if (!isset($vars[$argument]) || empty($vars[$argument]) || $vars[$argument] == "all") {
            $list[$argument] = TRUE;
        }
    }
    // Hide device if we know entity_id
    if (isset($vars['entity_id'])) {
        $list['device_id'] = FALSE;
    }
    // Hide entity_type if we know the alert_test_id
    if (isset($vars['alert_test_id']) || TRUE) {
        $list['entity_type'] = FALSE;
    }
    // Hide entity types in favour of icons to save space
    if ($vars['pagination'] && !$short) {
        $pagination_html = pagination($vars, $count);
        echo $pagination_html;
    }
    echo '<table class="table table-condensed table-bordered table-striped table-rounded table-hover">
  <thead>
    <tr>
      <th class="state-marker"></th>
      <th style="width: 1px;"></th>';
    // No table id
    //<th style="width: 5%;">Id</th>');
    if ($list['device_id']) {
        echo '      <th style="width: 15%">设备</th>';
    }
    if ($list['alert_test_id']) {
        echo '      <th style="min-width: 15%;">警报</th>';
    }
    if ($list['entity_type']) {
        echo '      <th style="width: 10%">类型</th>';
    }
    if ($list['entity_id']) {
        echo '      <th style="">实体</th>';
    }
    echo '
      <th style="width: 20px">状态</th>
      <th style="width: 100px;">信息</th>
      <th style="width: 90px;">已检测</th>
      <th style="width: 90px;">已更改</th>
      <th style="width: 90px;">警告</th>
      <th style="width: 20px;"></th>
    </tr>
  </thead>
  <tbody>' . PHP_EOL;
    foreach ($alerts as $alert) {
        // Process the alert entry, generating colours and classes from the data
        humanize_alert_entry($alert);
        // Get the entity array using the cache
        $entity = get_entity_by_id_cache($alert['entity_type'], $alert['entity_id']);
        // Get the device array using the cache
        $device = device_by_id_cache($alert['device_id']);
        // Get the entity_name.
        ### FIXME - This is probably duplicated effort from above. We should pass it $entity
        $entity_name = entity_name($alert['entity_type'], $entity);
        // Set the alert_rule from the prebuilt cache array
        $alert_rule = $alert_rules[$alert['alert_test_id']];
        echo '<tr class="' . $alert['html_row_class'] . '" style="cursor: pointer;" onclick="location.href=\'' . generate_url(array('page' => 'device', 'device' => $device['device_id'], 'tab' => 'alert', 'alert_entry' => $alert['alert_table_id'])) . '\'">';
        echo '<td class="state-marker"></td>';
        echo '<td style="width: 1px;"></td>';
        // If we know the device, don't show the device
        if ($list['device_id']) {
            echo '<td><span class="entity-title">' . generate_device_link($device) . '</span></td>';
        }
        // Print link to the alert rule page
        if ($list['alert_test_id']) {
            echo '<td><a href="', generate_url(array('page' => 'alert_check', 'alert_test_id' => $alert_rule['alert_test_id'])), '">', $alert_rule['alert_name'], '</a></td>';
        }
        // If we're showing all entity types, print the entity type here
        if ($list['entity_type']) {
            echo '<td>' . nicecase($alert['entity_type']) . '</td>';
        }
        // Print a link to the entity
        if ($list['entity_id']) {
            echo '<td><span class="entity-title"><i class="' . $config['entities'][$alert['entity_type']]['icon'] . '"></i> ' . generate_entity_link($alert['entity_type'], $alert['entity_id']) . '</span></td>';
        }
        echo '<td>';
        ## FIXME -- generate a nice popup with parsed information from the state array
        echo overlib_link("", '<i class="icon-info-sign"></i>', "<pre>" . print_r(json_decode($alert['state'], TRUE), TRUE) . "</pre>", NULL);
        echo '</td>';
        echo '<td class="' . $alert['class'] . '">' . $alert['last_message'] . '</td>';
        echo '<td>' . overlib_link('', $alert['checked'], format_unixtime($alert['last_checked'], 'r'), NULL) . '</td>';
        echo '<td>' . overlib_link('', $alert['changed'], format_unixtime($alert['last_changed'], 'r'), NULL) . '</td>';
        echo '<td>' . overlib_link('', $alert['alerted'], format_unixtime($alert['last_alerted'], 'r'), NULL) . '</td>';
        echo '<td><a href="' . generate_url(array('page' => 'device', 'device' => $device['device_id'], 'tab' => 'alert', 'alert_entry' => $alert['alert_table_id'])) . '"><i class="oicon-gear" /></a></td>';
        echo '</tr>';
    }
    echo '  </tbody>' . PHP_EOL;
    echo '</table>' . PHP_EOL;
    if ($vars['pagination'] && !$short) {
        echo $pagination_html;
    }
}
Пример #29
0
                }
            }
            print_debug("Timing housekeeping: deleted {$rows} entries (per-device)");
            logfile("housekeeping.log", "Timing: deleted {$rows} entries older than " . format_unixtime($cutoff) . " (per-device)");
            $rows = dbDelete('perf_times', $where);
            if ($rows === FALSE) {
                // Use LIMIT with big tables
                print_debug("Performance table (per-run) is too big, using LIMIT for delete entries");
                $rows = 0;
                $i = 1000;
                while ($i && $rows < $count_run) {
                    $iter = dbDelete('perf_times', $where . ' LIMIT 1000000');
                    if ($iter === FALSE) {
                        break;
                    }
                    $rows += $iter;
                    $i--;
                }
            }
            print_debug("Timing housekeeping: deleted {$rows} entries (per-run)");
            logfile("housekeeping.log", "Timing: deleted {$rows} entries older than " . format_unixtime($cutoff) . " (per-run)");
        }
    } else {
        if ($prompt) {
            print_message("No perfomance entries found older than " . format_unixtime($cutoff));
        }
    }
} else {
    print_message("Timing housekeeping disabled in configuration or less than 24h.");
}
// EOF
Пример #30
0
/**
 * Generate notifications for an alert entry
 *
 * @param array entry
 * @return NULL
 */
function alert_notifier($entry, $type = "alert")
{
    global $config, $alert_rules;
    $device = device_by_id_cache($entry['device_id']);
    $alert = $alert_rules[$entry['alert_test_id']];
    $state = json_decode($entry['state'], TRUE);
    $conditions = json_decode($alert['conditions'], TRUE);
    $entity = get_entity_by_id_cache($entry['entity_type'], $entry['entity_id']);
    $condition_array = array();
    foreach ($state['failed'] as $failed) {
        $condition_array[] = $failed['metric'] . " " . $failed['condition'] . " " . $failed['value'] . " (" . $state['metrics'][$failed['metric']] . ")";
    }
    $metric_array = array();
    foreach ($state['metrics'] as $metric => $value) {
        $metric_array[] = $metric . ' = ' . $value;
    }
    $graphs = array();
    $graph_done = array();
    foreach ($state['metrics'] as $metric => $value) {
        if ($config['email']['graphs'] !== FALSE && is_array($config['entities'][$entry['entity_type']]['metric_graphs'][$metric]) && !in_array($config['entities'][$entry['entity_type']]['metric_graphs'][$metric]['type'], $graph_done)) {
            $graph_array = $config['entities'][$entry['entity_type']]['metric_graphs'][$metric];
            foreach ($graph_array as $key => $val) {
                // Check to see if we need to do any substitution
                if (substr($val, 0, 1) == '@') {
                    $nval = substr($val, 1);
                    //echo(" replaced " . $val . " with " . $entity[$nval] . " from entity. " . PHP_EOL . "<br />");
                    $graph_array[$key] = $entity[$nval];
                }
            }
            $image_data_uri = generate_alert_graph($graph_array);
            $image_url = generate_graph_url($graph_array);
            $graphs[] = array('label' => $graph_array['type'], 'type' => $graph_array['type'], 'url' => $image_url, 'data' => $image_data_uri);
            $graph_done[] = $graph_array['type'];
        }
        unset($graph_array);
    }
    if ($config['email']['graphs'] !== FALSE && count($graph_done) == 0 && is_array($config['entities'][$entry['entity_type']]['graph'])) {
        // We can draw a graph for this type/metric pair!
        $graph_array = $config['entities'][$entry['entity_type']]['graph'];
        foreach ($graph_array as $key => $val) {
            // Check to see if we need to do any substitution
            if (substr($val, 0, 1) == '@') {
                $nval = substr($val, 1);
                //echo(" replaced ".$val." with ". $entity[$nval] ." from entity. ".PHP_EOL."<br />");
                $graph_array[$key] = $entity[$nval];
            }
        }
        //print_vars($graph_array);
        $image_data_uri = generate_alert_graph($graph_array);
        $image_url = generate_graph_url($graph_array);
        $graphs[] = array('label' => $graph_array['type'], 'type' => $graph_array['type'], 'url' => $image_url, 'data' => $image_data_uri);
        unset($graph_array);
    }
    $graphs_html = "";
    foreach ($graphs as $graph) {
        $graphs_html .= '<h4>' . $graph['type'] . '</h4>';
        $graphs_html .= '<a href="' . $graph['url'] . '"><img src="' . $graph['data'] . '"></a><br />';
    }
    //print_vars($graphs);
    //print_vars($graphs_html);
    //print_vars($entry);
    $message_tags = array('ALERT_STATE' => $entry['alert_status'] == '1' ? "RECOVER" : "ALERT", 'ALERT_URL' => generate_url(array('page' => 'device', 'device' => $device['device_id'], 'tab' => 'alert', 'alert_entry' => $entry['alert_table_id'])), 'ALERT_ID' => $entry['alert_table_id'], 'ALERT_MESSAGE' => $alert['alert_message'], 'CONDITIONS' => implode(PHP_EOL . '             ', $condition_array), 'METRICS' => implode(PHP_EOL . '             ', $metric_array), 'DURATION' => $entry['alert_status'] == '1' ? $entry['last_ok'] > 0 ? formatUptime(time() - $entry['last_ok']) . " (" . format_unixtime($entry['last_ok']) . ")" : "Unknown" : ($entry['last_ok'] > 0 ? formatUptime(time() - $entry['last_ok']) . " (" . format_unixtime($entry['last_ok']) . ")" : "Unknown"), 'ENTITY_LINK' => generate_entity_link($entry['entity_type'], $entry['entity_id'], $entity['entity_name']), 'ENTITY_NAME' => $entity['entity_name'], 'ENTITY_TYPE' => $alert['entity_type'], 'ENTITY_DESCRIPTION' => $entity['entity_descr'], 'ENTITY_GRAPHS_ARRAY' => json_encode($graphs), 'DEVICE_HOSTNAME' => $device['hostname'], 'DEVICE_LINK' => generate_device_link($device), 'DEVICE_HARDWARE' => $device['hardware'], 'DEVICE_OS' => $device['os_text'] . ' ' . $device['version'] . ' ' . $device['features'], 'DEVICE_LOCATION' => $device['location'], 'DEVICE_UPTIME' => deviceUptime($device));
    //logfile('debug.log', var_export($message, TRUE));
    $title = alert_generate_subject($device, $message_tags['ALERT_STATE'], $message_tags);
    $message_tags['TITLE'] = $title;
    $alert_id = $entry['alert_test_id'];
    $notify_status = FALSE;
    // Set alert notify status to FALSE by default
    $notification_type = 'alert';
    $transports = get_alert_contacts($device, $alert_id, $notification_type);
    if (!empty($transports)) {
        // WARNING, alerts queue currently experimental
        if (isset($config['alerts']['queue']) && isset($config['alerts']['queue'])) {
            // Add notification to queue
            $notification = array('device_id' => $device['device_id'], 'log_id' => $log_id, 'aca_type' => $notification_type, 'endpoints' => json_encode($transports), 'message_graphs' => $message_tags['ENTITY_GRAPHS_ARRAY'], 'notification_added' => time(), 'notification_lifetime' => 300, 'notification_entry' => json_encode($entry));
            $notification_message_tags = $message_tags;
            unset($notification_message_tags['ENTITY_GRAPHS_ARRAY']);
            $notification['message_tags'] = json_encode($notification_message_tags);
            $notification_id = dbInsert($notification, 'notifications_queue');
        } else {
            // Use classic instant notifications send
            $notification_count = 0;
            foreach ($transports as $method => $endpoints) {
                if (isset($config['alerts']['disable'][$method]) && $config['alerts']['disable'][$method]) {
                    continue;
                }
                // Skip if method disabled globally
                foreach ($endpoints as $endpoint) {
                    $method_include = $config['install_dir'] . "/includes/alerting/" . $method . ".inc.php";
                    if (is_file($method_include)) {
                        print_cli_data("Notifying", "[" . $method . "] " . $endpoint['contact_descr'] . ": " . $endpoint['contact_endpoint']);
                        // Split out endpoint data as stored JSON in the database into array for use in transport
                        // The original string also remains available as the contact_endpoint key
                        foreach (json_decode($endpoint['contact_endpoint']) as $field => $value) {
                            $endpoint[$field] = $value;
                        }
                        include $method_include;
                        // FIXME check success
                        // FIXME log notification + success/failure!
                        if ($notify_status['success']) {
                            $notification_count++;
                        }
                    } else {
                        print_cli_data("Missing include", $method_include);
                    }
                }
            }
            if ($notification_count) {
                dbUpdate(array('notified' => 1), 'alert_log', '`event_id` = ?', array($notification['log_id']));
            }
        }
    }
}