prepareScript() public static method

public static prepareScript ( $scriptSettings, DBServer $targetServer, AbstractServerEvent $event = null )
$targetServer DBServer
$event AbstractServerEvent
Beispiel #1
0
 /**
  * @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;
 }
Beispiel #2
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');
     }
 }
 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;
 }
Beispiel #4
0
 public function xExecuteAction()
 {
     $this->request->restrictAccess(Acl::RESOURCE_FARMS_SCRIPTS, Acl::PERM_FARMS_SCRIPTS_EXECUTE);
     $this->request->defineParams(array('farmId' => array('type' => 'int'), 'farmRoleId' => array('type' => 'int'), 'serverId' => array('type' => 'string'), 'scriptId' => array('type' => 'int'), 'scriptIsSync' => array('type' => 'int'), 'scriptTimeout' => array('type' => 'int'), 'scriptVersion' => array('type' => 'int'), 'scriptOptions' => array('type' => 'array'), 'createMenuLink' => array('type' => 'int')));
     $eventName = Scalr_Scripting_Manager::generateEventName('CustomEvent');
     if ($this->getParam('serverId')) {
         $dbServer = DBServer::LoadByID($this->getParam('serverId'));
         $this->user->getPermissions()->validate($dbServer);
         $target = Scalr_Script::TARGET_INSTANCE;
         $serverId = $dbServer->serverId;
         $farmRoleId = $dbServer->farmRoleId;
         $farmId = $dbServer->farmId;
     } else {
         if ($this->getParam('farmRoleId')) {
             $dbFarmRole = DBFarmRole::LoadByID($this->getParam('farmRoleId'));
             $this->user->getPermissions()->validate($dbFarmRole);
             $target = Scalr_Script::TARGET_ROLE;
             $farmRoleId = $dbFarmRole->ID;
             $farmId = $dbFarmRole->FarmID;
         } else {
             if (!$this->getParam('farmId')) {
                 $target = Scalr_Script::TARGET_ALL;
             } else {
                 $dbFarm = DBFarm::LoadByID($this->getParam('farmId'));
                 $this->user->getPermissions()->validate($dbFarm);
                 $target = Scalr_Script::TARGET_FARM;
                 $farmId = $dbFarm->ID;
             }
         }
     }
     if (!$this->getParam('eventName')) {
         if ($this->getParam('createMenuLink')) {
             $this->db->Execute("INSERT INTO farm_role_scripts SET\n                    scriptid\t= ?,\n                    farmid\t\t= ?,\n                    farm_roleid\t= ?,\n                    params\t\t= ?,\n                    event_name\t= ?,\n                    target\t\t= ?,\n                    version\t\t= ?,\n                    timeout\t\t= ?,\n                    issync\t\t= ?,\n                    ismenuitem\t= ?\n                ", array($this->getParam('scriptId'), (int) $farmId, (int) $farmRoleId, serialize($this->getParam('scriptOptions')), $eventName, $target, $this->getParam('scriptVersion'), $this->getParam('scriptTimeout'), $this->getParam('scriptIsSync'), $this->getParam('createMenuLink')));
         }
         $farmScriptId = $this->db->Insert_ID();
         $executeScript = true;
     } else {
         $info = $this->db->Execute("SELECT farmid FROM farm_role_scripts WHERE event_name=?", array($this->getParam('eventName')));
         if ($info['farmid'] != $dbFarm->ID) {
             throw new Exception("You cannot change farm for script shortcut");
         }
         if ($this->getParam('isShortcut')) {
             $this->db->Execute("UPDATE farm_role_scripts SET\n                    scriptid\t= ?,\n                    farm_roleid\t= ?,\n                    params\t\t= ?,\n                    target\t\t= ?,\n                    version\t\t= ?,\n                    timeout\t\t= ?,\n                    issync\t\t= ?\n                WHERE event_name = ? AND farmid = ?\n                ", array($this->getParam('scriptId'), (int) $farmRoleId, serialize($this->getParam('scriptOptions')), $target, $this->getParam('scriptVersion'), $this->getParam('scriptTimeout'), $this->getParam('scriptIsSync'), $this->getParam('eventName'), $farmId));
         }
         if (!$this->getParam('isShortcut')) {
             $executeScript = true;
         }
     }
     if ($executeScript) {
         switch ($target) {
             case Scalr_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 Scalr_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 Scalr_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 Scalr_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' => $this->getParam('scriptVersion'), 'scriptid' => $this->getParam('scriptId'), 'timeout' => $this->getParam('scriptTimeout'), 'issync' => $this->getParam('scriptIsSync'), 'params' => serialize($this->getParam('scriptOptions')));
         // 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->executionId = $script['execution_id'];
                 $msg->scripts = array($itm);
                 try {
                     $msg->globalVariables = array();
                     $globalVariables = new Scalr_Scripting_GlobalVariables($DBServer->envId);
                     $vars = $globalVariables->listVariables($DBServer->roleId, $DBServer->farmId, $DBServer->farmRoleId);
                     foreach ($vars as $k => $v) {
                         $msg->globalVariables[] = (object) array('name' => $k, 'value' => $v);
                     }
                 } catch (Exception $e) {
                 }
                 $DBServer->SendMessage($msg, false, true);
             }
         }
     }
     $this->response->success('Script execution has been queued. Script will be executed on selected instance(s) within couple of minutes.');
 }
Beispiel #5
0
 public function ScriptExecute($ScriptID, $Timeout, $Async, $FarmID, $FarmRoleID = null, $ServerID = null, $Revision = null, array $ConfigVariables = null)
 {
     $this->restrictAccess(Acl::RESOURCE_SCRIPTS_ENVIRONMENT, Acl::PERM_SCRIPTS_ENVIRONMENT_EXECUTE);
     $response = $this->CreateInitialResponse();
     $stmt = "SELECT * FROM farms f WHERE id=? AND env_id=? AND " . $this->getFarmSqlQuery();
     $args = array($FarmID, $this->Environment->id);
     $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 is_scalarized = 1 AND 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 is_scalarized = 1 AND 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 is_scalarized = 1 AND 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);
             if ($script) {
                 $DBServer->executeScript($script, $msg);
                 $this->auditLog('script.execute', $script, $DBServer);
             }
         }
     }
     $response->Result = true;
     return $response;
 }
Beispiel #6
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');
     }
 }
Beispiel #7
0
 public function xUpdateAgentAction()
 {
     $this->request->restrictAccess(Acl::RESOURCE_FARMS_SERVERS);
     $this->request->defineParams(array('serverId'));
     if (!$this->db->GetOne("SELECT id FROM scripts WHERE id='2102' AND clientid='0' LIMIT 1")) {
         throw new Exception("Automatical scalarizr update doesn't supported by this scalr version");
     }
     $dbServer = DBServer::LoadByID($this->getParam('serverId'));
     $this->user->getPermissions()->validate($dbServer);
     $scriptSettings = array('version' => $this->db->GetOne("SELECT MAX(revision) FROM script_revisions WHERE scriptid='2102'"), 'scriptid' => 2102, 'timeout' => 300, 'issync' => 0, 'params' => serialize(array()));
     $message = new Scalr_Messaging_Msg_ExecScript("Manual");
     $message->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'];
     $message->scripts = array($itm);
     $dbServer->SendMessage($message);
     $this->response->success('Scalarizr update successfully initiated. Please wait a few minutes and then refresh the page');
 }
Beispiel #8
0
 public function xUpdateAgentAction()
 {
     $this->request->restrictAccess(Acl::RESOURCE_FARMS_SERVERS);
     $this->request->defineParams(array('serverId'));
     /* @var Entity\Script $scr */
     $scr = Entity\Script::find(array(array('id' => 2102), array('accountId' => NULL)));
     if (!$scr) {
         throw new Exception("Automatical scalarizr update doesn't supported by this scalr version");
     }
     $dbServer = DBServer::LoadByID($this->getParam('serverId'));
     $this->user->getPermissions()->validate($dbServer);
     $scriptSettings = array('version' => $scr->getLatestVersion()->version, 'scriptid' => 2102, 'timeout' => 300, 'issync' => 0, 'params' => serialize(array()), 'type' => Scalr_Scripting_Manager::ORCHESTRATION_SCRIPT_TYPE_SCALR);
     $message = new Scalr_Messaging_Msg_ExecScript("Manual");
     $message->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'];
     $message->scripts = array($itm);
     $dbServer->SendMessage($message);
     $this->response->success('Scalarizr update successfully initiated. Please wait a few minutes and then refresh the page');
 }
