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;
 }
Beispiel #2
0
 /**
  * @param JsonData $variables
  */
 public function xSaveVariablesAction(JsonData $variables)
 {
     $vars = new Scalr_Scripting_GlobalVariables(0, 0, ScopeInterface::SCOPE_SCALR);
     $result = $vars->setValues($variables, 0, 0, 0, '', false);
     if ($result === true) {
         $this->response->success('Variables saved');
     } else {
         $this->response->failure();
         $this->response->data(array('errors' => array('variables' => $result)));
     }
 }
Beispiel #3
0
 /**
  * @param JsonData $variables JSON encoded structure
  */
 public function xSaveVariablesAction(JsonData $variables)
 {
     $vars = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), 0, Scalr_Scripting_GlobalVariables::SCOPE_ACCOUNT);
     $result = $vars->setValues($variables, 0, 0, 0, '', false);
     if ($result === true) {
         $this->response->success('Variables saved');
     } else {
         $this->response->failure();
         $this->response->data(array('errors' => array('variables' => $result)));
     }
 }
Beispiel #4
0
 /**
  * @param JsonData $variables JSON encoded structure
  */
 public function xSaveVariablesAction(JsonData $variables)
 {
     $this->request->restrictAccess(Acl::RESOURCE_GLOBAL_VARIABLES_ACCOUNT, Acl::PERM_GLOBAL_VARIABLES_ACCOUNT_MANAGE);
     $vars = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), 0, ScopeInterface::SCOPE_ACCOUNT);
     $result = $vars->setValues($variables, 0, 0, 0, '', false);
     if ($result === true) {
         $this->response->success('Variables saved');
     } else {
         $this->response->failure();
         $this->response->data(array('errors' => array('variables' => $result)));
     }
 }
Beispiel #5
0
 public function xCloneAction()
 {
     if (!$this->user->isAccountSuperAdmin() && !$this->request->isAllowed(Acl::RESOURCE_ENV_CLOUDS_ENVIRONMENT)) {
         throw new Scalr_Exception_InsufficientPermissions();
     }
     $params = array('envId' => array('type' => 'int'), 'name' => array('type' => 'string', 'validator' => array(Scalr_Validator::REQUIRED => true, Scalr_Validator::NOHTML => true)));
     $this->request->defineParams($params);
     $this->request->validate();
     $oldEnv = Scalr_Environment::init()->loadById($this->getParam('envId'));
     $this->user->getPermissions()->validate($oldEnv);
     if ($this->request->isValid()) {
         if (!$this->user->isAccountOwner() && !$this->user->isAccountSuperAdmin()) {
             throw new Scalr_Exception_InsufficientPermissions();
         }
         $this->user->getAccount()->validateLimit(Scalr_Limits::ACCOUNT_ENVIRONMENTS, 1);
         $env = $this->user->getAccount()->createEnvironment($this->getParam('name'));
         $env->status = Scalr_Environment::STATUS_ACTIVE;
         //Copy cloud credentials
         $cloudConfig = $oldEnv->getFullConfiguration();
         foreach ($cloudConfig as $group => $props) {
             $env->setPlatformConfig($props, null, $group);
         }
         //Copy teams & ACLs
         $teams = $oldEnv->getTeams();
         foreach ($teams as $teamId) {
             $env->addTeam($teamId);
         }
         //Copy Env level global variables
         $oldGv = new Scalr_Scripting_GlobalVariables($oldEnv->clientId, $oldEnv->id, ScopeInterface::SCOPE_ENVIRONMENT);
         $variables = $oldGv->getValues();
         $newGv = new Scalr_Scripting_GlobalVariables($env->clientId, $env->id, ScopeInterface::SCOPE_ENVIRONMENT);
         $newGv->setValues($variables, 0, 0, 0, '', false, true);
         //Copy governance rules
         $oldGov = new Scalr_Governance($oldEnv->id);
         $govRules = $oldGov->getValues();
         $newGov = new Scalr_Governance($env->id);
         foreach ($govRules as $category => $rules) {
             foreach ($rules as $name => $data) {
                 $newGov->setValue($category, $name, $data['enabled'], $data['limits']);
             }
         }
         $this->response->success("Environment successfully cloned");
         $this->response->data(array('env' => array('id' => $env->id, 'name' => $env->name, 'status' => $env->status, 'platforms' => $env->getEnabledPlatforms(), 'teams' => $teams, 'ccId' => $env->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID))));
     } else {
         $this->response->failure($this->request->getValidationErrorsMessage(), true);
     }
 }
 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;
 }
Beispiel #7
0
 public function getDefinition()
 {
     $roleDefinition = new stdClass();
     $roleDefinition->roleId = $this->RoleID;
     $roleDefinition->platform = $this->Platform;
     $roleDefinition->cloudLocation = $this->CloudLocation;
     $roleDefinition->alias = $this->Alias;
     // Settings
     $roleDefinition->settings = array();
     foreach ($this->GetAllSettings() as $k => $v) {
         $roleDefinition->settings[$k] = $v;
     }
     //Farm Global Variables
     $variables = new Scalr_Scripting_GlobalVariables($this->GetFarmObject()->ClientID, $this->GetFarmObject()->EnvID, Scalr_Scripting_GlobalVariables::SCOPE_FARMROLE);
     $roleDefinition->globalVariables = $variables->getValues($this->RoleID, $this->FarmID, $this->ID);
     //Storage
     $storage = $this->getStorage();
     $configs = $storage->getConfigs();
     if (!empty($configs)) {
         foreach ($configs as $cfg) {
             $cfg = (array) $cfg;
             unset($cfg['id']);
             unset($cfg['status']);
             $roleDefinition->storage[] = $cfg;
         }
     }
     // Scripts
     $scripts = $this->DB->GetAll("SELECT * FROM farm_role_scripts WHERE farm_roleid=? AND issystem='1'", array($this->ID));
     $roleDefinition->scripts = array();
     foreach ($scripts as $script) {
         $itm = new stdClass();
         $itm->event = $script['event_name'];
         $itm->scriptId = (int) $script['scriptid'];
         $itm->params = unserialize($script['params']);
         $itm->target = $script['target'];
         $itm->version = (int) $script['version'];
         $itm->timeout = $script['timeout'];
         $itm->isSync = $script['issync'];
         $itm->isMenuItem = $script['ismenuitem'];
         $itm->orderIndex = $script['order_index'];
         $itm->scriptPath = $script['script_path'];
         $itm->runAs = $script['run_as'];
         $roleDefinition->scripts[] = $itm;
     }
     // Scaling times
     $scalingTimes = $this->DB->GetAll("SELECT * FROM farm_role_scaling_times WHERE farm_roleid = ?", array($this->ID));
     $roleDefinition->scalingTimes = array();
     foreach ($scalingTimes as $time) {
         $itm = new stdClass();
         $itm->startTime = $time['start_time'];
         $itm->endTime = $time['end_time'];
         $itm->daysOfWeek = $time['days_of_week'];
         $itm->instanceCount = $time['instances_count'];
         $roleDefinition->scalingTimes[] = $itm;
     }
     // Scaling metrics
     $scalingMetrics = $this->DB->GetAll("SELECT * FROM farm_role_scaling_metrics WHERE farm_roleid = ?", array($this->ID));
     $roleDefinition->scalingMetrics = array();
     foreach ($scalingMetrics as $metric) {
         $itm = new stdClass();
         $itm->metricId = $metric['metric_id'];
         $itm->settings = unserialize($metric['settings']);
         $roleDefinition->scalingMetrics[] = $itm;
     }
     return $roleDefinition;
 }
