예제 #1
0
 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();
     }
 }
예제 #2
0
 /**
  * Performs upgrade literally for the stage ONE.
  *
  * Implementation of this method performs update steps needs to be taken
  * to accomplish upgrade successfully.
  *
  * If there are any error during an execution of this scenario it must
  * throw an exception.
  *
  * @param   int  $stage  optional The stage number
  * @throws  \Exception
  */
 protected function run1($stage)
 {
     $observers = $this->db->Execute("SELECT * FROM farm_event_observers WHERE event_observer_name = 'MailEventObserver'");
     while ($observer = $observers->FetchRow()) {
         $dbFarm = \DBFarm::LoadByID($observer['farmid']);
         // Create endpoint
         $endpointId = $this->db->GetOne("SELECT endpoint_id FROM webhook_endpoints WHERE env_id = ? AND url = ?", array($dbFarm->EnvID, 'SCALR_MAIL_SERVICE'));
         if ($endpointId) {
             $endpoint = WebhookEndpoint::findPk(bin2hex($endpointId));
         } else {
             $endpoint = new WebhookEndpoint();
             $endpoint->level = WebhookEndpoint::LEVEL_ENVIRONMENT;
             $endpoint->accountId = $dbFarm->ClientID;
             $endpoint->envId = $dbFarm->EnvID;
             $endpoint->securityKey = \Scalr::GenerateRandomKey(64);
             $endpoint->isValid = true;
             $endpoint->url = "SCALR_MAIL_SERVICE";
             $endpoint->save();
         }
         //Create webhook configuration
         $webhook = new WebhookConfig();
         $webhook->level = WebhookConfig::LEVEL_ENVIRONMENT;
         $webhook->accountId = $dbFarm->ClientID;
         $webhook->envId = $dbFarm->EnvID;
         $webhook->name = "MailEventObserver(FarmID: {$dbFarm->ID})";
         $webhook->postData = $this->db->GetOne("SELECT value FROM farm_event_observers_config WHERE `key` = ? AND observerid = ?", array('EventMailTo', $observer['id']));
         $webhook->save();
         //save endpoints
         $configEndpoint = new WebhookConfigEndpoint();
         $configEndpoint->webhookId = $webhook->webhookId;
         $configEndpoint->setEndpoint($endpoint);
         $configEndpoint->save();
         //save events
         $dbEvents = $this->db->Execute("SELECT * FROM farm_event_observers_config WHERE `key` LIKE '%Notify' AND observerid = ?", array($observer['id']));
         while ($info = $dbEvents->FetchRow()) {
             preg_match('/On([A-Za-z0-9]+)Notify/si', $info['key'], $matches);
             $configEvent = new WebhookConfigEvent();
             $configEvent->webhookId = $webhook->webhookId;
             $configEvent->eventType = $matches[1];
             $configEvent->save();
         }
         //save farms
         $configFarm = new WebhookConfigFarm();
         $configFarm->webhookId = $webhook->webhookId;
         $configFarm->farmId = $dbFarm->ID;
         $configFarm->save();
     }
 }
예제 #3
0
 /**
  * @param string $endpointId
  * @param string $url
  * @throws Exception
  */
 public function xValidateAction($endpointId, $url)
 {
     $endpoint = WebhookEndpoint::findPk($endpointId);
     if (!$this->canEditEndpoint($endpoint)) {
         throw new Scalr_Exception_Core('Insufficient permissions to edit endpoint in this scope');
     }
     if ($endpoint->url != $url) {
         $endpoint->url = $url;
         $endpoint->save();
     }
     if ($endpoint->validateUrl()) {
         $this->response->success(sprintf('Endpoint %s successfully validated', $endpoint->url));
     } else {
         $this->response->failure(sprintf('Unable to validate endpoint %s. Token was not returned.', $endpoint->url));
     }
     $this->response->data(array('endpoint' => array('endpointId' => $endpoint->endpointId, 'url' => $endpoint->url, 'isValid' => $endpoint->isValid, 'validationToken' => $endpoint->validationToken, 'securityKey' => $endpoint->securityKey)));
 }
예제 #4
0
 public function xValidateAction()
 {
     $endpoint = WebhookEndpoint::findPk($this->request->getParam('endpointId'));
     if ($endpoint->envId != $this->getEnvironmentId() || $endpoint->accountId != $this->getEnvironment()->clientId) {
         throw new Scalr_Exception_Core('Insufficient permissions to edit endpoint');
     }
     if ($endpoint->url != $this->request->getParam('url')) {
         $endpoint->url = $this->request->getParam('url');
         $endpoint->save();
     }
     if ($endpoint->validateUrl()) {
         $this->response->success(sprintf('Endpoint %s successfully validated', $endpoint->url));
     } else {
         $this->response->failure(sprintf('Unable to validate endpoint %s. Token was not returned.', $endpoint->url));
     }
     $this->response->data(array('endpoint' => array('endpointId' => $endpoint->endpointId, 'url' => $endpoint->url, 'isValid' => $endpoint->isValid, 'validationToken' => $endpoint->validationToken, 'securityKey' => $endpoint->securityKey)));
 }
예제 #5
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);
        }
    }
예제 #6
0
 /**
  * Fetches endpoint from database
  *
  * @return WebhookEndpoint|null Returns endpoint object or null
  */
 public function fetchEndpoint()
 {
     $this->_endpoint = WebhookEndpoint::findPk($this->endpointId);
     return $this->_endpoint;
 }