Ejemplo n.º 1
0
 public static function getScriptingBuiltinVariables()
 {
     if (!self::$BUILTIN_VARIABLES_LOADED) {
         $ReflectEVENT_TYPE = new ReflectionClass("EVENT_TYPE");
         $event_types = $ReflectEVENT_TYPE->getConstants();
         foreach ($event_types as $event_type) {
             if (class_exists("{$event_type}Event")) {
                 $ReflectClass = new ReflectionClass("{$event_type}Event");
                 $retval = $ReflectClass->getMethod("GetScriptingVars")->invoke(null);
                 if (!empty($retval)) {
                     foreach ($retval as $k => $v) {
                         if (!self::$BUILTIN_VARIABLES[$k]) {
                             self::$BUILTIN_VARIABLES[$k] = array("PropName" => $v, "EventName" => "{$event_type}");
                         } else {
                             if (!is_array(self::$BUILTIN_VARIABLES[$k]['EventName'])) {
                                 $events = array(self::$BUILTIN_VARIABLES[$k]['EventName']);
                             } else {
                                 $events = self::$BUILTIN_VARIABLES[$k]['EventName'];
                             }
                             $events[] = $event_type;
                             self::$BUILTIN_VARIABLES[$k] = array("PropName" => $v, "EventName" => $events);
                         }
                     }
                 }
             }
         }
         foreach (self::$BUILTIN_VARIABLES as $k => $v) {
             self::$BUILTIN_VARIABLES["event_{$k}"] = $v;
         }
         self::$BUILTIN_VARIABLES_LOADED = true;
     }
     return self::$BUILTIN_VARIABLES;
 }
Ejemplo n.º 2
0
 public function setRevision($script, $version = null)
 {
     if ($version == null) {
         $version = $this->getLatestRevision() + 1;
     }
     $variables = array();
     $builtin = array_keys(Scalr_Scripting_Manager::getScriptingBuiltinVariables());
     foreach ((array) $this->getCustomVariables($script) as $var) {
         if (!in_array($var, $builtin)) {
             $variables[$var] = ucwords(str_replace("_", " ", $var));
         }
     }
     $variables = serialize($variables);
     $this->db->Execute('INSERT INTO `script_revisions` SET
             scriptid = ?,
             revision = ?,
             script = ?,
             variables = ?,
             dtcreated = NOW()
         ON DUPLICATE KEY UPDATE
             script = ?,
             variables = ?,
             dtcreated = NOW()
         ', array($this->id, $version, $script, $variables, $script, $variables));
 }
Ejemplo n.º 3
0
 public function save()
 {
     $this->variables = [];
     $variables = Script::fetchVariables($this->content);
     if (!empty($variables)) {
         $builtin = array_keys(\Scalr_Scripting_Manager::getScriptingBuiltinVariables());
         foreach ($variables as $var) {
             if (!in_array($var, $builtin)) {
                 $this->variables[$var] = ucwords(str_replace("_", " ", $var));
             }
         }
     }
     parent::save();
 }
Ejemplo n.º 4
0
 public function save()
 {
     $this->variables = [];
     $matches = [];
     $text = preg_replace('/(\\\\%)/si', '$$scalr$$', $this->content);
     preg_match_all("/\\%([^\\%\\s]+)\\%/si", $text, $matches);
     $builtin = array_keys(\Scalr_Scripting_Manager::getScriptingBuiltinVariables());
     foreach ($matches[1] as $var) {
         if (!in_array($var, $builtin)) {
             $this->variables[$var] = ucwords(str_replace("_", " ", $var));
         }
     }
     parent::save();
 }
Ejemplo n.º 5
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');
     }
 }
Ejemplo n.º 6
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;
 }
Ejemplo n.º 7
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.');
 }
