function get_instance_stats() { // Overall Ports/Devices statistics $stats['ports'] = dbFetchCell("SELECT COUNT(*) FROM ports"); $stats['devices'] = dbFetchCell("SELECT COUNT(*) FROM devices"); $stats['edition'] = OBSERVIUM_EDITION; // Per-feature statistics $stats['sensors'] = dbFetchCell("SELECT COUNT(*) FROM `sensors`"); $stats['services'] = dbFetchCell("SELECT COUNT(*) FROM `services`"); $stats['applications'] = dbFetchCell("SELECT COUNT(*) FROM `applications`"); $stats['bgp'] = dbFetchCell("SELECT COUNT(*) FROM `bgpPeers`"); $stats['ospf'] = dbFetchCell("SELECT COUNT(*) FROM `ospf_ports`"); $stats['eigrp'] = dbFetchCell("SELECT COUNT(*) FROM `eigrp_ports`"); $stats['ipsec_tunnels'] = dbFetchCell("SELECT COUNT(*) FROM `ipsec_tunnels`"); $stats['munin_plugins'] = dbFetchCell("SELECT COUNT(*) FROM `munin_plugins`"); $stats['pseudowires'] = dbFetchCell("SELECT COUNT(*) FROM `pseudowires`"); $stats['vrfs'] = dbFetchCell("SELECT COUNT(*) FROM `vrfs`"); $stats['vminfo'] = dbFetchCell("SELECT COUNT(*) FROM `vminfo`"); $stats['users'] = dbFetchCell("SELECT COUNT(*) FROM `users`"); $stats['bills'] = dbFetchCell("SELECT COUNT(*) FROM `bills`"); $stats['alerts'] = dbFetchCell("SELECT COUNT(*) FROM `alert_table`"); $stats['alert_tests'] = dbFetchCell("SELECT COUNT(*) FROM `alert_tests`"); $stats['slas'] = dbFetchCell("SELECT COUNT(*) FROM `slas`"); $stats['statuses'] = dbFetchCell("SELECT COUNT(*) FROM `status`"); $stats['groups'] = dbFetchCell("SELECT COUNT(*) FROM `groups`"); $stats['group_members'] = dbFetchCell("SELECT COUNT(*) FROM `group_table`"); $stats['poller_time'] = dbFetchCell("SELECT SUM(`last_polled_timetaken`) FROM devices"); $stats['discovery_time'] = dbFetchCell("SELECT SUM(`last_discovered_timetaken`) FROM devices"); $stats['php_version'] = phpversion(); $os_text = external_exec("DISTROFORMAT=export " . $GLOBALS['config']['install_dir'] . "/scripts/distro"); foreach (explode("\n", $os_text) as $part) { list($a, $b) = explode("=", $part); $stats['os'][$a] = $b; } // sysObjectID for Generic devices foreach (dbFetchRows("SELECT `sysObjectID`, COUNT(*) AS `count` FROM `devices` WHERE `os` = 'generic' GROUP BY `sysObjectID`") as $data) { $stats['generics'][$data['sysObjectID']] = $data['count']; } // Per-OS counts foreach (dbFetchRows("SELECT COUNT(*) AS `count`, `os` FROM `devices` GROUP BY `os`") as $data) { $stats['devicetypes'][$data['os']] = $data['count']; } // Per-type counts foreach (dbFetchRows("SELECT COUNT(*) AS `count`, `type` FROM `devices` GROUP BY `type`") as $data) { $stats['types'][$data['type']] = $data['count']; } // Per-apptype counts foreach (dbFetchRows("SELECT COUNT(*) AS `count`, `app_type` FROM `applications` GROUP BY `app_type`") as $data) { $stats['app_types'][$data['app_type']] = $data['count']; } $stats['misc']['max_len']['port_label'] = dbFetchCell("SELECT MAX(LENGTH(`port_label`)) FROM `ports`"); $stats['misc']['max_len']['port_label_short'] = dbFetchCell("SELECT MAX(LENGTH(`port_label_short`)) FROM `ports`"); $stats['misc']['max_len']['port_label_base'] = dbFetchCell("SELECT MAX(LENGTH(`port_label_base`)) FROM `ports`"); $stats['misc']['max_len']['port_label_num'] = dbFetchCell("SELECT MAX(LENGTH(`port_label_num`)) FROM `ports`"); $stats['version'] = OBSERVIUM_VERSION; $stats['uuid'] = get_unique_id(); return $stats; }
function get_localhost() { global $cache; if (!isset($cache['localhost'])) { $cache['localhost'] = php_uname('n'); if (!strpos($cache['localhost'], '.')) { // try use hostname -f for get FQDN hostname $localhost_t = external_exec('/bin/hostname -f'); if (strpos($localhost_t, '.')) { $cache['localhost'] = $localhost_t; } } } return $cache['localhost']; }
function wmi_query($wql, $override = NULL, $namespace = NULL) { if (!isset($namespace)) { $namespace = $GLOBALS['config']['wmi']['namespace']; } if (isset($override) && is_array($override)) { $hostname = $override['hostname']; $domain = $override['domain']; $username = $override['username']; $password = $override['password']; } else { $hostname = $GLOBALS['device']['hostname']; $domain = $GLOBALS['config']['wmi']['domain']; $username = $GLOBALS['config']['wmi']['user']; $password = $GLOBALS['config']['wmi']['pass']; } $options = "--user="******" "; if (empty($password)) { $options .= "--no-pass "; } else { $options .= "--password="******" "; } if (!empty($domain)) { $options .= "--workgroup=" . $domain . " "; } if (empty($GLOBALS['config']['wmi']['delimiter'])) { $options .= "--delimiter=## "; } else { $options .= "--delimiter=" . $GLOBALS['config']['wmi']['delimiter'] . " "; } if (empty($namespace)) { $options .= "--namespace='root\\CIMV2' "; } else { $options .= "--namespace='" . $namespace . "' "; } if ($GLOBALS['debug']) { $options .= "-d2 "; } $options .= "//" . $hostname; $cmd = $GLOBALS['config']['wmic'] . " " . $options . " " . "\"" . $wql . "\""; return external_exec($cmd); }
if (isset($_SESSION['cache']['response_' . $vars['entity_type'] . '_' . $ip])) { echo $_SESSION['cache']['response_' . $vars['entity_type'] . '_' . $ip]; //echo '<h2>CACHED!</h2>'; exit; } $response = ''; $reverse_dns = gethostbyaddr6($ip); if ($reverse_dns) { $response .= '<h4>' . $reverse_dns . '</h4><hr />' . PHP_EOL; } // WHOIS if (is_executable($config['whois']) && !isset($config['http_proxy'])) { // Use direct whois cmd query (preferred) // NOTE, for now not tested and not supported for KRNIC, ie: 202.30.50.0, 2001:02B8:00A2:: $cmd = $config['whois'] . ' ' . $ip; $whois = external_exec($cmd); $multi_whois = explode('# start', $whois); // Some time whois return multiple (ie: whois 8.8.8.8), than use last if (count($multi_whois) > 1) { $whois = array_pop($multi_whois); } $org = 0; foreach (explode("\n", $whois) as $line) { if (preg_match('/^(\\w[\\w\\s\\-\\/]+):.*$/', $line, $matches)) { if (in_array($matches[1], array('Ref', 'source', 'nic-hdl-br'))) { if ($org === 1) { $response .= PHP_EOL; $org++; continue; } else { break;
/** * Get information about process by it identifier (pid) * * @param int $pid The process identifier. * @param boolean $stats If true, additionally show cpu/memory stats * @return array Array with information about process, If process not found, return FALSE */ function get_pid_info($pid, $stats = FALSE) { $pid = intval($pid); if ($pid < 1) { print_debug("Incorrect PID passed"); //trigger_error("PID ".$pid." doesn't exists", E_USER_WARNING); return FALSE; } if ($stats) { // Add CPU/Mem stats $options = 'pid,ppid,uid,gid,pcpu,pmem,vsz,rss,tty,stat,time,lstart,args'; } else { $options = 'pid,ppid,uid,gid,tty,stat,time,lstart,args'; } $ps = external_exec('/bin/ps -ww -o ' . $options . ' -p ' . $pid); $ps = explode("\n", rtrim($ps)); if ($GLOBALS['exec_status']['exitcode'] === 127) { print_debug("/bin/ps command not found, not possible to get process info."); return NULL; } else { if ($GLOBALS['exec_status']['exitcode'] !== 0 || count($ps) < 2) { print_debug("PID " . $pid . " doesn't exists"); //trigger_error("PID ".$pid." doesn't exists", E_USER_WARNING); return FALSE; } } // " PID PPID UID GID %CPU %MEM VSZ RSS TT STAT TIME STARTED COMMAND" // "14675 10250 1000 1000 0.0 0.2 194640 11240 pts/4 S+ 00:00:00 Mon Mar 21 14:48:08 2016 php ./test_pid.php" // // " PID PPID UID GID TT STAT TIME STARTED COMMAND" // "14675 10250 1000 1000 pts/4 S+ 00:00:00 Mon Mar 21 14:48:08 2016 php ./test_pid.php" //print_vars($ps); $timezone = get_timezone(); // Get system timezone info, for correct started time conversion // Parse output $keys = preg_split("/\\s+/", $ps[0], -1, PREG_SPLIT_NO_EMPTY); $entries = preg_split("/\\s+/", $ps[1], count($keys) - 1, PREG_SPLIT_NO_EMPTY); $started = preg_split("/\\s+/", array_pop($entries), 6, PREG_SPLIT_NO_EMPTY); $command = array_pop($started); $started[] = str_replace(':', '', $timezone['system']); // Add system TZ to started time $started_rfc = array_shift($started) . ', '; $started_rfc .= implode(' ', $started); // Reimplode and convert to RFC2822 started date 'Sun, Mar 20 18:01:53 2016 +0300' $entries[] = $started_rfc; $entries[] = $command; // Readd command //print_vars($entries); //print_vars($started); $pid_info = array(); foreach ($keys as $i => $key) { $pid_info[$key] = $entries[$i]; } $pid_info['STARTED_UNIX'] = strtotime($pid_info['STARTED']); //print_vars($pid_info); return $pid_info; }
function snmp_translate($oid, $module, $mibdir = null) { if ($module !== 'all') { $oid = "{$module}::{$oid}"; } $cmd = 'snmptranslate' . mibdir($mibdir); $cmd .= " -m {$module} {$oid}"; // load all the MIBs looking for our object $cmd .= ' 2>/dev/null'; // ignore invalid MIBs $lines = preg_split('/\\n+/', external_exec($cmd)); if (empty($lines)) { d_echo("No results from snmptranslate\n"); return null; } $matches = array(); if (!preg_match('/(.*)::(.*)/', $lines[0], $matches)) { d_echo("This doesn't look like a MIB: {$lines['0']}\n"); return null; } d_echo("SNMP translated: {$module}::{$oid} -> {$matches['1']}::{$matches['2']}\n"); return array($matches[1], $matches[2]); }
/** * @dataProvider providerExternalExec * @group exec */ public function testExternalExec($cmd, $timeout, $result) { $test = external_exec($cmd, $timeout); unset($GLOBALS['exec_status']['runtime']); $this->assertSame($result, $GLOBALS['exec_status']); }
<?php $ipmi_rows = dbFetchRows("SELECT * FROM sensors WHERE device_id = ? AND poller_type='ipmi'", array($device['device_id'])); d_echo($ipmi_rows); if ($ipmi['host'] = get_dev_attrib($device, 'ipmi_hostname')) { $ipmi['user'] = get_dev_attrib($device, 'ipmi_username'); $ipmi['password'] = get_dev_attrib($device, 'ipmi_password'); $ipmi['type'] = get_dev_attrib($device, 'ipmi_type'); echo 'Fetching IPMI sensor data...'; if ($config['own_hostname'] != $device['hostname'] || $ipmi['host'] != 'localhost') { $remote = ' -H ' . $ipmi['host'] . ' -U ' . $ipmi['user'] . ' -P ' . $ipmi['password']; } $results = external_exec($config['ipmitool'] . ' -I ' . $ipmi['type'] . ' -c ' . $remote . ' sdr 2>/dev/null'); d_echo($results); echo " done.\n"; foreach (explode("\n", $results) as $row) { list($desc, $value, $type, $status) = explode(',', $row); $ipmi_sensor[$desc][$config['ipmi_unit'][$type]]['value'] = $value; $ipmi_sensor[$desc][$config['ipmi_unit'][$type]]['unit'] = $type; } foreach ($ipmi_rows as $ipmisensors) { echo 'Updating IPMI sensor ' . $ipmisensors['sensor_descr'] . '... '; $sensor = $ipmi_sensor[$ipmisensors['sensor_descr']][$ipmisensors['sensor_class']]['value']; $unit = $ipmi_sensor[$ipmisensors['sensor_descr']][$ipmisensors['sensor_class']]['unit']; echo $sensor . " {$unit}\n"; $rrd_name = get_sensor_rrd_name($device, $ipmisensors); $rrd_def = 'DS:sensor:GAUGE:600:-20000:20000'; $fields = array('sensor' => $sensor); $tags = array('sensor_class' => $sensor['sensor_class'], 'sensor_type' => $sensor['sensor_type'], 'sensor_descr' => $sensor['sensor_descr'], 'sensor_index' => $sensor['sensor_index'], 'rrd_name' => $rrd_name, 'rrd_def' => $rrd_def); data_update($device, 'ipmi', $tags, $fields); // FIXME warnings in event & mail not done here yet!
$cmd_diff = $config['svn'] . ' diff -r' . $rev['prev'] . ':' . $rev['curr'] . ' ' . $cmd_file; $prev_name = 'r' . $rev['prev']; break; case 'git': $cmd_cat = $config['git'] . ' --git-dir=' . $git_dir . ' --work-tree=' . $cmd_dir . ' show ' . $rev['curr'] . ':' . escapeshellarg(basename($device_config_file)); $cmd_diff = $config['git'] . ' --git-dir=' . $git_dir . ' --work-tree=' . $cmd_dir . ' diff ' . $rev['prev'] . ' ' . $rev['curr'] . ' ' . $cmd_file; $prev_name = $rev['prev']; } $device_config = external_exec($cmd_cat); if (!isset($rev['prev'])) { $diff = ''; if (empty($device_config)) { $device_config = '# 初始化设备添加.'; } } else { $diff = external_exec($cmd_diff); if (!$diff) { $diff = '无差异'; } } } else { $fh = fopen($device_config_file, 'r') or die("无法打开文件"); $device_config = fread($fh, filesize($device_config_file)); fclose($fh); } if ($config['rancid_ignorecomments']) { if (isset($config['os'][$device['os']]['comments'])) { $comments_pattern = $config['os'][$device['os']]['comments']; } else { // Default pattern $comments_pattern = '/^\\s*#/';
function snmpget_cache_multi($device, $oids, $array, $mib = NULL, $mibdir = NULL, $flags = OBS_QUOTES_TRIM) { global $snmp_stats, $mibs_loaded; $output = 'QUs'; $numeric_oids = is_flag_set(OBS_SNMP_NUMERIC, $flags); // Numeric oids, do not parse oid part if (is_flag_set(OBS_SNMP_NUMERIC_INDEX, $flags)) { $output .= 'b'; } if ($numeric_oids) { $output .= 'n'; } if (is_flag_set(OBS_SNMP_ENUM, $flags)) { $output .= 'e'; } if (is_flag_set(OBS_SNMP_HEX, $flags)) { $output .= 'x'; } $options = "-O{$output}"; if (is_array($oids)) { $data = ''; $oid_chunks = array_chunk($oids, 16); $GLOBALS['snmp_status'] = FALSE; foreach ($oid_chunks as $oid_chunk) { $oid_text = implode($oid_chunk, ' '); $cmd = snmp_command('snmpget', $device, $oid_text, $options, $mib, $mibdir, $flags); $start = microtime(TRUE); $this_data = trim(external_exec($cmd)); $runtime = microtime(TRUE) - $start; $GLOBALS['snmp_status'] = $GLOBALS['exec_status']['exitcode'] === 0 ? TRUE : $GLOBALS['snmp_status']; snmp_log_errors('snmpget', $device, $oid_text, $options, $mib, $mibdir); $data .= $this_data . "\n"; $GLOBALS['snmp_stats']['snmpget']['count']++; $GLOBALS['snmp_stats']['snmpget']['time'] += $runtime; } } else { $cmd = snmp_command('snmpget', $device, $oids, $options, $mib, $mibdir, $flags); $start = microtime(TRUE); $data = trim(external_exec($cmd)); $runtime = microtime(TRUE) - $start; $GLOBALS['snmp_status'] = $GLOBALS['exec_status']['exitcode'] === 0 ? TRUE : FALSE; snmp_log_errors('snmpget', $device, $oids, $options, $mib, $mibdir); $GLOBALS['snmp_stats']['snmpget']['count']++; $GLOBALS['snmp_stats']['snmpget']['time'] += $runtime; } foreach (explode("\n", $data) as $entry) { list($oid, $value) = explode('=', $entry, 2); $oid = trim($oid); $value = trim_quotes($value, $flags); if (strpos($value, 'Wrong Type') === 0) { // Remove Wrong Type string $value = preg_replace('/Wrong Type .*?: (.*)/s', '\\1', $value); } // For numeric oids do not split oid and index part if ($numeric_oids && isset($oid[0]) && is_valid_snmp_value($value)) { $array[$oid] = $value; continue; } list($oid, $index) = explode('.', $oid, 2); if (isset($oid[0]) && isset($index) && is_valid_snmp_value($value)) { $array[$index][$oid] = $value; } } if (empty($array)) { $GLOBALS['snmp_status'] = FALSE; snmp_log_errors('snmpget', $device, $oids, $options, $mib, $mibdir); } if (OBS_DEBUG) { print_message('SNMP STATUS[' . ($GLOBALS['snmp_status'] ? '%gTRUE' : '%rFALSE') . '%n]', 'color'); } return $array; }
function rrdtool_file_info($file) { global $config; $info = array('filename' => $file); $rrd = array_filter(explode(PHP_EOL, external_exec($config['rrdtool'] . ' info ' . $file)), 'strlen'); if ($rrd) { foreach ($rrd as $s) { $p = strpos($s, '='); if ($p === false) { continue; } $key = trim(substr($s, 0, $p)); $value = trim(substr($s, $p + 1)); if (strncmp($key, 'ds[', 3) == 0) { /* DS definition */ $p = strpos($key, ']'); $ds = substr($key, 3, $p - 3); if (!isset($info['DS'])) { $info['DS'] = array(); } $ds_key = substr($key, $p + 2); if (strpos($ds_key, '[') === false) { if (!isset($info['DS']["{$ds}"])) { $info['DS']["{$ds}"] = array(); } $info['DS']["{$ds}"]["{$ds_key}"] = rrd_strip_quotes($value); } } else { if (strncmp($key, 'rra[', 4) == 0) { /* RRD definition */ $p = strpos($key, ']'); $rra = substr($key, 4, $p - 4); if (!isset($info['RRA'])) { $info['RRA'] = array(); } $rra_key = substr($key, $p + 2); if (strpos($rra_key, '[') === false) { if (!isset($info['RRA']["{$rra}"])) { $info['RRA']["{$rra}"] = array(); } $info['RRA']["{$rra}"]["{$rra_key}"] = rrd_strip_quotes($value); } } else { if (strpos($key, '[') === false) { $info[$key] = rrd_strip_quotes($value); } } } } } return $info; }
<?php /** * Observium * * This file is part of Observium. * * @package observium * @subpackage alerting * @copyright (C) 2006-2013 Adam Armstrong, (C) 2013-2016 Observium Limited * */ // Export all tags for external program usage foreach (array_keys($message_tags) as $key) { putenv("OBSERVIUM_{$key}=" . $message_tags[$key]); } // Execute given script external_exec($endpoint['script']); // If script's exit code is 0, success. Otherwise we mark it as failed. if ($GLOBALS['exec_status']['exitcode'] == 0) { $notify_status['success'] = TRUE; } else { $notify_status['success'] = FALSE; } // Clean out all set environment variable we set before execution foreach (array_keys($message_tags) as $key) { putenv("OBSERVIUM_{$key}"); } unset($message, $output, $exitcode); // EOF
<?php $ipmi_rows = dbFetchRows("SELECT * FROM sensors WHERE device_id = ? AND poller_type='ipmi'", array($device['device_id'])); if ($ipmi['host'] = get_dev_attrib($device, 'ipmi_hostname')) { $ipmi['user'] = get_dev_attrib($device, 'ipmi_username'); $ipmi['password'] = get_dev_attrib($device, 'ipmi_password'); echo "Fetching IPMI sensor data..."; if ($config['own_hostname'] != $device['hostname'] || $ipmi['host'] != 'localhost') { $remote = " -H " . $ipmi['host'] . " -U " . $ipmi['user'] . " -P " . $ipmi['password']; } $results = external_exec($config['ipmitool'] . " -c " . $remote . " sdr 2>/dev/null"); echo " done.\n"; foreach (explode("\n", $results) as $row) { list($desc, $value, $type, $status) = explode(',', $row); $ipmi_sensor[$desc][$config['ipmi_unit'][$type]]['value'] = $value; $ipmi_sensor[$desc][$config['ipmi_unit'][$type]]['unit'] = $type; } foreach ($ipmi_rows as $ipmisensors) { echo "Updating IPMI sensor " . $ipmisensors['sensor_descr'] . "... "; $sensor = $ipmi_sensor[$ipmisensors['sensor_descr']][$ipmisensors['sensor_class']]['value']; $unit = $ipmi_sensor[$ipmisensors['sensor_descr']][$ipmisensors['sensor_class']]['unit']; $rrd_file = get_sensor_rrd($device, $ipmisensors); if (is_file($old_rrd_file)) { rename($old_rrd_file, $rrd_file); } if (!is_file($rrd_file)) { rrdtool_create($rrd_file, "--step 300 \\\n DS:sensor:GAUGE:600:-20000:20000 " . $config['rrd_rra']); } echo $sensor . " {$unit}\n"; rrdtool_update($rrd_file, "N:{$sensor}"); // FIXME warnings in event & mail not done here yet!
function snmp_walk($device, $oid, $options = NULL, $mib = NULL, $mibdir = NULL, $strip_quotes = 1) { global $runtime_stats; $cmd = snmp_command('snmpwalk', $device, $oid, $options, $mib, $mibdir); $data = trim(external_exec($cmd)); $GLOBALS['snmp_status'] = $GLOBALS['exec_status']['exitcode'] === 0 ? TRUE : FALSE; if ($strip_quotes) { $data = str_replace("\"", "", $data); } if (is_string($data) && preg_match("/No Such (Object|Instance)/i", $data)) { $data = FALSE; $GLOBALS['snmp_status'] = FALSE; } else { if (preg_match('/No more variables left in this MIB View \\(It is past the end of the MIB tree\\)$/', $data) || preg_match('/End of MIB$/', $data)) { # Bit ugly :-( $d_ex = explode("\n", $data); $d_ex_count = count($d_ex); if ($d_ex_count > 1) { // Remove last line unset($d_ex[$d_ex_count - 1]); $data = implode("\n", $d_ex); } else { $data = FALSE; $GLOBALS['snmp_status'] = FALSE; } } } $runtime_stats['snmpwalk']++; if (OBS_DEBUG) { print_message('SNMP_STATUS[' . ($GLOBALS['snmp_status'] ? '%gTRUE' : '%rFALSE') . '%n]', 'color'); } return $data; }
$stats['ospf'] = dbFetchCell("SELECT COUNT(*) FROM `ospf_ports`"); $stats['eigrp'] = dbFetchCell("SELECT COUNT(*) FROM `eigrp_ports`"); $stats['ipsec_tunnels'] = dbFetchCell("SELECT COUNT(*) FROM `ipsec_tunnels`"); $stats['munin_plugins'] = dbFetchCell("SELECT COUNT(*) FROM `munin_plugins`"); $stats['pseudowires'] = dbFetchCell("SELECT COUNT(*) FROM `pseudowires`"); $stats['vrfs'] = dbFetchCell("SELECT COUNT(*) FROM `vrfs`"); $stats['vminfo'] = dbFetchCell("SELECT COUNT(*) FROM `vminfo`"); $stats['users'] = dbFetchCell("SELECT COUNT(*) FROM `users`"); $stats['bills'] = dbFetchCell("SELECT COUNT(*) FROM `bills`"); $stats['alerts'] = dbFetchCell("SELECT COUNT(*) FROM `alert_table`"); $stats['alert_tests'] = dbFetchCell("SELECT COUNT(*) FROM `alert_tests`"); $stats['groups'] = dbFetchCell("SELECT COUNT(*) FROM `groups`"); $stats['group_members'] = dbFetchCell("SELECT COUNT(*) FROM `group_table`"); $stats['poller_time'] = dbFetchCell("SELECT SUM(`last_polled_timetaken`) FROM devices"); $stats['php_version'] = phpversion(); $os_text = external_exec("DISTROFORMAT=export " . $config['install_dir'] . "/scripts/distro"); foreach (explode("\n", $os_text) as $part) { list($a, $b) = explode("=", $part); $stats['os'][$a] = $b; } // sysObjectID for Generic devices foreach (dbFetchRows("SELECT `sysObjectID`, COUNT(*) AS `count` FROM `devices` WHERE `os` = 'generic' GROUP BY `sysObjectID`") as $data) { $stats['generics'][$data['sysObjectID']] = $data['count']; } // Per-OS counts foreach (dbFetchRows("SELECT COUNT(*) AS `count`, `os` FROM `devices` GROUP BY `os`") as $data) { $stats['devicetypes'][$data['os']] = $data['count']; } // Per-type counts foreach (dbFetchRows("SELECT COUNT(*) AS `count`, `type` FROM `devices` GROUP BY `type`") as $data) { $stats['types'][$data['type']] = $data['count'];
/// FIXME. From this uses only check_valid_sensors(), maybe need move to global functions or copy to polling. --mike include_once "includes/discovery/functions.inc.php"; if ($ipmi['host'] = get_dev_attrib($device, 'ipmi_hostname')) { $ipmi['user'] = get_dev_attrib($device, 'ipmi_username'); $ipmi['password'] = get_dev_attrib($device, 'ipmi_password'); $ipmi['port'] = get_dev_attrib($device, 'ipmi_port'); $ipmi['interface'] = get_dev_attrib($device, 'ipmi_interface'); $ipmi['userlevel'] = get_dev_attrib($device, 'ipmi_userlevel'); if (!is_numeric($ipmi['port'])) { $ipmi['port'] = 623; } if ($ipmi['userlevel'] == '') { $ipmi['userlevel'] = 'USER'; } if (array_search($ipmi['interface'], array_keys($config['ipmi']['interfaces'])) === FALSE) { $ipmi['interface'] = 'lan'; } // Also triggers on empty value if ($config['own_hostname'] != $device['hostname'] || $ipmi['host'] != 'localhost') { $remote = " -I " . escapeshellarg($ipmi['interface']) . " -p " . $ipmi['port'] . " -H " . escapeshellarg($ipmi['host']) . " -L " . escapeshellarg($ipmi['userlevel']) . " -U " . escapeshellarg($ipmi['user']) . " -P " . escapeshellarg($ipmi['password']); } $results = external_exec($config['ipmitool'] . $remote . " sensor 2>/dev/null"); $ipmi_sensors = parse_ipmitool_sensor($device, $results); } if (OBS_DEBUG) { print_vars($ipmi_sensors); } foreach ($config['ipmi_unit'] as $type) { check_valid_sensors($device, $type, $ipmi_sensors, 'ipmi'); } // EOF
/** * Checks device availability by icmp echo response * If flag OBS_PING_SKIP passed, pings skipped and returns 0.001 (1ms) * * @param string $hostname Device hostname or IP address * @param int Flags. Supported OBS_DNS_A, OBS_DNS_AAAA and OBS_PING_SKIP * @return float Average response time for used retries count (default retries is 3) */ function isPingable($hostname, $flags = OBS_DNS_ALL) { global $config; $ping_debug = isset($config['ping']['debug']) && $config['ping']['debug']; $try_a = is_flag_set(OBS_DNS_A, $flags); if (is_flag_set(OBS_PING_SKIP, $flags)) { return 0.001; // Ping is skipped, just return 1ms } $timeout = isset($config['ping']['timeout']) ? (int) $config['ping']['timeout'] : 500; if ($timeout < 50) { $timeout = 50; } else { if ($timeout > 2000) { $timeout = 2000; } } $retries = isset($config['ping']['retries']) ? (int) $config['ping']['retries'] : 3; if ($retries < 1) { $retries = 3; } else { if ($retries > 10) { $retries = 10; } } $sleep = floor(1000000 / $retries); // interval between retries, max 1 sec if ($ip_version = get_ip_version($hostname)) { // Ping by IP if ($ip_version === 6) { $cmd = $config['fping6'] . " -t {$timeout} -c 1 -q {$hostname} 2>&1"; } else { if (!$try_a) { if ($ping_debug) { logfile('debug.log', __FUNCTION__ . "() | DEVICE: {$hostname} | Passed IPv4 address but device use IPv6 transport"); } print_debug('Into function ' . __FUNCTION__ . '() passed IPv4 address (' . $hostname . 'but device use IPv6 transport'); return 0; } // Forced check for actual IPv4 address $cmd = $config['fping'] . " -t {$timeout} -c 1 -q {$hostname} 2>&1"; } } else { // First try IPv4 $ip = $try_a ? gethostbyname($hostname) : FALSE; // Do not check IPv4 if transport IPv6 if ($ip && $ip != $hostname) { $cmd = $config['fping'] . " -t {$timeout} -c 1 -q {$ip} 2>&1"; } else { $ip = gethostbyname6($hostname, OBS_DNS_AAAA); // Second try IPv6 if ($ip) { $cmd = $config['fping6'] . " -t {$timeout} -c 1 -q {$ip} 2>&1"; } else { // No DNS records if ($ping_debug) { logfile('debug.log', __FUNCTION__ . "() | DEVICE: {$hostname} | NO DNS record found"); } return 0; } } } for ($i = 1; $i <= $retries; $i++) { $output = external_exec($cmd); if ($GLOBALS['exec_status']['exitcode'] === 0) { // normal $output = '8.8.8.8 : xmt/rcv/%loss = 1/1/0%, min/avg/max = 1.21/1.21/1.21' $tmp = explode('/', $output); $ping = $tmp[7]; if (!$ping) { $ping = 0.001; } // Protection from zero (exclude false status) } else { $ping = 0; } if ($ping) { break; } if ($ping_debug) { logfile('debug.log', __FUNCTION__ . "() | DEVICE: {$hostname} | FPING OUT ({$i}): " . $output[0]); if ($i == $retries) { $mtr = $config['mtr'] . " -r -n -c 5 {$ip}"; logfile('debug.log', __FUNCTION__ . "() | DEVICE: {$hostname} | MTR OUT:\n" . external_exec($mtr)); } } if ($i < $retries) { usleep($sleep); } } return $ping; }
print_debug("Found file ending in '.rrd': " . $file); if ($cutoff) { $file_data = stat($file); if ($file_data['mtime'] < $cutoff) { print_debug("File modification time is " . format_unixtime($file_data['mtime']) . " - deleting"); logfile("housekeeping.log", "File {$file} modification time is " . format_unixtime($file_data['mtime']) . " - deleting"); unlink($file); $count_notmodified++; } } // Not using finfo functions from PHP, whatever I tried always resulted in application/octet-stream. Dumb thing. 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));
function snmp_cache_portName($device, $array) { global $config; if (is_numeric($device['timeout']) && $device['timeout'] > 0) { $timeout = $device['timeout']; } elseif (isset($config['snmp']['timeout'])) { $timeout = $config['snmp']['timeout']; } if (is_numeric($device['retries']) && $device['retries'] > 0) { $retries = $device['retries']; } elseif (isset($config['snmp']['retries'])) { $retries = $config['snmp']['retries']; } if (!isset($device['transport'])) { $device['transport'] = "udp"; } $cmd = $config['snmpwalk']; $cmd .= snmp_gen_auth($device); $cmd .= " -CI -m CISCO-STACK-MIB -O Qs"; $cmd .= " -M " . $config['install_dir'] . "/mibs"; if (isset($timeout)) { $cmd .= " -t " . $timeout; } if (isset($retries)) { $cmd .= " -r " . $retries; } $cmd .= " " . $device['transport'] . ":" . $device['hostname'] . ":" . $device['port'] . " portName"; $output = trim(external_exec($cmd)); $device_id = $device['device_id']; #echo("Caching: portName\n"); foreach (explode("\n", $output) as $entry) { $entry = str_replace("portName.", "", $entry); list($slotport, $portName) = explode("=", $entry); $slotport = trim($slotport); $portName = trim($portName); if ($array[$slotport]['ifIndex']) { $ifIndex = $array[$slotport]['ifIndex']; $array[$slotport]['portName'] = $portName; $array[$ifIndex]['portName'] = $portName; } } return $array; }
function snmp_walk($device, $oid, $options = NULL, $mib = NULL, $mibdir = NULL, $strip_quotes = 1) { global $debug, $config, $runtime_stats; $cmd = snmp_command('snmpwalk', $device, $oid, $options, $mib, $mibdir); $data = trim(external_exec($cmd)); $GLOBALS['snmp_status'] = $GLOBALS['exec_status']['exitcode'] === 0 ? TRUE : FALSE; if ($strip_quotes) { $data = str_replace("\"", "", $data); } if (is_string($data) && preg_match("/No Such (Object|Instance)/i", $data)) { $data = false; $GLOBALS['snmp_status'] = FALSE; } else { if (preg_match('/No more variables left in this MIB View \\(It is past the end of the MIB tree\\)$/', $data) || preg_match('/End of MIB$/', $data)) { # Bit ugly :-( $d_ex = explode("\n", $data); unset($d_ex[count($d_ex) - 1]); $data = implode("\n", $d_ex); } } $runtime_stats['snmpwalk']++; return $data; }
echo OBSERVIUM_PRODUCT_LONG; ?> </h2> <div class="row"> <div class="col-md-6"> <?php if (is_executable($config['install_dir'] . '/scripts/distro')) { $os = explode('|', external_exec($config['install_dir'] . '/scripts/distro'), 5); $os_version = $os[0] . ' ' . $os[1] . ' [' . $os[2] . '] (' . $os[3] . ' ' . $os[4] . ')'; unset($os); } $apache_version = str_replace("Apache/", "", $_SERVER['SERVER_SOFTWARE']); $php_version = phpversion(); $mysql_version = dbFetchCell("SELECT version()"); $snmp_version = str_replace(" version:", "", external_exec($config['snmpget'] . " --version 2>&1")); $rrdtool_version = implode(" ", array_slice(explode(" ", external_exec($config['rrdtool'] . " --version |head -n1")), 1, 1)); ?> <div class="well info_box"> <div class="title"><i class="oicon-information"></i> 版本信息</div> <div class="content"> <table class="table table-bordered table-striped table-condensed-more"> <tbody> <tr><td><b><?php echo escape_html(OBSERVIUM_PRODUCT); ?> </b></td><td><?php echo escape_html(OBSERVIUM_VERSION); ?> </td></tr> <tr><td><b>OS</b></td><td><?php echo escape_html($os_version);
function isPingable($hostname, $try_a = TRUE) { global $config; $timeout = isset($config['ping']['timeout']) ? (int) $config['ping']['timeout'] : 500; if ($timeout < 50) { $timeout = 50; } else { if ($timeout > 2000) { $timeout = 2000; } } $retries = isset($config['ping']['retries']) ? (int) $config['ping']['retries'] : 3; if ($retries < 1) { $retries = 1; } else { if ($retries > 10) { $retries = 10; } } $sleep = floor(1000000 / $retries); // interval between retries, max 1 sec $ping_debug = isset($config['ping']['debug']) && $config['ping']['debug']; if (Net_IPv4::validateIP($hostname)) { if (!$try_a) { logfile('debug.log', __FUNCTION__ . "() | DEVICE: {$hostname} | 通过的IPv4地址, 但是设备使用了IPv6通信"); print_debug('进入函数 ' . __FUNCTION__ . '() 通过IPv4地址 (' . $hostname . '但使用IPv6的通信设置'); return 0; } // Forced check for actual IPv4 address $cmd = $config['fping'] . " -t {$timeout} -c 1 -q {$hostname} 2>&1"; } else { if (Net_IPv6::checkIPv6($hostname)) { // Forced check for actual IPv6 address $cmd = $config['fping6'] . " -t {$timeout} -c 1 -q {$hostname} 2>&1"; } else { // First try IPv4 $ip = $try_a ? gethostbyname($hostname) : FALSE; // Do not check IPv4 if transport IPv6 if ($ip && $ip != $hostname) { $cmd = $config['fping'] . " -t {$timeout} -c 1 -q {$ip} 2>&1"; } else { $ip = gethostbyname6($hostname, FALSE); // Second try IPv6 if ($ip) { $cmd = $config['fping6'] . " -t {$timeout} -c 1 -q {$ip} 2>&1"; } else { // No DNS records logfile('debug.log', __FUNCTION__ . "() | DEVICE: {$hostname} | NO DNS record found"); return 0; } } } } for ($i = 1; $i <= $retries; $i++) { $output = external_exec($cmd); if ($GLOBALS['exec_status']['exitcode'] === 0) { // normal $output = '8.8.8.8 : xmt/rcv/%loss = 1/1/0%, min/avg/max = 1.21/1.21/1.21' $tmp = explode('/', $output); $ping = $tmp[7]; if (!$ping) { $ping = 0.01; } // Protection from zero (exclude false status) } else { $ping = 0; } if ($ping) { break; } if ($ping_debug) { logfile('debug.log', __FUNCTION__ . "() | DEVICE: {$hostname} | FPING OUT ({$i}): " . $output[0]); if ($i == $retries) { $mtr = $config['mtr'] . " -r -n -c 5 {$ip}"; logfile('debug.log', __FUNCTION__ . "() | DEVICE: {$hostname} | MTR OUT:\n" . external_exec($mtr)); } } if ($i < $retries) { usleep($sleep); } } return $ping; }
if ($rrd_options) { rrdtool_graph($graphfile, $rrd_options); //print_debug($rrd_cmd); if (is_file($graphfile)) { if ($vars['image_data_uri'] == TRUE) { $image_data_uri = data_uri($graphfile, 'image/png'); } else { if (!OBS_DEBUG) { $fd = fopen($graphfile, 'rb'); header('Content-type: image/png'); header('Content-Disposition: inline; filename="' . basename($graphfile) . '"'); header('Content-Length: ' . filesize($graphfile)); fpassthru($fd); fclose($fd); } else { external_exec('/bin/ls -l ' . $graphfile); echo '<img src="' . data_uri($graphfile, 'image/png') . '" alt="graph" />'; } } unlink($graphfile); } else { if ($width < 200) { graph_error("Draw Error"); } else { graph_error("Error Drawing Graph"); } } } else { if ($width < 200) { graph_error("Def Error"); } else {
<?php // IPMI - We can discover this on poll! if ($ipmi['host'] = get_dev_attrib($device, 'ipmi_hostname')) { echo 'IPMI : '; $ipmi['user'] = get_dev_attrib($device, 'ipmi_username'); $ipmi['password'] = get_dev_attrib($device, 'ipmi_password'); if ($config['own_hostname'] != $device['hostname'] || $ipmi['host'] != 'localhost') { $remote = " -H " . $ipmi['host'] . " -U '" . $ipmi['user'] . "' -P '" . $ipmi['password'] . "' -L USER"; } foreach ($config['ipmi']['type'] as $ipmi_type) { $results = external_exec($config['ipmitool'] . " -I {$ipmi_type}" . $remote . ' sensor 2>/dev/null|sort'); if ($results != '') { set_dev_attrib($device, 'ipmi_type', $ipmi_type); break; } } echo $ipmi_type; $index = 0; foreach (explode("\n", $results) as $sensor) { // BB +1.1V IOH | 1.089 | Volts | ok | na | 1.027 | 1.054 | 1.146 | 1.177 | na list($desc, $current, $unit, $state, $low_nonrecoverable, $low_limit, $low_warn, $high_warn, $high_limit, $high_nonrecoverable) = explode('|', $sensor); $index++; if (trim($current) != 'na' && $config['ipmi_unit'][trim($unit)]) { discover_sensor($valid['sensor'], $config['ipmi_unit'][trim($unit)], $device, trim($desc), $index, 'ipmi', trim($desc), '1', '1', trim($low_limit) == 'na' ? null : trim($low_limit), trim($low_warn) == 'na' ? null : trim($low_warn), trim($high_warn) == 'na' ? null : trim($high_warn), trim($high_limit) == 'na' ? null : trim($high_limit), $current, 'ipmi'); } } echo "\n"; } check_valid_sensors($device, 'voltage', $valid['sensor'], 'ipmi'); check_valid_sensors($device, 'temperature', $valid['sensor'], 'ipmi');
// DB schema not installed $schema_insert = $db_rev == 0 && !dbQuery('SELECT 1 FROM `devices` LIMIT 1;'); // Try to use mysql cmd for insert initial db schema if ($schema_insert && is_file($config['install_dir'] . '/update/db_schema_mysql.sql')) { if (is_executable('/usr/bin/mysql')) { // Default path $mysql_cmd = '/usr/bin/mysql'; } else { // Try to find mysql executable in search paths $mysql_cmd = external_exec('which mysql'); } if (is_executable($mysql_cmd)) { // If mysql executable exist (or find) use insert initial schema $cmd = $mysql_cmd . ' -u' . escapeshellarg($config['db_user']) . ' -p' . escapeshellarg($config['db_pass']) . ' -h' . escapeshellarg($config['db_host']) . ' -D ' . escapeshellarg($config['db_name']) . ' < ' . escapeshellarg($config['install_dir'] . '/update/db_schema_mysql.sql'); echo 'Install initial database schema ...'; external_exec($cmd); $mysql_status = $GLOBALS['exec_status']['exitcode'] === 0; // Recheck if initial schema installed $db_rev = get_db_version(); $schema_insert = $db_rev == 0 && !dbQuery('SELECT 1 FROM `devices` LIMIT 1;'); if ($mysql_status) { echo ' done.' . PHP_EOL; } else { echo ' FALSE.' . PHP_EOL; if (!$schema_insert) { print_error("Error during installation initial schema, but tables exist. Run update again."); // Not should happen NEVER exit(2); } } }