Exemplo n.º 1
0
 /**
  * Query Environment object and return result;
  */
 public function Query($operation, array $args)
 {
     $this->debugObject = new stdClass();
     $this->SetRequest($args);
     // Get Method name by operation
     $method_name = str_replace(" ", "", ucwords(str_replace("-", " ", $operation)));
     // Check method
     if (method_exists($this, $method_name)) {
         // Call method
         try {
             $this->DBServer = $this->GetCallingInstance();
             $result = call_user_func(array($this, $method_name));
             if ($result instanceof DOMDocument) {
                 header("Content-Type: text/xml");
                 return $result->saveXML();
             } else {
                 if (is_object($result)) {
                     header("Content-Type: application/json");
                     $retval = new stdClass();
                     $retval->result = new stdClass();
                     $serializer = Scalr_Messaging_JsonSerializer::getInstance();
                     $serializer->walkSerialize($result, $retval->result, 'underScope');
                     return json_encode($retval->result);
                 } else {
                     throw new Exception(sprintf("%s:%s() returns invalid response. DOMDocument expected.", get_class($this), $method_name));
                 }
             }
         } catch (\Scalr\Exception\Http\HttpException $e) {
             throw $e;
         } catch (DOMException $e) {
             throw $e;
         } catch (Exception $e) {
             throw new Exception(sprintf(_("Cannot retrieve environment by operation '%s': %s"), $operation, $e->getMessage()));
         }
     } else {
         throw new BadRequestException(sprintf("Operation '%s' is not supported", $operation));
     }
 }