Ejemplo n.º 8
0
 private function getScripts(Event $event, DBServer $eventServer, DBServer $targetServer)
 {
     $retval = array();
     try {
         $scripts = Scalr_Scripting_Manager::getEventScriptList($event, $eventServer, $targetServer);
         if (count($scripts) > 0) {
             foreach ($scripts as $script) {
                 $retval[] = $itm;
             }
         }
     } catch (Exception $e) {
     }
     return $retval;
 }
Ejemplo n.º 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;
 }
Ejemplo n.º 10
0
 public function xUpdateAgentAction()
 {
     $this->request->defineParams(array('serverId'));
     if (!$this->db->GetOne("SELECT id FROM scripts WHERE id='2102' AND clientid='0'")) {
         throw new Exception("Automatical scalarizr update doesn't supported by this scalr version");
     }
     $dbServer = DBServer::LoadByID($this->getParam('serverId'));
     $this->user->getPermissions()->validate($dbServer);
     $eventName = Scalr_Scripting_Manager::generateEventName('CustomEvent');
     $target = SCRIPTING_TARGET::INSTANCE;
     $serverId = $dbServer->serverId;
     $farmRoleId = $dbServer->farmRoleId;
     $farmId = $dbServer->farmId;
     $this->db->Execute("INSERT INTO farm_role_scripts SET\n\t\t\tscriptid\t= ?,\n\t\t\tfarmid\t\t= ?,\n\t\t\tfarm_roleid\t= ?,\n\t\t\tparams\t\t= ?,\n\t\t\tevent_name\t= ?,\n\t\t\ttarget\t\t= ?,\n\t\t\tversion\t\t= ?,\n\t\t\ttimeout\t\t= ?,\n\t\t\tissync\t\t= ?,\n\t\t\tismenuitem\t= ?\n\t\t", array(2102, (int) $farmId, (int) $farmRoleId, serialize(array()), $eventName, $target, $this->db->GetOne("SELECT MAX(revision) FROM script_revisions WHERE scriptid='2102'"), 300, 0, 0));
     $farmScriptId = $this->db->Insert_ID();
     $message = new Scalr_Messaging_Msg_ExecScript($eventName);
     $message->meta[Scalr_Messaging_MsgMeta::EVENT_ID] = "FRSID-{$farmScriptId}";
     $dbServer->SendMessage($message);
     $this->response->success('Scalarizr update successfully initiated. Please wait a few minutes and then refresh the page');
 }
 private function getScripts(Event $event, DBServer $eventServer, DBServer $targetServer)
 {
     $retval = array();
     try {
         $scripts = Scalr_Scripting_Manager::getEventScriptList($event, $eventServer, $targetServer);
         if (count($scripts) > 0) {
             foreach ($scripts as $script) {
                 $itm = new stdClass();
                 $itm->asynchronous = $script['issync'] == 1 ? '0' : '1';
                 $itm->timeout = $script['timeout'];
                 $itm->name = $script['name'];
                 $itm->body = $script['body'];
                 $retval[] = $itm;
             }
         }
     } catch (Exception $e) {
     }
     return $retval;
 }
Ejemplo n.º 12
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');
 }