Beispiel #8
0
 /**
  * Apply FarmRole global variables to a value
  *
  * @return string
  */
 public function applyGlobalVarsToValue($value)
 {
     if (empty($this->globalVariablesCache)) {
         $formats = \Scalr::config("scalr.system.global_variables.format");
         $systemVars = array('env_id' => $this->GetFarmObject()->EnvID, 'env_name' => $this->GetFarmObject()->GetEnvironmentObject()->name, 'farm_team' => $this->GetFarmObject()->teamId ? (new Scalr_Account_Team())->loadById($this->GetFarmObject()->teamId)->name : '', 'farm_id' => $this->GetFarmObject()->ID, 'farm_name' => $this->GetFarmObject()->Name, 'farm_hash' => $this->GetFarmObject()->Hash, 'farm_owner_email' => $this->GetFarmObject()->createdByUserEmail, 'farm_role_id' => $this->ID, 'farm_role_alias' => $this->Alias, 'cloud_location' => $this->CloudLocation);
         if (\Scalr::getContainer()->analytics->enabled) {
             $projectId = $this->GetFarmObject()->GetSetting(Entity\FarmSetting::PROJECT_ID);
             if ($projectId) {
                 /* @var $project ProjectEntity */
                 $project = ProjectEntity::findPk($projectId);
                 $systemVars['project_id'] = $projectId;
                 $systemVars['project_bc'] = $project->getProperty(ProjectPropertyEntity::NAME_BILLING_CODE);
                 $systemVars['project_name'] = $project->name;
                 $ccId = $project->ccId;
             }
             if ($ccId) {
                 /* @var $cc CostCentreEntity */
                 $cc = CostCentreEntity::findPk($ccId);
                 if ($cc) {
                     $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->GetFarmObject()->ClientID, $this->GetFarmObject()->EnvID, ScopeInterface::SCOPE_FARMROLE);
         $vars = $gv->listVariables($this->RoleID, $this->FarmID, $this->ID);
         foreach ($vars as $v) {
             $this->globalVariablesCache[$v['name']] = $v['value'];
         }
     }
     //Parse variable
     $keys = array_map(function ($item) {
         return "{" . $item . "}";
     }, array_keys($this->globalVariablesCache));
     $values = array_values($this->globalVariablesCache);
     $retval = str_replace($keys, $values, $value);
     // Strip undefined variables & return value
     return preg_replace("/{[A-Za-z0-9_-]+}/", "", $retval);
 }
Beispiel #9
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;
 }
Beispiel #10
0
 public function setGlobalVariables(DBServer $dbServer, $includeSystem = false, AbstractServerEvent $event = null)
 {
     $this->globalVariables = Scalr_Scripting_GlobalVariables::listServerGlobalVariables($dbServer, $includeSystem, $event);
 }
Beispiel #11
0
 public function getFarm2($farmId)
 {
     $dbFarm = DBFarm::LoadByID($farmId);
     $this->user->getPermissions()->validate($dbFarm);
     $farmRoleId = $this->getParam('farmRoleId');
     $farmRoles = array();
     $variables = new Scalr_Scripting_GlobalVariables($this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARM);
     $farmRoleVariables = new Scalr_Scripting_GlobalVariables($this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARMROLE);
     foreach ($dbFarm->GetFarmRoles() as $dbFarmRole) {
         if ($farmRoleId && $farmRoleId != $dbFarmRole->ID) {
             continue;
         }
         $scripts = $this->db->GetAll("\n                SELECT farm_role_scripts.*, scripts.name\n                FROM farm_role_scripts\n                LEFT JOIN scripts ON scripts.id = farm_role_scripts.scriptid\n                WHERE farm_roleid=? AND issystem='1'\n            ", array($dbFarmRole->ID));
         $scriptsObject = array();
         foreach ($scripts as $script) {
             if (!empty($script['scriptid']) || !empty($script['script_path'])) {
                 $s = array('script_id' => $script['scriptid'], 'script' => $script['name'], 'params' => unserialize($script['params']), 'target' => $script['target'], 'version' => $script['version'], 'timeout' => $script['timeout'], 'issync' => $script['issync'], 'order_index' => $script['order_index'], 'event' => $script['event_name'], 'script_path' => $script['script_path'], 'run_as' => $script['run_as']);
             }
             if ($script['target'] == Scalr_Script::TARGET_BEHAVIORS || $script['target'] == Scalr_Script::TARGET_ROLES) {
                 $varName = $script['target'] == Scalr_Script::TARGET_ROLES ? 'target_roles' : 'target_behaviors';
                 $s[$varName] = array();
                 $r = $this->db->GetAll("SELECT `target` FROM farm_role_scripting_targets WHERE farm_role_script_id = ?", array($script['id']));
                 foreach ($r as $v) {
                     array_push($s[$varName], $v['target']);
                 }
             }
             $scriptsObject[] = $s;
         }
         //Scripting params
         $scriptingParams = $this->db->Execute("\n                SELECT * FROM farm_role_scripting_params\n                WHERE farm_role_id = ? AND farm_role_script_id = '0'\n            ", array($dbFarmRole->ID));
         $sParams = array();
         while ($p = $scriptingParams->FetchRow()) {
             $sParams[] = array('hash' => $p['hash'], 'role_script_id' => $p['role_script_id'], 'params' => unserialize($p['params']));
         }
         $scalingManager = new Scalr_Scaling_Manager($dbFarmRole);
         $scaling = array();
         foreach ($scalingManager->getFarmRoleMetrics() as $farmRoleMetric) {
             $scaling[$farmRoleMetric->metricId] = $farmRoleMetric->getSettings();
         }
         $dbPresets = $this->db->GetAll("SELECT * FROM farm_role_service_config_presets WHERE farm_roleid=?", array($dbFarmRole->ID));
         $presets = array();
         foreach ($dbPresets as $preset) {
             $presets[$preset['behavior']] = $preset['preset_id'];
         }
         if ($dbFarmRole->NewRoleID) {
             $roleName = DBRole::loadById($dbFarmRole->NewRoleID)->name;
             $isBundling = true;
         } else {
             $roleName = $dbFarmRole->GetRoleObject()->name;
             $isBundling = false;
         }
         $imageDetails = $dbFarmRole->GetRoleObject()->getImageDetails($dbFarmRole->Platform, $dbFarmRole->CloudLocation);
         $storages = array('configs' => $dbFarmRole->getStorage()->getConfigs());
         foreach ($dbFarmRole->getStorage()->getVolumes() as $configKey => $config) {
             $storages['devices'][$configKey] = array();
             foreach ($config as $device) {
                 $info = array('farmRoleId' => $device->farmRoleId, 'placement' => $device->placement, 'serverIndex' => $device->serverIndex, 'storageId' => $device->storageId, 'storageConfigId' => $device->storageConfigId, 'status' => $device->status);
                 try {
                     $server = DBServer::LoadByFarmRoleIDAndIndex($device->farmRoleId, $device->serverIndex);
                     if ($server->status != SERVER_STATUS::TERMINATED && $server->status != SERVER_STATUS::TROUBLESHOOTING) {
                         $info['serverId'] = $server->serverId;
                         $info['serverInstanceId'] = $server->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID);
                     }
                 } catch (Exception $e) {
                     $this->response->varDump($e->getMessage());
                     $this->response->varDump($e->getTraceAsString());
                 }
                 $storages['devices'][$configKey][] = $info;
             }
         }
         $imageInfo = $dbFarmRole->GetRoleObject()->getImageDetails($dbFarmRole->Platform, $dbFarmRole->CloudLocation);
         $architecture = $imageInfo['architecture'];
         $securityGroups = $this->getInitialSecurityGroupsList($dbFarmRole);
         $farmRoles[] = array('farm_role_id' => $dbFarmRole->ID, 'alias' => $dbFarmRole->Alias ? $dbFarmRole->Alias : $dbFarmRole->GetRoleObject()->name, 'role_id' => $dbFarmRole->RoleID, 'platform' => $dbFarmRole->Platform, 'os' => $dbFarmRole->GetRoleObject()->os, 'os_family' => $dbFarmRole->GetRoleObject()->osFamily, 'os_generation' => $dbFarmRole->GetRoleObject()->osGeneration, 'os_version' => $dbFarmRole->GetRoleObject()->osVersion, 'generation' => $dbFarmRole->GetRoleObject()->generation, 'group' => $dbFarmRole->GetRoleObject()->getCategoryName(), 'cat_id' => $dbFarmRole->GetRoleObject()->catId, 'arch' => $architecture, 'name' => $roleName, 'is_bundle_running' => $isBundling, 'behaviors' => implode(",", $dbFarmRole->GetRoleObject()->getBehaviors()), 'scripting' => $scriptsObject, 'scripting_params' => $sParams, 'settings' => $dbFarmRole->GetAllSettings(), 'cloud_location' => $dbFarmRole->CloudLocation, 'launch_index' => (int) $dbFarmRole->LaunchIndex, 'scaling' => $scaling, 'config_presets' => $presets, 'tags' => $dbFarmRole->GetRoleObject()->getTags(), 'storages' => $storages, 'variables' => $farmRoleVariables->getValues($dbFarmRole->GetRoleID(), $dbFarm->ID, $dbFarmRole->ID), 'running_servers' => $dbFarmRole->GetRunningInstancesCount(), 'security_groups' => $securityGroups);
     }
     $vpc = array();
     if ($dbFarm->GetSetting(DBFarm::SETTING_EC2_VPC_ID)) {
         $vpc = array('id' => $dbFarm->GetSetting(DBFarm::SETTING_EC2_VPC_ID), 'region' => $dbFarm->GetSetting(DBFarm::SETTING_EC2_VPC_REGION));
     }
     return array('farm' => array('name' => $dbFarm->Name, 'description' => $dbFarm->Comments, 'rolesLaunchOrder' => $dbFarm->RolesLaunchOrder, 'timezone' => $dbFarm->GetSetting(DBFarm::SETTING_TIMEZONE), 'variables' => $variables->getValues(0, $dbFarm->ID), 'vpc' => $vpc, 'status' => $dbFarm->Status), 'roles' => $farmRoles, 'lock' => $dbFarm->isLocked(false), 'changed' => $dbFarm->changedTime);
 }
Beispiel #12
0
 /**
  * Store event in database
  *
  * @param integer $farmid
  * @param string $event_name
  */
 public static function StoreEvent($farmid, Event $event, $eventTime = null)
 {
     if ($event->DBServer) {
         $eventServerId = $event->DBServer->serverId;
     }
     try {
         $DB = self::getDb();
         // Generate event message
         $message = $event->getTextDetails();
         //short_message temporary used for time tracking
         // Store event in database
         $DB->Execute("INSERT INTO events SET\n                farmid\t= ?,\n                type\t= ?,\n                dtadded\t= NOW(),\n                message\t= ?,\n                event_object = '',\n                event_id\t = ?,\n                event_server_id = ?,\n                short_message = ?,\n                msg_expected = ?,\n                msg_created = ?,\n                scripts_total = ?,\n                is_suspend = ?", array($farmid, $event->GetName(), $message, $event->GetEventID(), $eventServerId, $eventTime, $event->msgExpected, $event->msgCreated, $event->scriptsCount, $event->isSuspended ? 1 : 0));
     } catch (Exception $e) {
         Logger::getLogger(__CLASS__)->fatal(sprintf(_("Cannot store event in database: %s"), $e->getMessage()));
     }
     try {
         if ($eventServerId) {
             $dbServer = DBServer::LoadByID($eventServerId);
             if (!$dbServer->farmRoleId) {
                 return true;
             }
             $dt = new DateTime('now', new DateTimeZone("UTC"));
             $timestamp = $dt->format("D d M Y H:i:s e");
             $payload = new stdClass();
             $payload->eventName = $event->GetName();
             $payload->eventId = $event->GetEventID();
             $payload->timestamp = $timestamp;
             $globalVars = Scalr_Scripting_GlobalVariables::listServerGlobalVariables($dbServer, true, $event);
             $webhooks = WebhookConfig::findByEvent($event->GetName(), $farmid, $dbServer->clientId, $dbServer->envId);
             $count = 0;
             foreach ($webhooks as $webhook) {
                 /* @var $webhook \Scalr\Model\Entity\WebhookConfig */
                 $payload->configurationId = $webhook->webhookId;
                 $payload->data = array();
                 $variables = [];
                 foreach ($globalVars as $gv) {
                     $variables[$gv->name] = $gv->value;
                     if ($gv->private && $webhook->skipPrivateGv == 1 && !$gv->system) {
                         continue;
                     }
                     $payload->data[$gv->name] = $gv->value;
                 }
                 if ($webhook->postData) {
                     //Parse variable
                     $keys = array_keys($variables);
                     $f = create_function('$item', 'return "{".$item."}";');
                     $keys = array_map($f, $keys);
                     $values = array_values($variables);
                     // Strip undefined variables & return value
                     $payload->userData = preg_replace("/{[A-Za-z0-9_-]+}/", "", str_replace($keys, $values, $webhook->postData));
                 } else {
                     $payload->userData = '';
                 }
                 foreach ($webhook->getEndpoints() as $ce) {
                     /* @var $ce \Scalr\Model\Entity\WebhookConfigEndpoint */
                     $endpoint = $ce->getEndpoint();
                     if (!$endpoint->isValid) {
                         continue;
                     }
                     $payload->endpointId = $endpoint->endpointId;
                     $encPayload = json_encode($payload);
                     $history = new WebhookHistory();
                     $history->eventId = $event->GetEventID();
                     $history->eventType = $event->GetName();
                     $history->payload = $encPayload;
                     $history->serverId = $event->DBServer ? $event->DBServer->serverId : null;
                     $history->endpointId = $endpoint->endpointId;
                     $history->webhookId = $webhook->webhookId;
                     $history->farmId = $farmid;
                     $history->save();
                     $count++;
                 }
             }
             if ($count != 0) {
                 $DB->Execute("UPDATE events SET wh_total = ? WHERE event_id = ?", array($count, $event->GetEventID()));
             }
         }
     } catch (Exception $e) {
         Logger::getLogger(__CLASS__)->fatal(sprintf(_("WebHooks: %s"), $e->getMessage()));
     }
 }