Exemplo n.º 2
0
 /**
  * Send message to instance
  * @param Scalr_Messaging_Msg $message
  * @return Scalr_Messaging_Msg
  */
 public function SendMessage(Scalr_Messaging_Msg $message, $isEventNotice = false, $delayed = false)
 {
     $startTime = microtime(true);
     if ($this->farmId && $message->getName() != 'BeforeHostTerminate') {
         if ($this->GetFarmObject()->Status == FARM_STATUS::TERMINATED) {
             $this->Db->Execute("UPDATE messages SET status = ? WHERE messageid = ?", array(MESSAGE_STATUS::FAILED, $message->messageId));
             return;
         }
     }
     // We don't need to send any messages other then it's own to the server that is not in Running state
     if ($message->serverId != $this->serverId && !in_array($this->status, array(SERVER_STATUS::RUNNING, SERVER_STATUS::TEMPORARY, SERVER_STATUS::IMPORTING))) {
         return;
     }
     // Ignore OLD messages (ami-scripts)
     if (!$this->IsSupported("0.5")) {
         return;
     }
     // Put access data and reserialize message
     $pl = PlatformFactory::NewPlatform($this->platform);
     $pl->PutAccessData($this, $message);
     $logger = \Scalr::getContainer()->logger('DBServer');
     $serializer = Scalr_Messaging_XmlSerializer::getInstance();
     $cryptoTool = \Scalr::getContainer()->srzcrypto($this->GetKey(true));
     if ($this->GetProperty(\SERVER_PROPERTIES::SZR_MESSAGE_FORMAT) == 'json') {
         $serializer = Scalr_Messaging_JsonSerializer::getInstance();
         $rawMessage = $serializer->serialize($message);
         $messageType = 'json';
     } else {
         $rawMessage = $serializer->serialize($message);
         $messageType = 'xml';
     }
     //$rawJsonMessage = @json_encode($message);
     $time = microtime(true) - $startTime;
     // Add message to database
     $this->Db->Execute("INSERT INTO messages SET\n                `messageid`             = ?,\n                `processing_time`       = ?,\n                `server_id`             = ?,\n                `event_server_id`       = ?,\n                `message`               = ?,\n                `type`                  = 'out',\n                `message_name`          = ?,\n                `handle_attempts`       = ?,\n                `message_version`       = ?,\n                `dtlasthandleattempt`   = NOW(),\n                `dtadded`               = NOW(),\n                `message_format`        = ?,\n                `event_id`              = ?\n            ON DUPLICATE KEY UPDATE handle_attempts = handle_attempts+1, dtlasthandleattempt = NOW()\n            ", array($message->messageId, $time, $this->serverId, $message->serverId, $rawMessage, $message->getName(), $delayed ? '0' : '1', 2, $messageType, isset($message->eventId) ? $message->eventId : ''));
     if ($delayed) {
         return $message;
     }
     $isVPC = false;
     if ($this->farmId) {
         if (DBFarm::LoadByID($this->farmId)->GetSetting(Entity\FarmSetting::EC2_VPC_ID)) {
             $isVPC = true;
         }
     }
     if (!$this->remoteIp && !$this->localIp && !$isVPC) {
         return;
     }
     $cryptoTool->setCryptoKey($this->GetKey(true));
     $encMessage = $cryptoTool->encrypt($rawMessage);
     $timestamp = date("c", time());
     $signature = $cryptoTool->sign($encMessage, null, $timestamp);
     try {
         $request = new Request();
         $request->setRequestMethod('POST');
         $ctrlPort = $this->getPort(self::PORT_CTRL);
         $requestHost = $this->getSzrHost() . ":{$ctrlPort}";
         if ($isVPC) {
             $routerFarmRoleId = $this->GetFarmRoleObject()->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_SCALR_ROUTER_ID);
             if ($routerFarmRoleId) {
                 $routerRole = DBFarmRole::LoadByID($routerFarmRoleId);
             } else {
                 $routerRole = $this->GetFarmObject()->GetFarmRoleByBehavior(ROLE_BEHAVIORS::VPC_ROUTER);
             }
             if ($routerRole) {
                 // No public IP need to use proxy
                 if (!$this->remoteIp) {
                     $requestHost = $routerRole->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_IP) . ":80";
                     $request->addHeaders(array("X-Receiver-Host" => $this->localIp, "X-Receiver-Port" => $ctrlPort));
                     // There is public IP, can use it
                 } else {
                     $requestHost = "{$this->remoteIp}:{$ctrlPort}";
                 }
             }
         }
         //Prepare request
         $request->setRequestUrl("http://{$requestHost}/control");
         $request->setOptions(array('timeout' => \Scalr::config('scalr.system.instances_connection_timeout'), 'connecttimeout' => \Scalr::config('scalr.system.instances_connection_timeout')));
         $request->addHeaders(array("Date" => $timestamp, "X-Signature" => $signature, 'X-Server-Id' => $this->serverId));
         if ($messageType == 'json') {
             $request->addHeaders(array('Content-type' => 'application/json'));
         }
         $request->append($encMessage);
         // Send request
         $response = \Scalr::getContainer()->srzhttp->sendRequest($request);
         // Process response
         if ($response->getResponseCode() == 201) {
             $logger->info(sprintf("[FarmID: %s] Sending message '%s' via REST to server '%s' (server_id: %s) completed", $this->farmId, $message->getName(), $this->remoteIp, $this->serverId));
             if (in_array($message->getName(), array('ExecScript'))) {
                 $this->Db->Execute("DELETE FROM messages WHERE messageid = ?", array($message->messageId));
             } else {
                 if ($messageType != 'json') {
                     $this->Db->Execute("UPDATE messages SET status = ?, message = '' WHERE messageid = ?", array(MESSAGE_STATUS::HANDLED, $message->messageId));
                 } else {
                     $this->Db->Execute("UPDATE messages SET status = ? WHERE messageid = ?", array(MESSAGE_STATUS::HANDLED, $message->messageId));
                 }
                 if (!empty($message->eventId)) {
                     $this->Db->Execute("UPDATE events SET msg_sent = msg_sent + 1 WHERE event_id = ?", array($message->eventId));
                 }
             }
         } else {
             $logger->warn(sprintf("[FarmID: %s] Cannot deliver message '%s' (message_id: %s) via REST" . " to server '%s' (server_id: %s). Error: %s %s", $this->farmId, $message->getName(), $message->messageId, $this->remoteIp, $this->serverId, $response->getResponseCode(), $response->getResponseStatus()));
         }
     } catch (http\Exception $e) {
         if (isset($e->innerException)) {
             $msg = $e->innerException->getMessage();
         } else {
             $msg = $e->getMessage();
         }
         if ($this->farmId) {
             $logger->warn(new FarmLogMessage($this->farmId, sprintf("Cannot deliver message '%s' (message_id: %s) via REST to server '%s' (server_id: %s). Error: %s", $message->getName(), $message->messageId, $this->remoteIp, $this->serverId, $msg), $this->serverId));
         } else {
             $logger->fatal(sprintf("Cannot deliver message '%s' (message_id: %s) via REST" . " to server '%s' (server_id: %s). Error: %s", $message->getName(), $message->messageId, $this->remoteIp, $this->serverId, $msg));
         }
         return false;
     }
     return $message;
 }