Ejemplo n.º 13
0
 public function ScriptExecute($ScriptID, $Timeout, $Async, $FarmID, $FarmRoleID = null, $ServerID = null, $Revision = null, array $ConfigVariables = null)
 {
     $response = $this->CreateInitialResponse();
     $farminfo = $this->DB->GetRow("SELECT * FROM farms WHERE id=? AND env_id=?", array($FarmID, $this->Environment->id));
     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 = SCRIPTING_TARGET::INSTANCE;
     } else {
         if ($FarmRoleID) {
             $target = SCRIPTING_TARGET::ROLE;
         } else {
             $target = SCRIPTING_TARGET::FARM;
         }
     }
     $event_name = 'APIEvent-' . date("YmdHi") . '-' . rand(1000, 9999);
     $version = $Revision;
     $farmid = (int) $FarmID;
     $timeout = (int) $Timeout;
     $issync = $Async == 1 ? 0 : 1;
     $this->DB->Execute("INSERT INTO farm_role_scripts SET\r\n\t\t\t\tscriptid\t= ?,\r\n\t\t\t\tfarmid\t\t= ?,\r\n\t\t\t\tfarm_roleid\t= ?,\r\n\t\t\t\tparams\t\t= ?,\r\n\t\t\t\tevent_name\t= ?,\r\n\t\t\t\ttarget\t\t= ?,\r\n\t\t\t\tversion\t\t= ?,\r\n\t\t\t\ttimeout\t\t= ?,\r\n\t\t\t\tissync\t\t= ?,\r\n\t\t\t\tismenuitem\t= ?\r\n\t\t\t", array($scriptid, $farmid, $FarmRoleID, serialize($config), $event_name, $target, $version, $timeout, $issync, 0));
     $farm_rolescript_id = $this->DB->Insert_ID();
     switch ($target) {
         case SCRIPTING_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 SCRIPTING_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 SCRIPTING_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 Trap
     //
     if (count($servers) > 0) {
         foreach ($servers as $server) {
             $DBServer = DBServer::LoadByID($server['server_id']);
             $msg = new Scalr_Messaging_Msg_ExecScript($event_name);
             $msg->meta[Scalr_Messaging_MsgMeta::EVENT_ID] = "FRSID-{$farm_rolescript_id}";
             $msg = Scalr_Scripting_Manager::extendMessage($msg, $DBServer);
             $isEventNotice = !$DBServer->IsSupported("0.5");
             $DBServer->SendMessage($msg, $isEventNotice);
         }
     }
     $response->Result = true;
     return $response;
 }
