listVariables() public method

public listVariables ( $roleId, $farmId, $farmRoleId, $serverId = '' )
 public function ListGlobalVariables()
 {
     $ResponseDOMDocument = $this->CreateResponse();
     $configNode = $ResponseDOMDocument->createElement("variables");
     $globalVariables = new Scalr_Scripting_GlobalVariables($this->DBServer->envId, Scalr_Scripting_GlobalVariables::SCOPE_FARMROLE);
     $vars = $globalVariables->listVariables($this->DBServer->roleId, $this->DBServer->farmId, $this->DBServer->farmRoleId);
     foreach ($vars as $key => $value) {
         $settingNode = $ResponseDOMDocument->createElement("variable", $value);
         $settingNode->setAttribute("name", $key);
         $configNode->appendChild($settingNode);
     }
     $formats = \Scalr::config("scalr.system.global_variables.format");
     foreach ($this->DBServer->GetScriptingVars() as $name => $value) {
         $name = "SCALR_" . strtoupper($name);
         $value = trim($value);
         if (isset($formats[$name])) {
             $value = @sprintf($formats[$name], $value);
         }
         $settingNode = $ResponseDOMDocument->createElement("variable", $value);
         $settingNode->setAttribute("name", $name);
         $configNode->appendChild($settingNode);
     }
     $ResponseDOMDocument->documentElement->appendChild($configNode);
     return $ResponseDOMDocument;
 }
 public function ListGlobalVariables()
 {
     $ResponseDOMDocument = $this->CreateResponse();
     $configNode = $ResponseDOMDocument->createElement("variables");
     $globalVariables = new Scalr_Scripting_GlobalVariables($this->DBServer->clientId, $this->DBServer->envId, Scalr_Scripting_GlobalVariables::SCOPE_SERVER);
     $vars = $globalVariables->listVariables($this->DBServer->GetFarmRoleObject()->RoleID, $this->DBServer->farmId, $this->DBServer->farmRoleId, $this->DBServer->serverId);
     foreach ($vars as $key => $value) {
         $settingNode = $ResponseDOMDocument->createElement("variable");
         if (preg_match("/[\\<\\>\\&]+/", $value['value'])) {
             $valueEl = $ResponseDOMDocument->createCDATASection($value['value']);
         } else {
             $valueEl = $ResponseDOMDocument->createTextNode($value['value']);
         }
         $settingNode->appendChild($valueEl);
         $settingNode->setAttribute("name", $value['name']);
         $settingNode->setAttribute("private", $value['private']);
         $configNode->appendChild($settingNode);
     }
     $formats = \Scalr::config("scalr.system.global_variables.format");
     foreach ($this->DBServer->GetScriptingVars() as $name => $value) {
         $name = "SCALR_" . strtoupper($name);
         $value = trim($value);
         if (isset($formats[$name])) {
             $value = @sprintf($formats[$name], $value);
         }
         $settingNode = $ResponseDOMDocument->createElement("variable");
         if (preg_match("/[\\<\\>\\&]+/", $value)) {
             $valueEl = $ResponseDOMDocument->createCDATASection($value);
         } else {
             $valueEl = $ResponseDOMDocument->createTextNode($value);
         }
         $settingNode->appendChild($valueEl);
         $settingNode->setAttribute("name", $name);
         $configNode->appendChild($settingNode);
     }
     $ResponseDOMDocument->documentElement->appendChild($configNode);
     return $ResponseDOMDocument;
 }