Beispiel #9
0
 public function ScriptExecute($ScriptID, $Timeout, $Async, $FarmID, $FarmRoleID = null, $ServerID = null, $Revision = null, array $ConfigVariables = null)
 {
     $this->restrictAccess(Acl::RESOURCE_FARMS_SCRIPTS, Acl::PERM_FARMS_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, Acl::PERM_FARMS_NOT_OWNED_FARMS)) {
         $stmt .= " AND created_by_id = ? ";
         array_push($args, $this->user->getId());
     }
     $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 = Scalr_Script::TARGET_INSTANCE;
     } else {
         if ($FarmRoleID) {
             $target = Scalr_Script::TARGET_ROLE;
         } else {
             $target = Scalr_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));
     switch ($target) {
         case Scalr_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 Scalr_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 Scalr_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);
             try {
                 $msg->globalVariables = array();
                 $globalVariables = new Scalr_Scripting_GlobalVariables($DBServer->envId);
                 $vars = $globalVariables->listVariables($DBServer->roleId, $DBServer->farmId, $DBServer->farmRoleId);
                 foreach ($vars as $k => $v) {
                     $msg->globalVariables[] = (object) array('name' => $k, 'value' => $v);
                 }
             } catch (Exception $e) {
             }
             $DBServer->SendMessage($msg, false, true);
         }
     }
     $response->Result = true;
     return $response;
 }
Beispiel #10
0
 /**
  * Executes the task
  *
  * @return bool $manual  optional Whether task is executed by manual
  * @throws Exception
  */
 public function execute($manual = false)
 {
     $farmRoleNotFound = false;
     $logger = $this->getLogger() ?: \Scalr::getContainer()->logger(__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, null, ['service.scheduler.task_id' => $this->id]));
                     $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
                     Scalr::FireEvent($farmId, new FarmTerminatedEvent($deleteDNSZones, $keepCloudObjects, false, $keepCloudObjects, true, null, ['service.scheduler.task_id' => $this->id]));
                     $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::FIRE_EVENT:
             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 (count($servers) == 0) {
                 throw new Exception("No running Servers found. Event was not fired.");
             }
             foreach ($servers as $server) {
                 /* @var $dbServer DBServer */
                 $dbServer = DBServer::LoadByID($server['server_id']);
                 Scalr::FireEvent($dbServer->farmId, new CustomEvent($dbServer, $this->config['eventName'], (array) $this->config['eventParams']));
             }
             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 is_scalarized = 1 AND `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 is_scalarized = 1 AND `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 is_scalarized = 1 AND `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);
                         if ($script) {
                             $DBServer->executeScript($script, $msg);
                             $this->getContainer()->auditlogger->log('script.execute', $script, $DBServer, $this->id);
                         }
                     }
                 } 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;
 }