Ejemplo n.º 14
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');
 }
 public function OnStartForking()
 {
     // start cron, which runs scripts by it's schedule queue
     try {
         $db = Core::GetDBInstance(null, true);
         // set status to "finished" for active tasks, which ended or executed once
         $info = $db->Execute("UPDATE scheduler SET `status` = ? WHERE\r\n\t\t\t\t`status` = ? AND (`end_time` < NOW() OR (`last_start_time` < NOW() AND `restart_every` = 0))", array(Scalr_SchedulerTask::STATUS_FINISHED, Scalr_SchedulerTask::STATUS_ACTIVE));
         // get active tasks: first run (condition and last_start_time is null), others (condition and last_start_time + interval * 0.9 < now())
         $taskList = $db->GetAll("SELECT *\r\n\t\t\t\tFROM scheduler\r\n\t\t\t\tWHERE `status` = ? AND (`end_time` > NOW() OR `end_time` IS NULL) AND (`start_time` <= NOW() OR `start_time` IS NULL) AND (\r\n\t\t\t\t\t`last_start_time` IS NULL OR\r\n\t\t\t\t\t`last_start_time` IS NOT NULL AND (last_start_time + INTERVAL (restart_every * 0.9 * 60) SECOND < NOW())\r\n\t\t\t\t)\r\n\t\t\t\tORDER BY IF (last_start_time, last_start_time, start_time), order_index ASC\r\n\t\t\t", array(Scalr_SchedulerTask::STATUS_ACTIVE));
         if (!$taskList) {
             $this->Logger->info(_("There is no tasks to execute in scheduler table"));
             exit;
         }
         foreach ($taskList as $task) {
             // check account status (active or inactive)
             try {
                 if (Scalr_Account::init()->loadById($task['account_id'])->status != Scalr_Account::STATUS_ACTIVE) {
                     continue;
                 }
             } catch (Exception $e) {
                 $this->Logger->info("Invalid scheduler task #{$task['id']}: {$e->getMessage()}");
             }
             // check time
             $lastStartTime = $task['last_start_time'] ? strtotime($task['last_start_time']) : NULL;
             if ($lastStartTime) {
                 if ($task['start_time'] == NULL) {
                     // disallow execute earlier
                     if ($lastStartTime + $task['restart_every'] * 60 > time()) {
                         continue;
                     }
                 } else {
                     // try to auto-align time to start time
                     $startTime = strtotime($task['start_time']);
                     $num = (time() - $startTime) / ($task['restart_every'] * 60);
                     /*file_put_contents("test.txt", print_r($task['name'], true), FILE_APPEND);
                     		file_put_contents("test.txt", " - ", FILE_APPEND);
                     		file_put_contents("test.txt", print_r(date('r', $lastStartTime), true), FILE_APPEND);
                     		file_put_contents("test.txt", " - ", FILE_APPEND);
                     		file_put_contents("test.txt", print_r(date('r'), true), FILE_APPEND);
                     		file_put_contents("test.txt", " - ", FILE_APPEND);
                     		file_put_contents("test.txt", print_r($num, true), FILE_APPEND);
                     		file_put_contents("test.txt", " - ", FILE_APPEND);
                     		file_put_contents("test.txt", print_r(floor($num), true), FILE_APPEND);
                     		file_put_contents("test.txt", " - ", FILE_APPEND);
                     		file_put_contents("test.txt", print_r(round($num, 0, PHP_ROUND_HALF_UP), true), FILE_APPEND);
                     		file_put_contents("test.txt", "\n", FILE_APPEND);*/
                     // num sholud be less than 0.5
                     if (floor($num) != round($num, 0, PHP_ROUND_HALF_UP)) {
                         continue;
                     }
                 }
             }
             // Terminate, Launch farm  or execute script
             $farmRoleNotFound = false;
             switch ($task['type']) {
                 case Scalr_SchedulerTask::LAUNCH_FARM:
                     try {
                         $farmId = $task['target_id'];
                         $DBFarm = DBFarm::LoadByID($farmId);
                         if ($DBFarm->Status == FARM_STATUS::TERMINATED) {
                             // launch farm
                             Scalr::FireEvent($farmId, new FarmLaunchedEvent(true));
                             $this->Logger->info(sprintf("Farm #{$farmId} successfully launched"));
                         } elseif ($DBFarm->Status == FARM_STATUS::RUNNING) {
                             // farm is running
                             $this->Logger->info(sprintf("Farm #{$farmId} is already running"));
                         } else {
                             // farm can't be launched
                             $this->Logger->info(sprintf("Farm #{$farmId} can't be launched because of it's status: {$DBFarm->Status}"));
                         }
                     } catch (Exception $e) {
                         // farm  not found
                         $farmRoleNotFound = true;
                         $this->Logger->info(sprintf("Farm #{$farmId} was not found and can't be launched"));
                     }
                     break;
                 case SCHEDULE_TASK_TYPE::TERMINATE_FARM:
                     try {
                         // get config settings
                         $farmId = $task['target_id'];
                         $config = unserialize($task['config']);
                         $deleteDNSZones = (int) $config['deleteDNSZones'];
                         $deleteCloudObjects = (int) $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);
                             $this->Logger->info(sprintf("Farm successfully terminated"));
                         } else {
                             $this->Logger->info(sprintf("Farm #{$farmId} can't be terminated because of it's status"));
                         }
                     } catch (Exception $e) {
                         // role not found
                         $farmRoleNotFound = true;
                         $this->Logger->info(sprintf("Farm #{$farmId} was not found and can't be terminated"));
                     }
                     break;
                 case SCHEDULE_TASK_TYPE::SCRIPT_EXEC:
                     // generate event name
                     $eventName = Scalr_Scripting_Manager::generateEventName('CustomEvent');
                     $instances = array();
                     try {
                         // get variables for SQL INSERT or UPDATE
                         $config = unserialize($task['config']);
                         if (!$config['scriptId']) {
                             throw new Exception(_("Script %s is not existed"), $config['scriptId']);
                         }
                         // check avaliable script version
                         if (!$db->GetOne("SELECT id FROM script_revisions WHERE scriptid = ? AND revision = ? AND approval_state = ?", array($config['scriptId'], $config['scriptVersion'], APPROVAL_STATE::APPROVED))) {
                             throw new Exception(_("Selected version is not approved or no longer available"));
                         }
                         // get executing object by target_type variable
                         switch ($task['target_type']) {
                             case SCRIPTING_TARGET::FARM:
                                 $DBFarm = DBFarm::LoadByID($task['target_id']);
                                 $farmId = $DBFarm->ID;
                                 $farmRoleId = null;
                                 $servers = $db->GetAll("SELECT * FROM servers WHERE `status` IN (?,?) AND farm_id = ?", array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, $farmId));
                                 break;
                             case SCRIPTING_TARGET::ROLE:
                                 $farmRoleId = $task['target_id'];
                                 $DBFarmRole = DBFarmRole::LoadByID($farmRoleId);
                                 $farmId = $DBFarmRole->GetFarmObject()->ID;
                                 $servers = $db->GetAll("SELECT * FROM servers WHERE `status` IN (?,?) AND farm_roleid = ?", array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, $farmRoleId));
                                 break;
                             case SCRIPTING_TARGET::INSTANCE:
                                 $instanceArgs = explode(":", $task['target_id']);
                                 $farmRoleId = $instanceArgs[0];
                                 $DBFarmRole = DBFarmRole::LoadByID($farmRoleId);
                                 // target for instance looks like  "farm_roleid:index"
                                 // script gets farmid conformed to the roleid and index
                                 $servers = $db->GetAll("SELECT * FROM servers WHERE `status` IN (?,?) AND farm_roleid = ? AND `index` = ? ", array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, $farmRoleId, $instanceArgs[1]));
                                 $farmId = $servers[0]["farm_id"];
                                 break;
                         }
                         if ($servers) {
                             $db->Execute("INSERT INTO farm_role_scripts SET\r\n\t\t\t\t\t\t\t\t\tscriptid\t= ?,\r\n\t\t\t\t\t\t\t\t\tfarmid\t\t= ?,\r\n\t\t\t\t\t\t\t\t\tfarm_roleid\t= ?,\r\n\t\t\t\t\t\t\t\t\tparams\t\t= ?,\r\n\t\t\t\t\t\t\t\t\tevent_name\t= ?,\r\n\t\t\t\t\t\t\t\t\ttarget\t\t= ?,\r\n\t\t\t\t\t\t\t\t\tversion\t\t= ?,\r\n\t\t\t\t\t\t\t\t\ttimeout\t\t= ?,\r\n\t\t\t\t\t\t\t\t\tissync\t\t= ?,\r\n\t\t\t\t\t\t\t\t\torder_index = ?,\r\n\t\t\t\t\t\t\t\t\tismenuitem\t= ?,\r\n\t\t\t\t\t\t\t\t\t`debug`\t\t= ?\r\n\t\t\t\t\t\t\t\t", array($config['scriptId'], $farmId, $farmRoleId, serialize($config['scriptOptions']), $eventName, $task['target_type'], $config['scriptVersion'], $config['scriptTimeout'], $config['scriptIsSync'], $task["order_index"], 0, 'scheduler2'));
                             $farmRoleScriptId = $db->Insert_ID();
                             // 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->meta[Scalr_Messaging_MsgMeta::EVENT_ID] = "FRSID-{$farmRoleScriptId}";
                                 $msg = Scalr_Scripting_Manager::extendMessage($msg, $DBServer);
                                 $DBServer->SendMessage($msg);
                             }
                         }
                     } catch (Exception $e) {
                         // farm or role not found.
                         $farmRoleNotFound = true;
                         $this->Logger->warn(sprintf("Farm, role or instances were not found, script can't be executed"));
                     }
                     break;
             }
             if ($farmRoleNotFound) {
                 // delete task if farm or role not found.
                 //$db->Execute("DELETE FROM scheduler  WHERE id = ?", array($task['id']));
                 //$this->Logger->warn(sprintf("Task {$task['id']} was deleted, because of the farm or role was not found"));
             } else {
                 $db->Execute("UPDATE  scheduler SET last_start_time = NOW() WHERE id = ?", array($task['id']));
                 $this->Logger->info(sprintf("Task {$task['id']} successfully sent"));
             }
         }
     } catch (Exception $e) {
         $this->Logger->warn(sprintf("Can't execute task {$task['id']}. Error message: %s", $e->getMessage()));
     }
 }