示例#3
0
 public function applyGlobalVarsToValue($value)
 {
     if (empty($this->globalVariablesCache)) {
         $formats = \Scalr::config("scalr.system.global_variables.format");
         $at = new Entity\Account\Team();
         $ft = new Entity\FarmTeam();
         $teams = Entity\Account\Team::find([\Scalr\Model\AbstractEntity::STMT_FROM => "{$at->table()} JOIN {$ft->table()} ON {$ft->columnTeamId} = {$at->columnId}", \Scalr\Model\AbstractEntity::STMT_WHERE => "{$ft->columnFarmId} = '{$this->ID}'"])->map(function ($t) {
             return $t->name;
         });
         $systemVars = array('env_id' => $this->EnvID, 'env_name' => $this->GetEnvironmentObject()->name, 'farm_team' => join(",", $teams), 'farm_id' => $this->ID, 'farm_name' => $this->Name, 'farm_hash' => $this->Hash, 'farm_owner_email' => $this->createdByUserEmail);
         if (\Scalr::getContainer()->analytics->enabled) {
             $projectId = $this->GetSetting(Entity\FarmSetting::PROJECT_ID);
             if ($projectId) {
                 $project = ProjectEntity::findPk($projectId);
                 /* @var $project ProjectEntity */
                 $systemVars['project_id'] = $projectId;
                 $systemVars['project_bc'] = $project->getProperty(ProjectPropertyEntity::NAME_BILLING_CODE);
                 $systemVars['project_name'] = $project->name;
                 $ccId = $project->ccId;
             }
             if ($ccId) {
                 $cc = CostCentreEntity::findPk($ccId);
                 if ($cc) {
                     /* @var $cc CostCentreEntity */
                     $systemVars['cost_center_id'] = $ccId;
                     $systemVars['cost_center_bc'] = $cc->getProperty(CostCentrePropertyEntity::NAME_BILLING_CODE);
                     $systemVars['cost_center_name'] = $cc->name;
                 } else {
                     throw new Exception("Cost center {$ccId} not found");
                 }
             }
         }
         // Get list of Server system vars
         foreach ($systemVars as $name => $val) {
             $name = "SCALR_" . strtoupper($name);
             $val = trim($val);
             if (isset($formats[$name])) {
                 $val = @sprintf($formats[$name], $val);
             }
             $this->globalVariablesCache[$name] = $val;
         }
         // Add custom variables
         $gv = new Scalr_Scripting_GlobalVariables($this->ClientID, $this->EnvID, ScopeInterface::SCOPE_FARM);
         $vars = $gv->listVariables(0, $this->ID);
         foreach ($vars as $v) {
             $this->globalVariablesCache[$v['name']] = $v['value'];
         }
     }
     //Parse variable
     $keys = array_keys($this->globalVariablesCache);
     $keys = array_map(function ($item) {
         return '{' . $item . '}';
     }, $keys);
     $values = array_values($this->globalVariablesCache);
     $retval = str_replace($keys, $values, $value);
     // Strip undefined variables & return value
     return preg_replace("/{[A-Za-z0-9_-]+}/", "", $retval);
 }
示例#4
0
 public function GlobalVariablesList($ServerID = null, $FarmID = null, $FarmRoleID = null, $RoleID = null)
 {
     if (empty($FarmID) && empty($FarmRoleID) && empty($RoleID) && empty($ServerID)) {
         $this->restrictAccess(Acl::RESOURCE_ENVADMINISTRATION_GLOBAL_VARIABLES);
     }
     $response = $this->CreateInitialResponse();
     $response->VariableSet = new stdClass();
     $response->VariableSet->Item = array();
     if ($ServerID) {
         $DBServer = DBServer::LoadByID($ServerID);
         if ($DBServer->envId != $this->Environment->id) {
             throw new Exception(sprintf("Server ID #%s not found", $ServerID));
         }
         $this->user->getPermissions()->validate($DBServer);
         $globalVariables = new Scalr_Scripting_GlobalVariables($this->Environment->clientId, $this->Environment->id, Scalr_Scripting_GlobalVariables::SCOPE_FARMROLE);
         $vars = $globalVariables->listVariables($DBServer->roleId, $DBServer->farmId, $DBServer->farmRoleId, $ServerID);
     } elseif ($FarmID) {
         $DBFarm = DBFarm::LoadByID($FarmID);
         if ($DBFarm->EnvID != $this->Environment->id) {
             throw new Exception(sprintf("Farm ID #%s not found", $FarmID));
         }
         $this->user->getPermissions()->validate($DBFarm);
         $globalVariables = new Scalr_Scripting_GlobalVariables($this->Environment->clientId, $this->Environment->id, Scalr_Scripting_GlobalVariables::SCOPE_FARM);
         $vars = $globalVariables->listVariables(null, $DBFarm->ID, null);
     } elseif ($RoleID) {
         $DBRole = DBRole::LoadByID($RoleID);
         if ($DBRole->envId != $this->Environment->id) {
             throw new Exception(sprintf("Role ID #%s not found", $RoleID));
         }
         $globalVariables = new Scalr_Scripting_GlobalVariables($this->Environment->clientId, $this->Environment->id, Scalr_Scripting_GlobalVariables::SCOPE_ROLE);
         $vars = $globalVariables->listVariables($RoleID, null, null);
     } elseif ($FarmRoleID) {
         $DBFarmRole = DBFarmRole::LoadByID($FarmRoleID);
         if ($DBFarmRole->GetFarmObject()->EnvID != $this->Environment->id) {
             throw new Exception(sprintf("FarmRole ID #%s not found", $FarmRoleID));
         }
         $this->user->getPermissions()->validate($DBFarmRole);
         $globalVariables = new Scalr_Scripting_GlobalVariables($this->Environment->clientId, $this->Environment->id, Scalr_Scripting_GlobalVariables::SCOPE_FARMROLE);
         $vars = $globalVariables->listVariables($DBFarmRole->RoleID, $DBFarmRole->FarmID, $DBFarmRole->ID);
     } else {
         $globalVariables = new Scalr_Scripting_GlobalVariables($this->Environment->clientId, $this->Environment->id, Scalr_Scripting_GlobalVariables::SCOPE_ENVIRONMENT);
         $vars = $globalVariables->listVariables();
     }
     foreach ($vars as $v) {
         $itm = new stdClass();
         $itm->{"Name"} = $v['name'];
         $itm->{"Value"} = $v['value'];
         $itm->{"Private"} = $v['private'];
         $response->VariableSet->Item[] = $itm;
     }
     return $response;
 }
