/** * @return bool * @throws Exception */ public function execute($manual = false) { $farmRoleNotFound = false; $logger = Logger::getLogger(__CLASS__); switch ($this->type) { case self::LAUNCH_FARM: try { $farmId = $this->targetId; $DBFarm = DBFarm::LoadByID($farmId); if ($DBFarm->Status == FARM_STATUS::TERMINATED) { // launch farm Scalr::FireEvent($farmId, new FarmLaunchedEvent(true)); $logger->info(sprintf("Farm #{$farmId} successfully launched")); } elseif ($DBFarm->Status == FARM_STATUS::RUNNING) { // farm is running $logger->info(sprintf("Farm #{$farmId} is already running")); } else { // farm can't be launched $logger->info(sprintf("Farm #{$farmId} can't be launched because of it's status: {$DBFarm->Status}")); } } catch (Exception $e) { $farmRoleNotFound = true; $logger->info(sprintf("Farm #{$farmId} was not found and can't be launched")); } break; case self::TERMINATE_FARM: try { // get config settings $farmId = $this->targetId; $deleteDNSZones = (int) $this->config['deleteDNSZones']; $deleteCloudObjects = (int) $this->config['deleteCloudObjects']; $keepCloudObjects = $deleteCloudObjects == 1 ? 0 : 1; $DBFarm = DBFarm::LoadByID($farmId); if ($DBFarm->Status == FARM_STATUS::RUNNING) { // terminate farm $event = new FarmTerminatedEvent($deleteDNSZones, $keepCloudObjects, false, $keepCloudObjects); Scalr::FireEvent($farmId, $event); $logger->info(sprintf("Farm successfully terminated")); } else { $logger->info(sprintf("Farm #{$farmId} can't be terminated because of it's status")); } } catch (Exception $e) { $farmRoleNotFound = true; $logger->info(sprintf("Farm #{$farmId} was not found and can't be terminated")); } break; case self::SCRIPT_EXEC: // generate event name $eventName = "Scheduler (TaskID: {$this->id})"; if ($manual) { $eventName .= ' (manual)'; } try { if (!\Scalr\Model\Entity\Script::findPk($this->config['scriptId'])) { throw new Exception('Script not found'); } // get executing object by target_type variable switch ($this->targetType) { case self::TARGET_FARM: $DBFarm = DBFarm::LoadByID($this->targetId); $farmId = $DBFarm->ID; $farmRoleId = null; $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 self::TARGET_ROLE: $farmRoleId = $this->targetId; $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 self::TARGET_INSTANCE: $servers = $this->db->GetAll("SELECT server_id FROM servers WHERE `status` IN (?,?) AND farm_roleid = ? AND `index` = ? ", array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, $this->targetId, $this->targetServerIndex)); break; } if ($servers) { $scriptSettings = array('version' => $this->config['scriptVersion'], 'scriptid' => $this->config['scriptId'], 'timeout' => $this->config['scriptTimeout'], 'issync' => $this->config['scriptIsSync'], 'params' => serialize($this->config['scriptOptions']), 'type' => Scalr_Scripting_Manager::ORCHESTRATION_SCRIPT_TYPE_SCALR); // send message to start executing task (starts script) foreach ($servers as $server) { $DBServer = DBServer::LoadByID($server['server_id']); $msg = new Scalr_Messaging_Msg_ExecScript($eventName); $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->executionId = $script['execution_id']; $msg->scripts = array($itm); $msg->setGlobalVariables($DBServer, true); /* if ($DBServer->IsSupported('2.5.12')) { $api = $DBServer->scalarizr->system; $api->timeout = 5; $api->executeScripts( $msg->scripts, $msg->globalVariables, $msg->eventName, $msg->roleName ); } else */ $DBServer->SendMessage($msg, false, true); } } else { $farmRoleNotFound = true; } } catch (Exception $e) { // farm or role not found. $farmRoleNotFound = true; $logger->warn(sprintf("Farm, role or instances were not found, script can't be executed")); } break; } return !$farmRoleNotFound; }
/** * @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 ScriptExecute($ScriptID, $Timeout, $Async, $FarmID, $FarmRoleID = null, $ServerID = null, $Revision = null, array $ConfigVariables = null) { $this->restrictAccess(Acl::RESOURCE_ADMINISTRATION_SCRIPTS, Acl::PERM_ADMINISTRATION_SCRIPTS_EXECUTE); $response = $this->CreateInitialResponse(); $stmt = "SELECT * FROM farms WHERE id=? AND env_id=?"; $args = array($FarmID, $this->Environment->id); if (!$this->isAllowed(Acl::RESOURCE_FARMS)) { $q = []; if ($this->isAllowed(Acl::RESOURCE_TEAM_FARMS)) { $t = array_map(function ($t) { return $t['id']; }, $this->user->getTeams()); if (count($t)) { $q[] = 'team_id IN(' . join(',', $t) . ')'; } } if ($this->isAllowed(Acl::RESOURCE_OWN_FARMS)) { $q[] = 'created_by_id = ?'; $args[] = $this->user->getId(); } if (count($q)) { $stmt .= ' AND (' . join(' OR ', $q) . ')'; } else { $stmt .= ' AND false'; // no permissions } } $farminfo = $this->DB->GetRow($stmt, $args); if (!$farminfo) { throw new Exception(sprintf("Farm #%s not found", $FarmID)); } if ($FarmRoleID) { $dbFarmRole = DBFarmRole::LoadByID($FarmRoleID); if ($dbFarmRole->FarmID != $FarmID) { throw new Exception(sprintf("FarmRole #%s not found on farm #%s", $FarmRoleID, $FarmID)); } } if (!$Revision) { $Revision = 'latest'; } if ($ServerID && !$FarmRoleID) { $DBServer = DBServer::LoadByID($ServerID); $FarmRoleID = $DBServer->farmRoleId; } $config = $ConfigVariables; $scriptid = (int) $ScriptID; if ($ServerID) { $target = Script::TARGET_INSTANCE; } else { if ($FarmRoleID) { $target = Script::TARGET_ROLE; } else { $target = Script::TARGET_FARM; } } $event_name = 'APIEvent-' . date("YmdHi") . '-' . rand(1000, 9999); $version = $Revision; $farmid = (int) $FarmID; $timeout = (int) $Timeout; $issync = $Async == 1 ? 0 : 1; $scriptSettings = array('version' => $version, 'scriptid' => $scriptid, 'timeout' => $timeout, 'issync' => $issync, 'params' => serialize($config), 'type' => Scalr_Scripting_Manager::ORCHESTRATION_SCRIPT_TYPE_SCALR); 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=? AND farm_id=?", array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, $DBServer->serverId, $farmid)); break; } // 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("Executed via API"); $msg->eventId = $response->TransactionID; $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->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); } } $response->Result = true; return $response; }
/** * Executes script * * @param array $script Script settings * @param Scalr_Messaging_Msg_ExecScript $msg Scalarizr message * @return void */ public function executeScript(array $script, Scalr_Messaging_Msg_ExecScript $msg) { $itm = new stdClass(); $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']; if ($msg->eventName == 'Manual') { $itm->name = "local-" . crc32($script['path']) . mt_rand(100, 999); } } $itm->executionId = $script['execution_id']; $msg->scripts = [$itm]; $msg->setGlobalVariables($this, true); $this->SendMessage($msg, false, true); }