Ejemplo n.º 16
0
 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;
 }
Ejemplo n.º 17
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;
 }
Ejemplo n.º 18
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');
     }
 }
Ejemplo n.º 19
0
 public function OnHostDown(HostDownEvent $event)
 {
     if ($event->DBServer->IsRebooting() == 1) {
         $event->exit = 'reboot';
         return;
     }
     if (!$this->FarmID) {
         $event->exit = 'no-farm';
         return;
     }
     $dbFarm = DBFarm::LoadByID($this->FarmID);
     $servers = $dbFarm->GetServersByFilter(array('status' => array(SERVER_STATUS::RUNNING)));
     try {
         $DBFarmRole = $event->DBServer->GetFarmRoleObject();
         $is_synchronize = $DBFarmRole->NewRoleID ? true : false;
     } catch (Exception $e) {
         $is_synchronize = false;
     }
     try {
         $DBRole = DBRole::loadById($event->DBServer->roleId);
     } catch (Exception $e) {
     }
     //HUGE BUG HERE!
     $first_in_role_handled = false;
     $first_in_role_server = null;
     $event->msgExpected = count($servers);
     foreach ($servers as $DBServer) {
         if (!$DBServer instanceof DBServer) {
             continue;
         }
         $isfirstinrole = '0';
         $eventServerIsMaster = $event->DBServer->GetProperty(SERVER_PROPERTIES::DB_MYSQL_MASTER) || $event->DBServer->GetProperty(Scalr_Db_Msr::REPLICATION_MASTER);
         if ($eventServerIsMaster && !$first_in_role_handled) {
             if (!$is_synchronize && $DBServer->farmRoleId == $event->DBServer->farmRoleId) {
                 if (DBRole::loadById($DBServer->roleId)->hasBehavior(ROLE_BEHAVIORS::MYSQL) || DBRole::loadById($DBServer->roleId)->getDbMsrBehavior()) {
                     $first_in_role_handled = true;
                     $first_in_role_server = $DBServer;
                     $isfirstinrole = '1';
                 }
             }
         }
         $msg = new Scalr_Messaging_Msg_HostDown();
         //TODO:
         $msg->behaviour = $DBRole ? $DBRole->getBehaviors() : '*Unknown*';
         $msg->roleName = $DBRole ? $DBRole->name : '*Unknown*';
         $msg->localIp = $event->DBServer->localIp;
         $msg->remoteIp = $event->DBServer->remoteIp;
         $msg->isFirstInRole = $isfirstinrole;
         $msg->serverIndex = $event->DBServer->index;
         $msg->farmRoleId = $event->DBServer->farmRoleId;
         $msg->serverId = $event->DBServer->serverId;
         $msg->cloudLocation = $event->DBServer->GetCloudLocation();
         // If FarmRole was removed from farm, no configuration left
         if ($DBFarmRole) {
             $msg = Scalr_Scripting_Manager::extendMessage($msg, $event, $event->DBServer, $DBServer);
             if ($event->DBServer->farmRoleId != 0) {
                 foreach (Scalr_Role_Behavior::getListForRole(DBRole::loadById($event->DBServer->roleId)) as $behavior) {
                     $msg = $behavior->extendMessage($msg, $event->DBServer);
                 }
             }
         }
         $msg = $DBServer->SendMessage($msg, false, true);
         if ($msg->dbMessageId) {
             $event->msgCreated++;
         }
         $loopServerIsMaster = $DBServer->GetProperty(SERVER_PROPERTIES::DB_MYSQL_MASTER) || $DBServer->GetProperty(Scalr_Db_Msr::REPLICATION_MASTER);
         if ($loopServerIsMaster && $DBServer->status == SERVER_STATUS::RUNNING) {
             $doNotPromoteSlave2Master = true;
         }
     }
     if (!$DBFarmRole) {
         return;
     }
     if ($DBFarmRole->GetRoleObject()->getDbMsrBehavior() && !$doNotPromoteSlave2Master && !$DBFarmRole->GetSetting(Scalr_Db_Msr::SLAVE_TO_MASTER)) {
         $this->sendPromoteToMasterMessage($event);
     }
     //LEGACY MYSQL CODE:
     if ($DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::MYSQL)) {
         // If EC2 master down
         if ($event->DBServer->GetProperty(SERVER_PROPERTIES::DB_MYSQL_MASTER) && $DBFarmRole) {
             $master = $dbFarm->GetMySQLInstances(true);
             if ($master[0]) {
                 return;
             }
             $msg = new Scalr_Messaging_Msg_Mysql_PromoteToMaster($DBFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_ROOT_PASSWORD), $DBFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_REPL_PASSWORD), $DBFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_STAT_PASSWORD));
             if ($event->DBServer->IsSupported("0.7")) {
                 if (in_array($event->DBServer->platform, array(SERVER_PLATFORMS::EC2, SERVER_PLATFORMS::CLOUDSTACK, SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::UCLOUD))) {
                     try {
                         $volume = Scalr_Storage_Volume::init()->loadById($DBFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_SCALR_VOLUME_ID));
                         $msg->volumeConfig = $volume->getConfig();
                     } catch (Exception $e) {
                         $this->Logger->error(new FarmLogMessage($event->DBServer->farmId, "Cannot create volumeConfig for PromoteToMaster message: {$e->getMessage()}"));
                     }
                 }
             } elseif ($event->DBServer->platform == SERVER_PLATFORMS::EC2) {
                 $msg->volumeId = $DBFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_MASTER_EBS_VOLUME_ID);
             }
             // Send Mysql_PromoteToMaster to the first server in the same avail zone as old master (if exists)
             // Otherwise send to first in role
             $platform = $event->DBServer->platform;
             if ($platform == SERVER_PLATFORMS::EC2) {
                 $availZone = $event->DBServer->GetProperty(EC2_SERVER_PROPERTIES::AVAIL_ZONE);
             }
             foreach ($servers as $DBServer) {
                 if ($DBServer->serverId == $event->DBServer->serverId) {
                     continue;
                 }
                 if ($platform == SERVER_PLATFORMS::EC2 && $DBServer->GetProperty(EC2_SERVER_PROPERTIES::AVAIL_ZONE) == $availZone || $platform != SERVER_PLATFORMS::EC2) {
                     if (DBRole::loadById($DBServer->roleId)->hasBehavior(ROLE_BEHAVIORS::MYSQL)) {
                         $DBFarmRole->SetSetting(DBFarmRole::SETTING_MYSQL_SLAVE_TO_MASTER, 1);
                         $DBServer->SetProperty(SERVER_PROPERTIES::DB_MYSQL_MASTER, 1);
                         $DBServer->SendMessage($msg, false, true);
                         return;
                     }
                 }
             }
             if ($first_in_role_server) {
                 $DBFarmRole->SetSetting(DBFarmRole::SETTING_MYSQL_SLAVE_TO_MASTER, 1);
                 $first_in_role_server->SetProperty(SERVER_PROPERTIES::DB_MYSQL_MASTER, 1);
                 $first_in_role_server->SendMessage($msg, false, true);
             }
         }
     }
 }
Ejemplo n.º 20
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;
 }