Beispiel #13
0
 public static function createFromBundleTask(BundleTask $BundleTask)
 {
     $db = \Scalr::getDb();
     $DBServer = DBServer::LoadByID($BundleTask->serverId);
     if ($BundleTask->prototypeRoleId) {
         $proto_role = $db->GetRow("SELECT * FROM roles WHERE id=? LIMIT 1", array($BundleTask->prototypeRoleId));
         if (!$proto_role['architecture']) {
             $proto_role['architecture'] = $DBServer->GetProperty(SERVER_PROPERTIES::ARCHITECTURE);
         }
     } else {
         $behaviors = array_unique(explode(',', $DBServer->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_BEHAVIOR)));
         sort($behaviors);
         $proto_role = array("behaviors" => join(',', $behaviors), "architecture" => $DBServer->GetProperty(SERVER_PROPERTIES::ARCHITECTURE), "name" => "*import*");
     }
     if (!$proto_role['architecture']) {
         $proto_role['architecture'] = 'x86_64';
     }
     if (!$BundleTask->cloudLocation) {
         if ($DBServer) {
             $BundleTask->cloudLocation = $DBServer->GetCloudLocation();
         }
     }
     $osId = $BundleTask->osId;
     $meta = $BundleTask->getSnapshotDetails();
     if (!$osId) {
         if ($proto_role) {
             $osId = $proto_role['os_id'];
         } elseif ($meta['os'] && $meta['os']->version) {
             /*
                             if ($meta['os']->version == '2008Server') {
                                 $osInfo->name = 'Windows 2008 Server';
                                 $osInfo->family = 'windows';
                                 $osInfo->generation = '2008';
                                 $osInfo->version = '2008Server';
                             } elseif ($meta['os']->version == '2008ServerR2') {
                                 $osInfo->name = 'Windows 2008 Server R2';
                                 $osInfo->family = 'windows';
                                 $osInfo->generation = '2008';
                                 $osInfo->version = '2008ServerR2';
                             }*/
             //TODO:
         }
     }
     if ($proto_role['cat_id']) {
         $catId = $proto_role['cat_id'];
     } else {
         $catId = ROLE_BEHAVIORS::GetCategoryId($proto_role['behaviors']);
     }
     $db->Execute("INSERT INTO roles SET\n            name\t\t\t= ?,\n            origin\t\t\t= ?,\n            dtadded         = NOW(),\n            client_id\t\t= ?,\n            env_id\t\t\t= ?,\n            cat_id          = ?,\n            description\t\t= ?,\n            behaviors\t\t= ?,\n            generation\t\t= ?,\n            added_by_email  = ?,\n            added_by_userid = ?,\n            os_id\t\t\t= ?\n        ", array($BundleTask->roleName, ROLE_TYPE::CUSTOM, $BundleTask->clientId, $BundleTask->envId, $catId, $BundleTask->description, $proto_role['behaviors'], 2, $BundleTask->createdByEmail, $BundleTask->createdById, $osId));
     $role_id = $db->Insert_Id();
     $BundleTask->roleId = $role_id;
     $BundleTask->Save();
     $BundleTask->Log(sprintf("Created new role. Role name: %s. Role ID: %s", $BundleTask->roleName, $BundleTask->roleId));
     $role = self::loadById($role_id);
     $behaviors = explode(",", $proto_role['behaviors']);
     foreach ($behaviors as $behavior) {
         $db->Execute("INSERT IGNORE INTO role_behaviors SET\n                role_id\t\t\t= ?,\n                behavior\t\t= ?\n            ", array($role_id, $behavior));
     }
     // Set image
     $role->__getNewRoleObject()->setImage($BundleTask->platform, $BundleTask->cloudLocation, $BundleTask->snapshotId, $BundleTask->createdById, $BundleTask->createdByEmail);
     // Set params
     if ($proto_role['id']) {
         $dbSecRules = $db->GetAll("SELECT * FROM role_security_rules WHERE role_id = ?", array($proto_role['id']));
         foreach ($dbSecRules as $dbSecRule) {
             $db->Execute("INSERT INTO role_security_rules SET role_id = ?, rule = ?", array($role_id, $dbSecRule['rule']));
         }
         $props = $db->GetAll("SELECT * FROM role_properties WHERE role_id=?", array($proto_role['id']));
         foreach ($props as $prop) {
             $role->setProperty($prop['name'], $prop['value']);
         }
         $scripts = $db->GetAll("SELECT * FROM role_scripts WHERE role_id=?", array($proto_role['id']));
         foreach ($scripts as &$script) {
             $script['params'] = unserialize($script['params']);
         }
         $role->setScripts($scripts);
         $variables = new Scalr_Scripting_GlobalVariables($BundleTask->clientId, $proto_role['env_id'], ScopeInterface::SCOPE_ROLE);
         $variables->setValues($variables->getValues($proto_role['id']), $role->id);
     }
     $role->syncAnalyticsTags();
     return $role;
 }
Beispiel #14
0
 /**
  * @param   int         $roleId
  * @param   string      $name
  * @param   string      $description
  * @param   string      $osId
  * @param   int         $catId
  * @param   bool        $isQuickStart
  * @param   bool        $isDeprecated
  * @param   bool        $isScalarized
  * @param   JsonData    $behaviors
  * @param   JsonData    $images
  * @param   JsonData    $scripts
  * @param   JsonData    $variables
  * @param   JsonData    $chef
  * @param   JsonData    $environments
  * @throws  Exception
  * @throws  Scalr_Exception_Core
  * @throws  Scalr_Exception_InsufficientPermissions
  */
 public function xSaveAction($roleId = 0, $name, $description, $osId, $catId, $isQuickStart = false, $isDeprecated = false, $isScalarized = true, JsonData $behaviors, JsonData $images, JsonData $scripts, JsonData $variables, JsonData $chef, JsonData $environments)
 {
     $this->request->restrictAccess('ROLES', 'MANAGE');
     $accountId = $this->user->getAccountId() ?: NULL;
     if (!Role::isValidName($name)) {
         throw new Exception(_("Role name is incorrect"));
     }
     if (Role::isNameUsed($name, $accountId, $this->getEnvironmentId(true), $roleId)) {
         throw new Exception('Selected role name is already used. Please select another one.');
     }
     if (!$catId) {
         throw new Exception('Role category is required');
     }
     if ($roleId == 0) {
         if (!Os::findPk($osId)) {
             throw new Exception(sprintf('%s is not valid osId', $osId));
         }
         $role = new Role();
         $role->generation = 2;
         $role->origin = $this->user->isScalrAdmin() ? ROLE_TYPE::SHARED : ROLE_TYPE::CUSTOM;
         $role->accountId = $accountId;
         $role->envId = $this->getEnvironmentId(true);
         $role->name = $name;
         $role->catId = $catId;
         $role->osId = $osId;
         $role->isScalarized = $isScalarized ? 1 : 0;
         $role->addedByUserId = $this->user->getId();
         $role->addedByEmail = $this->user->getEmail();
         $role->setBehaviors((array) $behaviors);
         $role->save();
     } else {
         $role = Role::findPk($roleId);
         if (!$role) {
             throw new Scalr_Exception_Core(sprintf(_("Role ID#%s not found in database"), $roleId));
         }
         $this->request->checkPermissions($role, true);
         $role->name = $name;
         $role->catId = $catId;
     }
     $globalVariables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(true), ScopeInterface::SCOPE_ROLE);
     $globalVariables->setValues($variables, $role->id);
     foreach (RoleProperty::find([['roleId' => $role->id], ['name' => ['$like' => ['chef.%']]]]) as $prop) {
         $prop->delete();
     }
     foreach ($chef as $name => $value) {
         $prop = new RoleProperty();
         $prop->roleId = $role->id;
         $prop->name = $name;
         $prop->value = $value;
         $prop->save();
     }
     $role->description = $description;
     $role->isQuickStart = $isQuickStart;
     $role->isDeprecated = $isDeprecated;
     foreach ($images as $i) {
         if (isset($i['platform']) && isset($i['cloudLocation']) && isset($i['imageId'])) {
             $role->setImage($i['platform'], $i['cloudLocation'], $i['imageId'], $this->user->getId(), $this->user->getEmail());
         }
     }
     $role->setScripts((array) $scripts);
     $role->save();
     if ($this->request->getScope() == ScopeInterface::SCOPE_ACCOUNT) {
         foreach (RoleEnvironment::find([['roleId' => $roleId]]) as $re) {
             $re->delete();
         }
         $accountEnvironments = [];
         $allowedEnvironments = [];
         foreach (Environment::find([['accountId' => $this->user->getAccountId()]]) as $env) {
             $accountEnvironments[] = $env->id;
         }
         foreach ($environments as $e) {
             if ($e['enabled'] == 1 && in_array($e['id'], $accountEnvironments)) {
                 $allowedEnvironments[] = $e['id'];
             }
         }
         if (count($allowedEnvironments) < count($accountEnvironments)) {
             foreach ($allowedEnvironments as $id) {
                 $re = new RoleEnvironment();
                 $re->roleId = $role->id;
                 $re->envId = $id;
                 $re->save();
             }
         }
     }
     $this->response->data(['role' => $this->getInfo($role->id, true), 'categories' => $this->listRoleCategories(true)]);
     $this->response->success('Role saved');
 }
