Example #1
0
 /**
  * @param string $historyId
  * @throws Exception
  */
 public function xGetInfoAction($historyId)
 {
     $history = WebhookHistory::findPk($historyId);
     $webhook = WebhookConfig::findPk($history->webhookId);
     if (!$this->canViewPayload($webhook)) {
         throw new Scalr_Exception_InsufficientPermissions();
     }
     $this->response->data(array('info' => array('historyId' => $history->historyId, 'payload' => $history->payload)));
 }
 public function OnStartForking()
 {
     $db = \Scalr::getDb();
     // Get pid of running daemon
     $pid = @file_get_contents(CACHEPATH . "/" . __CLASS__ . ".Daemon.pid");
     $this->Logger->info("Current daemon process PID: {$pid}");
     // Check is daemon already running or not
     if ($pid) {
         $Shell = new Scalr_System_Shell();
         // Set terminal width
         putenv("COLUMNS=400");
         // Execute command
         $ps = $Shell->queryRaw("ps ax -o pid,ppid,command | grep ' 1' | grep {$pid} | grep -v 'ps x' | grep DBQueueEvent");
         $this->Logger->info("Shell->queryRaw(): {$ps}");
         if ($ps) {
             // daemon already running
             $this->Logger->info("Daemon running. All ok!");
             return true;
         }
     }
     $rows = $db->Execute("SELECT history_id FROM webhook_history WHERE status='0'");
     while ($row = $rows->FetchRow()) {
         $history = WebhookHistory::findPk(bin2hex($row['history_id']));
         if (!$history) {
             continue;
         }
         $endpoint = WebhookEndpoint::findPk($history->endpointId);
         $request = new HttpRequest();
         $request->setMethod(HTTP_METH_POST);
         if ($endpoint->url == 'SCALR_MAIL_SERVICE') {
             $request->setUrl('https://my.scalr.com/webhook_mail.php');
         } else {
             $request->setUrl($endpoint->url);
         }
         $request->setOptions(array('timeout' => 3, 'connecttimeout' => 3));
         $dt = new DateTime('now', new DateTimeZone("UTC"));
         $timestamp = $dt->format("D, d M Y H:i:s e");
         $canonical_string = $history->payload . $timestamp;
         $signature = hash_hmac('SHA1', $canonical_string, $endpoint->securityKey);
         $request->addHeaders(array('Date' => $timestamp, 'X-Signature' => $signature, 'X-Scalr-Webhook-Id' => $history->historyId, 'Content-type' => 'application/json'));
         $request->setBody($history->payload);
         try {
             $request->send();
             $history->responseCode = $request->getResponseCode();
             if ($request->getResponseCode() <= 205) {
                 $history->status = WebhookHistory::STATUS_COMPLETE;
             } else {
                 $history->status = WebhookHistory::STATUS_FAILED;
             }
         } catch (Exception $e) {
             $history->status = WebhookHistory::STATUS_FAILED;
         }
         $history->save();
     }
 }