示例#5
0
 public function applyGlobalVarsToValue($value)
 {
     if (empty($this->globalVariablesCache)) {
         $formats = \Scalr::config("scalr.system.global_variables.format");
         // Get list of Server system vars
         foreach ($this->GetScriptingVars() as $name => $val) {
             $name = "SCALR_" . strtoupper($name);
             $val = trim($val);
             if (isset($formats[$name])) {
                 $val = @sprintf($formats[$name], $val);
             }
             $this->globalVariablesCache[$name] = $val;
         }
         // Add custom variables
         $gv = new Scalr_Scripting_GlobalVariables($this->clientId, $this->envId, ScopeInterface::SCOPE_SERVER);
         $vars = $gv->listVariables($this->GetFarmRoleObject()->RoleID, $this->farmId, $this->farmRoleId, $this->serverId);
         foreach ($vars as $v) {
             $this->globalVariablesCache[$v['name']] = $v['value'];
         }
     }
     //Parse variable
     $keys = array_keys($this->globalVariablesCache);
     $f = create_function('$item', 'return "{".$item."}";');
     $keys = array_map($f, $keys);
     $values = array_values($this->globalVariablesCache);
     $retval = str_replace($keys, $values, $value);
     // Strip undefined variables & return value
     return preg_replace("/{[A-Za-z0-9_-]+}/", "", $retval);
 }
示例#6
0
 public static function listServerGlobalVariables(DBServer $dbServer, $includeSystem = false, AbstractServerEvent $event = null)
 {
     $retval = array();
     if ($includeSystem) {
         $variables = $dbServer->GetScriptingVars();
         if ($event) {
             if ($event->DBServer) {
                 foreach ($event->DBServer->GetScriptingVars() as $k => $v) {
                     $variables["event_{$k}"] = $v;
                 }
             }
             foreach ($event->GetScriptingVars() as $k => $v) {
                 $variables[$k] = $event->{$v};
             }
             if (isset($event->params) && is_array($event->params)) {
                 foreach ($event->params as $k => $v) {
                     $variables[$k] = $v;
                 }
             }
             $variables['event_name'] = $event->GetName();
         }
         $formats = \Scalr::config("scalr.system.global_variables.format");
         foreach ($variables as $name => $value) {
             $name = "SCALR_" . strtoupper($name);
             $value = trim($value);
             if (isset($formats[$name])) {
                 $value = @sprintf($formats[$name], $value);
             }
             $private = strpos($name, 'SCALR_EVENT_') === 0 ? 1 : 0;
             $retval[] = (object) array('name' => $name, 'value' => $value, 'private' => $private, 'system' => 1);
         }
     }
     try {
         $globalVariables = new Scalr_Scripting_GlobalVariables($dbServer->GetEnvironmentObject()->clientId, $dbServer->envId, ScopeInterface::SCOPE_SERVER);
         $vars = $globalVariables->listVariables($dbServer->GetFarmRoleObject()->RoleID, $dbServer->farmId, $dbServer->farmRoleId, $dbServer->serverId);
         foreach ($vars as $v) {
             $retval[] = (object) $v;
         }
     } catch (Exception $e) {
     }
     return $retval;
 }