Beispiel #15
0
 public function xExecuteAction()
 {
     $this->request->restrictAccess(Acl::RESOURCE_FARMS_SCRIPTS, Acl::PERM_FARMS_SCRIPTS_EXECUTE);
     $this->request->defineParams(array('farmId' => array('type' => 'int'), 'farmRoleId' => array('type' => 'int'), 'serverId' => array('type' => 'string'), 'scriptId' => array('type' => 'int'), 'scriptIsSync' => array('type' => 'int'), 'scriptTimeout' => array('type' => 'int'), 'scriptVersion' => array('type' => 'int'), 'scriptOptions' => array('type' => 'array'), 'createMenuLink' => array('type' => 'int')));
     $eventName = Scalr_Scripting_Manager::generateEventName('CustomEvent');
     if ($this->getParam('serverId')) {
         $dbServer = DBServer::LoadByID($this->getParam('serverId'));
         $this->user->getPermissions()->validate($dbServer);
         $target = Scalr_Script::TARGET_INSTANCE;
         $serverId = $dbServer->serverId;
         $farmRoleId = $dbServer->farmRoleId;
         $farmId = $dbServer->farmId;
     } else {
         if ($this->getParam('farmRoleId')) {
             $dbFarmRole = DBFarmRole::LoadByID($this->getParam('farmRoleId'));
             $this->user->getPermissions()->validate($dbFarmRole);
             $target = Scalr_Script::TARGET_ROLE;
             $farmRoleId = $dbFarmRole->ID;
             $farmId = $dbFarmRole->FarmID;
         } else {
             if (!$this->getParam('farmId')) {
                 $target = Scalr_Script::TARGET_ALL;
             } else {
                 $dbFarm = DBFarm::LoadByID($this->getParam('farmId'));
                 $this->user->getPermissions()->validate($dbFarm);
                 $target = Scalr_Script::TARGET_FARM;
                 $farmId = $dbFarm->ID;
             }
         }
     }
     if (!$this->getParam('eventName')) {
         if ($this->getParam('createMenuLink')) {
             $this->db->Execute("INSERT INTO farm_role_scripts SET\n                    scriptid\t= ?,\n                    farmid\t\t= ?,\n                    farm_roleid\t= ?,\n                    params\t\t= ?,\n                    event_name\t= ?,\n                    target\t\t= ?,\n                    version\t\t= ?,\n                    timeout\t\t= ?,\n                    issync\t\t= ?,\n                    ismenuitem\t= ?\n                ", array($this->getParam('scriptId'), (int) $farmId, (int) $farmRoleId, serialize($this->getParam('scriptOptions')), $eventName, $target, $this->getParam('scriptVersion'), $this->getParam('scriptTimeout'), $this->getParam('scriptIsSync'), $this->getParam('createMenuLink')));
         }
         $farmScriptId = $this->db->Insert_ID();
         $executeScript = true;
     } else {
         $info = $this->db->Execute("SELECT farmid FROM farm_role_scripts WHERE event_name=?", array($this->getParam('eventName')));
         if ($info['farmid'] != $dbFarm->ID) {
             throw new Exception("You cannot change farm for script shortcut");
         }
         if ($this->getParam('isShortcut')) {
             $this->db->Execute("UPDATE farm_role_scripts SET\n                    scriptid\t= ?,\n                    farm_roleid\t= ?,\n                    params\t\t= ?,\n                    target\t\t= ?,\n                    version\t\t= ?,\n                    timeout\t\t= ?,\n                    issync\t\t= ?\n                WHERE event_name = ? AND farmid = ?\n                ", array($this->getParam('scriptId'), (int) $farmRoleId, serialize($this->getParam('scriptOptions')), $target, $this->getParam('scriptVersion'), $this->getParam('scriptTimeout'), $this->getParam('scriptIsSync'), $this->getParam('eventName'), $farmId));
         }
         if (!$this->getParam('isShortcut')) {
             $executeScript = true;
         }
     }
     if ($executeScript) {
         switch ($target) {
             case Scalr_Script::TARGET_FARM:
                 $servers = $this->db->GetAll("SELECT server_id FROM servers WHERE status IN (?,?) AND farm_id=?", array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, $farmId));
                 break;
             case Scalr_Script::TARGET_ROLE:
                 $servers = $this->db->GetAll("SELECT server_id FROM servers WHERE status IN (?,?) AND farm_roleid=?", array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, $farmRoleId));
                 break;
             case Scalr_Script::TARGET_INSTANCE:
                 $servers = $this->db->GetAll("SELECT server_id FROM servers WHERE status IN (?,?) AND server_id=?", array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, $serverId));
                 break;
             case Scalr_Script::TARGET_ALL:
                 $servers = $this->db->GetAll("SELECT server_id FROM servers WHERE status IN (?,?) AND env_id = ?", array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, $this->getEnvironmentId()));
                 break;
         }
         $scriptSettings = array('version' => $this->getParam('scriptVersion'), 'scriptid' => $this->getParam('scriptId'), 'timeout' => $this->getParam('scriptTimeout'), 'issync' => $this->getParam('scriptIsSync'), 'params' => serialize($this->getParam('scriptOptions')));
         // send message to start executing task (starts script)
         if (count($servers) > 0) {
             foreach ($servers as $server) {
                 $DBServer = DBServer::LoadByID($server['server_id']);
                 $msg = new Scalr_Messaging_Msg_ExecScript("Manual");
                 $msg->setServerMetaData($DBServer);
                 $script = Scalr_Scripting_Manager::prepareScript($scriptSettings, $DBServer);
                 $itm = new stdClass();
                 // Script
                 $itm->asynchronous = $script['issync'] == 1 ? '0' : '1';
                 $itm->timeout = $script['timeout'];
                 if ($script['body']) {
                     $itm->name = $script['name'];
                     $itm->body = $script['body'];
                 } else {
                     $itm->path = $script['path'];
                 }
                 $itm->executionId = $script['execution_id'];
                 $msg->scripts = array($itm);
                 try {
                     $msg->globalVariables = array();
                     $globalVariables = new Scalr_Scripting_GlobalVariables($DBServer->envId);
                     $vars = $globalVariables->listVariables($DBServer->roleId, $DBServer->farmId, $DBServer->farmRoleId);
                     foreach ($vars as $k => $v) {
                         $msg->globalVariables[] = (object) array('name' => $k, 'value' => $v);
                     }
                 } catch (Exception $e) {
                 }
                 $DBServer->SendMessage($msg, false, true);
             }
         }
     }
     $this->response->success('Script execution has been queued. Script will be executed on selected instance(s) within couple of minutes.');
 }
Beispiel #16
0
 public function getFarm2($farmId)
 {
     $dbFarm = DBFarm::LoadByID($farmId);
     $this->user->getPermissions()->validate($dbFarm);
     $farmRoles = array();
     $variables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARM);
     $farmRoleVariables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARMROLE);
     foreach ($dbFarm->GetFarmRoles() as $dbFarmRole) {
         $scripts = $this->db->GetAll("\n                SELECT farm_role_scripts.*, scripts.name, scripts.os\n                FROM farm_role_scripts\n                LEFT JOIN scripts ON scripts.id = farm_role_scripts.scriptid\n                WHERE farm_roleid=? AND issystem='1'\n            ", array($dbFarmRole->ID));
         $scriptsObject = array();
         foreach ($scripts as $script) {
             if (!empty($script['scriptid']) && $script['script_type'] == Scalr_Scripting_Manager::ORCHESTRATION_SCRIPT_TYPE_SCALR || !empty($script['script_path']) && $script['script_type'] == Scalr_Scripting_Manager::ORCHESTRATION_SCRIPT_TYPE_LOCAL || !empty($script['params']) && $script['script_type'] == Scalr_Scripting_Manager::ORCHESTRATION_SCRIPT_TYPE_CHEF) {
                 $s = array('script_type' => $script['script_type'], 'script_id' => (int) $script['scriptid'], 'script' => $script['name'], 'os' => $script['os'], 'params' => unserialize($script['params']), 'target' => $script['target'], 'version' => (int) $script['version'], 'timeout' => $script['timeout'], 'isSync' => (int) $script['issync'], 'order_index' => $script['order_index'], 'event' => $script['event_name'], 'script_path' => $script['script_path'], 'run_as' => $script['run_as']);
                 if ($script['target'] == Script::TARGET_BEHAVIORS || $script['target'] == Script::TARGET_ROLES || $script['target'] == Script::TARGET_FARMROLES) {
                     switch ($script['target']) {
                         case $script['target'] == Script::TARGET_ROLES:
                             $varName = 'target_roles';
                             break;
                         case $script['target'] == Script::TARGET_FARMROLES:
                             $varName = 'target_farmroles';
                             break;
                         case $script['target'] == Script::TARGET_BEHAVIORS:
                             $varName = 'target_behaviors';
                             break;
                     }
                     $s[$varName] = array();
                     $r = $this->db->GetAll("SELECT `target` FROM farm_role_scripting_targets WHERE farm_role_script_id = ?", array($script['id']));
                     foreach ($r as $v) {
                         array_push($s[$varName], $v['target']);
                     }
                 }
                 $scriptsObject[] = $s;
             }
         }
         //Scripting params
         $scriptingParams = $this->db->Execute("\n                SELECT * FROM farm_role_scripting_params\n                WHERE farm_role_id = ? AND farm_role_script_id = '0'\n            ", array($dbFarmRole->ID));
         $sParams = array();
         while ($p = $scriptingParams->FetchRow()) {
             $sParams[] = array('hash' => $p['hash'], 'role_script_id' => $p['role_script_id'], 'params' => unserialize($p['params']));
         }
         $scalingManager = new Scalr_Scaling_Manager($dbFarmRole);
         $scaling = array();
         foreach ($scalingManager->getFarmRoleMetrics() as $farmRoleMetric) {
             $scaling[$farmRoleMetric->metricId] = $farmRoleMetric->getSettings();
         }
         $dbPresets = $this->db->GetAll("SELECT * FROM farm_role_service_config_presets WHERE farm_roleid=?", array($dbFarmRole->ID));
         $presets = array();
         foreach ($dbPresets as $preset) {
             $presets[$preset['behavior']] = $preset['preset_id'];
         }
         if ($dbFarmRole->NewRoleID) {
             $roleName = DBRole::loadById($dbFarmRole->NewRoleID)->name;
             $isBundling = true;
         } else {
             $roleName = $dbFarmRole->GetRoleObject()->name;
             $isBundling = false;
         }
         $storages = array('configs' => $dbFarmRole->getStorage()->getConfigs());
         foreach ($dbFarmRole->getStorage()->getVolumes() as $configKey => $config) {
             $storages['devices'][$configKey] = array();
             foreach ($config as $device) {
                 $info = array('farmRoleId' => $device->farmRoleId, 'placement' => $device->placement, 'serverIndex' => $device->serverIndex, 'storageId' => $device->storageId, 'storageConfigId' => $device->storageConfigId, 'status' => $device->status);
                 try {
                     $server = DBServer::LoadByFarmRoleIDAndIndex($device->farmRoleId, $device->serverIndex);
                     if ($server->status != SERVER_STATUS::TERMINATED && $server->status != SERVER_STATUS::TROUBLESHOOTING) {
                         $info['serverId'] = $server->serverId;
                         $info['serverInstanceId'] = $server->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID);
                     }
                 } catch (Exception $e) {
                     $this->response->debugException($e);
                 }
                 $storages['devices'][$configKey][] = $info;
             }
         }
         $image = $dbFarmRole->GetRoleObject()->__getNewRoleObject()->getImage($dbFarmRole->Platform, $dbFarmRole->CloudLocation);
         $securityGroups = $this->getInitialSecurityGroupsList($dbFarmRole);
         $farmRoles[] = array('farm_role_id' => $dbFarmRole->ID, 'alias' => $dbFarmRole->Alias ? $dbFarmRole->Alias : $dbFarmRole->GetRoleObject()->name, 'role_id' => $dbFarmRole->RoleID, 'platform' => $dbFarmRole->Platform, 'os' => $dbFarmRole->GetRoleObject()->getOs()->name, 'os_family' => $dbFarmRole->GetRoleObject()->getOs()->family, 'os_generation' => $dbFarmRole->GetRoleObject()->getOs()->generation, 'os_version' => $dbFarmRole->GetRoleObject()->getOs()->version, 'osId' => $dbFarmRole->GetRoleObject()->getOs()->id, 'generation' => $dbFarmRole->GetRoleObject()->generation, 'group' => $dbFarmRole->GetRoleObject()->getCategoryName(), 'cat_id' => $dbFarmRole->GetRoleObject()->catId, 'name' => $roleName, 'is_bundle_running' => $isBundling, 'behaviors' => implode(",", $dbFarmRole->GetRoleObject()->getBehaviors()), 'scripting' => $scriptsObject, 'scripting_params' => $sParams, 'settings' => $dbFarmRole->GetAllSettings(), 'cloud_location' => $dbFarmRole->CloudLocation, 'launch_index' => (int) $dbFarmRole->LaunchIndex, 'scaling' => $scaling, 'config_presets' => $presets, 'image' => $image->getImage(), 'storages' => $storages, 'variables' => $farmRoleVariables->getValues($dbFarmRole->GetRoleID(), $dbFarm->ID, $dbFarmRole->ID), 'running_servers' => $dbFarmRole->GetRunningInstancesCount(), 'suspended_servers' => $dbFarmRole->GetSuspendedInstancesCount(), 'security_groups' => $securityGroups, 'hourly_rate' => $this->getInstanceTypeHourlyRate($dbFarmRole->Platform, $dbFarmRole->CloudLocation, $dbFarmRole->getInstanceType(), $dbFarmRole->GetRoleObject()->osFamily));
     }
     $vpc = array();
     if ($dbFarm->GetSetting(DBFarm::SETTING_EC2_VPC_ID)) {
         $vpc = array('id' => $dbFarm->GetSetting(DBFarm::SETTING_EC2_VPC_ID), 'region' => $dbFarm->GetSetting(DBFarm::SETTING_EC2_VPC_REGION));
     }
     $farmOwnerEditable = $dbFarm->createdByUserId == $this->user->getId() || $this->user->isAccountOwner() || $this->request->isFarmAllowed($dbFarm, Acl::PERM_FARMS_CHANGE_OWNERSHIP);
     return array('farm' => array('name' => $dbFarm->Name, 'description' => $dbFarm->Comments, 'rolesLaunchOrder' => $dbFarm->RolesLaunchOrder, 'timezone' => $dbFarm->GetSetting(DBFarm::SETTING_TIMEZONE), 'variables' => $variables->getValues(0, $dbFarm->ID), 'vpc' => $vpc, 'status' => $dbFarm->Status, 'hash' => $dbFarm->Hash, 'owner' => $farmOwnerEditable ? $dbFarm->createdByUserId : $dbFarm->createdByUserEmail, 'ownerEditable' => $farmOwnerEditable, 'teamOwner' => $farmOwnerEditable ? $dbFarm->teamId : ($dbFarm->teamId ? (new Scalr_Account_Team())->loadById($dbFarm->teamId)->name : ''), 'teamOwnerEditable' => $farmOwnerEditable, 'launchPermission' => $this->request->isFarmAllowed($dbFarm, Acl::PERM_FARMS_LAUNCH_TERMINATE), DBFarm::SETTING_SZR_UPD_REPOSITORY => $dbFarm->GetSetting(DBFarm::SETTING_SZR_UPD_REPOSITORY), DBFarm::SETTING_SZR_UPD_SCHEDULE => $dbFarm->GetSetting(DBFarm::SETTING_SZR_UPD_SCHEDULE)), 'roles' => $farmRoles, 'lock' => $dbFarm->isLocked(false), 'changed' => $dbFarm->changedTime);
 }