Example #3
0
 public function xListEventsAction()
 {
     $this->request->defineParams(array('farmId' => array('type' => 'int'), 'eventServerId', 'eventId', 'query' => array('type' => 'string'), 'sort' => array('type' => 'string', 'default' => 'id'), 'dir' => array('type' => 'string', 'default' => 'DESC')));
     $sql = "SELECT farmid, message, type, dtadded, event_server_id, event_id FROM events WHERE farmid='{$this->dbFarm->ID}'";
     if ($this->getParam('eventServerId')) {
         $sql .= " AND event_server_id = " . $this->db->qstr($this->getParam('eventServerId'));
     }
     if ($this->getParam('eventId')) {
         $sql .= " AND event_id = " . $this->db->qstr($this->getParam('eventId'));
     }
     $response = $this->buildResponseFromSql($sql, array("message", "type", "dtadded", "event_server_id", "event_id"));
     $cache = array();
     foreach ($response['data'] as &$row) {
         $row['message'] = nl2br($row['message']);
         $row["dtadded"] = Scalr_Util_DateTime::convertTz($row["dtadded"]);
         $row['scripts'] = $this->db->GetOne("SELECT COUNT(*) FROM scripting_log WHERE event_id = ?", array($row['event_id']));
         if ($row['event_server_id']) {
             $esInfo = $this->db->GetRow("SELECT role_id, farm_roleid, `index`, farm_id FROM servers WHERE server_id = ? LIMIT 1", array($row['event_server_id']));
             if ($esInfo) {
                 if (!$cache['farm_names'][$esInfo['farm_id']]) {
                     $cache['farm_names'][$esInfo['farm_id']] = $this->db->GetOne("SELECT name FROM farms WHERE id=?", array($esInfo['farm_id']));
                 }
                 $row['event_farm_name'] = $cache['farm_names'][$esInfo['farm_id']];
                 $row['event_farm_id'] = $esInfo['farm_id'];
                 $row['event_farm_roleid'] = $esInfo['farm_roleid'];
                 if (!$cache['role_names'][$esInfo['role_id']]) {
                     $cache['role_names'][$esInfo['role_id']] = $this->db->GetOne("SELECT name FROM roles WHERE id=?", array($esInfo['role_id']));
                 }
                 $row['event_role_name'] = $cache['role_names'][$esInfo['role_id']];
                 $row['event_server_index'] = $esInfo['index'];
             }
         }
         $row['webhooks_count'] = count(WebhookHistory::findByEventId($row['event_id']));
     }
     $this->response->data($response);
 }
Example #4
0
 /**
  * Store event in database
  *
  * @param integer $farmid
  * @param string $event_name
  */
 public static function StoreEvent($farmid, Event $event, $eventTime = null)
 {
     if ($event->DBServer) {
         $eventServerId = $event->DBServer->serverId;
     }
     try {
         $DB = self::getDb();
         // Generate event message
         $message = $event->getTextDetails();
         //short_message temporary used for time tracking
         // Store event in database
         $DB->Execute("INSERT INTO events SET\n                farmid\t= ?,\n                type\t= ?,\n                dtadded\t= NOW(),\n                message\t= ?,\n                event_object = '',\n                event_id\t = ?,\n                event_server_id = ?,\n                short_message = ?,\n                msg_expected = ?,\n                msg_created = ?,\n                scripts_total = ?,\n                is_suspend = ?", array($farmid, $event->GetName(), $message, $event->GetEventID(), $eventServerId, $eventTime, $event->msgExpected, $event->msgCreated, $event->scriptsCount, $event->isSuspended ? 1 : 0));
     } catch (Exception $e) {
         Logger::getLogger(__CLASS__)->fatal(sprintf(_("Cannot store event in database: %s"), $e->getMessage()));
     }
     try {
         if ($eventServerId) {
             $dbServer = DBServer::LoadByID($eventServerId);
             if (!$dbServer->farmRoleId) {
                 return true;
             }
             $dt = new DateTime('now', new DateTimeZone("UTC"));
             $timestamp = $dt->format("D d M Y H:i:s e");
             $payload = new stdClass();
             $payload->eventName = $event->GetName();
             $payload->eventId = $event->GetEventID();
             $payload->timestamp = $timestamp;
             $globalVars = Scalr_Scripting_GlobalVariables::listServerGlobalVariables($dbServer, true, $event);
             $webhooks = WebhookConfig::findByEvent($event->GetName(), $farmid, $dbServer->clientId, $dbServer->envId);
             $count = 0;
             foreach ($webhooks as $webhook) {
                 /* @var $webhook \Scalr\Model\Entity\WebhookConfig */
                 $payload->configurationId = $webhook->webhookId;
                 $payload->data = array();
                 $variables = [];
                 foreach ($globalVars as $gv) {
                     $variables[$gv->name] = $gv->value;
                     if ($gv->private && $webhook->skipPrivateGv == 1 && !$gv->system) {
                         continue;
                     }
                     $payload->data[$gv->name] = $gv->value;
                 }
                 if ($webhook->postData) {
                     //Parse variable
                     $keys = array_keys($variables);
                     $f = create_function('$item', 'return "{".$item."}";');
                     $keys = array_map($f, $keys);
                     $values = array_values($variables);
                     // Strip undefined variables & return value
                     $payload->userData = preg_replace("/{[A-Za-z0-9_-]+}/", "", str_replace($keys, $values, $webhook->postData));
                 } else {
                     $payload->userData = '';
                 }
                 foreach ($webhook->getEndpoints() as $ce) {
                     /* @var $ce \Scalr\Model\Entity\WebhookConfigEndpoint */
                     $endpoint = $ce->getEndpoint();
                     if (!$endpoint->isValid) {
                         continue;
                     }
                     $payload->endpointId = $endpoint->endpointId;
                     $encPayload = json_encode($payload);
                     $history = new WebhookHistory();
                     $history->eventId = $event->GetEventID();
                     $history->eventType = $event->GetName();
                     $history->payload = $encPayload;
                     $history->serverId = $event->DBServer ? $event->DBServer->serverId : null;
                     $history->endpointId = $endpoint->endpointId;
                     $history->webhookId = $webhook->webhookId;
                     $history->farmId = $farmid;
                     $history->save();
                     $count++;
                 }
             }
             if ($count != 0) {
                 $DB->Execute("UPDATE events SET wh_total = ? WHERE event_id = ?", array($count, $event->GetEventID()));
             }
         }
     } catch (Exception $e) {
         Logger::getLogger(__CLASS__)->fatal(sprintf(_("WebHooks: %s"), $e->getMessage()));
     }
 }