Exemplo n.º 3
0
 /**
  * @param int $farmId
  * @param int $farmRoleId optional
  * @param string $serverId optional
  * @param int $scriptId optional
  * @param string $scriptPath optional
  * @param int $scriptIsSync
  * @param int $scriptTimeout
  * @param int $scriptVersion
  * @param array $scriptParams optional
  * @param int $shortcutId optional
  * @param int $editShortcut optional
  * @throws Exception
  */
 public function xExecuteAction($farmId, $farmRoleId = 0, $serverId = '', $scriptId = 0, $scriptPath = '', $scriptIsSync, $scriptTimeout, $scriptVersion, array $scriptParams = [], $shortcutId = null, $editShortcut = null)
 {
     $this->request->restrictAccess(Acl::RESOURCE_SCRIPTS_ENVIRONMENT, Acl::PERM_SCRIPTS_ENVIRONMENT_EXECUTE);
     if ($serverId) {
         $dbServer = DBServer::LoadByID($serverId);
         $this->user->getPermissions()->validate($dbServer);
         $target = Script::TARGET_INSTANCE;
         $serverId = $dbServer->serverId;
         $farmRoleId = $dbServer->farmRoleId;
         $farmId = $dbServer->farmId;
     } else {
         if ($farmRoleId) {
             $dbFarmRole = DBFarmRole::LoadByID($farmRoleId);
             $this->user->getPermissions()->validate($dbFarmRole);
             $target = Script::TARGET_ROLE;
             $farmRoleId = $dbFarmRole->ID;
             $farmId = $dbFarmRole->FarmID;
         } else {
             if (!$farmId) {
                 $target = Script::TARGET_ALL;
             } else {
                 $dbFarm = DBFarm::LoadByID($farmId);
                 $this->user->getPermissions()->validate($dbFarm);
                 $target = Script::TARGET_FARM;
                 $farmId = $dbFarm->ID;
             }
         }
     }
     if ($farmId) {
         $this->request->checkPermissions(Entity\Farm::findPk($farmId), Acl::PERM_FARMS_SERVERS);
     }
     if ($scriptId) {
         $script = Script::findPk($scriptId);
         /* @var $script Script */
         if (!$script) {
             throw new Scalr_UI_Exception_NotFound();
         }
         $script->checkPermission($this->user, $this->getEnvironmentId());
     } elseif (!$scriptPath) {
         throw new Scalr_Exception_Core('scriptId or scriptPath should be set');
     }
     if (!$scriptTimeout) {
         $scriptTimeout = $scriptIsSync == 1 ? Scalr::config('scalr.script.timeout.sync') : Scalr::config('scalr.script.timeout.async');
     }
     $executeScript = true;
     if ($shortcutId && ($target != Script::TARGET_INSTANCE || $target != Script::TARGET_ALL)) {
         if ($shortcutId == -1) {
             $shortcut = new ScriptShortcut();
             $shortcut->farmId = $farmId;
         } else {
             $shortcut = ScriptShortcut::findPk($shortcutId);
             /* @var $shortcut ScriptShortcut */
             if (!$shortcut) {
                 throw new Scalr_UI_Exception_NotFound();
             }
             if ($editShortcut == 1) {
                 $executeScript = false;
             }
         }
         $shortcut->farmRoleId = $farmRoleId == 0 ? NULL : $farmRoleId;
         if ($scriptId) {
             $shortcut->scriptId = $scriptId;
             $shortcut->scriptPath = '';
         } else {
             $shortcut->scriptPath = $scriptPath;
             $shortcut->scriptId = NULL;
         }
         $shortcut->isSync = $scriptIsSync;
         $shortcut->version = $scriptVersion;
         $shortcut->timeout = $scriptTimeout;
         $shortcut->params = $scriptParams;
         $shortcut->save();
     }
     if ($executeScript) {
         switch ($target) {
             case Script::TARGET_FARM:
                 $servers = $this->db->GetAll("\n                        SELECT server_id\n                        FROM servers\n                        WHERE is_scalarized = 1 AND status IN (?,?) AND farm_id=?", [SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, $farmId]);
                 break;
             case Script::TARGET_ROLE:
                 $servers = $this->db->GetAll("\n                        SELECT server_id\n                        FROM servers\n                        WHERE is_scalarized = 1 AND status IN (?,?) AND farm_roleid=?", [SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, $farmRoleId]);
                 break;
             case Script::TARGET_INSTANCE:
                 $servers = $this->db->GetAll("\n                        SELECT server_id\n                        FROM servers\n                        WHERE is_scalarized = 1 AND status IN (?,?) AND server_id=?", [SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, $serverId]);
                 break;
             case Script::TARGET_ALL:
                 $sql = "\n                        SELECT s.server_id\n                        FROM servers s\n                        JOIN farms f ON f.id = s.farm_id\n                        WHERE s.is_scalarized = 1\n                        AND s.status IN (?,?)\n                        AND s.env_id = ?\n                        AND " . $this->request->getFarmSqlQuery(Acl::PERM_FARMS_SERVERS);
                 $args = [SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, $this->getEnvironmentId()];
                 $servers = $this->db->GetAll($sql, $args);
                 break;
         }
         $scriptSettings = array('version' => $scriptVersion, 'timeout' => $scriptTimeout, 'issync' => $scriptIsSync, 'params' => serialize($scriptParams));
         if ($scriptId) {
             $scriptSettings['scriptid'] = $scriptId;
             $scriptSettings['type'] = Scalr_Scripting_Manager::ORCHESTRATION_SCRIPT_TYPE_SCALR;
         } else {
             $scriptSettings['script_path'] = $scriptPath;
             $scriptSettings['type'] = Scalr_Scripting_Manager::ORCHESTRATION_SCRIPT_TYPE_LOCAL;
         }
         $serializer = Scalr_Messaging_JsonSerializer::getInstance();
         $cryptoTool = \Scalr::getContainer()->srzcrypto;
         // send message to start executing task (starts script)
         if (count($servers) > 0) {
             foreach ($servers as $server) {
                 $DBServer = DBServer::LoadByID($server['server_id']);
                 $msg = new Scalr_Messaging_Msg_ExecScript("Manual");
                 $msg->setServerMetaData($DBServer);
                 $script = Scalr_Scripting_Manager::prepareScript($scriptSettings, $DBServer);
                 if ($script) {
                     $DBServer->executeScript($script, $msg);
                     $this->auditLog("script.execute", $script, $DBServer);
                     $manualLog = new OrchestrationLogManualScript($script['execution_id'], $msg->serverId);
                     $manualLog->userId = $this->getUser()->getId();
                     $manualLog->userEmail = $this->getUser()->getEmail();
                     $manualLog->added = new DateTime('now', new DateTimeZone('UTC'));
                     $manualLog->save();
                 }
             }
         }
         $this->response->success('Script execution has been queued and will occur on the selected instance(s) within a couple of minutes.');
     } else {
         $this->response->success('Script shortcut successfully saved');
     }
 }