Beispiel #17
0
 /**
  * @param int $farmId optional
  * @param int $roleId optional
  * @param string $scalrPageHash optional
  * @param string $scalrPageUiHash optional
  * @throws Scalr_Exception_InsufficientPermissions
  */
 public function xGetFarmAction($farmId = null, $roleId = null, $scalrPageHash = null, $scalrPageUiHash = null)
 {
     if ($scalrPageHash && $scalrPageHash != $this->calcFarmDesignerHash()) {
         $this->response->data(['scalrPageHashMismatch' => true]);
         return;
     }
     if ($scalrPageUiHash && $scalrPageUiHash != $this->response->pageUiHash()) {
         $this->response->data(['scalrPageUiHashMismatch' => true]);
         return;
     }
     $moduleParams = array('farmId' => $farmId, 'roleId' => $roleId, 'behaviors' => ROLE_BEHAVIORS::GetName(null, true));
     unset($moduleParams['behaviors'][ROLE_BEHAVIORS::CASSANDRA]);
     unset($moduleParams['behaviors'][ROLE_BEHAVIORS::CUSTOM]);
     unset($moduleParams['behaviors'][ROLE_BEHAVIORS::HAPROXY]);
     //platforms list
     $platforms = self::loadController('Platforms')->getEnabledPlatforms();
     if (empty($platforms)) {
         throw new Exception('Before building new farm you need to configure environment and setup cloud credentials');
     }
     $moduleParams['categories'] = self::loadController('Roles')->listRoleCategories(true, true);
     $moduleParams['farmVpcEc2Enabled'] = $this->getEnvironment()->isPlatformEnabled(SERVER_PLATFORMS::EC2);
     if ($moduleParams['farmVpcEc2Enabled']) {
         $moduleParams['farmVpcEc2Locations'] = self::loadController('Platforms')->getCloudLocations(SERVER_PLATFORMS::EC2, false);
     }
     if ($farmId) {
         $this->request->checkPermissions(DBFarm::LoadByID($farmId)->__getNewFarmObject(), Acl::PERM_FARMS_UPDATE);
         $c = self::loadController('Builder', 'Scalr_UI_Controller_Farms');
         $moduleParams['farm'] = $c->getFarm2($farmId);
     } else {
         $this->request->restrictAccess(Acl::RESOURCE_OWN_FARMS, Acl::PERM_FARMS_CREATE);
         // TODO: remove hack, do better
         $vars = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), ScopeInterface::SCOPE_FARM);
         $moduleParams['farmVariables'] = $vars->getValues();
     }
     $moduleParams['tabs'] = array('vpcrouter', 'dbmsr', 'mongodb', 'mysql', 'scaling', 'network', 'cloudfoundry', 'rabbitmq', 'haproxy', 'proxy', 'scripting', 'ec2', 'openstack', 'gce', 'azure', 'security', 'devel', 'storage', 'variables', 'advanced', 'chef');
     //deprecated tabs
     if (\Scalr::config('scalr.ui.show_deprecated_features')) {
         $moduleParams['tabs'][] = 'ebs';
     }
     $conf = $this->getContainer()->config->get('scalr.load_statistics.connections.plotter');
     $moduleParams['tabParams'] = array('farmId' => $farmId, 'farmHash' => $moduleParams['farm'] ? $moduleParams['farm']['farm']['hash'] : '', 'accountId' => $this->environment->keychain(SERVER_PLATFORMS::EC2)->properties[Entity\CloudCredentialsProperty::AWS_ACCOUNT_ID], 'remoteAddress' => $this->request->getRemoteAddr(), 'monitoringHostUrl' => "{$conf['scheme']}://{$conf['host']}:{$conf['port']}", 'nginx' => array('server_section' => file_get_contents(APPPATH . '/templates/services/nginx/server_section.tpl'), 'server_section_ssl' => file_get_contents(APPPATH . '/templates/services/nginx/server_section_ssl.tpl')));
     $moduleParams['tabParams']['scalr.instances_connection_policy'] = \Scalr::config('scalr.instances_connection_policy');
     $moduleParams['tabParams']['scalr.scalarizr_update.default_repo'] = \Scalr::config('scalr.scalarizr_update.default_repo');
     if (Scalr::isHostedScalr()) {
         $moduleParams['tabParams']['scalr.scalarizr_update.repos'] = ['latest' => Utils::getScalarizrUpdateRepoTitle('latest')];
         if ($this->user->getAccount()->priority == 100) {
             $moduleParams['tabParams']['scalr.scalarizr_update.repos']['stable'] = Utils::getScalarizrUpdateRepoTitle('stable');
         }
     } else {
         $repos = array_keys(\Scalr::config('scalr.scalarizr_update.repos'));
         $moduleParams['tabParams']['scalr.scalarizr_update.repos'] = array_combine($repos, $repos);
     }
     $moduleParams['tabParams']['scalr.scalarizr_update.devel_repos'] = is_array(\Scalr::config('scalr.scalarizr_update.devel_repos')) ? array_keys(\Scalr::config('scalr.scalarizr_update.devel_repos')) : [];
     $moduleParams['tabParams']['scalr.aws.ec2.limits.security_groups_per_instance'] = \Scalr::config('scalr.aws.ec2.limits.security_groups_per_instance');
     $moduleParams['metrics'] = Entity\ScalingMetric::getList($this->getEnvironmentId());
     $moduleParams['timezones_list'] = Scalr_Util_DateTime::getTimezones();
     $moduleParams['timezone_default'] = $this->user->getSetting(Scalr_Account_User::SETTING_UI_TIMEZONE);
     if ($moduleParams['farm']['farm']['ownerEditable']) {
         $moduleParams['usersList'] = [];
         foreach (Entity\Account\User::findByAccountId($this->user->getAccountId()) as $user) {
             $moduleParams['usersList'][] = ['id' => $user->id, 'email' => $user->email];
         }
     }
     $defaultFarmRoleSecurityGroups = array('default');
     if (\Scalr::config('scalr.aws.security_group_name')) {
         $defaultFarmRoleSecurityGroups[] = \Scalr::config('scalr.aws.security_group_name');
     }
     $moduleParams['roleDefaultSettings'] = array('base.keep_scripting_logs_time' => \Scalr::config('scalr.system.scripting.default_instance_log_rotation_period'), 'security_groups.list' => json_encode($defaultFarmRoleSecurityGroups), 'base.abort_init_on_script_fail' => \Scalr::config('scalr.system.scripting.default_abort_init_on_script_fail') ? 1 : 0, 'base.disable_firewall_management' => \Scalr::config('scalr.system.default_disable_firewall_management') ? 1 : 0);
     //cost analytics
     if ($this->getContainer()->analytics->enabled && $this->getEnvironment()->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID)) {
         $farmCostData = $this->getFarmCostData($farmId);
         $moduleParams['analytics'] = $farmCostData['analytics'];
         if ($farmId) {
             $moduleParams['farm']['farm']['projectId'] = $farmCostData['projectId'];
             $moduleParams['analytics']['farmCostMetering'] = $farmCostData['farmCostMetering'];
         }
     }
     $moduleParams['farmLaunchPermission'] = $farmId ? $moduleParams['farm']['farm']['launchPermission'] : $this->request->isAllowed([Acl::RESOURCE_FARMS, Acl::RESOURCE_TEAM_FARMS, Acl::RESOURCE_OWN_FARMS], Acl::PERM_FARMS_LAUNCH_TERMINATE);
     $this->response->data($moduleParams);
 }
