protected function execute($arguments = array(), $options = array()) { $stop_watch = new StopWatch(); $stop_watch->start(); logline('Started processing.'); $databaseManager = new sfDatabaseManager($this->configuration); $queries = QueryPeer::doSelect(new Criteria()); logline(sprintf("There are %s queries to process.", sizeof($queries))); foreach ($queries as $query) { $connection = Propel::getConnection(); $sql = "SELECT STD(%s) as standard_deviation FROM %s where %s=%s"; $sql = sprintf($sql, QueryResultPeer::RESULT_SIZE, QueryResultPeer::TABLE_NAME, QueryResultPeer::QUERY_ID, $query->getId()); $statement = $connection->prepareStatement($sql); $resultset = $statement->executeQuery(); $resultset->next(); $std = $resultset->getString('standard_deviation'); $sql = "SELECT AVG(%s) as mean_of_all FROM %s where %s=%s"; $sql = sprintf($sql, QueryResultPeer::RESULT_SIZE, QueryResultPeer::TABLE_NAME, QueryResultPeer::QUERY_ID, $query->getId()); $statement = $connection->prepareStatement($sql); $resultset = $statement->executeQuery(); $resultset->next(); $mean = $resultset->getString('mean_of_all'); $query->setStandardDeviation($std / $mean); logline(sprintf('Average stdev for query %s is %s.', $query->getQuery(), $query->getStandardDeviation())); $query->save(); //logLine(sprintf("Standart deviation for %s is %s.", $query->getQuery(), $deviation)); } logline(sprintf("Finished processing.")); $stop_watch->end(); logline(sprintf('Execution time: %s seconds.', $stop_watch->getTime())); logline(sprintf('!!!!!CAN RUN %s TIMES A DAY!!!!!', 24 * 60 * 60 / ($stop_watch->getTime() == 0 ? 1 : $stop_watch->getTime()))); }
function doSplunkSearch($query, $start, $end, $config, $max_results = 10000) { $splunk_baseurl = $config['base_url']; $splunk_username = $config['username']; $splunk_password = $config['password']; $params = array('exec_mode' => 'oneshot', 'earliest_time' => $start, 'latest_time' => $end, 'search' => "search {$query}", 'output_mode' => 'json', 'count' => $max_results); $q_params = http_build_query($params); $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($ch, CURLOPT_URL, "{$splunk_baseurl}/services/search/jobs"); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $q_params); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_USERPWD, "{$splunk_username}:{$splunk_password}"); if (!($response = curl_exec($ch))) { return array("success" => false, "error" => "curl failed, error: " . curl_error($ch)); } $curl_info = curl_getinfo($ch); logline("Splunk provider HTTP status: {$curl_info['http_code']}"); $json = json_decode($response); if (is_null($json)) { logline("NULL response from Splunk. This likely means no events matched our search criteria."); //return array("success" => false, "error" => "JSON decode failed!"); return array("success" => true, "data" => array()); } else { return array("success" => true, "data" => $json); } }
protected function execute($arguments = array(), $options = array()) { $stop_watch = new StopWatch(); $stop_watch->start(); logline('Started processing.'); $searchEngine = new GoogleHitFetcher(); $databaseManager = new sfDatabaseManager($this->configuration); $queries = QueryPeer::doSelect(new Criteria()); logline(sprintf("There are %s queries to process.", sizeof($queries))); foreach ($queries as $query) { $qr = new QueryResultBulk(); $qr->setQuery($query); $result_size = $searchEngine->fetch($query->getQuery()); $qr->setResultSize($result_size); logline(sprintf("Found %s results for %s.", $result_size, $query->getQuery())); $qr->save(); } logline(sprintf("Finished processing.")); $stop_watch->end(); logline(sprintf('Execution time: %s seconds.', $stop_watch->getTime())); logline(sprintf('!!!!!CAN RUN %s TIMES A DAY!!!!!', 24 * 60 * 60 / $stop_watch->getTime())); }
function purgeOld($loglevel) { global $purgeage, $path_rrd; if ($purgeage == 0) { logline("PURGER: Purge has been disabled in the config. Quitting now. ", 0, $loglevel); return false; } $unixpurgeage = time() - $purgeage; logline("PURGER: Beginning purge of old RRD files that have since gone down", 0, $loglevel); logline("PURGER: Your purge age is set to delete any RRDs/ports older than " . _ago($unixpurgeage), 1, $loglevel); connectToDB(); $findold = "SELECT * FROM ports WHERE lastpoll < {$unixpurgeage}"; $results = mysql_query($findold); $numresults = mysql_num_rows($results); if ($numresults > 0) { logline("PURGER: Found {$numresults} candidate old RRDs/ports for deletion (older than " . _ago($unixpurgeage) . ")", 0, $loglevel); while ($row = mysql_fetch_assoc($results)) { logline("PURGER: Deleting '{$row['name']}' from host '{$row['host']}' and graphtype '{$row['graphtype']}' from the database", 2, $loglevel); $filetodelete = "{$path_rrd}{$row['host']}/{$row['host']}-{$row['safename']}_{$row['graphtype']}.rrd"; logline("PURGER: Deleting '{$filetodelete}'. ", 2, $loglevel); unlink($filetodelete); logline("PURGER: Deleting row for '{$row['name']}' from the database", 2, $loglevel); $deleterow = 'DELETE FROM ports WHERE host="' . $row['host'] . '" AND safename="' . $row['safename'] . '" AND graphtype="' . $row['graphtype'] . '"'; mysql_query($deleterow); logline("PURGER: Done deleting '{$row['name']}' ", 1, $loglevel); } } else { logline("PURGER: No RRDs/ports were older than " . _ago($unixpurgeage), 0, $loglevel); } return true; }
$hostname = mysql_real_escape_string($n['hostname']); $output = mysql_real_escape_string($n['output']); $service = mysql_real_escape_string($n['service']); $state = mysql_real_escape_string($n['state']); $tag = mysql_real_escape_string($n['tag']); $notes = mysql_real_escape_string(htmlentities($n['notes'], ENT_QUOTES)); $alert_id = generateOnCallAlertID($timestamp, $hostname, $service); if ($sleep) { // Run the sleep tracking provider for this alert $sleep_info = getSleepDetailAtTimestamp($timestamp, $sleeptracking_settings[$sleep_provider], $sleepprovider_settings); if ($sleep_info) { $sleep_state = $sleep_info['sleep_state']; $mtts = $sleep_info['mtts']; $sleep_level = $sleep_info['sleep_level']; $confidence = $sleep_info['confidence']; } } $query = "INSERT INTO oncall_weekly (alert_id, range_start, range_end, timestamp, hostname, service, state, contact, output, tag, sleep_state, mtts, sleep_level, sleep_confidence, notes) VALUES\n ('{$alert_id}', '{$range_start}', '{$range_end}', '{$timestamp}', '{$hostname}', '{$service}', '{$state}', '{$username}', '{$output}', '{$tag}', '{$sleep_state}', '{$mtts}', '{$sleep_level}', '{$confidence}','{$notes}')"; logline("Processing on call line with data: {$query}"); if (!mysql_query($query)) { echo "Database update failed, error: " . mysql_error(); logline("Database update failed, error: " . mysql_error()); } } logline("Everything worked great, redirecting the user with success"); Header('Location: add.php?oncall_succ=hellyeah'); } else { logline("We didn't find any notifications to process, redirect user back to add page"); Header('Location: add.php'); } }
function getSleepDetailAtTimestamp($timestamp, $user_options, $plugin_options) { $graphite_host = $plugin_options['graphite_host']; $graphite_prefix = $user_options['graphite_prefix']; // We allow some tolerances here to account for differences in time sync and graphite timestamp rounding $from = floor(($timestamp - 180) / 100) * 100; $to = $timestamp + 120 * 60; // Generated URL. Add together all the states, so 1 == awake, 2 == light sleep, 3 == deep sleep. $url = "{$graphite_host}/render/?target=sumSeries({$graphite_prefix}.details.deep,{$graphite_prefix}.details.light,{$graphite_prefix}.details.awake)"; $url .= "&from={$from}&until={$to}&format=json"; logline("SleepUP plugin is using URL {$url} for sleep data..."); logline("SleepUP: Raw timestamp is {$timestamp}, searching from {$from} to {$to}"); if (!($json = file_get_contents($url))) { return false; } if (!($data = json_decode($json, true))) { return false; } $mtts = -1; $confidence = -1; // We're not going to submit sleep level for the UP, because it's not accurate enough. // sure we will! use the below as default $sleep_level = -1; $jawboneSleepStates = array(1 => 'awake', 2 => 'in light sleep', 3 => 'in deep sleep'); $firstWakeStateEpoch = ""; $previousWakeStateEpoch = ""; $firstWakeState = 1; # default to 'stayed awake' for cases where we see null data $previousSleepState = 1; # default to 'awake' // TODO: there's duplicate code in this block; dedupe it foreach ($data[0]['datapoints'] as $arrayKey => $sleepState) { # if we see null state, typically the person is fully awake (i.e. no data) if ($sleepState[1] >= $timestamp and empty($sleepState[0])) { $firstWakeStateEpoch = $sleepState[1]; // get a slice of the previous sleep states so we can check for // previous sleep states to be certain of the engineer's sleep state // reverse the slice to speed up iterations looking back $allPreviousSleepStates = array_reverse(array_slice($data[0]['datapoints'], 0, $arrayKey), true); foreach ($allPreviousSleepStates as $array => $previousSleepStatePair) { if ($previousSleepStatePair[0] == 2 or $previousSleepStatePair[0] == 3) { $previousSleepState = $previousSleepStatePair[0]; $previousWakeStateEpoch = $previousSleepStatePair[1]; break; } } // make a clean break break; # otherwise, continue until we encounter the first wake state } elseif ($sleepState[1] >= $timestamp and $sleepState[0] == "1.0") { $firstWakeState = $sleepState[0]; $firstWakeStateEpoch = $sleepState[1]; // get a slice of the previous sleep states so we can check for // previous sleep states to be certain of the engineer's sleep state // reverse the slice to speed up iterations looking back $allPreviousSleepStates = array_reverse(array_slice($data[0]['datapoints'], 0, $arraykey), true); foreach ($allPreviousSleepStates as $previousArrayKey => $previousSleepStatePair) { if ($previousSleepStatePair[0] == 2 or $previousSleepStatePair[0] == 3) { $previousSleepState = $previousSleepStatePair[0]; $previousWakeStateEpoch = $previousSleepStatePair[1]; break; } } // make a clean break break; } } logline("SleepUP: First wake state epoch: {$firstWakeStateEpoch} Alert epoch: {$timestamp}"); logline("SleepUP: The engineer was {$jawboneSleepStates[$previousSleepState]} when the alert fired."); # find the next non-wake state $nextSleepStateEpoch = ""; foreach ($data[0]['datapoints'] as $array => $sleepState) { # continue until we encounter the next non-wake state (2 or 3) # start from $firstWakeStateEpoch if ($sleepState[1] >= $firstWakeStateEpoch and empty($sleepState[0])) { break; } elseif ($sleepState[1] > $firstWakeStateEpoch and $sleepState[0] != "1.0") { $nextSleepStateEpoch = $sleepState[1]; break; } } if (!empty($nextSleepStateEpoch)) { $mtts = $nextSleepStateEpoch - $firstWakeStateEpoch; } else { // this msg should make more sense if the engineer is already awake logline("SleepUP: The engineer never went back to sleep!"); // Set the time to sleep to 0 to track this horrible occasion $mtts = 0; } // frantz # rationale for assigning $sleep_state based on Jawbone sleep state comes # from http://en.wikipedia.org/wiki/Non-rapid_eye_movement_sleep: # Stage 2 – ... The sleeper is quite easily awakened... == Jawbone light sleep (2) # Stage 3 - ... associated with "deep" sleep... == Jawbone deep sleep (3) switch ($previousSleepState) { case 1: // If we have a data point saying the user was awake, they were definitely awake. $sleep_state = 0; $confidence = 100; break; case 2: $sleep_state = 1; // light sleep $sleep_level = 2; $confidence = 100; break; case 3: $sleep_state = 1; // deep sleep $sleep_level = 3; $confidence = 100; break; default: // Because of the way the UP graphite plugin works, if there is no data the user probably was awake. // this manifests as null sleep state values $sleep_state = 0; $confidence = 75; break; } logline("SleepUP: Finished, returning sleep_state: {$sleep_state} mtts: {$mtts} sleep_level: {$sleep_level} confidence: {$confidence}"); return array("sleep_state" => $sleep_state, "mtts" => $mtts, "sleep_level" => $sleep_level, "confidence" => $confidence); }
# worker for every host that is enabled for polling. # include_once 'functions.php'; # Check the master kill switch if ($pollingenabled != true) { logline("Polling has been disabled. Not going to run this time. Check config.php to enable. ", 0, $verbose); exit; } logline("MASTER: Starting to spawn polling children", 0, $verbose); # Spawn a new poller child process for every host in the config foreach ($pollhosts as $thishost) { # But only the ones that are enabled! if ($thishost['enabled'] == true) { logline("MASTER: Spawing polling child for {$thishost['prettyname']}", 1, $verbose); $cwd = dirname(__FILE__); $command = "nohup /usr/bin/env php -f {$cwd}/poller_child.php {$thishost['prettyname']} >> {$cwd}/poller.log 2>&1 & echo \$!"; $pid = shell_exec($command); logline("MASTER: Child spawned, PID is {$pid}", 1, $verbose); } else { logline("MASTER: Not spawning polling child for {$thishost['prettyname']}, is disabled in config.php", 1, $verbose); } } logline("MASTER: Done spawning polling children", 0, $verbose); logline("MASTER: Writing last poll time", 2, $verbose); if (!file_put_contents($path_rrd . "lastpolltime.txt", time())) { logline("MASTER: Warning! Could not write last poll time, check directory perms", 0, $verbose); } # Execute cleanup job to purge any ports and RRD files older than $purgeage in the config purgeOld($verbose); logline("MASTER: Going away now. Be back later. ", 2, $verbose);
/** * getOnCallNotifications - Returns the notifications for a given time period and parameters * * Parameters: * $on_call_name - The username of the user compiling this report * $provider_global_config - All options from config.php in $oncall_providers - That is, global options. * $provider_team_config - All options from config.php in $teams - That is, specific team configuration options * $start - The unix timestamp of when to start looking for notifications * $end - The unix timestamp of when to stop looking for notifications * * Returns 0 or more notifications as array() * - Each notification should have the following keys: * - time: Unix timestamp of when the alert was sent to the user * - hostname: Ideally contains the hostname of the problem. Must be populated but feel free to make bogus if not applicable. * - service: Contains the service name or a description of the problem. Must be populated. Perhaps use "Host Check" for host alerts. * - output: The plugin output, e.g. from Nagios, describing the issue so the user can reference easily/remember issue * - state: The level of the problem. One of: CRITICAL, WARNING, UNKNOWN, DOWN */ function getOnCallNotifications($name, $global_config, $team_config, $start, $end) { $base_url = $global_config['base_url']; $service_key = $team_config['service_key']; $separator = $team_config['separator']; if ($base_url !== '' && $service_key != '') { // convert single Openduty service, to array construct in order to hold multiple services. if (!is_array($service_key)) { $service_key = array($service_key); } // loop through all Openduty services foreach ($service_key as $skey) { // check if the service key is formated correctly if (!sanitizeOpenDutyServiceKey($skey)) { logline('Incorect format for Openduty Service ID: ' . $skey); // skip to the next Service Key in the array continue; } // loop through Openduty's maximum incidents count per API request. $running_total = 0; $page = 1; do { // Connect to the Openduty API and collect all incidents in the time period. $parameters = array('since' => date('c', $start), 'service_key' => $skey, 'until' => date('c', $end), 'page' => $page); $incident_json = doOpenDutyAPICall('/opsweekly', $parameters, $base_url); if (!($incidents = json_decode($incident_json))) { return 'Could not retrieve incidents from Openduty! Please check your settings'; } // skip if no incidents are recorded if (count($incidents->results) == 0) { continue; } logline("Incidents on Service Key: " . $skey); logline("Total incidents: " . $incidents->count); logline("Number of page:" . $page); $page += 1; $running_total += count($incidents->results); logline("Running total: " . $running_total); foreach ($incidents->results as $incident) { $time = strtotime($incident->occurred_at); $service_key = $incident->incindent_key; $output = $incident->output; $service_parts = explode(":", $service_key); if (count($service_parts) > 1) { $hostname = array_shift($service_parts); $service = implode(":", $service_parts); } else { $hostname = "Openduty"; $service = $service_key; } $valid_states = array("WARNING", "UNKNOWN", "DOWN"); #Dont include CRITICAL, as it's the default $state = "CRITICAL"; foreach ($valid_states as $astate) { if (strpos($output, $astate) !== false) { $state = $astate; } } $notifications[] = array("time" => $time, "hostname" => $hostname, "service" => $service, "output" => $output, "state" => $state); } } while ($running_total < $incidents->count); } // if no incidents are reported, don't generate the table if (count($notifications) == 0) { return array(); } else { return $notifications; } } else { return false; } }
protected function execute($arguments = array(), $options = array()) { $frequencies = array('D' => 'Daily', 'W' => 'Weekly', 'M' => 'Monthly'); $frequency = $arguments['frequency']; if (!array_key_exists($frequency, $frequencies)) { logline(sprintf('Invalid frequency %s use [D|W|M]', $frequency)); exit; } sfLoader::loadHelpers('Partial', 'My'); $context = sfContext::createInstance($this->configuration); $stop_watch = new StopWatch(); $stop_watch->start(); logline(sprintf('Started processing %s mails.', $frequencies[$frequency])); $databaseManager = new sfDatabaseManager($this->configuration); $c1 = new Criteria(); $c1->addJoin(sfGuardUserPeer::ID, ReportPeer::USER_ID); $c1->add(ReportPeer::MAIL_FREQUENCY, $frequency); $c1->setDistinct(); $users = sfGuardUserPeer::doSelect($c1); foreach ($users as $user) { $c = new Criteria(); $c->add(ReportPeer::USER_ID, $user->getId()); $c->add(ReportPeer::MAIL_FREQUENCY, $frequency); $reports = ReportPeer::doSelect($c); logline(sprintf("There are %s reports to process.", sizeof($reports))); $sfGuardUserProfile = $user->getsfGuardUserProfiles(); $sfGuardUserProfile = $sfGuardUserProfile[0]; $connection = new Swift_Connection_SMTP('mail.sis-nav.com', 25); $connection->setUsername('*****@*****.**'); $connection->setPassword('gahve123'); $mailer = new Swift($connection); $message = new Swift_Message(sprintf("Goole Volume - %s notifications.", $frequencies[$frequency])); $images = array(); foreach ($reports as $report) { // $rtn = ReportPeer::_getReportChart( // $report, date('Y-m-d', strtotime(date('Ymd') . ' -1 months')), // date('Y-m-d', strtotime(date('Y-m-d') . ' +1 days')), // QueryResultPeer::FREQUENCY_DAY, new MailChartDecorator()); $rtn = ReportPeer::_getReportChartt($report, new MailChartDecorator()); $data = $rtn['values']; $line_chart = $rtn['chart']; $image_path = $local_url = sfConfig::get('app_web_images') . '/' . $line_chart->__toString(); $images[$report->getTitle()] = new Swift_Message_Image(new Swift_File($image_path)); $imageReferences = array(); foreach ($images as $name => $image) { $imageReferences[$name] = $message->attach($image); } $mailContext = array('data' => $data, 'full_name' => $sfGuardUserProfile->getFullName(), 'report' => $report, 'images' => $imageReferences); } try { $message->attach(new Swift_Message_Part(get_partial('mail/mailReportHtmlBody', $mailContext), 'text/html')); $message->attach(new Swift_Message_Part(get_partial('mail/mailReportTextBody', $mailContext), 'text/plain')); $mailer->send($message, $sfGuardUserProfile->getEmail(), '*****@*****.**'); $mailer->disconnect(); } catch (Exception $e) { logline(sprintf('Exception while sending email to %s about %s. %s', $sfGuardUserProfile->getEmail(), $report->getTitle(), $e)); $mailer->disconnect(); } logline(sprintf('Sent mail to %s.', $sfGuardUserProfile->getEmail())); } logline(sprintf("Finished processing.")); $stop_watch->end(); logline(sprintf('Execution time: %s seconds.', $stop_watch->getTime())); logline(sprintf('!!!!!CAN RUN %s TIMES A DAY!!!!!', 24 * 60 * 60 / ($stop_watch->getTime() == 0 ? 1 : $stop_watch->getTime()))); }
function printOnCallNotifications($on_call_name, $start, $end, $oncall_start, $oncall_end) { global $nagios_state_to_badge, $nagios_alert_tags; # Non timezone version to store the data $range_start = $start; $range_end = $end; // Call the correct provider $oncall_config = getTeamConfig('oncall'); if (!$oncall_config) { return '<div class="alert alert-error">Something terrible has happened. This team doesn\'t have on call enabled!</div>'; } $provider_name = $oncall_config['provider']; logline("printOnCallNotifications has started, looking for provider {$provider_name}. "); // Get the global configuration for the provider $provider_config = getOnCallProvider($provider_name); $provider_global_options = $provider_config['options']; // Get the per team options for the provider $provider_team_options = getTeamOnCallConfig('provider_options'); // Hopefully the user entered a valid oncall provider name... if (!$provider_config) { return '<div class="alert alert-error">Something terrible has happened. We cannot find an on-call provider named "' . $provider_name . '"</div>'; } logline("printOnCallNotifications is loading {$provider_config['lib']}"); // Load the provider specified. include_once "{$provider_config['lib']}"; logline("Firing getOnCallNotificationsFromDb to get events stored in the database for the period..."); $notifications_from_db = getOnCallNotificationsFromDb($oncall_start, $oncall_end); if (empty($notifications_from_db)) { logline("getOnCallNotificationsFromDb returned an empty array! The oncall provider may have events..."); } else { logline("getOnCallNotificationsFromDb returned an array containing " . count($notifications_from_db) . " notifications"); // Find the most recent event in the database and return its timestamp. // We'll use this as the start timestamp for querying the oncall provider. $most_recent_db_event_timestamp = getMostRecentEventTimestampFromDb($oncall_start, $oncall_end); logline("Most recent event timestamp from the database: {$most_recent_db_event_timestamp}"); $oncall_start = $most_recent_db_event_timestamp; } logline("Firing getOnCallNotifications..."); // And now ask for the notifications $notifications_from_provider = getOnCallNotifications($on_call_name, $provider_global_options, $provider_team_options, $oncall_start, $oncall_end); if (empty($notifications_from_provider)) { logline("getOnCallNotifications returned an empty array! Continuing with the events stored in the database."); $notifications = $notifications_from_db; } else { logline("getOnCallNotifications returned an array containing " . count($notifications) . " notifications"); if (empty($notifications_from_db)) { // This is probably the first time the on-call engineer started writing the report so nothing is stored in the database. $notifications = $notifications_from_provider; } else { // Merge the results from the database into what we've received from our oncall provider. logline("Merging the database results with the provider results."); $notifications = array_merge($notifications_from_provider, $notifications_from_db); } } // Data collection complete. Time to render the form items for report submission. // First, we populate the field with the on call ranges so the report is saved with the correct timestamp $html = "<input type='hidden' name='oncall[range_start]' value='{$range_start}'>"; $html .= "<input type='hidden' name='oncall[range_end]' value='{$range_end}'>"; // Add some javascript so we can toggle hidden events. $html .= "<script type='text/javascript'>"; $html .= " function toggleHiddenEvents() {"; $html .= " var events = document.getElementsByClassName('hiddenEvent');"; $html .= " for (var i=0; i < events.length; i++) {"; $html .= " events[i].style.display = events[i].style.display == 'none' ? '' : 'none';"; $html .= " }"; $html .= " }"; $html .= "</script>"; // Allow the user to display/hide hidden events. $html .= "<button class='btn btn-primary pull-right' type='button' onclick='toggleHiddenEvents()'>Toggle Hidden Events</button><br><br>"; $timezone = getTimezoneSetting(); date_default_timezone_set($timezone); $n_num = 0; $n_total = count($notifications); $timesaver = false; if ($n_total > 1) { foreach ($notifications as $n) { # Add a row that lets the user potentially stop halfway and come back later if ($n_num >= $n_total / 2 && !$timesaver) { $timesaver = true; $html .= "<tr><td colspan='7'><div class='well'><b>Hey!</b> You made it halfway. If you want you can save up to here and continue later."; $html .= "<button class='btn btn-primary pull-right' type='submit'>Save draft</button></div></td></tr>"; } // Determine if we need to display a checked box for a hidden event. $hide_checked = $n['hide_event'] ? "checked" : ""; $pretty_date = date("D d M H:i:s T", $n['time']); if ($n['hide_event']) { $html .= "<tr class='hiddenEvent' style='display:none'>"; } else { $html .= "<tr>"; } $html .= "<td>{$pretty_date}</td><td>{$n['hostname']}</td><td>{$n['service']}</td><td><pre><small>{$n['output']}</small></pre></td>"; $html .= "<td><span class='label label-{$nagios_state_to_badge[$n['state']]}'>{$n['state']}</span></td>"; # Need to populate all the information into hidden fields so we get all the data back nicely when the form is submitted $html .= "<input type='hidden' name='oncall[notifications][not_{$n_num}][hostname]' value='{$n['hostname']}'>"; $html .= "<input type='hidden' name='oncall[notifications][not_{$n_num}][output]' value='{$n['output']}'>"; $html .= "<input type='hidden' name='oncall[notifications][not_{$n_num}][time]' value='{$n['time']}'>"; $html .= "<input type='hidden' name='oncall[notifications][not_{$n_num}][state]' value='{$n['state']}'>"; $html .= "<input type='hidden' name='oncall[notifications][not_{$n_num}][service]' value='{$n['service']}'>"; if ($n['id']) { $html .= "<input type='hidden' name='oncall[notifications][not_{$n_num}][id]' value='{$n['id']}'>"; } $html .= "<td><input class='bulk-check' data-num='{$n_num}' type='checkbox'></td>"; $html .= "<td><input class='hide-check' data-num='{$n_num}' name='oncall[notifications][not_{$n_num}][hide_event]' type='checkbox' {$hide_checked}></td>"; $html .= "</tr>"; if ($n['hide_event']) { $html .= "<tr class='hiddenEvent' style='display:none'>"; } else { $html .= "<tr>"; } $html .= "<td colspan='2'>"; # Dropdown that lets the user choose a tag for the alert $html .= "<select name='oncall[notifications][not_{$n_num}][tag]' class='input-xlarge'>"; foreach ($nagios_alert_tags as $tag => $tag_name) { //$selected = ($tag == $previous_tag) ? " selected" : ""; $selected = $tag == $n['tag'] ? " selected" : ""; $html .= "<option value='{$tag}'{$selected}>{$tag_name}</option>"; } $html .= "</select></td>"; $html .= "<td colspan='5'><div class='control-group'><label class='control-label'><b>Notes:</b> </label>\n <div class='controls'><input type='text' name='oncall[notifications][not_{$n_num}][notes]' class='input-xxlarge' placeholder='Notes' value='{$n['notes']}'></div></div></td>"; $html .= "</tr>"; $n_num++; } } date_default_timezone_set("UTC"); return $html; }
function createResponseForUserByLogin($login, $link, $log, $vectorini) { $myquery = $vectorini["QUERYBYLOGIN"]; $myquery = str_replace("<login>", $login, $myquery); if ($vectorini['DEBUG']) { logline($log, 'Mysql statement:' . $myquery); } $result = mysql_query($myquery); if (!$result) { if ($vectorini['DEBUG']) { logline($log, 'Mysql error:' . mysql_error()); } } createSOAPResponseName($result, $vectorini); }
</head> <body style="background-color:#FCFCFE; margin:3px"> <table class="warning"> <tr><td><b>Could not open file cfg.php for writing!</b><p> Please edit the file manually and replace it with the contents of the textarea below. After changing the configuration manually, please click <a href="admin.php">here</a>.</td></tr> </table> <form><textarea style="width:600px;height:400px"><?php echo htmlspecialchars($buf); ?> </textarea></form></body></html><?php exit; } fwrite($fh, $buf); fclose($fh); include "cfg.php"; logline(1, $_SERVER["REMOTE_ADDR"] . " Config changed by admin"); $msg = "Configuration saved successfully"; } ?> <html> <head> <title>HTTPTunnel PHP Server Administration</title> <link rel="shortcut icon" href="common/server.ico" type="image/x-icon" /> <link type="text/css" rel="StyleSheet" href="common/tab.css" /> <script type="text/javascript" src="common/tabpane.js"></script> <script type="text/javascript" src="common/overlib_mini.js"></script> <script> function initAddUser() { var dialog=window.open('','user','height=130,width=385,dependent=yes,directories=no,location=no,menubar=no,resizable=yes,scrollbars=no,status=no,toolbar=no'); dialog.document.write(getUserHTML('Add','','',-1)); dialog.document.close();
function baseutils_errorHandler($errno, $errstr, $errfile, $errline) { global $baseutils_errors_visible; if (!(error_reporting() & $errno)) { // This error code is not included in error_reporting return; } $errtype = 'UNKNOWN'; switch ($errno) { case E_USER_ERROR: $errtype = 'ERROR'; break; case E_USER_WARNING: $errtype = 'WARNING'; break; case E_USER_NOTICE: $errtype = 'NOTICE'; break; } $s = explode("\r", $errstr); foreach ($s as $line) { $line = trim($line); if ($line != 'Above error reporting') { if ($baseutils_errors_visible) { echo "\r\n" . $errtype . ' (' . $errfile . ':' . $errline . '): ' . $line; } logline($errtype . ' (' . $errfile . ':' . $errline . '): ' . $line); } } if ($baseutils_errors_visible) { echo "\r\n"; } if ($errtype == 'ERROR') { exit(1); } return true; }
$insertvalues = ""; $i = 0; $numberofds = count($thisgraphdef['datasources']); foreach ($thisgraphdef['datasources'] as $thisds) { $insertvalues .= $thisint[$thisds]; if ($i < $numberofds - 1) { $insertvalues .= ":"; } $i++; } logline("{$pollprettyhost} - {$intname} - Going to update RRD {$genrrdname} with data {$insertvalues}", 2, $verbose); updateRRD($genrrdname, $pollprettyhost, $timestamp, $insertvalues); logline("{$pollprettyhost} - {$intname} - Update RRD done", 1, $verbose); logline("{$pollprettyhost} - {$intname} - Updating database", 2, $verbose); # Insert the details of this graph/port into the database for future reference connectToDB(); # first, delete the previous row if it exists mysql_query('DELETE FROM ports where host="' . $pollprettyhost . '" AND safename="' . $thisint['name'] . '" AND graphtype="' . $thisgraph . '"'); # Now insert the values mysql_query('INSERT INTO ports (host, name, safename, filename, alias, graphtype, lastpoll) VALUES ("' . $pollprettyhost . '", "' . $thisint[2] . '", "' . $thisint['name'] . '", "' . $genrrdname . '", "' . $thisint['alias'] . '", "' . $thisgraph . '", "' . $timestamp . '")'); logline("{$pollprettyhost} - {$intname} - Done Updating database", 2, $verbose); logline("{$pollprettyhost} - {$intname} - Done loop for interface {$thisint['name']} and graph type {$thisgraph}", 2, $verbose); } } else { logline("{$pollprettyhost} - Interface {$thisint['name']} was either admin down or oper down, not polling this run", 1, $verbose); } logline("{$pollprettyhost} - {$intname} - Loop for interface {$thisint['name']} complete", 1, $verbose); } logline("{$pollprettyhost} - Poller has completed it's run for this host. ", 0, $verbose);
function printOnCallNotifications($on_call_name, $start, $end, $oncall_start, $oncall_end) { global $nagios_state_to_badge, $nagios_alert_tags; # Non timezone version to store the data $range_start = $start; $range_end = $end; // Call the correct provider $oncall_config = getTeamConfig('oncall'); if (!$oncall_config) { return '<div class="alert alert-error">Something terrible has happened. This team doesn\'t have on call enabled!</div>'; } $provider_name = $oncall_config['provider']; logline("printOnCallNotifications has started, looking for provider {$provider_name}. "); // Get the global configuration for the provider $provider_config = getOnCallProvider($provider_name); $provider_global_options = $provider_config['options']; // Get the per team options for the provider $provider_team_options = getTeamOnCallConfig('provider_options'); // Hopefully the user entered a valid oncall provider name... if (!$provider_config) { return '<div class="alert alert-error">Something terrible has happened. We cannot find an on-call provider named "' . $provider_name . '"</div>'; } logline("printOnCallNotifications is loading {$provider_config['lib']}"); // Load the provider specified. include_once "{$provider_config['lib']}"; logline("Firing getOnCallNotifications..."); // And now ask for the notifications $notifications = getOnCallNotifications($on_call_name, $provider_global_options, $provider_team_options, $oncall_start, $oncall_end); // If the returned data wasn't an array, something is wrong... if (!is_array($notifications)) { logline("getOnCallNotifications didn't return an array! Returned data was {$notifications} "); return '<div class="alert alert-error">The oncall provider failed. It returned: <pre>' . $notifications . '</pre></div>'; } else { logline("getOnCallNotifications returned an array containing " . count($notifications) . " notifications"); } // Data collection complete. Time to render the form items for report submission. // First, we populate the field with the on call ranges so the report is saved with the correct timestamp $html = "<input type='hidden' name='oncall[range_start]' value='{$range_start}'>"; $html .= "<input type='hidden' name='oncall[range_end]' value='{$range_end}'>"; $timezone = getTimezoneSetting(); date_default_timezone_set($timezone); $n_num = 0; $n_total = count($notifications); $timesaver = false; foreach ($notifications as $n) { # Add a row that lets the user potentially stop halfway and come back later if ($n_num >= $n_total / 2 && !$timesaver) { $timesaver = true; $html .= "<tr><td colspan='5'><div class='well'><b>Hey!</b> You made it halfway. If you want you can save up to here and continue later."; $html .= "<button class='btn btn-primary pull-right' type='submit'>Save draft</button></div></td></tr>"; } # Look for a previous copy of this alert if ($previous_data = checkForPreviousOnCallItem(generateOnCallAlertID($n['time'], $n['hostname'], $n['service']))) { $previous_notes = $previous_data['notes']; $previous_tag = $previous_data['tag']; } else { $previous_notes = null; $previous_tag = null; } $pretty_date = date("D d M H:i:s T", $n['time']); $html .= "<tr>"; $html .= "<td>{$pretty_date}</td><td>{$n['hostname']}</td><td>{$n['service']}</td><td><pre><small>{$n['output']}</small></pre></td>"; $html .= "<td><span class='label label-{$nagios_state_to_badge[$n['state']]}'>{$n['state']}</span></td>"; # Need to populate all the information into hidden fields so we get all the data back nicely when the form is submitted $html .= "<input type='hidden' name='oncall[notifications][not_{$n_num}][hostname]' value='{$n['hostname']}'>"; $html .= "<input type='hidden' name='oncall[notifications][not_{$n_num}][output]' value='{$n['output']}'>"; $html .= "<input type='hidden' name='oncall[notifications][not_{$n_num}][time]' value='{$n['time']}'>"; $html .= "<input type='hidden' name='oncall[notifications][not_{$n_num}][state]' value='{$n['state']}'>"; $html .= "<input type='hidden' name='oncall[notifications][not_{$n_num}][service]' value='{$n['service']}'>"; $html .= "</tr>"; $html .= "<tr><td colspan='2'>"; # Dropdown that lets the user choose a tag for the alert $html .= "<select name='oncall[notifications][not_{$n_num}][tag]' class='input-xlarge'>"; foreach ($nagios_alert_tags as $tag => $tag_name) { $selected = $tag == $previous_tag ? " selected" : ""; $html .= "<option value='{$tag}'{$selected}>{$tag_name}</option>"; } $html .= "</select></td>"; $html .= "<td colspan='2'><div class='control-group'><label class='control-label'><b>Notes:</b> </label>\n <div class='controls'><input type='text' name='oncall[notifications][not_{$n_num}][notes]' class='input-xxlarge' placeholder='Notes' value='{$previous_notes}'></div></div></td>"; $html .= "<td><input class='bulk-check' data-num='{$n_num}' type='checkbox'></td></tr>"; $n_num++; } date_default_timezone_set("UTC"); return $html; }
/** * getOnCallNotifications - Returns the notifications for a given time period and parameters * * Parameters: * $on_call_name - The username of the user compiling this report * $provider_global_config - All options from config.php in $oncall_providers - That is, global options. * $provider_team_config - All options from config.php in $teams - That is, specific team configuration options * $start - The unix timestamp of when to start looking for notifications * $end - The unix timestamp of when to stop looking for notifications * * Returns 0 or more notifications as array() * - Each notification should have the following keys: * - time: Unix timestamp of when the alert was sent to the user * - hostname: Ideally contains the hostname of the problem. Must be populated but feel free to make bogus if not applicable. * - service: Contains the service name or a description of the problem. Must be populated. Perhaps use "Host Check" for host alerts. * - output: The plugin output, e.g. from Nagios, describing the issue so the user can reference easily/remember issue * - state: The level of the problem. One of: CRITICAL, WARNING, UNKNOWN, DOWN */ function getOnCallNotifications($name, $global_config, $team_config, $start, $end) { $base_url = $global_config['base_url']; $username = $global_config['username']; $password = $global_config['password']; $apikey = $global_config['apikey']; $service_id = $team_config['pagerduty_service_id']; if ($base_url !== '' && $username !== '' && $password !== '' && $service_id !== '') { // convert single PagerDuty service, to array construct in order to hold multiple services. if (!is_array($service_id)) { $service_id = array($service_id); } // loop through all PagerDuty services foreach ($service_id as $sid) { // check if the service id is formated correctly if (!sanitizePagerDutyServiceId($sid)) { logline('Incorect format for PagerDuty Service ID: ' . $sid); // skip to the next Service ID in the array continue; } // loop through PagerDuty's maximum incidents count per API request. $running_total = 0; do { // Connect to the Pagerduty API and collect all incidents in the time period. $parameters = array('since' => date('c', $start), 'service' => $sid, 'until' => date('c', $end), 'offset' => $running_total); $incident_json = doPagerdutyAPICall('/incidents', $parameters, $base_url, $username, $password, $apikey); if (!($incidents = json_decode($incident_json))) { return 'Could not retrieve incidents from Pagerduty! Please check your login details'; } // skip if no incidents are recorded if (count($incidents->incidents) == 0) { continue; } logline("Incidents on Service ID: " . $sid); logline("Total incidents: " . $incidents->total); logline("Limit in this request: " . $incidents->limit); logline("Offset: " . $incidents->offset); $running_total += count($incidents->incidents); logline("Running total: " . $running_total); foreach ($incidents->incidents as $incident) { $time = strtotime($incident->created_on); // try to determine and set the service if (isset($incident->trigger_summary_data->subject)) { $service = $incident->trigger_summary_data->subject; } elseif (isset($incident->trigger_summary_data->SERVICEDESC)) { $service = $incident->trigger_summary_data->SERVICEDESC; } else { $service = "unknown"; } $output = $incident->trigger_details_html_url; $output .= "\n"; // Add to the output all the trigger_summary_data info foreach ($incident->trigger_summary_data as $key => $key_data) { $output .= "{$key}: {$key_data}\n"; } $output .= $incident->url; // try to determine the hostname if (isset($incident->trigger_summary_data->HOSTNAME)) { $hostname = $incident->trigger_summary_data->HOSTNAME; } else { // fallback is to just say it was pagerduty that sent it in $hostname = "Pagerduty"; } $notifications[] = array("time" => $time, "hostname" => $hostname, "service" => $service, "output" => $output, "state" => "CRITICAL"); } } while ($running_total < $incidents->total); } // if no incidents are reported, don't generate the table if (count($notifications) == 0) { return array(); } else { return $notifications; } } else { return false; } }
function write_to_socket($socket, $buffer, $count) { global $READ_WRITE_ATTEMPTS; $totalCount = 0; $retryCount = 0; do { if ($retryCount > 0) { usleep(10000); // 10ms } if (!$socket) { break; } $written = fwrite($socket, $buffer, $count); $buffer = substr($buffer, $written); $totalCount += $written; if ($retryCount > 0) { logdebug("Attempt to write #" . ($retryCount + 1) . " Write: " . $written); } $retryCount = $retryCount + 1; } while ($totalCount < $count && $retryCount < $READ_WRITE_ATTEMPTS); if ($totalCount != $count) { logline("ERROR: Failed to write to socket {$count} bytes, {$totalCount} actually written."); } return $totalCount; }
function openRemote($http_user, $http_pass) { global $copts, $dad, $dpo, $bad, $bpo, $CASCADING, $CAS_SERVER, $CAS_PORT, $CAS_AUTH_PASSTHROUGH, $CAS_AUTH_USER, $CAS_AUTH_PASS, $usock, $rmsock, $ident; if ($CASCADING == 4 && $copts & 4) { return "UDP connections cannot be cascaded over SOCKS4"; } $s = $CASCADING ? $CAS_SERVER : $dad; $p = $CASCADING ? $CAS_PORT : $dpo; if ($copts & 4) { // udp socket $usock = stream_socket_server("udp://0.0.0.0:0", $errno, $errstr, STREAM_SERVER_BIND); if (!$usock) { return "UDP stream_socket_server() failed: reason: {$errstr}"; } $bad = "0.0.0.0"; $bpo = 0; } if (!$CASCADING && $copts & 8) { // bind and no cascading $bad = getmyip(true); $rmsock = stream_socket_server("tcp://0.0.0.0:0", $errno, $errstr); if (!$rmsock) { return "BIND stream_socket_server() failed: reason: {$errstr}"; } $bpo = preg_replace('/^.*?:/', '', stream_socket_get_name($rmsock, false)); logline(4, "{$ident}: opened BIND server on {$bad}:{$bpo}"); } if ($CASCADING || !($copts & 12)) { // tcp socket $rmsock = stream_socket_client("tcp://{$s}:{$p}", $errno, $errstr); if (!$rmsock) { return "TCP stream_socket_client(tcp://{$s}:{$p}) failed: reason: {$errstr}"; } $bad = preg_replace('/:.*$/', '', stream_socket_get_name($rmsock, false)); $bpo = preg_replace('/^.*?:/', '', stream_socket_get_name($rmsock, false)); stream_set_blocking($rmsock, 1); } $user = $CAS_AUTH_PASSTHROUGH ? $http_user : $CAS_AUTH_USER; $pass = $CAS_AUTH_PASSTHROUGH ? $http_pass : $CAS_AUTH_PASS; if ($CASCADING == 4) { # SOCKS4 connect $iaddr = ip2long(gethostbyname($dad)); # try to resolve target ip if ($iaddr) { myfwrite($rmsock, pack("CCCCN", 0x4, $copts & 8 ? 0x2 : 0x1, floor($dpo / 256), $dpo % 256, $iaddr) . $user . chr(0)); } else { myfwrite($rmsock, pack("C*", 0x4, $copts & 8 ? 0x2 : 0x1, floor($dpo / 256), $dpo % 256, 0, 0, 0, 1) . $user . chr(0) . $server . chr(0)); } $a = get_socks4_reply($rmsock); if ($a[0]) { return $a[0]; } $bad = $a[1]; $bpo = $a[2]; } elseif ($CASCADING == 5) { # SOCKS5 connect if ($copts & 4) { # UDP connection cascading $dpo = preg_replace('/^.*?:/', '', stream_socket_get_name($usock, false)); $dad = preg_replace('/:.*$/', '', stream_socket_get_name($rmsock, false)); } # send greeting myfwrite($rmsock, pack("C*", 0x5, 0x2, 0x0, 0x2)); $buf = fread($rmsock, 2); if (empty($buf)) { return $msg; } $a = unpack("C*", $buf); if ($a[2] == 2) { # authenticate myfwrite($rmsock, chr(1) . chr(strlen($user)) . $user . chr(strlen($pass)) . $pass); $buf = fread($rmsock, 2); if (empty($buf)) { return $msg; } $a = unpack("C*", $buf); if ($a[2] != 0) { return "SOCKS5 authentication failed"; } } $iaddr = ip2long(gethostbyname($dad)); if ($iaddr) { $buf = pack("CCCCNCC", 0x5, $copts & 4 ? 0x3 : ($copts & 8 ? 0x2 : 0x1), 0x0, 0x1, $iaddr, floor($dpo / 256), $dpo % 256); } else { $buf = pack("C*", 0x5, $copts & 4 ? 0x3 : ($copts & 8 ? 0x2 : 0x1), 0x0, 0x3, strlen($dad)) . $dad . chr(floor($dpo / 256)) . chr($dpo % 256); } myfwrite($rmsock, $buf); $a = get_socks5_reply($rmsock); if ($a[0]) { return $a[0]; } $bad = $a[1]; $bpo = $a[2]; } return ""; }
if ($rin[0] == $usock) { $buf = stream_socket_recvfrom($usock, 65536, 0, $addr); } else { $buf = fread($rmsock, 65536); } $i = strlen($buf); if (!empty($buf)) { if ($copts & 4) { if (!$CASCADING) { list($s, $p) = preg_split('/:/', $addr); $buf = "" . pack("N", ip2long($s)) . pack("n", $p) . $buf; } else { $i -= 10; } } logline(3, "{$ident}: <- " . bin2txt(substr($buf, -$i))); $incount += $i; if ($copts & 1) { $buf = gzcompress($buf, 9); } if ($copts & 2) { $buf = mcrypt_generic($te, $buf); } echo base64_encode($buf) . "\n"; if ($ka) { $nk = time() + $ki; } } } } }