Exemplo n.º 4
0
 /**
  * @param int $farmId
  * @param int $farmRoleId optional
  * @param string $serverId optional
  * @param int $scriptId optional
  * @param string $scriptPath optional
  * @param int $scriptIsSync
  * @param int $scriptTimeout
  * @param int $scriptVersion
  * @param array $scriptParams optional
  * @param int $shortcutId optional
  * @param int $editShortcut optional
  * @throws Exception
  */
 public function xExecuteAction($farmId, $farmRoleId = 0, $serverId = '', $scriptId = 0, $scriptPath = '', $scriptIsSync, $scriptTimeout, $scriptVersion, array $scriptParams = [], $shortcutId = null, $editShortcut = null)
 {
     $this->request->restrictAccess(Acl::RESOURCE_ADMINISTRATION_SCRIPTS, Acl::PERM_ADMINISTRATION_SCRIPTS_EXECUTE);
     if ($serverId) {
         $dbServer = DBServer::LoadByID($serverId);
         $this->user->getPermissions()->validate($dbServer);
         $target = Script::TARGET_INSTANCE;
         $serverId = $dbServer->serverId;
         $farmRoleId = $dbServer->farmRoleId;
         $farmId = $dbServer->farmId;
     } else {
         if ($farmRoleId) {
             $dbFarmRole = DBFarmRole::LoadByID($farmRoleId);
             $this->user->getPermissions()->validate($dbFarmRole);
             $target = Script::TARGET_ROLE;
             $farmRoleId = $dbFarmRole->ID;
             $farmId = $dbFarmRole->FarmID;
         } else {
             if (!$farmId) {
                 $target = Script::TARGET_ALL;
             } else {
                 $dbFarm = DBFarm::LoadByID($this->getParam('farmId'));
                 $this->user->getPermissions()->validate($dbFarm);
                 $target = Script::TARGET_FARM;
                 $farmId = $dbFarm->ID;
             }
         }
     }
     if ($scriptId) {
         $script = Script::findPk($scriptId);
         /* @var Script $script */
         if (!$script) {
             throw new Scalr_UI_Exception_NotFound();
         }
         $script->checkPermission($this->user, $this->getEnvironmentId());
     } elseif (!$scriptPath) {
         throw new Scalr_Exception_Core('scriptId or scriptPath should be set');
     }
     if (!$scriptTimeout) {
         $scriptTimeout = $scriptIsSync == 1 ? Scalr::config('scalr.script.timeout.sync') : Scalr::config('scalr.script.timeout.async');
     }
     $executeScript = true;
     if ($shortcutId && ($target != Script::TARGET_INSTANCE || $target != Script::TARGET_ALL)) {
         if ($shortcutId == -1) {
             $shortcut = new ScriptShortcut();
             $shortcut->farmId = $farmId;
         } else {
             $shortcut = ScriptShortcut::findPk($shortcutId);
             /* @var ScriptShortcut $shortcut */
             if (!$shortcut) {
                 throw new Scalr_UI_Exception_NotFound();
             }
             if ($editShortcut == 1) {
                 $executeScript = false;
             }
         }
         $shortcut->farmRoleId = $farmRoleId == 0 ? NULL : $farmRoleId;
         if ($scriptId) {
             $shortcut->scriptId = $scriptId;
             $shortcut->scriptPath = '';
         } else {
             $shortcut->scriptPath = $scriptPath;
             $shortcut->scriptId = NULL;
         }
         $shortcut->isSync = $scriptIsSync;
         $shortcut->version = $scriptVersion;
         $shortcut->timeout = $scriptTimeout;
         $shortcut->params = $scriptParams;
         $shortcut->save();
     }
     if ($executeScript) {
         switch ($target) {
             case Script::TARGET_FARM:
                 $servers = $this->db->GetAll("SELECT server_id FROM servers WHERE status IN (?,?) AND farm_id=?", array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, $farmId));
                 break;
             case Script::TARGET_ROLE:
                 $servers = $this->db->GetAll("SELECT server_id FROM servers WHERE status IN (?,?) AND farm_roleid=?", array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, $farmRoleId));
                 break;
             case Script::TARGET_INSTANCE:
                 $servers = $this->db->GetAll("SELECT server_id FROM servers WHERE status IN (?,?) AND server_id=?", array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, $serverId));
                 break;
             case Script::TARGET_ALL:
                 $servers = $this->db->GetAll("SELECT server_id FROM servers WHERE status IN (?,?) AND env_id = ?", array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, $this->getEnvironmentId()));
                 break;
         }
         $scriptSettings = array('version' => $scriptVersion, 'timeout' => $scriptTimeout, 'issync' => $scriptIsSync, 'params' => serialize($scriptParams));
         if ($scriptId) {
             $scriptSettings['scriptid'] = $scriptId;
             $scriptSettings['type'] = Scalr_Scripting_Manager::ORCHESTRATION_SCRIPT_TYPE_SCALR;
         } else {
             $scriptSettings['script_path'] = $scriptPath;
             $scriptSettings['type'] = Scalr_Scripting_Manager::ORCHESTRATION_SCRIPT_TYPE_LOCAL;
         }
         $serializer = Scalr_Messaging_JsonSerializer::getInstance();
         $cryptoTool = Scalr_Messaging_CryptoTool::getInstance();
         // send message to start executing task (starts script)
         if (count($servers) > 0) {
             foreach ($servers as $server) {
                 $DBServer = DBServer::LoadByID($server['server_id']);
                 $msg = new Scalr_Messaging_Msg_ExecScript("Manual");
                 $msg->setServerMetaData($DBServer);
                 $script = Scalr_Scripting_Manager::prepareScript($scriptSettings, $DBServer);
                 $itm = new stdClass();
                 // Script
                 $itm->asynchronous = $script['issync'] == 1 ? '0' : '1';
                 $itm->timeout = $script['timeout'];
                 if ($script['body']) {
                     $itm->name = $script['name'];
                     $itm->body = $script['body'];
                 } else {
                     $itm->path = $script['path'];
                     $itm->name = "local-" . crc32($script['path']) . mt_rand(100, 999);
                 }
                 $itm->executionId = $script['execution_id'];
                 $msg->scripts = array($itm);
                 $msg->setGlobalVariables($DBServer, true);
                 /*
                                     if ($DBServer->IsSupported('2.5.12')) {
                 $DBServer->scalarizr->system->executeScripts(
                     $msg->scripts,
                     $msg->globalVariables,
                     $msg->eventName,
                     $msg->roleName
                 );
                                     } else
                 */
                 $DBServer->SendMessage($msg, false, true);
             }
         }
         $this->response->success('Script execution has been queued and will occur on the selected instance(s) within a couple of minutes.');
     } else {
         $this->response->success('Script shortcut successfully saved');
     }
 }