Beispiel #18
0
 public function xSave2Action()
 {
     $this->request->restrictAccess(Acl::RESOURCE_FARMS_ROLES, Acl::PERM_FARMS_ROLES_MANAGE);
     $this->request->defineParams(array('roleId' => array('type' => 'int'), 'behaviors' => array('type' => 'array'), 'tags' => array('type' => 'array'), 'description', 'name', 'os', 'parameters' => array('type' => 'json'), 'removedImages' => array('type' => 'json'), 'images' => array('type' => 'json'), 'properties' => array('type' => 'json'), 'scripts' => array('type' => 'json'), 'chef' => array('type' => 'json')));
     $id = $this->getParam('roleId');
     if ($id == 0) {
         if ($this->user->isScalrAdmin()) {
             $origin = ROLE_TYPE::SHARED;
             $envId = 0;
             $clientId = 0;
         } else {
             $origin = ROLE_TYPE::CUSTOM;
             $envId = $this->environment->id;
             $clientId = $this->user->getAccountId();
         }
         $dbRole = new DBRole(0);
         $dbRole->generation = 2;
         $dbRole->origin = $origin;
         $dbRole->envId = $envId;
         $dbRole->clientId = $clientId;
         $dbRole->catId = $this->getParam('catId');
         $dbRole->name = $this->getParam('name');
         $dbRole->os = $this->getParam('os');
         $dbRole->osGeneration = $this->getParam('osGeneration');
         $dbRole->osFamily = $this->getParam('osFamily');
         $dbRole->osVersion = $this->getParam('osVersion');
         $dbRole->addedByEmail = $this->user->getEmail();
         $dbRole->addedByUserId = $this->user->getId();
         $dbRole->save();
         $dbRole->setBehaviors(array_values($this->getParam('behaviors')));
     } else {
         $dbRole = DBRole::loadById($id);
         if (!$this->user->isScalrAdmin()) {
             $this->user->getPermissions()->validate($dbRole);
         }
     }
     if ($dbRole->origin == ROLE_TYPE::CUSTOM) {
         $variables = new Scalr_Scripting_GlobalVariables($this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_ROLE);
         $variables->setValues(json_decode($this->getParam('variables'), true), $dbRole->id);
     }
     $dbRole->description = $this->getParam('description');
     foreach ($this->getParam('removedImages') as $imageId) {
         $dbRole->removeImage($imageId);
     }
     foreach ($this->getParam('images') as $image) {
         $image = (array) $image;
         $dbRole->setImage($image['image_id'], $image['platform'], $image['location'], $image['szr_version'], $image['architecture']);
     }
     $dbRole->setScripts($this->getParam('scripts'));
     //todo
     //$dbRole->setChefSettings($this->getParam('chef'));
     if ($this->user->isScalrAdmin()) {
         $dbRole->setTags($this->getParam('tags'));
     }
     $dbRole->save();
     $this->response->success('Role saved');
 }
Beispiel #19
0
 /**
  * @param int $farmId optional
  * @param int $roleId optional
  * @param string $scalrPageHash optional
  * @param string $scalrPageUiHash optional
  * @throws Scalr_Exception_InsufficientPermissions
  */
 public function xGetFarmAction($farmId = null, $roleId = null, $scalrPageHash = null, $scalrPageUiHash = null)
 {
     if ($scalrPageHash && $scalrPageHash != $this->calcFarmDesignerHash()) {
         $this->response->data(['scalrPageHashMismatch' => true]);
         return;
     }
     if ($scalrPageUiHash && $scalrPageUiHash != $this->response->pageUiHash()) {
         $this->response->data(['scalrPageUiHashMismatch' => true]);
         return;
     }
     $moduleParams = array('farmId' => $farmId, 'roleId' => $roleId, 'behaviors' => ROLE_BEHAVIORS::GetName(null, true));
     unset($moduleParams['behaviors'][ROLE_BEHAVIORS::CASSANDRA]);
     unset($moduleParams['behaviors'][ROLE_BEHAVIORS::CUSTOM]);
     unset($moduleParams['behaviors'][ROLE_BEHAVIORS::HAPROXY]);
     //platforms list
     $platforms = self::loadController('Platforms')->getEnabledPlatforms();
     if (empty($platforms)) {
         throw new Exception('Before building new farm you need to configure environment and setup cloud credentials');
     }
     //categories list
     $categories = $this->db->GetAll("SELECT c.id, c.name, COUNT(DISTINCT r.id) AS total\n             FROM role_categories c\n             LEFT JOIN roles r ON c.id = r.cat_id AND (r.env_id IS NULL OR r.env_id = ?) AND r.id IN (\n                SELECT role_id\n                FROM role_images\n                WHERE role_id = r.id\n                AND platform IN ('" . implode("','", array_keys($platforms)) . "')\n             )\n             WHERE c.env_id IS NULL OR c.env_id = ?\n             GROUP BY c.id\n            ", array($this->environment->id, $this->environment->id));
     $moduleParams['categories'] = array();
     foreach ($categories as $g) {
         $moduleParams['categories'][$g['id']] = $g;
     }
     $moduleParams['farmVpcEc2Enabled'] = $this->getEnvironment()->isPlatformEnabled(SERVER_PLATFORMS::EC2);
     if ($moduleParams['farmVpcEc2Enabled']) {
         $moduleParams['farmVpcEc2Locations'] = self::loadController('Platforms')->getCloudLocations(SERVER_PLATFORMS::EC2, false);
     }
     if ($farmId) {
         $this->request->restrictFarmAccess(DBFarm::LoadByID($farmId), Acl::PERM_FARMS_MANAGE);
         $c = self::loadController('Builder', 'Scalr_UI_Controller_Farms');
         $moduleParams['farm'] = $c->getFarm2($farmId);
     } else {
         $this->request->restrictFarmAccess(null, Acl::PERM_FARMS_MANAGE);
         // TODO: remove hack, do better
         $vars = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), ScopeInterface::SCOPE_FARM);
         $moduleParams['farmVariables'] = $vars->getValues();
     }
     $moduleParams['tabs'] = array('vpcrouter', 'dbmsr', 'mongodb', 'mysql', 'scaling', 'network', 'cloudfoundry', 'rabbitmq', 'haproxy', 'proxy', 'scripting', 'ec2', 'openstack', 'gce', 'azure', 'security', 'devel', 'storage', 'variables', 'advanced', 'chef');
     //deprecated tabs
     if (\Scalr::config('scalr.ui.show_deprecated_features')) {
         $moduleParams['tabs'][] = 'deployments';
         $moduleParams['tabs'][] = 'ebs';
         $moduleParams['tabs'][] = 'servicesconfig';
     }
     $conf = $this->getContainer()->config->get('scalr.load_statistics.connections.plotter');
     $moduleParams['tabParams'] = array('farmId' => $farmId, 'farmHash' => $moduleParams['farm'] ? $moduleParams['farm']['farm']['hash'] : '', 'accountId' => $this->environment->cloudCredentials(SERVER_PLATFORMS::EC2)->properties[Entity\CloudCredentialsProperty::AWS_ACCOUNT_ID], 'remoteAddress' => $this->request->getRemoteAddr(), 'monitoringHostUrl' => "{$conf['scheme']}://{$conf['host']}:{$conf['port']}", 'nginx' => array('server_section' => file_get_contents(APPPATH . '/templates/services/nginx/server_section.tpl'), 'server_section_ssl' => file_get_contents(APPPATH . '/templates/services/nginx/server_section_ssl.tpl')));
     $moduleParams['tabParams']['scalr.dns.global.enabled'] = \Scalr::config('scalr.dns.global.enabled');
     $moduleParams['tabParams']['scalr.instances_connection_policy'] = \Scalr::config('scalr.instances_connection_policy');
     $moduleParams['tabParams']['scalr.scalarizr_update.repos'] = array_keys(\Scalr::config('scalr.scalarizr_update.repos'));
     $moduleParams['tabParams']['scalr.scalarizr_update.devel_repos'] = is_array(\Scalr::config('scalr.scalarizr_update.devel_repos')) ? array_keys(\Scalr::config('scalr.scalarizr_update.devel_repos')) : [];
     $moduleParams['tabParams']['scalr.scalarizr_update.default_repo'] = \Scalr::config('scalr.scalarizr_update.default_repo');
     $moduleParams['tabParams']['scalr.aws.ec2.limits.security_groups_per_instance'] = \Scalr::config('scalr.aws.ec2.limits.security_groups_per_instance');
     $moduleParams['metrics'] = Entity\ScalingMetric::getList($this->getEnvironmentId());
     $moduleParams['timezones_list'] = Scalr_Util_DateTime::getTimezones();
     $moduleParams['timezone_default'] = $this->user->getSetting(Scalr_Account_User::SETTING_UI_TIMEZONE);
     if ($moduleParams['farm']['farm']['ownerEditable']) {
         $moduleParams['usersList'] = Scalr_Account_User::getList($this->user->getAccountId());
     }
     $defaultFarmRoleSecurityGroups = array('default');
     if (\Scalr::config('scalr.aws.security_group_name')) {
         $defaultFarmRoleSecurityGroups[] = \Scalr::config('scalr.aws.security_group_name');
     }
     $moduleParams['roleDefaultSettings'] = array('base.keep_scripting_logs_time' => \Scalr::config('scalr.system.scripting.default_instance_log_rotation_period'), 'security_groups.list' => json_encode($defaultFarmRoleSecurityGroups), 'base.abort_init_on_script_fail' => \Scalr::config('scalr.system.scripting.default_abort_init_on_script_fail') ? 1 : 0, 'base.disable_firewall_management' => \Scalr::config('scalr.system.default_disable_firewall_management') ? 1 : 0);
     //cost analytics
     if ($this->getContainer()->analytics->enabled && $this->getEnvironment()->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID)) {
         $farmCostData = $this->getFarmCostData($farmId);
         $moduleParams['analytics'] = $farmCostData['analytics'];
         if ($farmId) {
             $moduleParams['farm']['farm']['projectId'] = $farmCostData['projectId'];
             $moduleParams['analytics']['farmCostMetering'] = $farmCostData['farmCostMetering'];
         }
     }
     $moduleParams['farmLaunchPermission'] = $farmId ? $moduleParams['farm']['farm']['launchPermission'] : $this->request->isFarmAllowed(null, Acl::PERM_FARMS_LAUNCH_TERMINATE);
     if ($moduleParams['farm']['farm']['teamOwnerEditable'] || !$farmId) {
         if ($this->user->canManageAcl()) {
             $teams = $this->db->getAll('SELECT id, name, description FROM account_teams WHERE account_id = ?', array($this->user->getAccountId()));
         } else {
             $teams = $this->user->getTeams();
             $teamId = $moduleParams['farm']['farm']['teamOwner'];
             $flag = !!$teamId;
             foreach ($teams as $t) {
                 if ($t['id'] == $teamId) {
                     $flag = false;
                     break;
                 }
             }
             if ($flag) {
                 // team is missed in list, add manually
                 $team = $this->db->GetRow('SELECT name, description FROM account_teams WHERE id = ?', [$teamId]);
                 array_unshift($teams, ['id' => $teamId, 'name' => $team ? $team['name'] : '', 'description' => $team ? $team['description'] : '']);
             }
         }
         array_unshift($teams, ['id' => 0, 'name' => '']);
         $moduleParams['teamsList'] = $teams;
     }
     $this->response->data($moduleParams);
 }