示例#7
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 {
                 $scr = new Scalr_Script();
                 $scr->loadById($this->config['scriptId']);
                 // 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']));
                     // 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);
                         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);
                     }
                 } 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;
 }
示例#8
0
文件: Scripts.php 项目: recipe/scalr
 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.');
 }
示例#9
0
 public function applyGlobalVarsToValue($value)
 {
     if (empty($this->globalVariablesCache)) {
         $formats = \Scalr::config("scalr.system.global_variables.format");
         $systemVars = array('env_id' => $this->EnvID, 'env_name' => $this->GetEnvironmentObject()->name, 'farm_id' => $this->ID, 'farm_name' => $this->Name, 'farm_hash' => $this->Hash, 'farm_owner_email' => $this->createdByUserEmail);
         if (\Scalr::getContainer()->analytics->enabled) {
             $projectId = $this->GetSetting(DBFarm::SETTING_PROJECT_ID);
             if ($projectId) {
                 $project = ProjectEntity::findPk($projectId);
                 /* @var $project ProjectEntity */
                 $systemVars['project_id'] = $projectId;
                 $systemVars['project_bc'] = $project->getProperty(ProjectPropertyEntity::NAME_BILLING_CODE);
                 $systemVars['project_name'] = $project->name;
                 $ccId = $project->ccId;
             }
             if ($ccId) {
                 $cc = CostCentreEntity::findPk($ccId);
                 if ($cc) {
                     /* @var $cc CostCentreEntity */
                     $systemVars['cost_center_id'] = $ccId;
                     $systemVars['cost_center_bc'] = $cc->getProperty(CostCentrePropertyEntity::NAME_BILLING_CODE);
                     $systemVars['cost_center_name'] = $cc->name;
                 } else {
                     throw new Exception("Cost center {$ccId} not found");
                 }
             }
         }
         // Get list of Server system vars
         foreach ($systemVars as $name => $val) {
             $name = "SCALR_" . strtoupper($name);
             $val = trim($val);
             if (isset($formats[$name])) {
                 $val = @sprintf($formats[$name], $val);
             }
             $this->globalVariablesCache[$name] = $val;
         }
         // Add custom variables
         $gv = new Scalr_Scripting_GlobalVariables($this->ClientID, $this->EnvID, Scalr_Scripting_GlobalVariables::SCOPE_FARM);
         $vars = $gv->listVariables(0, $this->ID);
         foreach ($vars as $v) {
             $this->globalVariablesCache[$v['name']] = $v['value'];
         }
     }
     //Parse variable
     $keys = array_keys($this->globalVariablesCache);
     $f = create_function('$item', 'return "{".$item."}";');
     $keys = array_map($f, $keys);
     $values = array_values($this->globalVariablesCache);
     $retval = str_replace($keys, $values, $value);
     // Strip undefined variables & return value
     return preg_replace("/{[A-Za-z0-9_-]+}/", "", $retval);
 }
示例#10
0
 public function applyGlobalVarsToValue($value)
 {
     if (empty($this->globalVariablesCache)) {
         $formats = \Scalr::config("scalr.system.global_variables.format");
         // Get list of Server system vars
         foreach ($this->GetScriptingVars() as $name => $val) {
             $name = "SCALR_" . strtoupper($name);
             $val = trim($val);
             if (isset($formats[$name])) {
                 $value = @sprintf($formats[$name], $val);
             }
             $this->globalVariablesCache[$name] = $val;
         }
         // Add custom variables
         $gv = new Scalr_Scripting_GlobalVariables($this->envId);
         $vars = $gv->listVariables($this->roleId, $this->farmId, $this->farmRoleId);
         foreach ($vars as $k => $v) {
             $this->globalVariablesCache[$k] = trim($v);
         }
     }
     //Parse variable
     $keys = array_keys($this->globalVariablesCache);
     $f = create_function('$item', 'return "{".$item."}";');
     $keys = array_map($f, $keys);
     $values = array_values($this->globalVariablesCache);
     return str_replace($keys, $values, $value);
 }
