function search($uname, &$u) { $utimer = utime(); $filter = '(sAMAccountName=' . $uname . ')'; if ($result = ldap_search($this->c, LDAPTREE, $filter)) { $data = ldap_get_entries($this->c, $result); $keys = array_keys($data[0]); $member = ''; while (list($k, $v) = each($keys)) { // echo "<!-- [$v] -->\n"; if (isset($u->{$v})) { if ($v == 'memberof') { for ($i = 0; $i < $data[0][$v]['count']; $i++) { $member .= $data[0][$v][$i] . ';'; } $u->{$v} = $member; } else { $u->{$v} = $data[0][$v]['0']; } } // debug - et mis meil üldse AD'st saada on // $uu = $data['0'][$v]['0']; // echo "<!-- $v = $uu -->\n"; } if ($this->debug) { $t = stop_utimer($utimer); $this->m[] = "<!-- LDAP [{$t}] userdata for [{$uname}] -->\n"; } return true; } return false; }
function add_to_timeline($timestamp, $type, $title, $url) { global $conf, $timeline; $utime = utime(); $time_since = $utime - $conf->last_utime; $conf->last_utime = $utime; echo "{$time_since} [{$type}]: {$timestamp} - {$title}<br />\n"; $timeline[$timestamp][] = array("type" => $type, "url" => $url, "title" => $title); }
public function parse($vars, $fname) { $utimer = utime(); $this->vars = $vars; // loop peab nägema $this::open($fname, 'r'); $this->content = $this::read(); $parsed = $this::rip_open_and_do_replacements($vars); if ($this->debug) { $this->msg[] = "<!-- file: [{$fname}] parsed in " . stop_utimer($utimer) . " s. -->\n"; } return $parsed; }
function conf() { $this->now = date("YmdHi"); $this->last_utime = utime(); $this->created_on = "created_on_{$this->now}"; $this->compiled_on = date("l dS \\of F Y h:i:s A"); $this->user = "******"; $this->keywords = "John, Carmack, id, archive, compilation, doom, quake"; $this->title = "The John Carmack Archive"; $this->fullname = "John Carmack"; $this->header = read_file("template/header.html"); $this->footer = read_file("template/footer.html"); }
function debug($mode, $cur_query = null) { if (!$this->dbg_enabled) { return; } $id =& $this->dbg_id; $dbg =& $this->dbg[$id]; if ($mode == 'start') { $this->sql_starttime = utime(); $dbg['sql'] = isset($cur_query) ? short_query($cur_query) : short_query($this->cur_query); $dbg['src'] = $this->debug_find_source(); $dbg['file'] = $this->debug_find_source('file'); $dbg['line'] = $this->debug_find_source('line'); $dbg['time'] = ''; } else { if ($mode == 'stop') { $this->cur_query_time = utime() - $this->sql_starttime; $this->sql_timetotal += $this->cur_query_time; $dbg['time'] = $this->cur_query_time; $id++; } } }
function discover_device($device, $options = NULL) { global $config, $valid, $exec_status, $discovered_devices; // Initialise variables $valid = array(); // Reset $valid array $modules = array(); $cache_discovery = array(); // Specific discovery cache for exchange snmpwalk data between modules (memory/storage/sensors/etc) $attribs = get_entity_attribs('device', $device['device_id']); $device_start = utime(); // Start counting device poll time // Check if device discovery already running $pid_info = check_process_run($device); if ($pid_info) { // Process ID exist in DB print_message("%rAnother " . $pid_info['process_name'] . " process (PID: " . $pid_info['PID'] . ", UID: " . $pid_info['UID'] . ", STARTED: " . $pid_info['STARTED'] . ") already running for device " . $device['hostname'] . " (" . $device['device_id'] . ").%n", 'color'); return FALSE; } add_process_info($device); // Store process info print_cli_heading($device['hostname'] . " [" . $device['device_id'] . "]", 1); $detect_os = TRUE; // Set TRUE or FALSE for module 'os' (exclude double os detection) if ($device['os'] == 'generic' || isset($options['h']) && $options['h'] == 'new') { $detect_os = FALSE; $old_os = $device['os']; $device['os'] = get_device_os($device); if ($device['os'] != $old_os) { print_cli_data("Device OS changed", $old_os . " -> " . $device['os'], 1); log_event('OS changed: ' . $old_os . ' -> ' . $device['os'], $device, 'device', $device['device_id'], 'warning'); dbUpdate(array('os' => $device['os']), 'devices', '`device_id` = ?', array($device['device_id'])); } } print_cli_data("OS Type", $device['os'], 1); if ($config['os'][$device['os']]['group']) { $device['os_group'] = $config['os'][$device['os']]['group']; print_cli_data("OS Group", $device['os_group'], 1); } print_cli_data("SNMP Version", $device['snmp_version'], 1); print_cli_data("Last discovery", $device['last_discovered'], 1); print_cli_data("Last duration", $device['last_discovered_timetaken'] . " seconds", 1); echo PHP_EOL; // Either only run the modules specified on the commandline, or run all modules in config. if ($options['m']) { foreach (explode(",", $options['m']) as $module) { $modules[$module] = TRUE; } } else { if ($device['force_discovery'] && $options['h'] == 'new' && isset($attribs['force_discovery_modules'])) { // Forced discovery specific modules foreach (json_decode($attribs['force_discovery_modules'], TRUE) as $module) { $modules[$module] = TRUE; } log_event('Forced discovery module(s): ' . implode(', ', array_keys($modules)), $device, 'device', $device['device_id'], 'debug'); } else { $modules = $config['discovery_modules']; } } // Use os specific modules order //print_vars($modules); if (isset($config['os'][$device['os']]['discovery_order'])) { //print_vars($config['os'][$device['os']]['discovery_order']); foreach ($config['os'][$device['os']]['discovery_order'] as $module => $module_order) { if (array_key_exists($module, $modules)) { $module_status = $modules[$module]; switch ($module_order) { case 'last': // add to end of modules list unset($modules[$module]); $modules[$module] = $module_status; break; case 'first': // add to begin of modules list, but not before os/system $new_modules = array(); if ($modules['os']) { $new_modules['os'] = $modules['os']; unset($modules['os']); } if ($modules['system']) { $new_modules['system'] = $modules['system']; unset($modules['system']); } $new_modules[$module] = $module_status; unset($modules[$module]); $modules = $new_modules + $modules; break; default: // add into specific place (after module name in $module_order) // yes, this is hard and magically if (array_key_exists($module_order, $modules)) { unset($modules[$module]); $new_modules = array(); foreach ($modules as $new_module => $new_status) { array_shift($modules); $new_modules[$new_module] = $new_status; if ($new_module == $module_order) { $new_modules[$module] = $module_status; break; } } $modules = array_merge($new_modules, (array) $modules); } } } } //print_vars($modules); } foreach ($modules as $module => $module_status) { if (discovery_module_excluded($device, $module) === FALSE) { if ($attribs['discover_' . $module] || $module_status && !isset($attribs['discover_' . $module])) { $m_start = utime(); $GLOBALS['module_stats'][$module] = array(); print_cli_heading("Module Start: %R" . $module . ""); include "includes/discovery/{$module}.inc.php"; $m_end = utime(); $GLOBALS['module_stats'][$module]['time'] = round($m_end - $m_start, 4); print_module_stats($device, $module); echo PHP_EOL; //print_cli_heading("Module End: %R".$module.""); } elseif (isset($attribs['discover_' . $module]) && $attribs['discover_' . $module] == "0") { print_debug("Module [ {$module} ] disabled on host."); } else { print_debug("Module [ {$module} ] disabled globally."); } } } // Set type to a predefined type for the OS if it's not already set if ($device['type'] == "unknown" || $device['type'] == "") { if ($config['os'][$device['os']]['type']) { $device['type'] = $config['os'][$device['os']]['type']; } } $device_end = utime(); $device_run = $device_end - $device_start; $device_time = substr($device_run, 0, 5); dbUpdate(array('last_discovered' => array('NOW()'), 'type' => $device['type'], 'last_discovered_timetaken' => $device_time, 'force_discovery' => 0), 'devices', '`device_id` = ?', array($device['device_id'])); if (isset($attribs['force_discovery_modules'])) { del_entity_attrib('device', $device['device_id'], 'force_discovery_modules'); } // Put performance into devices_perftimes table // Not worth putting discovery data into rrd. it's not done every 5 mins :) dbInsert(array('device_id' => $device['device_id'], 'operation' => 'discover', 'start' => $device_start, 'duration' => $device_run), 'devices_perftimes'); print_cli_heading($device['hostname'] . " [" . $device['device_id'] . "] completed discovery modules at " . date("Y-m-d H:i:s"), 1); print_cli_data("Discovery time", $device_time . " seconds", 1); echo PHP_EOL; $discovered_devices++; // Clean del_process_info($device); // Remove process info unset($cache_discovery); }
$mask = $mask != NULL ? $mask : '32'; $range = $net . '/' . $mask; if ($mask >= 0 && $mask <= 32 && Net_IPv4::ipInNetwork($_SERVER['REMOTE_ADDR'], $range)) { $auth = TRUE; // hardcode authenticated for matched subnet print_debug("认证的CIDR匹配IPv4 {$range}."); break; } } elseif (Net_IPv6::checkIPv6($net)) { // IPv6 $mask = $mask != NULL ? $mask : '128'; $range = $net . '/' . $mask; if ($mask >= 0 && $mask <= 128 && Net_IPv6::isInNetmask($_SERVER['REMOTE_ADDR'], $range)) { $auth = TRUE; // hardcode authenticated for matched subnet print_debug("认证的CIDR匹配IPv6 {$range}"); break; } } } } if (!$auth) { // Normal auth include $config['html_dir'] . "/includes/authenticate.inc.php"; } // Push $_GET into $vars to be compatible with web interface naming $vars = get_vars('GET'); include $config['html_dir'] . "/includes/graphs/graph.inc.php"; $runtime = utime() - $start; print_debug("运行时间 " . $runtime . " 秒"); // EOF
$panel_html = ob_get_contents(); ob_end_clean(); register_html_panel($panel_html); } } else { if ($config['auth_mechanism'] == 'cas') { // Not Authenticated. CAS logon. echo 'Not authorized.'; exit; } else { // Not Authenticated. Print login. include $config['html_dir'] . "/pages/logon.inc.php"; exit; } } $gentime = utime() - $runtime_start; $fullsize = memory_get_usage(); unset($cache); $cachesize = $fullsize - memory_get_usage(); if ($cachesize < 0) { $cachesize = 0; } // Silly PHP! ?> </div> <?php if ($vars['bare'] != 'yes') { ?> <div class="navbar navbar-fixed-bottom">
} $filter = "({$attr}=*{$filter})"; break; case 'equals': $filter = "({$attr}={$filter})"; break; case 'sounds like': $filter = "({$attr}~={$filter})"; break; default: pla_error("Unrecognized criteria option: " . htmlspecialchars($criterion) . "If you want to add your own criteria to the list. Be sure to edit " . "search.php to handle them. Quitting."); } } $time_start = utime(); $results = pla_ldap_search($server_id, $filter, $base_dn, $search_result_attributes, $scope); $time_end = utime(); $time_elapsed = round($time_end - $time_start, 2); $count = count($results); ?> <br /> <center>Found <b><?php echo $count; ?> </b> <?php echo $count == 1 ? 'entry' : 'entries'; ?> . <?php if ($form == 'simple') {
public function accept() { $server = $this->getServer(); # Get the data to be exported $query = array(); $base = get_request('dn', 'REQUEST'); $query['baseok'] = true; $query['filter'] = get_request('filter', 'REQUEST', false, 'objectclass=*'); $query['scope'] = get_request('scope', 'REQUEST', false, 'base'); $query['deref'] = $_SESSION[APPCONFIG]->getValue('deref', 'export'); $query['size_limit'] = 0; $attrs = get_request('attributes', 'REQUEST'); $attrs = preg_replace('/\\s+/', '', $attrs); if ($attrs) { $query['attrs'] = explode(',', $attrs); } else { $query['attrs'] = array('*'); } if (get_request('sys_attr')) { if (!in_array('*', $query['attrs'])) { array_push($query['attrs'], '*'); } array_push($query['attrs'], '+'); } if (!$base) { $bases = $server->getBaseDN(); } else { $bases = array($base); } foreach ($bases as $base) { $query['base'] = $base; $time_start = utime(); $this->results[$base] = $server->query($query, null); $time_end = utime(); usort($this->results[$base], 'pla_compare_dns'); $this->resultsdata[$base]['time'] = round($time_end - $time_start, 2); # If no result, there is a something wrong if (!$this->results[$base] && $server->getErrorNum(null)) { system_message(array('title' => _('Encountered an error while performing search.'), 'body' => ldap_error_msg($server->getErrorMessage(null), $server->getErrorNum(null)), 'type' => 'error')); } $this->items += count($this->results[$base]); } $this->resultsdata['scope'] = $query['scope']; $this->resultsdata['filter'] = $query['filter']; $this->resultsdata['attrs'] = $query['attrs']; # Other settings switch (get_request('format', 'POST', false, 'unix')) { case 'win': $this->br = "\r\n"; break; case 'mac': $this->br = "\r"; break; case 'unix': default: $this->br = "\n"; } if (get_request('compress', 'REQUEST') == 'on') { $this->compress = true; } }
function poll_device($device, $options) { global $config, $debug, $device, $polled_devices, $db_stats, $memcache; $old_device_state = unserialize($device['device_state']); $attribs = get_dev_attribs($device['device_id']); $status = 0; unset($array); $device_start = utime(); // Start counting device poll time echo $device['hostname'] . " " . $device['device_id'] . " " . $device['os'] . " "; if ($config['os'][$device['os']]['group']) { $device['os_group'] = $config['os'][$device['os']]['group']; echo "(" . $device['os_group'] . ")"; } echo "\n"; unset($poll_update); unset($poll_update_query); unset($poll_separator); $poll_update_array = array(); $host_rrd = $config['rrd_dir'] . "/" . $device['hostname']; if (!is_dir($host_rrd)) { mkdir($host_rrd); echo "Created directory : {$host_rrd}\n"; } $device['pingable'] = isPingable($device['hostname']); if ($device['pingable']) { $device['snmpable'] = isSNMPable($device); if ($device['snmpable']) { $status = "1"; $status_type = ''; } else { echo "SNMP Unreachable"; $status = "0"; $status_type = ' (snmp)'; } } else { echo "Unpingable"; $status = "0"; $status_type = ' (ping)'; } if ($device['status'] != $status) { $poll_update .= $poll_separator . "`status` = '{$status}'"; $poll_separator = ", "; dbUpdate(array('status' => $status), 'devices', 'device_id=?', array($device['device_id'])); dbInsert(array('importance' => '0', 'device_id' => $device['device_id'], 'message' => "Device is " . ($status == '1' ? 'up' : 'down')), 'alerts'); log_event('Device status changed to ' . ($status == '1' ? 'Up' : 'Down') . $status_type, $device, 'system'); notify($device, "Device " . ($status == '1' ? 'Up' : 'Down') . ": " . $device['hostname'] . $status_type, "Device " . ($status == '1' ? 'up' : 'down') . ": " . $device['hostname']); } $rrd = $config['rrd_dir'] . "/" . $device['hostname'] . "/status.rrd"; if (!is_file($rrd)) { rrdtool_create($rrd, "DS:status:GAUGE:600:0:1 " . $config['rrd_rra']); } if ($status == "1" || $status == "0") { rrdtool_update($rrd, "N:" . $status); } else { rrdtool_update($rrd, "N:U"); } // Ping response RRD database. $ping_rrd = $config['rrd_dir'] . '/' . $device['hostname'] . '/ping.rrd'; if (!is_file($ping_rrd)) { rrdtool_create($ping_rrd, "DS:ping:GAUGE:600:0:65535 " . $config['rrd_rra']); } if ($device['pingable']) { rrdtool_update($ping_rrd, "N:" . $device['pingable']); } else { rrdtool_update($ping_rrd, "N:U"); } // SNMP response RRD database. $ping_snmp_rrd = $config['rrd_dir'] . '/' . $device['hostname'] . '/ping_snmp.rrd'; if (!is_file($ping_snmp_rrd)) { rrdtool_create($ping_snmp_rrd, "DS:ping_snmp:GAUGE:600:0:65535 " . $config['rrd_rra']); } if ($device['snmpable']) { rrdtool_update($ping_snmp_rrd, "N:" . $device['snmpable']); } else { rrdtool_update($ping_snmp_rrd, "N:U"); } if ($status == "1") { $graphs = array(); $oldgraphs = array(); // Enable Ping graphs $graphs['ping'] = TRUE; // Enable SNMP graphs $graphs['ping_snmp'] = TRUE; if ($options['m']) { foreach (explode(",", $options['m']) as $module) { if (is_file("includes/polling/" . $module . ".inc.php")) { include "includes/polling/" . $module . ".inc.php"; } } } else { foreach ($config['poller_modules'] as $module => $module_status) { if ($attribs['poll_' . $module] || $module_status && !isset($attribs['poll_' . $module])) { if ($debug) { echo "including: includes/polling/{$module}.inc.php\n"; } include 'includes/polling/' . $module . '.inc.php'; } elseif (isset($attribs['poll_' . $module]) && $attribs['poll_' . $module] == "0") { echo "Module [ {$module} ] disabled on host.\n"; } else { echo "Module [ {$module} ] disabled globally.\n"; } } } if (!isset($options['m'])) { // FIXME EVENTLOGGING -- MAKE IT SO WE DO THIS PER-MODULE? // This code cycles through the graphs already known in the database and the ones we've defined as being polled here // If there any don't match, they're added/deleted from the database. // Ideally we should hold graphs for xx days/weeks/polls so that we don't needlessly hide information. // Hardcoded poller performance $graphs['poller_perf'] = TRUE; foreach (dbFetch("SELECT `graph` FROM `device_graphs` WHERE `device_id` = ?", array($device['device_id'])) as $graph) { if (!isset($graphs[$graph["graph"]])) { dbDelete('device_graphs', "`device_id` = ? AND `graph` = ?", array($device['device_id'], $graph["graph"])); } else { $oldgraphs[$graph["graph"]] = TRUE; } } foreach ($graphs as $graph => $value) { if (!isset($oldgraphs[$graph])) { echo "+"; dbInsert(array('device_id' => $device['device_id'], 'graph' => $graph), 'device_graphs'); } echo $graph . " "; } } $device_end = utime(); $device_run = $device_end - $device_start; $device_time = substr($device_run, 0, 5); $update_array['last_polled'] = array('NOW()'); $update_array['last_polled_timetaken'] = $device_time; $update_array['device_state'] = serialize($device_state); #echo("$device_end - $device_start; $device_time $device_run"); echo "Polled in {$device_time} seconds\n"; // Only store performance data if we're not doing a single-module poll if (!$options['m']) { dbInsert(array('device_id' => $device['device_id'], 'operation' => 'poll', 'start' => $device_start, 'duration' => $device_run), 'devices_perftimes'); $poller_rrd = $config['rrd_dir'] . "/" . $device['hostname'] . "/perf-poller.rrd"; if (!is_file($poller_rrd)) { rrdtool_create($poller_rrd, "DS:val:GAUGE:600:0:38400 " . $config['rrd_rra']); } rrdtool_update($poller_rrd, "N:" . $device_time); } if ($debug) { echo "Updating " . $device['hostname'] . " - " . print_r($update_array) . " \n"; } $updated = dbUpdate($update_array, 'devices', '`device_id` = ?', array($device['device_id'])); if ($updated) { echo "UPDATED!\n"; } unset($storage_cache); // Clear cache of hrStorage ** MAYBE FIXME? ** unset($cache); // Clear cache (unify all things here?) } }
logfile("Connection to UNIX agent on " . $agent_socket . " failed. ERROR: " . $errno . " " . $errstr); /// Try check_mk port if the official one doesn't work. $agent_port = "6556"; $agent_start = utime(); $agent_socket = "tcp://" . $device['hostname'] . ":" . $agent_port; $agent = @stream_socket_client($agent_socket, $errno, $errstr, 10); if (!$agent) { echo "Connection to UNIX agent on " . $agent_socket . " failed. ERROR: " . $errno . " " . $errstr . "\n"; logfile("Connection to UNIX agent on " . $agent_socket . " failed. ERROR: " . $errno . " " . $errstr); } else { $agent_raw = stream_get_contents($agent); } } else { $agent_raw = stream_get_contents($agent); } $agent_end = utime(); $agent_time = round(($agent_end - $agent_start) * 1000); if (!empty($agent_raw)) { echo "execution time: " . $agent_time . "ms"; $agent_rrd = $config['rrd_dir'] . "/" . $device['hostname'] . "/agent.rrd"; if (!is_file($agent_rrd)) { rrdtool_create($agent_rrd, "DS:time:GAUGE:600:0:U " . $config['rrd_rra']); } rrdtool_update($agent_rrd, "N:" . $agent_time); $graphs['agent'] = TRUE; foreach (explode("<<<", $agent_raw) as $section) { list($section, $data) = explode(">>>", $section); list($sa, $sb, $sc) = explode("-", $section, 3); ## Compatibility with versions of scripts with and without app- ## Disabled for DRBD because it falsely detects the check_mk output if ($section == "apache") {
$key = $value[2]; $val = htmlspecialchars(stripslashes($pdef[$plkp[$key]])); if ($value[1]) { $checked = $val ? ' checked' : ''; } eval('$opt="' . addslashes($templates[$value[1]][1]) . ($value[1] == 'tf' ? '' : '<br />') . '";'); if ($value[1] != 'hidden') { tr($value[0], " {$opt} {$value['4']}", 1); } else { echo $opt; } } } } end_table(); ?> <br /> <center> <input name="action" type="hidden" value="submit" readonly> <input type="submit" name="Submit" value="Submit"> <input type="reset" name="Reset" value="Reset"> </center> </form> <?php end_frame(); end_main_frame(); $pgt = utime() - $pgs; echo "<center>Page Generated in {$pgt} Seconds</center>"; stdfoot(); die;
} } else { #$rrd_options .= " HRULE:0#999999"; if ($no_file) { if ($width < 200) { graph_error("无RRD"); } else { graph_error("未找到 RRD数据文件"); } } elseif (isset($vars['command_only']) && $vars['command_only'] == TRUE) { $graph_start = utime(); $return = rrdtool_graph($graphfile, $rrd_options); $graph_end = utime(); $graph_run = $graph_end - $graph_start; $graph_time = substr($graph_run, 0, 5); $total_end = utime(); $total_run = $total_end - $total_start; $total_time = substr($total_run, 0, 5); unlink($graphfile); $graph_return['total_time'] = $total_time; $graph_return['rrdtool_time'] = $graph_time; $graph_return['cmd'] = "rrdtool graph {$graphfile} {$rrd_options}"; } else { if ($rrd_options) { rrdtool_graph($graphfile, $rrd_options); if ($debug) { echo $rrd_cmd; } if (is_file($graphfile)) { if ($vars['image_data_uri'] == TRUE) { $image_data_uri = data_uri($graphfile, 'image/png');
function discover_device($device, $options = null) { global $config, $valid; $valid = array(); // Reset $valid array $attribs = get_dev_attribs($device['device_id']); $device_start = utime(); // Start counting device poll time echo $device['hostname'] . ' ' . $device['device_id'] . ' ' . $device['os'] . ' '; if ($device['os'] == 'generic') { // verify if OS has changed from generic $device['os'] = getHostOS($device); if ($device['os'] != 'generic') { echo "\nDevice os was updated to " . $device['os'] . '!'; dbUpdate(array('os' => $device['os']), 'devices', '`device_id` = ?', array($device['device_id'])); } } if ($config['os'][$device['os']]['group']) { $device['os_group'] = $config['os'][$device['os']]['group']; echo ' (' . $device['os_group'] . ')'; } echo "\n"; // If we've specified modules, use them, else walk the modules array if ($options['m']) { foreach (explode(',', $options['m']) as $module) { if (is_file("includes/discovery/{$module}.inc.php")) { include "includes/discovery/{$module}.inc.php"; } } } else { foreach ($config['discovery_modules'] as $module => $module_status) { if ($attribs['discover_' . $module] || $module_status && !isset($attribs['discover_' . $module])) { include 'includes/discovery/' . $module . '.inc.php'; } else { if (isset($attribs['discover_' . $module]) && $attribs['discover_' . $module] == '0') { echo "Module [ {$module} ] disabled on host.\n"; } else { echo "Module [ {$module} ] disabled globally.\n"; } } } } // Set type to a predefined type for the OS if it's not already set if ($device['type'] == 'unknown' || $device['type'] == '') { if ($config['os'][$device['os']]['type']) { $device['type'] = $config['os'][$device['os']]['type']; } } $device_end = utime(); $device_run = $device_end - $device_start; $device_time = substr($device_run, 0, 5); dbUpdate(array('last_discovered' => array('NOW()'), 'type' => $device['type'], 'last_discovered_timetaken' => $device_time), 'devices', '`device_id` = ?', array($device['device_id'])); echo "Discovered in {$device_time} seconds\n"; global $discovered_devices; echo "\n"; $discovered_devices++; }
$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']); } $ipmi_start = utime(); $results = external_exec($config['ipmitool'] . $remote . " sensor 2>/dev/null"); $ipmi_end = utime(); $ipmi_time = round(($ipmi_end - $ipmi_start) * 1000); echo '(' . $ipmi_time . 'ms) '; $ipmi_sensors = parse_ipmitool_sensor($device, $results); } if ($debug) { print_vars($ipmi_sensors); } foreach ($config['ipmi_unit'] as $type) { check_valid_sensors($device, $type, $ipmi_sensors, 'ipmi'); } echo "\n"; // EOF
// Additional common counts if ($config['enable_pseudowires']) { $cache['ports']['pseudowires'] = dbFetchColumn('SELECT DISTINCT `port_id` FROM `pseudowires` WHERE 1 ' . $cache['where']['ports_permitted']); $cache['pseudowires']['count'] = count($cache['ports']['pseudowires']); } if ($config['poller_modules']['cisco-cbqos'] || $config['discovery_modules']['cisco-cbqos']) { $cache['ports']['cbqos'] = dbFetchColumn('SELECT DISTINCT `port_id` FROM `ports_cbqos` WHERE 1 ' . $cache['where']['ports_permitted']); $cache['cbqos']['count'] = count($cache['ports']['cbqos']); } if ($config['poller_modules']['unix-agent']) { $cache['packages']['count'] = dbFetchCell("SELECT COUNT(*) FROM `packages` WHERE 1 " . $cache['where']['devices_permitted']); } if ($config['poller_modules']['applications']) { $cache['applications']['count'] = dbFetchCell("SELECT COUNT(*) FROM `applications` WHERE 1 " . $cache['where']['devices_permitted']); } if ($config['poller_modules']['wifi'] || $config['discovery_modules']['wifi']) { $cache['wifi_sessions']['count'] = dbFetchCell("SELECT COUNT(*) FROM `wifi_sessions` WHERE 1 " . $cache['where']['devices_permitted']); } if ($config['poller_modules']['printersupplies'] || $config['discovery_modules']['printersupplies']) { $cache['printersupplies']['count'] = dbFetchCell("SELECT COUNT(*) FROM `printersupplies` WHERE 1 " . $cache['where']['devices_permitted']); } $cache['neighbours']['count'] = dbFetchCell("SELECT COUNT(*) FROM `neighbours` WHERE `active` = 1 " . $cache['where']['ports_permitted']); $cache['sla']['count'] = dbFetchCell("SELECT COUNT(*) FROM `slas` WHERE `deleted` = 0 " . $cache['where']['devices_permitted']); $cache['p2pradios']['count'] = dbFetchCell("SELECT COUNT(*) FROM `p2p_radios` WHERE `deleted` = 0 " . $cache['where']['devices_permitted']); $cache['vm']['count'] = dbFetchCell("SELECT COUNT(*) FROM `vminfo` WHERE 1 " . $cache['where']['devices_permitted']); $cache_time = utime() - $cache_start; // Clean arrays (from DB queries) unset($devices_array, $ports_array, $sensors_array, $status_array, $graphs_array, $device_graphs); // Clean variables (generated by foreach) unset($device, $port, $sensor, $status, $bgp, $ospf); // EOF
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 { graph_error("Graph Definition Error"); } } } } } } // Total runtime and clean graph file $graph_return['total'] = utime() - $total_start; if (strlen($graph_return['filename']) && is_file($graph_return['filename'])) { unlink($graph_return['filename']); } // EOF
/** * Spam filter */ private function spam_filter($text) { global $bb_cfg; static $spam_words = null; static $spam_replace = ' СПАМ'; if (isset($this)) { $found_spam =& $this->found_spam; } // set $spam_words and $spam_replace if (!$bb_cfg['spam_filter_file_path']) { return $text; } if (is_null($spam_words)) { $spam_words = file_get_contents($bb_cfg['spam_filter_file_path']); $spam_words = strtolower($spam_words); $spam_words = explode("\n", $spam_words); } $found_spam = array(); $tm_start = utime(); $msg_decoded = $text; $msg_decoded = html_entity_decode($msg_decoded); $msg_decoded = urldecode($msg_decoded); $msg_decoded = str_replace('&', ' &', $msg_decoded); $msg_search = strtolower($msg_decoded); foreach ($spam_words as $spam_str) { if (!($spam_str = trim($spam_str))) { continue; } if (strpos($msg_search, $spam_str) !== false) { $found_spam[] = $spam_str; } } if ($found_spam) { $spam_exp = array(); foreach ($found_spam as $keyword) { $spam_exp[] = preg_quote($keyword, '/'); } $spam_exp = join('|', $spam_exp); $text = preg_replace("/({$spam_exp})(\\S*)/i", $spam_replace, $msg_decoded); $text = htmlCHR($text, false, ENT_NOQUOTES); # bb_log(date("H:i:s") ." | ". sprintf('%.4f', (utime() - $tm_start)) ." | ". sprintf('%-6s', strlen($text)) ." | ". join(' ** ', $found_spam) ."\n", 'spam_filter'); } return $text; }
if (isset($options['r'])) { $config['norrd'] = TRUE; } $cache['maint'] = cache_alert_maintenance(); rrdtool_pipe_open($rrd_process, $rrd_pipes); print_cli_heading("%WStarting polling run at " . date("Y-m-d H:i:s"), 0); $polled_devices = 0; if (!isset($query)) { $query = "SELECT `device_id` FROM `devices` WHERE `disabled` = 0 {$where} ORDER BY `device_id` ASC"; } foreach (dbFetch($query, $params) as $device) { $device = dbFetchRow("SELECT * FROM `devices` WHERE `device_id` = ?", array($device['device_id'])); poll_device($device, $options); $polled_devices++; } $poller_end = utime(); $poller_run = $poller_end - $poller_start; $poller_time = substr($poller_run, 0, 5); if ($polled_devices) { dbInsert(array('type' => 'poll', 'doing' => $doing, 'start' => $poller_start, 'duration' => $poller_time, 'devices' => $polled_devices), 'perf_times'); if (is_numeric($doing)) { $doing = $device['hostname']; } // Single device ID convert to hostname for log } else { print_warning("WARNING: 0 devices polled. Did you specify a device that does not exist?"); } $string = $argv[0] . ": {$doing} - {$polled_devices} devices polled in {$poller_time} secs"; print_debug($string); print_cli_heading("%WCompleted polling run at " . date("Y-m-d H:i:s"), 0); if (!isset($options['q'])) {
echo '</div>'; echo '<div id="public-logon" style="display:none;">'; echo '<div class="well"><h3>Logon<button class="btn btn-default" type="submit" style="float:right;" id="ToggleStatus">Status</button></h3></div>'; require 'pages/logon.inc.php'; echo '</div>'; } } else { require 'pages/logon.inc.php'; } } ?> </div> </div> </div> <?php $runtime_end = utime(); $runtime = $runtime_end - $runtime_start; $gentime = substr($runtime, 0, 5); # FIXME - move this if ($config['page_gen']) { echo ' <br />MySQL: Cell ' . ($db_stats['fetchcell'] + 0) . '/' . round($db_stats['fetchcell_sec'] + 0, 3) . 's' . ' Row ' . ($db_stats['fetchrow'] + 0) . '/' . round($db_stats['fetchrow_sec'] + 0, 3) . 's' . ' Rows ' . ($db_stats['fetchrows'] + 0) . '/' . round($db_stats['fetchrows_sec'] + 0, 3) . 's' . ' Column ' . ($db_stats['fetchcol'] + 0) . '/' . round($db_stats['fetchcol_sec'] + 0, 3) . 's'; $fullsize = memory_get_usage(); unset($cache); $cachesize = $fullsize - memory_get_usage(); if ($cachesize < 0) { $cachesize = 0; } // Silly PHP! echo ' <br />Cached data in memory is ' . formatStorage($cachesize) . '. Page memory usage is ' . formatStorage($fullsize) . ', peaked at ' . formatStorage(memory_get_peak_usage()) . '.'; echo ' <br />Generated in ' . $gentime . ' seconds.'; }
function print_form_box($data, $return = FALSE) { $form_id = isset($data['id']) ? $data['id'] : 'form-' . strgen(); $form_class = 'form form-horizontal'; if (isset($data['style'])) { $form_style = ' style="' . $data['style'] . '"'; } else { $form_style = ' style="margin-bottom:0;"'; } $base_class = array_key_exists('class', $data) ? $data['class'] : 'box'; $base_space = $data['space'] ? $data['space'] : '15px'; $used_vars = array(); // Cache permissions to session var permissions_cache_session(); //r($_SESSION['cache']); if ($data['submit_by_key']) { $action = ''; if ($data['url']) { $action .= 'this.form.prop(\'action\', form_to_path(\'' . $form_id . '\'));'; } register_html_resource('script', '$(function(){$(\'form#' . $form_id . '\').each(function(){$(this).find(\'input\').keypress(function(e){if(e.which==10||e.which==13){' . $action . 'this.form.submit();}});});});'); } $header = ''; if (isset($data['title'])) { $header .= ' <h2>' . $data['title'] . '</h2>' . PHP_EOL; } // Form elements $div_begin = '<div class="row">' . PHP_EOL; $div_end = '</div>' . PHP_EOL; if ($data['type'] == 'horizontal') { $row_style = ''; $fieldset = array(); foreach ($data['row'] as $k => $row) { $row_group = $k; $row_elements = ''; $row_label = ''; $row_control_group = FALSE; $i = 0; foreach ($row as $id => $element) { $used_vars[] = $id; $element['id'] = $id; if ($element['fieldset']) { $row_group = $element['fieldset']; // Add this element to group } // Additional element options for horizontal specific form switch ($element['type']) { case 'hidden': $div_class = ''; $div_style = ''; break; case 'submit': $div_class = 'form-actions'; $div_style = ' style="margin: 0px;"'; break; case 'text': case 'input': case 'password': case 'textarea': default: $row_control_group = TRUE; // In horizontal, name always placed at left if (!isset($element['placeholder'])) { $element['placeholder'] = TRUE; } if ($i < 1) { // Add laber for first element in row $row_label = ' <label class="control-label" for="' . $element['id'] . '">' . $element['name'] . '</label>' . PHP_EOL; $row_control_id = $element['id'] . '_div'; } $div_class = 'controls'; $div_style = ''; break; } if (!isset($element['div_class'])) { $element['div_class'] = $div_class; } //if ($element['right']) //{ // $element['div_class'] .= ' pull-right'; //} if ($id == 'search' && $data['url']) { // Add form_id here, for generate onclick action in submit button $element['form_id'] = $form_id; } $row_elements .= generate_form_element($element); $i++; } if ($element['div_class']) { // no additional divs if empty div class (hidden element for example) $row_elements = $row_label . PHP_EOL . ' <div class="' . $element['div_class'] . '"' . $div_style . '>' . PHP_EOL . $row_elements . ' </div>' . PHP_EOL; } else { $row_label = str_replace(' class="control-label"', '', $row_label); $row_elements = $row_label . PHP_EOL . $row_elements; } if ($row_control_group) { $fieldset[$row_group] .= ' <div id="' . $row_control_id . '" class="control-group"> <!-- START row-' . $k . ' -->' . PHP_EOL; $fieldset[$row_group] .= $row_elements; $fieldset[$row_group] .= ' </div> <!-- END row-' . $k . ' -->' . PHP_EOL; } else { // Do not add control group for submit/hidden $fieldset[$row_group] .= $row_elements; } //$row_style = 'style="margin-top: '.$base_space.';"'; // Add space between rows } $divs = array(); $fieldset_tooltip = ''; foreach ($data['fieldset'] as $group => $entry) { if (isset($fieldset[$group])) { if (!is_array($entry)) { $entry = array('title' => $entry); } // Custom style if (!isset($entry['style'])) { $entry['style'] = 'padding-bottom: 0px !important;'; // Remove last additional padding space } // Combinate fieldsets into common rows if ($entry['div']) { $divs[$entry['div']][] = $group; } else { $divs['row'][] = $group; } $box_args = array('header-border' => TRUE, 'padding' => TRUE, 'id' => $group); if (isset($entry['style'])) { $box_args['body-style'] = $entry['style']; } if (isset($entry['title'])) { $box_args['title'] = $entry['title']; if ($entry['icon']) { // $box_args['icon'] => $entry['icon']; } } if (isset($entry['tooltip'])) { $box_args['header-controls'] = array('controls' => array('tooltip' => array('icon' => 'icon-info text-primary', 'anchor' => TRUE, 'class' => 'tooltip-from-element', 'data' => 'data-tooltip-id="tooltip-' . $group . '"'))); $fieldset_tooltip .= '<div id="tooltip-' . $group . '" style="display: none;">' . PHP_EOL; $fieldset_tooltip .= $entry['tooltip'] . '</div>' . PHP_EOL; } if (isset($entry['tooltip'])) { $box_args['style'] = $entry['style']; } $fieldset_begin = generate_box_open($box_args); $fieldset_end = generate_box_close(); // Additional div class if set if (isset($entry['class'])) { $fieldset_begin = '<div class="' . $entry['class'] . '">' . PHP_EOL . $fieldset_begin; $fieldset_end .= '</div>' . PHP_EOL; } $row_elements = $fieldset_begin . ' <fieldset> <!-- START fieldset-' . $group . ' -->'; $row_elements .= PHP_EOL . $fieldset[$group] . ' </fieldset> <!-- END fieldset-' . $group . ' -->' . PHP_EOL; $fieldset[$group] = $row_elements . $fieldset_end; } } // Combinate fieldsets into common rows foreach ($divs as $entry) { $row_elements = $div_begin; foreach ($entry as $i => $group) { $row_elements .= $fieldset[$group]; if ($i > 0) { // unset all fieldsets except first one for replace later unset($fieldset[$group]); } } $row_elements .= $div_end; // now replace first fieldset in group $fieldset[array_shift($entry)] = $row_elements; } // Final combining elements $string_elements = implode('', $fieldset); } // Remove old vars from url if ($data['url']) { foreach ($used_vars as $var) { $data['url'] = preg_replace('/' . $var . '=[^\\/]+\\/?/', '', $data['url']); } } // Form header $string = PHP_EOL . "<!-- START {$form_id} -->" . PHP_EOL; $string .= $header; $string .= '<form method="POST" id="' . $form_id . '" name="' . $form_id . '" action="' . $data['url'] . '" class="' . $form_class . '"' . $form_style . '>' . PHP_EOL; // Form elements $string .= $string_elements; // Form footer $string .= '</form>' . PHP_EOL; $string .= $fieldset_tooltip; $string .= "<!-- END {$form_id} -->" . PHP_EOL; if ($return) { // Save generation time for profiling $GLOBALS['form_time'] += utime() - $form_start; // Return form as string return $string; } else { // Print form echo $string; // Save generation time for profiling (after echo) $GLOBALS['form_time'] += utime() - $form_start; } }
/** * Pings the server to check if it's still alive * * @return void */ public function pingServer() { if (empty($this->lastPing)) { $this->lastPing = time(); } if ($this->lastPing < time() - 130) { unset($this->lastPing); $this->errorConnectionReset(); return; } $this->pingTime = utime(); $this->raw("PING :" . $this->pingTime); $this->attach('pongServer', array($this, 'pongServer'), array('PONG')); Timer::add2('ping' . $this->network, 120, array($this, 'pingServer')); return; }
function discover_device($device, $options = NULL) { global $config, $valid, $exec_status, $discovered_devices; $valid = array(); // Reset $valid array $attribs = get_dev_attribs($device['device_id']); $device_start = utime(); // Start counting device poll time echo $device['hostname'] . " " . $device['device_id'] . " " . $device['os'] . " "; $detect_os = TRUE; // Set TRUE or FALSE for module 'os' (exclude double os detection) if ($device['os'] == 'generic' || isset($options['h']) && $options['h'] == 'new') { $detect_os = FALSE; $old_os = $device['os']; $device['os'] = get_device_os($device); if ($device['os'] != $old_os) { print_warning("Device OS changed: {$old_os} -> " . $device['os'] . "!"); log_event('OS changed: ' . $old_os . ' -> ' . $device['os'], $device, 'system'); dbUpdate(array('os' => $device['os']), 'devices', '`device_id` = ?', array($device['device_id'])); } } if ($config['os'][$device['os']]['group']) { $device['os_group'] = $config['os'][$device['os']]['group']; echo " (" . $device['os_group'] . ")"; } echo "\n"; // If we've specified a module, use that, else walk the modules array if ($options['m']) { foreach (explode(",", $options['m']) as $module) { if (is_file("includes/discovery/{$module}.inc.php")) { $m_start = utime(); include "includes/discovery/{$module}.inc.php"; $m_end = utime(); $m_run = round($m_end - $m_start, 4); print_message("Module [ {$module} ] time: {$m_run}" . "s"); } } } else { foreach ($config['discovery_modules'] as $module => $module_status) { if (in_array($device['os_group'], $config['os']['discovery_blacklist'])) { // Module is blacklisted for this OS. print_debug("Module [ {$module} ] is in the blacklist for " . $device['os_group']); } elseif (in_array($device['os'], $config['os']['discovery_blacklist'])) { // Module is blacklisted for this OS. print_debug("Module [ {$module} ] is in the blacklist for " . $device['os']); } else { if ($attribs['discover_' . $module] || $module_status && !isset($attribs['discover_' . $module])) { $m_start = utime(); include "includes/discovery/{$module}.inc.php"; $m_end = utime(); $m_run = round($m_end - $m_start, 4); print_message("Module [ {$module} ] time: {$m_run}" . "s"); } elseif (isset($attribs['discover_' . $module]) && $attribs['discover_' . $module] == "0") { print_debug("Module [ {$module} ] disabled on host."); } else { print_debug("Module [ {$module} ] disabled globally."); } } } } // Set type to a predefined type for the OS if it's not already set if ($device['type'] == "unknown" || $device['type'] == "") { if ($config['os'][$device['os']]['type']) { $device['type'] = $config['os'][$device['os']]['type']; } } $device_end = utime(); $device_run = $device_end - $device_start; $device_time = substr($device_run, 0, 5); dbUpdate(array('last_discovered' => array('NOW()'), 'type' => $device['type'], 'last_discovered_timetaken' => $device_time), 'devices', '`device_id` = ?', array($device['device_id'])); // put performance into devices_perftimes dbInsert(array('device_id' => $device['device_id'], 'operation' => 'discover', 'start' => $device_start, 'duration' => $device_run), 'devices_perftimes'); print_message("Discovered in {$device_time} seconds"); // not worth putting discovery data into rrd. it's not done every 5 mins :) echo PHP_EOL; $discovered_devices++; }
if (!defined('FT_ROOT')) { die(basename(__FILE__)); } global $ft_cfg, $userdata, $template, $DBS, $lang; if (!empty($template)) { $template->assign_vars(array('SIMPLE_FOOTER' => !empty($gen_simple_header), 'TRANSLATION_INFO' => isset($lang['TRANSLATION_INFO']) ? $lang['TRANSLATION_INFO'] : '', 'SHOW_ADMIN_LINK' => IS_ADMIN && !defined('IN_ADMIN'), 'ADMIN_LINK_HREF' => "admin/index.php")); $template->set_filenames(array('overall_footer' => 'overall_footer.tpl')); $template->pparse('overall_footer'); } $show_dbg_info = $userdata['user_level'] == ADMIN && !(isset($_GET['pane']) && $_GET['pane'] == 'left'); if (!$ft_cfg['gzip_compress']) { flush(); } if ($show_dbg_info) { $gen_time = utime() - TIMESTART; $gen_time_txt = sprintf('%.3f', $gen_time); $gzip_text = UA_GZIP_SUPPORTED ? 'GZIP ' : '<s>GZIP</s> '; $gzip_text .= $ft_cfg['gzip_compress'] ? 'Yes' : 'No'; $stat = '[ ' . $lang['EXECUTION_TIME'] . " {$gen_time_txt} " . $lang['SEC']; if (!empty($DBS)) { $sql_t = $DBS->sql_timetotal; $sql_time_txt = $sql_t ? sprintf('%.3f ' . $lang['SEC'] . ' (%d%%) · ', $sql_t, round($sql_t * 100 / $gen_time)) : ''; $num_q = $DBS->num_queries; $stat .= " | MySQL: {$sql_time_txt}{$num_q} " . $lang['QUERIES']; } $stat .= " | {$gzip_text}"; $stat .= ' | ' . $lang['MEMORY']; $stat .= humn_size($ft_cfg['mem_on_start'], 2) . ' / '; $stat .= humn_size(sys('mem_peak'), 2) . ' / '; $stat .= humn_size(sys('mem'), 2);
/** * Accept will run the query and store the results in results() */ public function accept() { if (DEBUG_ENABLED && (($fargs = func_get_args()) || ($fargs = 'NOARGS'))) { debug_log('Entered (%%)', 5, 0, __FILE__, __LINE__, __METHOD__, $fargs); } $server = $this->getServer(); $query = array(); $query['size_limit'] = get_request('size_limit', 'REQUEST', false, $_SESSION[APPCONFIG]->getValue('search', 'size_limit')); $query['format'] = get_request('format', 'REQUEST', false, $_SESSION[APPCONFIG]->getValue('search', 'display')); $query['orderby'] = get_request('orderby', 'REQUEST', false, 'dn'); # If this is a custom search, we need to populate are paramters if ($this->getID() == 'none') { $bases = get_request('base', 'REQUEST', false, null); $query['filter'] = get_request('filter', 'REQUEST', false, 'objectClass=*'); $query['scope'] = get_request('scope', 'REQUEST', false, 'sub'); $attrs = get_request('display_attrs', 'REQUEST'); $attrs = preg_replace('/\\s+/', '', $attrs); if ($attrs) { $query['attrs'] = explode(',', $attrs); } else { $query['attrs'] = array('*'); } } else { $bases = $this->base; $query['filter'] = $this->filter; $query['scope'] = $this->scope; $query['attrs'] = $this->getAttributeNames(); } if (!$bases) { $bases = $server->getBaseDN(); } elseif (!is_array($bases)) { $bases = explode('|', $bases); } foreach ($bases as $base) { $query['base'] = $base; $time_start = utime(); $this->results[$base] = $server->query($query, null); $time_end = utime(); $this->resultsdata[$base]['time'] = round($time_end - $time_start, 2); $this->resultsdata[$base]['scope'] = $query['scope']; $this->resultsdata[$base]['filter'] = $query['filter']; $this->resultsdata[$base]['attrs'] = $query['attrs']; if ($this->getAttrSortOrder() == 'dn') { usort($this->results[$base], 'pla_compare_dns'); } elseif ($this->getAttrSortOrder()) { masort($this->results[$base], $this->getAttrSortOrder()); } } }
function poll_device($device, $options) { global $config, $device, $polled_devices, $db_stats, $memcache; $attribs = get_dev_attribs($device['device_id']); $status = 0; unset($array); $device_start = utime(); // Start counting device poll time echo $device['hostname'] . ' ' . $device['device_id'] . ' ' . $device['os'] . ' '; if ($config['os'][$device['os']]['group']) { $device['os_group'] = $config['os'][$device['os']]['group']; echo '(' . $device['os_group'] . ')'; } echo "\n"; unset($poll_update); unset($poll_update_query); unset($poll_separator); $poll_update_array = array(); $update_array = array(); $host_rrd = $config['rrd_dir'] . '/' . $device['hostname']; if (!is_dir($host_rrd)) { mkdir($host_rrd); echo "Created directory : {$host_rrd}\n"; } $address_family = snmpTransportToAddressFamily($device['transport']); $ping_response = isPingable($device['hostname'], $address_family, $attribs); $device_perf = $ping_response['db']; $device_perf['device_id'] = $device['device_id']; $device_perf['timestamp'] = array('NOW()'); if (can_ping_device($attribs) === true && is_array($device_perf)) { dbInsert($device_perf, 'device_perf'); } $device['pingable'] = $ping_response['result']; $ping_time = $ping_response['last_ping_timetaken']; $response = array(); $status_reason = ''; if ($device['pingable']) { $device['snmpable'] = isSNMPable($device); if ($device['snmpable']) { $status = '1'; $response['status_reason'] = ''; } else { echo 'SNMP Unreachable'; $status = '0'; $response['status_reason'] = 'snmp'; } } else { echo 'Unpingable'; $status = '0'; $response['status_reason'] = 'icmp'; } if ($device['status'] != $status) { $poll_update .= $poll_separator . "`status` = '{$status}'"; $poll_separator = ', '; dbUpdate(array('status' => $status, 'status_reason' => $response['status_reason']), 'devices', 'device_id=?', array($device['device_id'])); dbInsert(array('importance' => '0', 'device_id' => $device['device_id'], 'message' => 'Device is ' . ($status == '1' ? 'up' : 'down')), 'alerts'); log_event('Device status changed to ' . ($status == '1' ? 'Up' : 'Down'), $device, $status == '1' ? 'up' : 'down'); } if ($status == '1') { $graphs = array(); $oldgraphs = array(); if ($options['m']) { foreach (explode(',', $options['m']) as $module) { if (is_file('includes/polling/' . $module . '.inc.php')) { include 'includes/polling/' . $module . '.inc.php'; } } } else { foreach ($config['poller_modules'] as $module => $module_status) { if ($attribs['poll_' . $module] || $module_status && !isset($attribs['poll_' . $module])) { // TODO per-module polling stats include 'includes/polling/' . $module . '.inc.php'; } else { if (isset($attribs['poll_' . $module]) && $attribs['poll_' . $module] == '0') { echo "Module [ {$module} ] disabled on host.\n"; } else { echo "Module [ {$module} ] disabled globally.\n"; } } } } //end if if (!$options['m']) { // FIXME EVENTLOGGING -- MAKE IT SO WE DO THIS PER-MODULE? // This code cycles through the graphs already known in the database and the ones we've defined as being polled here // If there any don't match, they're added/deleted from the database. // Ideally we should hold graphs for xx days/weeks/polls so that we don't needlessly hide information. foreach (dbFetch('SELECT `graph` FROM `device_graphs` WHERE `device_id` = ?', array($device['device_id'])) as $graph) { if (isset($graphs[$graph['graph']])) { $oldgraphs[$graph['graph']] = true; } else { dbDelete('device_graphs', '`device_id` = ? AND `graph` = ?', array($device['device_id'], $graph['graph'])); } } foreach ($graphs as $graph => $value) { if (!isset($oldgraphs[$graph])) { echo '+'; dbInsert(array('device_id' => $device['device_id'], 'graph' => $graph), 'device_graphs'); } echo $graph . ' '; } } //end if $device_end = utime(); $device_run = $device_end - $device_start; $device_time = substr($device_run, 0, 5); // TODO: These should be easy converts to rrd_create_update() // Poller performance rrd $poller_rrd = $config['rrd_dir'] . '/' . $device['hostname'] . '/poller-perf.rrd'; if (!is_file($poller_rrd)) { rrdtool_create($poller_rrd, 'DS:poller:GAUGE:600:0:U ' . $config['rrd_rra']); } if (!empty($device_time)) { $fields = array('poller' => $device_time); rrdtool_update($poller_rrd, $fields); } // Ping response rrd if (can_ping_device($attribs) === true) { $ping_rrd = $config['rrd_dir'] . '/' . $device['hostname'] . '/ping-perf.rrd'; if (!is_file($ping_rrd)) { rrdtool_create($ping_rrd, 'DS:ping:GAUGE:600:0:65535 ' . $config['rrd_rra']); } if (!empty($ping_time)) { $fields = array('ping' => $ping_time); rrdtool_update($ping_rrd, $fields); } $update_array['last_ping'] = array('NOW()'); $update_array['last_ping_timetaken'] = $ping_time; } $update_array['last_polled'] = array('NOW()'); $update_array['last_polled_timetaken'] = $device_time; // echo("$device_end - $device_start; $device_time $device_run"); echo "Polled in {$device_time} seconds\n"; d_echo('Updating ' . $device['hostname'] . "\n"); d_echo($update_array); $updated = dbUpdate($update_array, 'devices', '`device_id` = ?', array($device['device_id'])); if ($updated) { echo "UPDATED!\n"; } unset($storage_cache); // Clear cache of hrStorage ** MAYBE FIXME? ** unset($cache); // Clear cache (unify all things here?) } //end if }
/** * Store debug info */ function debug($mode) { if (!SQL_DEBUG) { return; } $id =& $this->dbg_id; $dbg =& $this->dbg[$id]; if ($mode == 'start') { if (SQL_CALC_QUERY_TIME || DBG_LOG || SQL_LOG_SLOW_QUERIES) { $this->sql_starttime = utime(); } if ($this->dbg_enabled) { $dbg['sql'] = preg_replace('#^(\\s*)(/\\*)(.*)(\\*/)(\\s*)#', '', $this->cur_query); $dbg['src'] = $this->debug_find_source(); $dbg['file'] = $this->debug_find_source('file'); $dbg['line'] = $this->debug_find_source('line'); $dbg['time'] = ''; $dbg['info'] = ''; $dbg['mem_before'] = sys('mem'); } if ($this->do_explain) { $this->explain('start'); } } else { if ($mode == 'stop') { if (SQL_CALC_QUERY_TIME || DBG_LOG || SQL_LOG_SLOW_QUERIES) { $this->cur_query_time = utime() - $this->sql_starttime; $this->sql_timetotal += $this->cur_query_time; $this->DBS['sql_timetotal'] += $this->cur_query_time; if (SQL_LOG_SLOW_QUERIES && $this->cur_query_time > $this->slow_time) { $this->log_slow_query(); } } if ($this->dbg_enabled) { $dbg['time'] = utime() - $this->sql_starttime; $dbg['info'] = $this->query_info(); $dbg['mem_after'] = sys('mem'); $id++; } if ($this->do_explain) { $this->explain('stop'); } // проверка установки $this->inited - для пропуска инициализационных запросов if ($this->DBS['log_counter'] && $this->inited) { $this->log_query($this->DBS['log_file']); $this->DBS['log_counter']--; } } } }
echo "Debugging and testing options:\n"; echo "-d Enable debugging output\n"; echo "-m Specify single module to be run\n"; echo "\n"; echo "Invalid arguments!\n"; exit; } include "includes/sql-schema/update.php"; $discovered_devices = 0; if ($config['distributed_poller'] === TRUE) { $where .= " AND poller_group IN(" . $config['distributed_poller_group'] . ")"; } foreach (dbFetch("SELECT * FROM `devices` WHERE status = 1 AND disabled = 0 {$where} ORDER BY device_id DESC") as $device) { discover_device($device, $options); } $end = utime(); $run = $end - $start; $proctime = substr($run, 0, 5); if ($discovered_devices) { dbInsert(array('type' => 'discover', 'doing' => $doing, 'start' => $start, 'duration' => $proctime, 'devices' => $discovered_devices), 'perf_times'); } $string = $argv[0] . " {$doing} " . date($config['dateformat']['compact']) . " - {$discovered_devices} devices discovered in {$proctime} secs"; if ($debug) { echo "{$string}\n"; } if ($options['h'] != "new" && $config['version_check']) { include "includes/versioncheck.inc.php"; } if (!isset($options['q'])) { echo 'MySQL: Cell[' . ($db_stats['fetchcell'] + 0) . '/' . round($db_stats['fetchcell_sec'] + 0, 2) . 's]' . ' Row[' . ($db_stats['fetchrow'] + 0) . '/' . round($db_stats['fetchrow_sec'] + 0, 2) . 's]' . ' Rows[' . ($db_stats['fetchrows'] + 0) . '/' . round($db_stats['fetchrows_sec'] + 0, 2) . 's]' . ' Column[' . ($db_stats['fetchcol'] + 0) . '/' . round($db_stats['fetchcol_sec'] + 0, 2) . 's]' . ' Update[' . ($db_stats['update'] + 0) . '/' . round($db_stats['update_sec'] + 0, 2) . 's]' . ' Insert[' . ($db_stats['insert'] + 0) . '/' . round($db_stats['insert_sec'] + 0, 2) . 's]' . ' Delete[' . ($db_stats['delete'] + 0) . '/' . round($db_stats['delete_sec'] + 0, 2) . 's]'; echo "\n";
function poll_device($device, $options) { global $config, $device, $polled_devices, $db_stats, $exec_status, $alert_rules, $alert_table, $graphs, $attribs; $alert_metrics = array(); $oid_cache = array(); $old_device_state = unserialize($device['device_state']); $attribs = get_entity_attribs('device', $device['device_id']); $pid_info = check_process_run($device); // This just clear stalled DB entries add_process_info($device); // Store process info $alert_rules = cache_alert_rules(); $alert_table = cache_device_alert_table($device['device_id']); if (OBS_DEBUG > 1 && (count($alert_rules) || count($alert_table))) { print_vars($alert_rules); print_vars($alert_table); } $status = 0; $device_start = utime(); // Start counting device poll time print_cli_heading($device['hostname'] . " [" . $device['device_id'] . "]", 1); print_cli_data("OS", $device['os'], 1); if ($config['os'][$device['os']]['group']) { $device['os_group'] = $config['os'][$device['os']]['group']; print_cli_data("OS Group", $device['os_group'], 1); } if (is_numeric($device['last_polled_timetaken'])) { print_cli_data("Last poll duration", $device['last_polled_timetaken'] . " seconds", 1); } print_cli_data("Last Polled", $device['last_polled'], 1); print_cli_data("SNMP Version", $device['snmp_version'], 1); //unset($poll_update); unset($poll_update_query); unset($poll_separator); $update_array = array(); $host_rrd_dir = $config['rrd_dir'] . "/" . $device['hostname']; if (!is_dir($host_rrd_dir)) { mkdir($host_rrd_dir); echo "Created directory : {$host_rrd_dir}\n"; } $flags = OBS_DNS_ALL; if ($device['snmp_transport'] == 'udp6' || $device['snmp_transport'] == 'tcp6') { $flags = $flags ^ OBS_DNS_A; } $attribs['ping_skip'] = isset($attribs['ping_skip']) && $attribs['ping_skip']; if ($attribs['ping_skip']) { $flags = $flags | OBS_PING_SKIP; // Add skip ping flag } $device['pingable'] = isPingable($device['hostname'], $flags); if ($device['pingable']) { $device['snmpable'] = isSNMPable($device); if ($device['snmpable']) { $ping_msg = $attribs['ping_skip'] ? '' : 'PING (' . $device['pingable'] . 'ms) and '; print_cli_data("Device status", "Device is reachable by " . $ping_msg . "SNMP (" . $device['snmpable'] . "ms)", 1); $status = "1"; $status_type = ''; } else { print_cli_data("Device status", "Device is not responding to SNMP requests", 1); $status = "0"; $status_type = 'snmp'; } } else { print_cli_data("Device status", "Device is not responding to PINGs", 1); $status = "0"; $status_type = 'ping'; } if ($device['status'] != $status) { dbUpdate(array('status' => $status), 'devices', 'device_id = ?', array($device['device_id'])); // dbInsert(array('importance' => '0', 'device_id' => $device['device_id'], 'message' => "Device is " .($status == '1' ? 'up' : 'down')), 'alerts'); $event_msg = 'Device status changed to '; if ($status == '1') { // Device Up, Severity Warning (4) $event_msg .= 'Up'; $event_severity = 4; } else { // Device Down, Severity Error (3)! $event_msg .= 'Down'; $event_severity = 3; } if ($status_type != '') { $event_msg .= ' (' . $status_type . ')'; } log_event($event_msg, $device, 'device', $device['device_id'], $event_severity); } rrdtool_update_ng($device, 'status', array('status' => $status)); if (!$attribs['ping_skip']) { // Ping response RRD database. rrdtool_update_ng($device, 'ping', array('ping' => $device['pingable'] ? $device['pingable'] : 'U')); } // SNMP response RRD database. rrdtool_update_ng($device, 'ping_snmp', array('ping_snmp' => $device['snmpable'] ? $device['snmpable'] : 'U')); $alert_metrics['device_status'] = $status; $alert_metrics['device_status_type'] = $status_type; $alert_metrics['device_ping'] = $device['pingable']; // FIXME, when ping skipped, here always 0.001 $alert_metrics['device_snmp'] = $device['snmpable']; if ($status == "1") { // Arrays for store and check enabled/disabled graphs $graphs = array(); $graphs_db = array(); foreach (dbFetchRows("SELECT * FROM `device_graphs` WHERE `device_id` = ?", array($device['device_id'])) as $entry) { $graphs_db[$entry['graph']] = isset($entry['enabled']) ? (bool) $entry['enabled'] : TRUE; } if (!$attribs['ping_skip']) { // Enable Ping graphs $graphs['ping'] = TRUE; } // Enable SNMP graphs $graphs['ping_snmp'] = TRUE; // Run these base modules always and before all other modules! $poll_modules = array('system', 'os'); $mods_disabled_global = array(); $mods_disabled_device = array(); $mods_excluded = array(); if ($options['m']) { foreach (explode(',', $options['m']) as $module) { $module = trim($module); if (in_array($module, $poll_modules)) { continue; } // Skip already added modules if ($module == 'unix-agent') { array_unshift($poll_modules, $module); // Add 'unix-agent' before all continue; } if (is_file($config['install_dir'] . "/includes/polling/{$module}.inc.php")) { $poll_modules[] = $module; } } } else { foreach ($config['poller_modules'] as $module => $module_status) { if (in_array($module, $poll_modules)) { continue; } // Skip already added modules if ($attribs['poll_' . $module] || $module_status && !isset($attribs['poll_' . $module])) { if (poller_module_excluded($device, $module)) { $mods_excluded[] = $module; //print_warning("Module [ $module ] excluded for device."); continue; } if ($module == 'unix-agent') { array_unshift($poll_modules, $module); // Add 'unix-agent' before all continue; } if (is_file($config['install_dir'] . "/includes/polling/{$module}.inc.php")) { $poll_modules[] = $module; } } elseif (isset($attribs['poll_' . $module]) && !$attribs['poll_' . $module]) { $mods_disabled_device[] = $module; //print_warning("Module [ $module ] disabled on device."); } else { $mods_disabled_global[] = $module; //print_warning("Module [ $module ] disabled globally."); } } } if (count($mods_excluded)) { print_cli_data("Modules Excluded", implode(", ", $mods_excluded), 1); } if (count($mods_disabled_global)) { print_cli_data("Disabled Globally", implode(", ", $mods_disabled_global), 1); } if (count($mods_disabled_device)) { print_cli_data("Disabled Device", implode(", ", $mods_disabled_global), 1); } if (count($poll_modules)) { print_cli_data("Modules Enabled", implode(", ", $poll_modules), 1); } echo PHP_EOL; foreach ($poll_modules as $module) { print_debug(PHP_EOL . "including: includes/polling/{$module}.inc.php"); print_cli_heading("Module Start: %R" . $module . ""); $m_start = utime(); include $config['install_dir'] . "/includes/polling/{$module}.inc.php"; $m_end = utime(); $m_run = round($m_end - $m_start, 4); $device_state['poller_mod_perf'][$module] = $m_run; print_cli_data("Module time", number_format($m_run, 4) . "s"); echo PHP_EOL; } print_cli_heading($device['hostname'] . " [" . $device['device_id'] . "] completed poller modules at " . date("Y-m-d H:i:s"), 1); // Check and update graphs DB $graphs_stat = array(); if (!isset($options['m'])) { // Hardcoded poller performance $graphs['poller_perf'] = TRUE; // Delete not exists graphs from DB (only if poller run without modules option) foreach ($graphs_db as $graph => $value) { if (!isset($graphs[$graph])) { dbDelete('device_graphs', "`device_id` = ? AND `graph` = ?", array($device['device_id'], $graph)); unset($graphs_db[$graph]); $graphs_stat['deleted'][] = $graph; } } } // Add or update graphs in DB foreach ($graphs as $graph => $value) { if (!isset($graphs_db[$graph])) { dbInsert(array('device_id' => $device['device_id'], 'graph' => $graph, 'enabled' => $value), 'device_graphs'); $graphs_stat['added'][] = $graph; } else { if ($value != $graphs_db[$graph]) { dbUpdate(array('enabled' => $value), 'device_graphs', '`device_id` = ? AND `graph` = ?', array($device['device_id'], $graph)); $graphs_stat['updated'][] = $graph; } else { $graphs_stat['checked'][] = $graph; } } } // Print graphs stats foreach ($graphs_stat as $key => $stat) { if (count($stat)) { print_cli_data('Graphs [' . $key . ']', implode(', ', $stat), 1); } } $device_end = utime(); $device_run = $device_end - $device_start; $device_time = round($device_run, 4); $update_array['last_polled'] = array('NOW()'); $update_array['last_polled_timetaken'] = $device_time; $update_array['device_state'] = serialize($device_state); #echo("$device_end - $device_start; $device_time $device_run"); print_cli_data("Poller time", $device_time . " seconds", 1); //print_message(PHP_EOL."Polled in $device_time seconds"); // Only store performance data if we're not doing a single-module poll if (!$options['m']) { dbInsert(array('device_id' => $device['device_id'], 'operation' => 'poll', 'start' => $device_start, 'duration' => $device_run), 'devices_perftimes'); rrdtool_update_ng($device, 'perf-poller', array('val' => $device_time)); } if (OBS_DEBUG) { echo "Updating " . $device['hostname'] . " - "; print_vars($update_array); echo " \n"; } $updated = dbUpdate($update_array, 'devices', '`device_id` = ?', array($device['device_id'])); if ($updated) { print_cli_data("Updated Data", implode(", ", array_keys($update_array)), 1); } $alert_metrics['device_uptime'] = $device['uptime']; $alert_metrics['device_rebooted'] = $rebooted; // 0 - not rebooted, 1 - rebooted $alert_metrics['device_duration_poll'] = $device['last_polled_timetaken']; unset($cache_storage); // Clear cache of hrStorage ** MAYBE FIXME? ** (ok, later) unset($cache); // Clear cache (unify all things here?) } check_entity('device', $device, $alert_metrics); echo PHP_EOL; // Clean del_process_info($device); // Remove process info unset($alert_metrics); }