Beispiel #20
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;
 }
Beispiel #21
0
 public function buildAction()
 {
     $this->request->restrictAccess(Acl::RESOURCE_FARMS, Acl::PERM_FARMS_MANAGE);
     $this->request->defineParams(array('farmId' => array('type' => 'int'), 'roleId' => array('type' => 'int')));
     $farmId = $this->getParam('farmId');
     $roleId = $this->getParam('roleId');
     $moduleParams = array('farmId' => $farmId, 'roleId' => $roleId, 'behaviors' => ROLE_BEHAVIORS::GetName(null, true));
     unset($moduleParams['behaviors'][ROLE_BEHAVIORS::CASSANDRA]);
     unset($moduleParams['behaviors'][ROLE_BEHAVIORS::CUSTOM]);
     unset($moduleParams['behaviors'][ROLE_BEHAVIORS::HAPROXY]);
     //platforms list
     $platforms = self::loadController('Platforms')->getEnabledPlatforms();
     if (empty($platforms)) {
         throw new Exception('Before building new farm you need to configure environment and setup cloud credentials');
     }
     //categories list
     $categories = $this->db->GetAll("SELECT c.id, c.name, COUNT(DISTINCT r.id) AS total\n             FROM role_categories c\n             LEFT JOIN roles r ON c.id = r.cat_id AND r.env_id IN(0, ?) AND r.id IN (\n                SELECT role_id\n                FROM role_images\n                WHERE role_id = r.id\n                AND platform IN ('" . implode("','", array_keys($platforms)) . "')\n             )\n             LEFT JOIN roles_queue q ON r.id = q.role_id\n             WHERE c.env_id IN (0, ?)\n             AND q.id IS NULL\n             GROUP BY c.id\n            ", array($this->environment->id, $this->environment->id));
     $moduleParams['categories'] = array();
     foreach ($categories as $g) {
         $moduleParams['categories'][$g['id']] = $g;
     }
     $moduleParams['farmVpcEc2Enabled'] = $this->getEnvironment()->isPlatformEnabled(SERVER_PLATFORMS::EC2);
     if ($moduleParams['farmVpcEc2Enabled']) {
         $moduleParams['farmVpcEc2Locations'] = self::loadController('Platforms')->getCloudLocations(SERVER_PLATFORMS::EC2, false);
     }
     if ($farmId) {
         $c = self::loadController('Builder', 'Scalr_UI_Controller_Farms');
         $moduleParams['farm'] = $c->getFarm2($farmId);
     } else {
         // TODO: remove hack, do better
         $vars = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARM);
         $moduleParams['farmVariables'] = $vars->getValues();
     }
     $moduleParams['tabs'] = array('vpcrouter', 'dbmsr', 'mongodb', 'mysql', 'scaling', 'network', 'gce', 'cloudfoundry', 'rabbitmq', 'haproxy', 'proxy', 'rds', 'scripting', 'nimbula', 'ec2', 'security', 'devel', 'storage', 'variables', 'advanced');
     if ($this->user->getAccount()->isFeatureEnabled(Scalr_Limits::FEATURE_CHEF)) {
         $moduleParams['tabs'][] = 'chef';
     }
     //deprecated tabs
     $moduleParams['tabs'][] = 'deployments';
     $moduleParams['tabs'][] = 'ebs';
     $moduleParams['tabs'][] = 'params';
     $moduleParams['tabs'][] = 'servicesconfig';
     $conf = $this->getContainer()->config->get('scalr.load_statistics.connections.plotter');
     $moduleParams['tabParams'] = array('farmId' => $farmId, 'farmHash' => $moduleParams['farm'] ? $moduleParams['farm']['farm']['hash'] : '', 'accountId' => $this->environment->getPlatformConfigValue(Ec2PlatformModule::ACCOUNT_ID), 'remoteAddress' => $this->request->getRemoteAddr(), 'monitoringHostUrl' => "{$conf['scheme']}://{$conf['host']}:{$conf['port']}", 'nginx' => array('server_section' => @file_get_contents("../templates/services/nginx/server_section.tpl"), 'server_section_ssl' => @file_get_contents("../templates/services/nginx/server_section_ssl.tpl")));
     // TODO: Features
     $moduleParams['tabParams']['featureRAID'] = $this->user->getAccount()->isFeatureEnabled(Scalr_Limits::FEATURE_RAID);
     $moduleParams['tabParams']['featureMFS'] = $this->user->getAccount()->isFeatureEnabled(Scalr_Limits::FEATURE_MFS);
     $moduleParams['tabParams']['scalr.dns.global.enabled'] = \Scalr::config('scalr.dns.global.enabled');
     $moduleParams['tabParams']['scalr.instances_connection_policy'] = \Scalr::config('scalr.instances_connection_policy');
     $moduleParams['tabParams']['scalr.scalarizr_update.repos'] = array_keys(\Scalr::config('scalr.scalarizr_update.repos'));
     $moduleParams['tabParams']['scalr.scalarizr_update.default_repo'] = \Scalr::config('scalr.scalarizr_update.default_repo');
     $moduleParams['metrics'] = self::loadController('Metrics', 'Scalr_UI_Controller_Scaling')->getList();
     $moduleParams['timezones_list'] = Scalr_Util_DateTime::getTimezones();
     $moduleParams['timezone_default'] = $this->user->getSetting(Scalr_Account_User::SETTING_UI_TIMEZONE);
     if ($moduleParams['farm']['farm']['ownerEditable']) {
         $moduleParams['usersList'] = Scalr_Account_User::getList($this->user->getAccountId());
     }
     $governance = new Scalr_Governance($this->getEnvironmentId());
     $moduleParams['governance'] = $governance->getValues(true);
     $defaultFarmRoleSecurityGroups = array('default');
     if (\Scalr::config('scalr.aws.security_group_name')) {
         $defaultFarmRoleSecurityGroups[] = \Scalr::config('scalr.aws.security_group_name');
     }
     $moduleParams['roleDefaultSettings'] = array('base.keep_scripting_logs_time' => \Scalr::config('scalr.system.scripting.default_instance_log_rotation_period'), 'security_groups.list' => json_encode($defaultFarmRoleSecurityGroups));
     //cost analytics
     if ($this->getContainer()->analytics->enabled && $this->getEnvironment()->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID)) {
         $costCenter = $this->getContainer()->analytics->ccs->get($this->getEnvironment()->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID));
         $projects = [];
         if ($costCenter instanceof CostCentreEntity) {
             $projectsIterator = new SharedProjectsFilterIterator($costCenter->getProjects(), $costCenter->ccId, $this->user, $this->getEnvironment());
             foreach ($projectsIterator as $item) {
                 /* @var $item ProjectEntity */
                 $projects[] = array('projectId' => $item->projectId, 'name' => $item->name);
             }
             $costCentreName = $costCenter->name;
         } else {
             $costCentreName = '';
         }
         $moduleParams['analytics'] = array('costCenterName' => $costCentreName, 'projects' => $projects);
         if ($farmId) {
             $dbFarm = DBFarm::LoadByID($farmId);
             $moduleParams['farm']['farm']['projectId'] = $dbFarm->GetSetting(DBFarm::SETTING_PROJECT_ID);
         }
     }
     $this->response->page('ui/farms/builder.js', $moduleParams, array('ui/farms/builder/selroles.js', 'ui/farms/builder/roleedit.js', 'ui/farms/builder/roleslibrary.js', 'ui/farms/builder/tabs/dbmsr.js', 'ui/farms/builder/tabs/cloudfoundry.js', 'ui/farms/builder/tabs/rabbitmq.js', 'ui/farms/builder/tabs/mongodb.js', 'ui/farms/builder/tabs/haproxy.js', 'ui/farms/builder/tabs/proxy.js', 'ui/farms/builder/tabs/mysql.js', 'ui/farms/builder/tabs/nimbula.js', 'ui/farms/builder/tabs/rds.js', 'ui/farms/builder/tabs/gce.js', 'ui/farms/builder/tabs/scaling.js', 'ui/farms/builder/tabs/scripting.js', 'ui/farms/builder/tabs/advanced.js', 'ui/farms/builder/tabs/ec2.js', 'ui/farms/builder/tabs/security.js', 'ui/farms/builder/tabs/storage.js', 'ui/farms/builder/tabs/variables.js', 'ui/farms/builder/tabs/devel.js', 'ui/farms/builder/tabs/chef.js', 'ui/farms/builder/tabs/vpcrouter.js', 'ui/farms/builder/tabs/network.js', 'ui/farms/builder/tabs/deployments.js', 'ui/farms/builder/tabs/ebs.js', 'ui/farms/builder/tabs/params.js', 'ui/farms/builder/tabs/servicesconfig.js', 'ui/farms/builder/roleslibrary/ec2.js', 'ui/farms/builder/roleslibrary/vpc.js', 'ui/farms/builder/roleslibrary/euca.js', 'ui/farms/builder/roleslibrary/rackspace.js', 'ui/farms/builder/roleslibrary/openstack.js', 'ui/farms/builder/roleslibrary/cloudstack.js', 'ui/farms/builder/roleslibrary/gce.js', 'ui/farms/builder/roleslibrary/mongodb.js', 'ui/farms/builder/roleslibrary/dbmsr.js', 'ui/farms/builder/roleslibrary/proxy.js', 'ui/farms/builder/roleslibrary/haproxy.js', 'ui/farms/builder/roleslibrary/chef.js', 'codemirror/codemirror.js', 'ui/core/variablefield.js', 'ui/scripts/scriptfield.js', 'ux-boxselect.js', 'ui/monitoring/window.js', 'ui/services/chef/chefsettings.js', 'ui/security/groups/sgeditor.js'), array('ui/farms/builder/selroles.css', 'ui/farms/builder/roleedit.css', 'ui/farms/builder/roleslibrary.css', 'codemirror/codemirror.css', 'ui/core/variablefield.css', 'ui/scripts/scriptfield.css', 'ui/farms/builder/tabs/scaling.css'));
 }
Beispiel #22
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);
 }
Beispiel #23
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);
 }
Beispiel #24
0
 public function getDefinition()
 {
     $farmDefinition = new stdClass();
     $farmDefinition->name = $this->Name;
     $farmDefinition->rolesLaunchOrder = $this->RolesLaunchOrder;
     // Farm Roles
     $farmDefinition->roles = array();
     foreach ($this->GetFarmRoles() as $dbFarmRole) {
         $farmDefinition->roles[] = $dbFarmRole->getDefinition();
     }
     //Farm Global Variables
     $variables = new Scalr_Scripting_GlobalVariables($this->ClientID, $this->EnvID, ScopeInterface::SCOPE_FARM);
     $farmDefinition->globalVariables = $variables->getValues(0, $this->ID, 0);
     //Farm Settings
     $farmDefinition->settings = $this->GetAllSettings();
     return $farmDefinition;
 }