示例#11
0
文件: Manager.php 项目: recipe/scalr
 public static function extendMessage(Scalr_Messaging_Msg $message, Event $event, DBServer $eventServer, DBServer $targetServer, $noScripts = false)
 {
     $db = \Scalr::getDb();
     $retval = array();
     if (!$noScripts) {
         try {
             $scripts = self::getEventScriptList($event, $eventServer, $targetServer);
             if (count($scripts) > 0) {
                 foreach ($scripts as $script) {
                     $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->name = "local-" . crc32($script['path']) . mt_rand(100, 999);
                         $itm->path = $script['path'];
                     }
                     if ($script['run_as']) {
                         $itm->runAs = $script['run_as'];
                     }
                     $itm->executionId = $script['execution_id'];
                     $retval[] = $itm;
                 }
             }
         } catch (Exception $e) {
         }
     }
     $message->scripts = $retval;
     $message->eventId = $event->GetEventID();
     $message->globalVariables = array();
     //Global variables
     try {
         /** System variables **/
         if ($targetServer) {
             $variables = $targetServer->GetScriptingVars();
         } else {
             $variables = array();
         }
         if ($event) {
             if ($eventServer) {
                 foreach ($eventServer->GetScriptingVars() as $k => $v) {
                     $variables["event_{$k}"] = $v;
                 }
             }
             foreach ($event->GetScriptingVars() as $k => $v) {
                 $variables[$k] = $event->{$v};
             }
             if (isset($event->params) && is_array($event->params)) {
                 foreach ($event->params as $k => $v) {
                     $variables[$k] = $v;
                 }
             }
             $variables['event_name'] = $event->GetName();
         }
         $formats = \Scalr::config("scalr.system.global_variables.format");
         foreach ($variables as $name => $value) {
             $name = "SCALR_" . strtoupper($name);
             $value = trim($value);
             if (isset($formats[$name])) {
                 $value = @sprintf($formats[$name], $value);
             }
             $message->globalVariables[] = (object) array('name' => $name, 'value' => $value);
         }
         // Add custom variables
         $globalVariables = new Scalr_Scripting_GlobalVariables($eventServer->envId);
         $vars = $globalVariables->listVariables($eventServer->roleId, $eventServer->farmId, $eventServer->farmRoleId);
         foreach ($vars as $k => $v) {
             $message->globalVariables[] = (object) array('name' => $k, 'value' => trim($v));
         }
     } catch (Exception $e) {
     }
     return $message;
 }
示例#12
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;
 }
示例#13
0
 public function applyGlobalVarsToValue($value)
 {
     if (empty($this->globalVariablesCache)) {
         $formats = \Scalr::config("scalr.system.global_variables.format");
         $systemVars = array('env_id' => $this->id, 'env_name' => $this->name);
         // Get list of Server system vars
         foreach ($systemVars as $name => $val) {
             $name = "SCALR_" . strtoupper($name);
             $val = trim($val);
             if (isset($formats[$name])) {
                 $val = @sprintf($formats[$name], $val);
             }
             $this->globalVariablesCache[$name] = $val;
         }
         // Add custom variables
         $gv = new Scalr_Scripting_GlobalVariables($this->clientId, $this->id, ScopeInterface::SCOPE_ENVIRONMENT);
         $vars = $gv->listVariables();
         foreach ($vars as $v) {
             $this->globalVariablesCache[$v['name']] = $v['value'];
         }
     }
     //Parse variable
     $keys = array_keys($this->globalVariablesCache);
     $keys = array_map(function ($item) {
         return '{' . $item . '}';
     }, $keys);
     $values = array_values($this->globalVariablesCache);
     $retval = str_replace($keys, $values, $value);
     // Strip undefined variables & return value
     return preg_replace("/{[A-Za-z0-9_-]+}/", "", $retval);
 }