function __construct() { $this->cryptoTool = Scalr_Messaging_CryptoTool::getInstance(); $this->serializer = new Scalr_Messaging_XmlSerializer(); $this->jsonSerializer = new Scalr_Messaging_JsonSerializer(); $this->logger = Logger::getLogger(__CLASS__); }
/** * @return Scalr_Messaging_CryptoTool */ static function getInstance() { if (self::$instance === null) { self::$instance = new Scalr_Messaging_CryptoTool(self::CRYPTO_ALGO, self::CIPHER_MODE, self::CRYPTO_KEY_SIZE, self::CRYPTO_BLOCK_SIZE); } return self::$instance; }
public function __construct(DBServer $dbServer, $port = 8010) { $this->dbServer = $dbServer; $this->port = $port; if ($this->dbServer->farmId) { if (DBFarm::LoadByID($this->dbServer->farmId)->GetSetting(DBFarm::SETTING_EC2_VPC_ID)) { $this->isVPC = true; } } $this->cryptoTool = Scalr_Messaging_CryptoTool::getInstance(); }
public static function initCrypto() { if (!self::$cryptoAes) { self::$cryptoAes = new \Scalr_Util_CryptoTool(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CFB, @mcrypt_get_key_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CFB), @mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CFB)); } if (!self::$cryptoDes) { self::$cryptoDes = new \Scalr_Util_CryptoTool(MCRYPT_TRIPLEDES, MCRYPT_MODE_CFB, 24, 8); } if (!self::$cryptoSzr) { self::$cryptoSzr = \Scalr_Messaging_CryptoTool::getInstance(); } if (!self::$cryptoKey) { self::$cryptoKey = file_get_contents(APPPATH . "/etc/.cryptokey"); } }
/** * @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'); } }
public function __construct(DBServer $dbServer, $port = 8008) { $this->dbServer = $dbServer; $this->port = $port; $this->cryptoTool = Scalr_Messaging_CryptoTool::getInstance(); }
/** * 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; } } // 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 = Logger::getLogger('DBServer'); $serializer = Scalr_Messaging_XmlSerializer::getInstance(); $cryptoTool = Scalr_Messaging_CryptoTool::getInstance(); 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; if (!$message->dbMessageId) { // Add message to database $this->Db->Execute("INSERT INTO messages SET\n `messageid`\t= ?,\n `processing_time` = ?,\n `server_id`\t= ?,\n `message`\t= ?,\n `type`\t\t= '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, $rawMessage, $message->getName(), $delayed ? '0' : '1', 2, $messageType, $message->eventId)); $message->dbMessageId = $this->Db->Insert_ID(); } else { $this->Db->Execute("UPDATE messages SET handle_attempts = handle_attempts+1, dtlasthandleattempt = NOW() WHERE id = ?", array($message->dbMessageId)); } if ($delayed) { return $message; } $isVPC = false; if ($this->farmId) { if (DBFarm::LoadByID($this->farmId)->GetSetting(DBFarm::SETTING_EC2_VPC_ID)) { $isVPC = true; } } if (!$this->remoteIp && !$this->localIp && !$isVPC) { return; } $cryptoKey = $this->GetKey(true); $encMessage = $cryptoTool->encrypt($rawMessage, $cryptoKey); list($signature, $timestamp) = $cryptoTool->sign($encMessage, $cryptoKey); try { $request = new HttpRequest(); $request->setMethod(HTTP_METH_POST); $ctrlPort = $this->GetProperty(SERVER_PROPERTIES::SZR_CTRL_PORT); if (!$ctrlPort) { $ctrlPort = 8013; } if (\Scalr::config('scalr.instances_connection_policy') == 'local') { $requestHost = "{$this->localIp}:{$ctrlPort}"; } elseif (\Scalr::config('scalr.instances_connection_policy') == 'public') { $requestHost = "{$this->remoteIp}:{$ctrlPort}"; } elseif (\Scalr::config('scalr.instances_connection_policy') == 'auto') { if ($this->remoteIp) { $requestHost = "{$this->remoteIp}:{$ctrlPort}"; } else { $requestHost = "{$this->localIp}:{$ctrlPort}"; } } if ($isVPC) { $routerRole = $this->GetFarmObject()->GetFarmRoleByBehavior(ROLE_BEHAVIORS::VPC_ROUTER); if ($routerRole) { // No remote IP need to use proxy if (!$this->remoteIp) { $routerRole = $this->GetFarmObject()->GetFarmRoleByBehavior(ROLE_BEHAVIORS::VPC_ROUTER); $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->setUrl("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)); if ($messageType == 'json') { $request->addHeaders(array('Content-type' => 'application/json')); } $request->setBody($encMessage); // Send request $request->send(); // Process response if ($request->getResponseCode() == 201) { $logger->info(sprintf("[FarmID: %s] Sending message '%s' via REST to server '%s' (server_id: %s) complete", $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 ($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, $request->getResponseCode(), $request->getResponseStatus())); } } catch (HttpException $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 %s", $message->getName(), $message->messageId, $this->remoteIp, $this->serverId, $request->getResponseCode(), $msg))); } else { $logger->fatal(sprintf("Cannot deliver message '%s' (message_id: %s) via REST" . " to server '%s' (server_id: %s). Error: %s %s", $message->getName(), $message->messageId, $this->remoteIp, $this->serverId, $request->getResponseCode(), $msg)); } return false; } return $message; }
/** * Send message to instance * @param Scalr_Messaging_Msg $message * @return Scalr_Messaging_Msg */ public function SendMessage(Scalr_Messaging_Msg $message, $isEventNotice = false, $delayed = false) { if ($this->farmId) { if ($this->GetFarmObject()->Status == FARM_STATUS::TERMINATED) { $this->Db->Execute("UPDATE messages SET status = ? WHERE messageid = ?", array(MESSAGE_STATUS::FAILED, $message->messageId)); return; } } $logger = Logger::getLogger('DBServer'); $serializer = Scalr_Messaging_XmlSerializer::getInstance(); $cryptoTool = Scalr_Messaging_CryptoTool::getInstance(); $rawMessage = $serializer->serialize($message); // Add message to database $this->Db->Execute("INSERT INTO messages SET\r\n\t\t\t\t`messageid`\t= ?,\r\n\t\t\t\t`server_id`\t= ?,\r\n\t\t\t\t`message`\t= ?,\r\n\t\t\t\t`type`\t\t= 'out',\r\n\t\t\t\t`message_name` = ?,\r\n\t\t\t\t`handle_attempts` = ?,\r\n\t\t\t\t`message_version` = ?,\r\n\t\t\t\t`dtlasthandleattempt` = NOW()\r\n\t\t\tON DUPLICATE KEY UPDATE handle_attempts = handle_attempts+1, dtlasthandleattempt = NOW() \r\n\t\t\t", array($message->messageId, $this->serverId, $rawMessage, $message->getName(), $delayed ? '0' : '1', $this->IsSupported("0.5") ? 2 : 1)); if ($this->platform == SERVER_PLATFORMS::RDS) { $logger->info("RDS platform doesn't support messaging. Skipping..."); $this->Db->Execute("UPDATE messages SET status = ? WHERE messageid = ?", array(MESSAGE_STATUS::UNSUPPORTED, $message->messageId)); return $message; } if ($delayed) { return $message; } if ($this->IsSupported("0.5") && !$isEventNotice) { if (!$this->remoteIp) { return; } // Put access data and reserialize message $pl = PlatformFactory::NewPlatform($this->platform); $pl->PutAccessData($this, $message); $rawMessage = $serializer->serialize($message); $cryptoKey = $this->GetKey(true); $encMessage = $cryptoTool->encrypt($rawMessage, $cryptoKey); list($signature, $timestamp) = $cryptoTool->sign($encMessage, $cryptoKey); try { $ctrlPort = $this->GetProperty(SERVER_PROPERTIES::SZR_CTRL_PORT); if (!$ctrlPort) { $ctrlPort = 8013; } // Prepare request $request = new HttpRequest("http://{$this->remoteIp}:{$ctrlPort}/control", HTTP_METH_POST); $request->setOptions(array('timeout' => 4, 'connecttimeout' => 4)); $request->setHeaders(array("Date" => $timestamp, "X-Signature" => $signature)); $request->setRawPostData($encMessage); // Send request $request->send(); // Process response if ($request->getResponseCode() == 201) { $logger->info(sprintf("[FarmID: %s] Sending message '%s' via REST to server '%s' (server_id: %s) complete", $this->farmId, $message->getName(), $this->remoteIp, $this->serverId)); $this->Db->Execute("UPDATE messages SET status = ?, message = '' WHERE messageid = ?", array(MESSAGE_STATUS::HANDLED, $message->messageId)); } 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, $request->getResponseCode(), $request->getResponseStatus())); } } catch (HttpException $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 %s", $message->getName(), $message->messageId, $this->remoteIp, $this->serverId, $request->getResponseCode(), $msg))); } else { $logger->fatal(sprintf("Cannot deliver message '%s' (message_id: %s) via REST" . " to server '%s' (server_id: %s). Error: %s %s", $message->getName(), $message->messageId, $this->remoteIp, $this->serverId, $request->getResponseCode(), $msg)); } return false; } } else { if ($this->remoteIp) { $community = $this->Db->GetOne("SELECT hash FROM farms WHERE id=?", array($this->farmId)); $snmpClient = new Scalr_Net_Snmp_Client(); $snmpClient->connect($this->remoteIp, 162, $community); $converter = Scalr_Messaging_SnmpConverter::getInstance(); $trap = $converter->convert($message, $isEventNotice); $res = $snmpClient->sendTrap($trap); Logger::getLogger('DBServer')->info("[FarmID: {$this->farmId}] Sending message " . $message->getName() . " via SNMP ({$trap}) to '{$this->serverId}' ('{$this->remoteIp}') complete ({$res})"); } } return $message; }