Example #5
0
 public function xGetInfoAction()
 {
     $history = WebhookHistory::findPk($this->getParam('historyId'));
     $this->response->data(array('info' => array('historyId' => $history->historyId, 'payload' => $history->payload)));
 }
Example #6
0
<?php

require __DIR__ . '/src/prepend.inc.php';
use Scalr\Model\Entity\WebhookHistory;
use Scalr\Model\Entity\WebhookEndpoint;
use Scalr\Model\Entity\WebhookConfig;
try {
    $webhookId = $_SERVER['HTTP_X_SCALR_WEBHOOK_ID'];
    $signature = $_SERVER['HTTP_X_SIGNATURE'];
    $date = $_SERVER['HTTP_DATE'];
    $history = WebhookHistory::findPk($webhookId);
    if (!$history) {
        throw new Exception("Bad request (1)");
    }
    $endpoint = WebhookEndpoint::findPk($history->endpointId);
    $webhook = WebhookConfig::findPk($history->webhookId);
    $canonicalString = $history->payload . $date;
    $validSignature = hash_hmac('SHA1', $canonicalString, $endpoint->securityKey);
    if ($signature != $validSignature) {
        throw new Exception("Bad request (2)");
    }
    $payload = json_decode($history->payload);
    $text = "\n========= Event ========\n\nEVENT_NAME: {$payload->eventName}\nEVENT_ID: {$payload->eventId}\n\n========= Farm ========\n\nFARM_ID: {$payload->data->SCALR_EVENT_FARM_ID}\nFARM_NAME: {$payload->data->SCALR_EVENT_FARM_NAME}\n\n========= Role ========\n\nFARM_ROLE_ID: {$payload->data->SCALR_EVENT_FARM_ROLE_ID}\nROLE_NAME: {$payload->data->SCALR_FARM_ROLE_ALIAS}\n\n========= Server =========\n\nSERVER_ID: {$payload->data->SCALR_EVENT_SERVER_ID}\nCLOUD_SERVER_ID: {$payload->data->SCALR_EVENT_CLOUD_SERVER_ID}\nPUBLIC_IP: {$payload->data->SCALR_EVENT_INTERNAL_IP}\nPRIVATE_IP: {$payload->data->SCALR_EVENT_EXTERNAL_IP}\nCLOUD_LOCATION: {$payload->data->SCALR_EVENT_CLOUD_LOCATION}\nCLOUD_LOCATION_ZONE: {$payload->data->SCALR_EVENT_CLOUD_LOCATION_ZONE}\n";
    $subject = "{$payload->data->SCALR_EVENT_FARM_NAME}: {$payload->eventName} on {$payload->data->SCALR_EVENT_SERVER_ID} ({$payload->data->SCALR_EVENT_EXTERNAL_IP})";
    $mailer = Scalr::getContainer()->mailer->setFrom('*****@*****.**', 'Scalr')->setMessage($text)->setSubject($subject);
    $emails = explode(",", $webhook->postData);
    foreach ($emails as $email) {
        if ($email) {
            $mailer->send($email);
        }
    }
Example #7
0
 /**
  * Store event in database
  *
  * @param integer $farmid
  * @param string $event_name
  */
 public static function StoreEvent($farmid, Event $event, $eventTime = null)
 {
     if ($event->DBServer) {
         $eventServerId = $event->DBServer->serverId;
     }
     try {
         $DB = self::getDb();
         // Generate event message
         $message = $event->getTextDetails();
         $eventStr = null;
         try {
             $eventStr = serialize($event);
         } catch (Exception $e) {
         }
         //short_message temporary used for time tracking
         // Store event in database
         $DB->Execute("INSERT INTO events SET\n                farmid\t= ?,\n                type\t= ?,\n                dtadded\t= NOW(),\n                message\t= ?,\n                event_object = ?,\n                event_id\t = ?,\n                event_server_id = ?,\n                short_message = ?,\n                msg_expected = ?,\n                msg_created = ?\n                ", array($farmid, $event->GetName(), $message, $eventStr, $event->GetEventID(), $eventServerId, $eventTime, $event->msgExpected, $event->msgCreated));
     } catch (Exception $e) {
         Logger::getLogger(__CLASS__)->fatal(sprintf(_("Cannot store event in database: %s"), $e->getMessage()));
     }
     try {
         if ($eventServerId) {
             $dbServer = DBServer::LoadByID($eventServerId);
             $dt = new DateTime('now', new DateTimeZone("UTC"));
             $timestamp = $dt->format("D d M Y H:i:s e");
             $payload = new stdClass();
             $payload->eventName = $event->GetName();
             $payload->eventId = $event->GetEventID();
             $payload->timestamp = $timestamp;
             $globalVars = Scalr_Scripting_GlobalVariables::listServerGlobalVariables($dbServer, true, $event);
             $webhooks = WebhookConfig::findByEvent($event->GetName(), $farmid, $dbServer->clientId, $dbServer->envId);
             foreach ($webhooks as $webhook) {
                 /* @var $webhook \Scalr\Model\Entity\WebhookConfig */
                 $payload->data = array();
                 foreach ($globalVars as $gv) {
                     if ($gv->private && $webhook->skipPrivateGv == 1 && !$gv->system) {
                         continue;
                     }
                     $payload->data[$gv->name] = $gv->value;
                 }
                 if ($webhook->postData) {
                     $payload->userData = $dbServer->applyGlobalVarsToValue($webhook->postData);
                 } else {
                     $payload->userData = '';
                 }
                 $encPayload = json_encode($payload);
                 foreach ($webhook->getEndpoints() as $ce) {
                     /* @var $ce \Scalr\Model\Entity\WebhookConfigEndpoint */
                     $endpoint = $ce->getEndpoint();
                     if (!$endpoint->isValid) {
                         continue;
                     }
                     $history = new WebhookHistory();
                     $history->eventId = $event->GetEventID();
                     $history->eventType = $event->GetName();
                     $history->payload = $encPayload;
                     $history->endpointId = $endpoint->endpointId;
                     $history->webhookId = $webhook->webhookId;
                     $history->farmId = $farmid;
                     $history->save();
                 }
             }
         }
     } catch (Exception $e) {
         Logger::getLogger(__CLASS__)->fatal(sprintf(_("WebHooks: %s"), $e->getMessage()));
     }
 }