Beispiel #25
0
 public function xSaveAction()
 {
     $this->request->restrictAccess(Acl::RESOURCE_FARMS_ROLES, Acl::PERM_FARMS_ROLES_MANAGE);
     $this->request->defineParams(array('roleId' => array('type' => 'int'), 'behaviors' => array('type' => 'json'), 'tags' => array('type' => 'json'), 'description', 'name', 'parameters' => array('type' => 'json'), 'removedImages' => array('type' => 'json'), 'images' => array('type' => 'json'), 'properties' => array('type' => 'json'), 'scripts' => array('type' => 'json'), 'variables' => array('type' => 'json'), 'chef' => array('type' => 'json')));
     $id = $this->getParam('roleId');
     if ($id == 0) {
         if ($this->user->isScalrAdmin()) {
             $origin = ROLE_TYPE::SHARED;
             $envId = null;
             $clientId = null;
         } else {
             $origin = ROLE_TYPE::CUSTOM;
             $envId = $this->environment->id;
             $clientId = $this->user->getAccountId();
         }
         // TODO: validate role name via Scalr\Model\Entity\Role::validateName(), validate other fields
         $dbRole = new DBRole(0);
         $dbRole->generation = 2;
         $dbRole->origin = $origin;
         $dbRole->envId = $envId;
         $dbRole->clientId = $clientId;
         $dbRole->catId = $this->getParam('catId');
         $dbRole->name = $this->getParam('name');
         //TODO: VALIDATE osId
         $dbRole->osId = $this->getParam('osId');
         $dbRole->addedByEmail = $this->user->getEmail();
         $dbRole->addedByUserId = $this->user->getId();
         $dbRole->save();
         $dbRole->setBehaviors(array_values($this->getParam('behaviors')));
     } else {
         $dbRole = DBRole::loadById($id);
         if (!$this->user->isScalrAdmin()) {
             $this->user->getPermissions()->validate($dbRole);
         }
     }
     if ($dbRole->origin == ROLE_TYPE::CUSTOM && $this->user->getAccountId()) {
         $variables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_ROLE);
         $variables->setValues(is_array($this->getParam('variables')) ? $this->getParam('variables') : [], $dbRole->id);
     } else {
         if ($this->user->isScalrAdmin()) {
             $variables = new Scalr_Scripting_GlobalVariables(0, 0, Scalr_Scripting_GlobalVariables::SCOPE_ROLE);
             $variables->setValues(is_array($this->getParam('variables')) ? $this->getParam('variables') : [], $dbRole->id);
         }
     }
     $dbRole->clearProperties('chef.');
     if (!is_null($this->getParam('chef'))) {
         $dbRole->setProperties($this->getParam('chef'));
     }
     $dbRole->description = $this->getParam('description');
     $images = $this->getParam('images');
     if (!empty($images)) {
         foreach ($images as $i) {
             $dbRole->__getNewRoleObject()->setImage($i['platform'], $i['cloudLocation'], $i['imageId'], $this->user->getId(), $this->user->getEmail());
         }
     }
     $scripts = $this->getParam('scripts');
     if (is_null($scripts)) {
         $scripts = [];
     }
     $dbRole->setScripts($scripts);
     $dbRole->save();
     $this->response->data(['role' => $this->getInfo($dbRole->id, true)]);
     $this->response->success('Role saved');
 }
Beispiel #26
0
 public static function createFromBundleTask(BundleTask $BundleTask)
 {
     $db = \Scalr::getDb();
     $DBServer = DBServer::LoadByID($BundleTask->serverId);
     if ($BundleTask->prototypeRoleId) {
         $proto_role = $db->GetRow("SELECT * FROM roles WHERE id=? LIMIT 1", array($BundleTask->prototypeRoleId));
         if (!$proto_role['architecture']) {
             $proto_role['architecture'] = $DBServer->GetProperty(SERVER_PROPERTIES::ARCHITECTURE);
         }
     } else {
         $proto_role = array("behaviors" => $DBServer->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_BEHAVIOR), "architecture" => $DBServer->GetProperty(SERVER_PROPERTIES::ARCHITECTURE), "name" => "*import*");
     }
     if (!$proto_role['architecture']) {
         $proto_role['architecture'] = 'x86_64';
     }
     if (!$BundleTask->cloudLocation) {
         if ($DBServer) {
             $BundleTask->cloudLocation = $DBServer->GetCloudLocation();
         }
     }
     $osInfo = $BundleTask->getOsDetails();
     $meta = $BundleTask->getSnapshotDetails();
     if (!$osInfo->family || !$osInfo->generation) {
         $osInfo = new stdClass();
         if ($proto_role) {
             $osInfo->name = $proto_role['os'];
             $osInfo->family = $proto_role['os_family'];
             $osInfo->generation = $proto_role['os_generation'];
             $osInfo->version = $proto_role['os_version'];
         } elseif ($meta['os'] && $meta['os']->version) {
             if ($meta['os']->version == '2008Server') {
                 $osInfo->name = 'Windows 2008 Server';
                 $osInfo->family = 'windows';
                 $osInfo->generation = '2008';
                 $osInfo->version = '2008Server';
             } elseif ($meta['os']->version == '2008ServerR2') {
                 $osInfo->name = 'Windows 2008 Server R2';
                 $osInfo->family = 'windows';
                 $osInfo->generation = '2008';
                 $osInfo->version = '2008ServerR2';
             }
         }
     }
     if ($proto_role['cat_id']) {
         $catId = $proto_role['cat_id'];
     } else {
         $catId = ROLE_BEHAVIORS::GetCategoryId($proto_role['behaviors']);
     }
     $db->Execute("INSERT INTO roles SET\n            name\t\t\t= ?,\n            origin\t\t\t= ?,\n            dtadded         = NOW(),\n            client_id\t\t= ?,\n            env_id\t\t\t= ?,\n            cat_id          = ?,\n            description\t\t= ?,\n            behaviors\t\t= ?,\n            history\t\t\t= ?,\n            generation\t\t= ?,\n            added_by_email  = ?,\n            added_by_userid = ?,\n            os\t\t\t\t= ?,\n            os_family       = ?,\n            os_version      = ?,\n            os_generation   = ?\n        ", array($BundleTask->roleName, ROLE_TYPE::CUSTOM, $BundleTask->clientId, $BundleTask->envId, $catId, $BundleTask->description, $proto_role['behaviors'], trim("{$proto_role['history']},{$proto_role['name']}", ","), 2, $BundleTask->createdByEmail, $BundleTask->createdById, $osInfo->name, $osInfo->family, $osInfo->version, $osInfo->generation));
     $role_id = $db->Insert_Id();
     $BundleTask->roleId = $role_id;
     $BundleTask->Save();
     $BundleTask->Log(sprintf("Created new role. Role name: %s. Role ID: %s", $BundleTask->roleName, $BundleTask->roleId));
     $role = self::loadById($role_id);
     $behaviors = explode(",", $proto_role['behaviors']);
     foreach ($behaviors as $behavior) {
         $db->Execute("INSERT INTO role_behaviors SET\n                role_id\t\t\t= ?,\n                behavior\t\t= ?\n            ", array($role_id, $behavior));
     }
     // Set image
     $role->setImage($BundleTask->snapshotId, $BundleTask->platform, $BundleTask->platform != SERVER_PLATFORMS::GCE ? $BundleTask->cloudLocation : "", $meta['szr_version'], $proto_role['architecture']);
     // Set params
     if ($proto_role['id']) {
         $dbParams = $db->GetAll("SELECT name,type,isrequired,defval,allow_multiple_choice,options,hash,issystem\n                FROM role_parameters WHERE role_id = ?", array($proto_role['id']));
         $role->setParameters($dbParams);
         $dbSecRules = $db->GetAll("SELECT * FROM role_security_rules WHERE role_id = ?", array($proto_role['id']));
         foreach ($dbSecRules as $dbSecRule) {
             $db->Execute("INSERT INTO role_security_rules SET role_id = ?, rule = ?", array($role_id, $dbSecRule['rule']));
         }
         $props = $db->GetAll("SELECT * FROM role_properties WHERE role_id=?", array($proto_role['id']));
         foreach ($props as $prop) {
             $role->setProperty($prop['name'], $prop['value']);
         }
         $scripts = $db->GetAll("SELECT * FROM role_scripts WHERE role_id=?", array($proto_role['id']));
         foreach ($scripts as &$script) {
             $script['params'] = unserialize($script['params']);
         }
         $role->setScripts($scripts);
         $variables = new Scalr_Scripting_GlobalVariables($proto_role['env_id'], Scalr_Scripting_GlobalVariables::SCOPE_ROLE);
         $variables->setValues($variables->getValues($proto_role['id']), $role->id);
     }
     // Set software
     if ($meta) {
         $software = array();
         foreach ((array) $meta['software'] as $soft) {
             $software[$soft->name] = $soft->version;
         }
         $role->setSoftware($software);
         $role->setTags((array) $meta['tags']);
         if ($BundleTask->platform == SERVER_PLATFORMS::NIMBULA) {
             $props = array(array('name' => self::PROPERTY_NIMBULA_INIT_ROOT_USER, 'value' => $meta['init_root_user']), array('name' => self::PROPERTY_NIMBULA_INIT_ROOT_PASS, 'value' => $meta['init_root_pass']), array('name' => self::PROPERTY_NIMBULA_ENTRY, 'value' => ''));
             foreach ($props as $prop) {
                 $role->setProperty($prop['name'], $prop['value']);
             }
         }
     }
     return $role;
 }
Beispiel #27
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;
 }
Beispiel #28
0
 /**
  * @param JsonData $variables JSON encoded structure
  */
 public function xSaveVariablesAction(JsonData $variables)
 {
     if ($this->user->isAdmin()) {
         throw new Scalr_Exception_InsufficientPermissions();
     }
     $this->request->restrictAccess(Acl::RESOURCE_ENVADMINISTRATION_GLOBAL_VARIABLES);
     $vars = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_ENVIRONMENT);
     $result = $vars->setValues($variables, 0, 0, 0, '', false);
     if ($result === true) {
         $this->response->success('Variables saved');
     } else {
         $this->response->failure();
         $this->response->data(array('errors' => array('variables' => $result)));
     }
 }
Beispiel #29
0
 /**
  * Gets a specific global variable data
  *
  * @param   int                                 $farmId     Numeric identifier of the Farm
  * @param   string                              $name       Variable name
  * @param   \Scalr_Scripting_GlobalVariables    $globalVar  Instance of Global variable handler
  *
  * @return  mixed
  * @throws  ApiErrorException
  */
 private function getGlobalVariable($farmId, $name, \Scalr_Scripting_GlobalVariables $globalVar)
 {
     $list = $globalVar->getValues(0, $farmId);
     $fetch = [];
     foreach ($list as $var) {
         if (!empty($var['current']['name']) && $var['current']['name'] == $name || !empty($var['default']['name']) && $var['default']['name'] == $name) {
             $fetch = $var;
             break;
         }
     }
     return $fetch;
 }
Beispiel #30
0
 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;
 }