public setValues ( array | ArrayObject $variables, integer $roleId, integer $farmId, integer $farmRoleId, string $serverId = '', boolean $throwException = true, boolean $skipValidation = false ) : array | boolean | ||
$variables | array | ArrayObject | |
$roleId | integer | optional |
$farmId | integer | optional |
$farmRoleId | integer | optional |
$serverId | string | optional |
$throwException | boolean | optional |
$skipValidation | boolean | optional |
return | array | boolean |
public function applyDefinition($definition, $reset = false) { $resetSettings = array(Entity\FarmRoleSetting::BALANCING_USE_ELB, Entity\FarmRoleSetting::BALANCING_HOSTNAME, Entity\FarmRoleSetting::BALANCING_NAME, Entity\FarmRoleSetting::BALANCING_HC_TIMEOUT, Entity\FarmRoleSetting::BALANCING_HC_TARGET, Entity\FarmRoleSetting::BALANCING_HC_INTERVAL, Entity\FarmRoleSetting::BALANCING_HC_UTH, Entity\FarmRoleSetting::BALANCING_HC_HTH, Entity\FarmRoleSetting::BALANCING_HC_HASH, Entity\FarmRoleSetting::BALANCING_AZ_HASH, Entity\FarmRoleSetting::CLOUDSTACK_STATIC_NAT_MAP, Entity\FarmRoleSetting::AWS_ELASIC_IPS_MAP, Entity\FarmRoleSetting::AWS_S3_BUCKET, Entity\FarmRoleSetting::MYSQL_PMA_USER, Entity\FarmRoleSetting::MYSQL_PMA_PASS, Entity\FarmRoleSetting::MYSQL_PMA_REQUEST_ERROR, Entity\FarmRoleSetting::MYSQL_PMA_REQUEST_TIME, Entity\FarmRoleSetting::MYSQL_LAST_BCP_TS, Entity\FarmRoleSetting::MYSQL_LAST_BUNDLE_TS, Entity\FarmRoleSetting::MYSQL_IS_BCP_RUNNING, Entity\FarmRoleSetting::MYSQL_IS_BUNDLE_RUNNING, Entity\FarmRoleSetting::MYSQL_BCP_SERVER_ID, Entity\FarmRoleSetting::MYSQL_BUNDLE_SERVER_ID, Entity\FarmRoleSetting::MYSQL_SLAVE_TO_MASTER, Entity\FarmRoleSetting::MYSQL_ROOT_PASSWORD, Entity\FarmRoleSetting::MYSQL_REPL_PASSWORD, Entity\FarmRoleSetting::MYSQL_STAT_PASSWORD, Entity\FarmRoleSetting::MYSQL_LOG_FILE, Entity\FarmRoleSetting::MYSQL_LOG_POS, Entity\FarmRoleSetting::MYSQL_SCALR_SNAPSHOT_ID, Entity\FarmRoleSetting::MYSQL_SCALR_VOLUME_ID, Entity\FarmRoleSetting::MYSQL_SNAPSHOT_ID, Entity\FarmRoleSetting::MYSQL_MASTER_EBS_VOLUME_ID, Entity\FarmRoleSetting::AWS_ELB_ID, Entity\FarmRoleSetting::AWS_ELB_ENABLED, Scalr_Db_Msr::DATA_BACKUP_IS_RUNNING, Scalr_Db_Msr::DATA_BACKUP_LAST_TS, Scalr_Db_Msr::DATA_BACKUP_SERVER_ID, Scalr_Db_Msr::DATA_BUNDLE_IS_RUNNING, Scalr_Db_Msr::DATA_BUNDLE_LAST_TS, Scalr_Db_Msr::DATA_BUNDLE_SERVER_ID, Scalr_Db_Msr::SLAVE_TO_MASTER, Scalr_Db_Msr::SNAPSHOT_ID, Scalr_Db_Msr::VOLUME_ID, Scalr_Role_Behavior_RabbitMQ::ROLE_COOKIE_NAME, Scalr_Role_Behavior_RabbitMQ::ROLE_PASSWORD, Scalr_Role_Behavior_RabbitMQ::ROLE_CP_SERVER_ID, Scalr_Role_Behavior_RabbitMQ::ROLE_CP_REQUESTED, Scalr_Role_Behavior_RabbitMQ::ROLE_CP_REQUEST_TIME, Scalr_Role_Behavior_RabbitMQ::ROLE_CP_ERROR_MSG, Scalr_Role_Behavior_RabbitMQ::ROLE_CP_URL, Scalr_Role_Behavior_MongoDB::ROLE_PASSWORD, Scalr_Role_Behavior_MongoDB::ROLE_KEYFILE, Scalr_Role_Behavior_MongoDB::ROLE_CLUSTER_STATUS, Scalr_Role_Behavior_MongoDB::ROLE_CLUSTER_IS_REMOVING_SHARD_INDEX, Scalr_Role_Behavior_MongoDB::DATA_BUNDLE_IS_RUNNING, Scalr_Role_Behavior_MongoDB::DATA_BUNDLE_SERVER_ID, Scalr_Role_Behavior_MongoDB::DATA_BUNDLE_LAST_TS, Scalr_Role_Behavior_Router::ROLE_VPC_NID, Scalr_Role_Behavior_Router::ROLE_VPC_IP, Scalr_Role_Behavior_Router::ROLE_VPC_AID, Scalr_Role_Behavior_Router::ROLE_VPC_ROUTER_CONFIGURED); // Set settings foreach ($definition->settings as $key => $value) { if ($reset && in_array($key, $resetSettings)) { continue; } $this->SetSetting($key, $value, Entity\FarmRoleSetting::TYPE_CFG); } //Farm Global Variables $variables = new Scalr_Scripting_GlobalVariables($this->GetFarmObject()->ClientID, $this->GetFarmObject()->EnvID, ScopeInterface::SCOPE_FARMROLE); $variables->setValues($definition->globalVariables, $this->RoleID, $this->FarmID, $this->ID); //Storage $this->getStorage()->setConfigs($definition->storage); // Scripts $scripts = array(); foreach ($definition->scripts as $script) { $scripts[] = array('params' => $script->params, 'target' => $script->target, 'order_index' => $script->orderIndex, 'version' => (int) $script->version, 'isSync' => (int) $script->isSync, 'timeout' => $script->timeout, 'event' => $script->event, 'script_id' => (int) $script->scriptId, 'script_path' => $script->scriptPath, 'script_type' => $script->scriptType, 'run_as' => $script->runAs, 'target_roles' => $script->targetRoles, 'target_farmroles' => $script->targetFarmroles, 'target_behaviors' => $script->targetBehaviors); } $this->SetScripts($scripts); // Scaling times $this->DB->Execute("DELETE FROM farm_role_scaling_times WHERE farm_roleid=?", array($this->ID)); foreach ($definition->scalingTimes as $scalingPeriod) { $this->DB->Execute("INSERT INTO farm_role_scaling_times SET\n farm_roleid = ?,\n start_time = ?,\n end_time = ?,\n days_of_week = ?,\n instances_count = ?\n ", array($this->ID, $scalingPeriod->startTime, $scalingPeriod->endTime, $scalingPeriod->daysOfWeek, $scalingPeriod->instanceCount)); } // metrics $scalingManager = new Scalr_Scaling_Manager($this); $metrics = array(); foreach ($definition->scalingMetrics as $metric) { $metrics[$metric->metricId] = $metric->settings; } $scalingManager->setFarmRoleMetrics($metrics); return true; }
/** * @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))); } }
/** * @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))); } }
/** * @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))); } }
public function SetGlobalVariable() { $scope = $this->GetArg("scope"); $paramName = $this->GetArg("param-name"); $paramValue = $this->GetArg("param-value"); $final = (int) $this->GetArg("flag-final"); $globalVariables = new Scalr_Scripting_GlobalVariables($this->DBServer->envId, $scope); $globalVariables->setValues(array(array('name' => $paramName, 'value' => $paramValue, 'flagFinal' => $final, 'flagRequired' => 0, 'scope' => $scope)), $this->DBServer->roleId, $this->DBServer->farmId, $this->DBServer->farmRoleId); $ResponseDOMDocument = $this->CreateResponse(); $configNode = $ResponseDOMDocument->createElement("variables"); $settingNode = $ResponseDOMDocument->createElement("variable", $paramValue); $settingNode->setAttribute("name", $paramName); $configNode->appendChild($settingNode); $ResponseDOMDocument->documentElement->appendChild($configNode); return $ResponseDOMDocument; }
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 SetGlobalVariable() { $scope = $this->GetArg("scope"); $paramName = $this->GetArg("param-name"); $paramValue = $this->GetArg("param-value"); $final = (int) $this->GetArg("flag-final"); if ($scope != Scalr_Scripting_GlobalVariables::SCOPE_SERVER && $scope != Scalr_Scripting_GlobalVariables::SCOPE_FARMROLE) { throw new Exception("query-env allows you to set global variables only on server/farmrole scopes"); } $globalVariables = new Scalr_Scripting_GlobalVariables($this->DBServer->clientId, $this->DBServer->envId, $scope); $globalVariables->setValues(array(array('name' => $paramName, 'value' => $paramValue, 'flagFinal' => $final, 'flagRequired' => 0)), $this->DBServer->GetFarmRoleObject()->RoleID, $this->DBServer->farmId, $this->DBServer->farmRoleId, $this->DBServer->serverId); $ResponseDOMDocument = $this->CreateResponse(); $configNode = $ResponseDOMDocument->createElement("variables"); $settingNode = $ResponseDOMDocument->createElement("variable", htmlspecialchars($paramValue)); $settingNode->setAttribute("name", $paramName); $configNode->appendChild($settingNode); $ResponseDOMDocument->documentElement->appendChild($configNode); return $ResponseDOMDocument; }
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'); }
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; }
/** * @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))); } }
public function xBuildAction() { $this->request->defineParams(array('farmId' => array('type' => 'int'), 'roles' => array('type' => 'json'), 'rolesToRemove' => array('type' => 'json'), 'farm' => array('type' => 'json'), 'launch' => array('type' => 'bool'))); if (!$this->isFarmConfigurationValid($this->getParam('farmId'), $this->getParam('farm'), (array) $this->getParam('roles'))) { if ($this->errors['error_count'] != 0) { $this->response->failure(); $this->response->data(array('errors' => $this->errors)); return; } } $farm = $this->getParam('farm'); $client = Client::Load($this->user->getAccountId()); if ($this->getParam('farmId')) { $dbFarm = DBFarm::LoadByID($this->getParam('farmId')); $this->user->getPermissions()->validate($dbFarm); $this->request->checkPermissions($dbFarm->__getNewFarmObject(), Acl::PERM_FARMS_UPDATE); $dbFarm->isLocked(); if ($this->getParam('changed') && $dbFarm->changedTime && $this->getParam('changed') != $dbFarm->changedTime) { $userName = '******'; $changed = explode(' ', $this->getParam('changed')); $changedTime = intval($changed[1]); try { $user = new Scalr_Account_User(); $user->loadById($dbFarm->changedByUserId); $userName = $user->getEmail(); } catch (Exception $e) { } $this->response->failure(); $this->response->data(array('changedFailure' => sprintf('%s changed this farm at %s', $userName, Scalr_Util_DateTime::convertTz($changedTime)))); return; } else { if ($this->getParam('changed')) { $this->checkFarmConfigurationIntegrity($this->getParam('farmId'), $this->getParam('farm'), (array) $this->getParam('roles'), (array) $this->getParam('rolesToRemove')); } } $dbFarm->changedByUserId = $this->user->getId(); $dbFarm->changedTime = microtime(); if ($this->getContainer()->analytics->enabled) { $projectId = $farm['projectId']; if (empty($projectId)) { $ccId = $dbFarm->GetEnvironmentObject()->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID); if (!empty($ccId)) { //Assigns Project automatically only if it is the one withing the Cost Center $projects = ProjectEntity::findByCcId($ccId); if (count($projects) == 1) { $projectId = $projects->getArrayCopy()[0]->projectId; } } } if (!empty($projectId) && $dbFarm->GetSetting(Entity\FarmSetting::PROJECT_ID) != $projectId) { $this->request->checkPermissions($dbFarm->__getNewFarmObject(), Acl::PERM_FARMS_PROJECTS); } } $bNew = false; } else { $this->request->restrictAccess(Acl::RESOURCE_OWN_FARMS, Acl::PERM_FARMS_CREATE); $this->user->getAccount()->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1); $dbFarm = new DBFarm(); $dbFarm->ClientID = $this->user->getAccountId(); $dbFarm->EnvID = $this->getEnvironmentId(); $dbFarm->Status = FARM_STATUS::TERMINATED; $dbFarm->ownerId = $this->user->getId(); $dbFarm->changedByUserId = $this->user->getId(); $dbFarm->changedTime = microtime(); $bNew = true; } if ($this->getParam('farm')) { $dbFarm->Name = $this->request->stripValue($farm['name']); $dbFarm->RolesLaunchOrder = $farm['rolesLaunchOrder']; $dbFarm->Comments = $this->request->stripValue($farm['description']); } if (empty($dbFarm->Name)) { throw new Exception(_("Farm name required")); } $setFarmTeams = false; if ($bNew) { $setFarmTeams = true; } else { if ($dbFarm->ownerId == $this->user->getId() || $this->request->hasPermissions($dbFarm->__getNewFarmObject(), Acl::PERM_FARMS_CHANGE_OWNERSHIP)) { if (is_numeric($farm['owner']) && $farm['owner'] != $dbFarm->ownerId) { $dbFarm->ownerId = $farm['owner']; $f = Entity\Farm::findPk($dbFarm->ID); Entity\FarmSetting::addOwnerHistory($f, User::findPk($farm['owner']), User::findPk($this->user->getId())); $f->save(); } $setFarmTeams = true; } } $dbFarm->save(); if ($setFarmTeams && is_array($farm['teamOwner'])) { /* @var $f Entity\Farm */ $f = Entity\Farm::findPk($dbFarm->ID); $f->setTeams(empty($farm['teamOwner']) ? [] : Entity\Account\Team::find([['name' => ['$in' => $farm['teamOwner']]], ['accountId' => $this->getUser()->accountId]])); $f->save(); } if ($bNew) { $dbFarm->SetSetting(Entity\FarmSetting::CREATED_BY_ID, $this->user->getId()); $dbFarm->SetSetting(Entity\FarmSetting::CREATED_BY_EMAIL, $this->user->getEmail()); } $governance = new Scalr_Governance($this->getEnvironmentId()); if (!$this->getParam('farmId') && $governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE)) { $dbFarm->SetSetting(Entity\FarmSetting::LEASE_STATUS, 'Active'); // for created farm } if (isset($farm['variables'])) { $variables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), ScopeInterface::SCOPE_FARM); $variables->setValues(is_array($farm['variables']) ? $farm['variables'] : [], 0, $dbFarm->ID, 0, '', false, true); } if (!$farm['timezone']) { $farm['timezone'] = date_default_timezone_get(); } $dbFarm->SetSetting(Entity\FarmSetting::TIMEZONE, $farm['timezone']); $dbFarm->SetSetting(Entity\FarmSetting::EC2_VPC_ID, isset($farm["vpc_id"]) ? $farm['vpc_id'] : null); $dbFarm->SetSetting(Entity\FarmSetting::EC2_VPC_REGION, isset($farm["vpc_id"]) ? $farm['vpc_region'] : null); $dbFarm->SetSetting(Entity\FarmSetting::SZR_UPD_REPOSITORY, $farm[Entity\FarmSetting::SZR_UPD_REPOSITORY]); $dbFarm->SetSetting(Entity\FarmSetting::SZR_UPD_SCHEDULE, $farm[Entity\FarmSetting::SZR_UPD_SCHEDULE]); if (!$dbFarm->GetSetting(Entity\FarmSetting::CRYPTO_KEY)) { $dbFarm->SetSetting(Entity\FarmSetting::CRYPTO_KEY, Scalr::GenerateRandomKey(40)); } if ($this->getContainer()->analytics->enabled) { //Cost analytics project must be set for the Farm object $dbFarm->setProject(!empty($farm['projectId']) ? $farm['projectId'] : null); } $virtualFarmRoles = array(); $roles = $this->getParam('roles'); if (!empty($roles)) { foreach ($roles as $role) { if (strpos($role['farm_role_id'], "virtual_") !== false) { $dbRole = DBRole::loadById($role['role_id']); $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index'], $role['alias']); $virtualFarmRoles[$role['farm_role_id']] = $dbFarmRole->ID; } } } $usedPlatforms = array(); $farmRoleVariables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), ScopeInterface::SCOPE_FARMROLE); if (!empty($roles)) { foreach ($roles as $role) { if ($role['farm_role_id']) { if (isset($virtualFarmRoles[$role['farm_role_id']])) { $role['farm_role_id'] = $virtualFarmRoles[$role['farm_role_id']]; } $update = true; $dbFarmRole = DBFarmRole::LoadByID($role['farm_role_id']); $dbRole = DBRole::loadById($dbFarmRole->RoleID); $role['role_id'] = $dbFarmRole->RoleID; if ($dbFarmRole->Platform == SERVER_PLATFORMS::GCE) { $dbFarmRole->CloudLocation = $role['cloud_location']; } } else { /** TODO: Remove because will be handled with virtual_ **/ $update = false; $dbRole = DBRole::loadById($role['role_id']); $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index']); } if ($dbRole->hasBehavior(ROLE_BEHAVIORS::RABBITMQ)) { $role['settings'][Entity\FarmRoleSetting::SCALING_MAX_INSTANCES] = $role['settings'][Entity\FarmRoleSetting::SCALING_MIN_INSTANCES]; } if ($update) { $dbFarmRole->LaunchIndex = (int) $role['launch_index']; $dbFarmRole->Alias = $role['alias']; $dbFarmRole->Save(); } $usedPlatforms[$role['platform']] = 1; $oldRoleSettings = $dbFarmRole->GetAllSettings(); // Update virtual farm_role_id with actual value $scripts = (array) $role['scripting']; if (!empty($virtualFarmRoles)) { array_walk_recursive($scripts, function (&$v, $k) use($virtualFarmRoles) { if (is_string($v)) { $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v); } }); array_walk_recursive($role['settings'], function (&$v, $k) use($virtualFarmRoles) { if (is_string($v)) { $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v); } }); } $dbFarmRole->ClearSettings("chef."); if (!empty($role['scaling_settings']) && is_array($role['scaling_settings'])) { foreach ($role['scaling_settings'] as $k => $v) { $dbFarmRole->SetSetting($k, $v, Entity\FarmRoleSetting::TYPE_CFG); } } foreach ($role['settings'] as $k => $v) { $dbFarmRole->SetSetting($k, $v, Entity\FarmRoleSetting::TYPE_CFG); } /****** Scaling settings ******/ $scalingManager = new Scalr_Scaling_Manager($dbFarmRole); $scalingManager->setFarmRoleMetrics(is_array($role['scaling']) ? $role['scaling'] : array()); //TODO: optimize this code... $this->db->Execute("DELETE FROM farm_role_scaling_times WHERE farm_roleid=?", array($dbFarmRole->ID)); // 5 = Time based scaling -> move to constants if (!empty($role['scaling'][Entity\ScalingMetric::METRIC_DATE_AND_TIME_ID])) { foreach ($role['scaling'][Entity\ScalingMetric::METRIC_DATE_AND_TIME_ID] as $scal_period) { $chunks = explode(":", $scal_period['id']); $this->db->Execute("INSERT INTO farm_role_scaling_times SET\n farm_roleid\t\t= ?,\n start_time\t\t= ?,\n end_time\t\t= ?,\n days_of_week\t= ?,\n instances_count\t= ?\n ", array($dbFarmRole->ID, $chunks[0], $chunks[1], $chunks[2], $chunks[3])); } } /*****************/ /* Add script options to databse */ $dbFarmRole->SetScripts($scripts, (array) $role['scripting_params']); /* End of scripting section */ /* Add storage configuration */ if (isset($role['storages']['configs'])) { $dbFarmRole->getStorage()->setConfigs($role['storages']['configs'], false); } $farmRoleVariables->setValues(is_array($role['variables']) ? $role['variables'] : [], $dbFarmRole->GetRoleID(), $dbFarm->ID, $dbFarmRole->ID, '', false, true); foreach (Scalr_Role_Behavior::getListForFarmRole($dbFarmRole) as $behavior) { $behavior->onFarmSave($dbFarm, $dbFarmRole); } /** * Platform specified updates */ if ($dbFarmRole->Platform == SERVER_PLATFORMS::EC2) { \Scalr\Modules\Platforms\Ec2\Helpers\EbsHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); \Scalr\Modules\Platforms\Ec2\Helpers\EipHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); if ($role['settings']['aws.elb.remove']) { $this->request->restrictAccess(Acl::RESOURCE_AWS_ELB, Acl::PERM_AWS_ELB_MANAGE); } \Scalr\Modules\Platforms\Ec2\Helpers\ElbHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); } if (in_array($dbFarmRole->Platform, array(SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::CLOUDSTACK))) { Scalr\Modules\Platforms\Cloudstack\Helpers\CloudstackHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); } } } $rolesToRemove = $this->getParam('rolesToRemove'); if (!empty($rolesToRemove)) { $currentFarmRoles = Entity\FarmRole::find([['farmId' => $dbFarm->ID], ['id' => ['$in' => $rolesToRemove]]]); /* @var $farmRole Entity\FarmRole */ foreach ($currentFarmRoles as $farmRole) { $farmRole->delete(); } } $dbFarm->save(); if (!$client->GetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED)) { $client->SetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED, time()); } if ($this->request->hasPermissions($dbFarm->__getNewFarmObject(), Acl::PERM_FARMS_LAUNCH_TERMINATE) && $this->getParam('launch')) { $this->user->getPermissions()->validate($dbFarm); $dbFarm->isLocked(); Scalr::FireEvent($dbFarm->ID, new FarmLaunchedEvent(true, $this->user->id)); $this->response->success('Farm successfully saved and launched'); } else { $this->response->success('Farm successfully saved'); } $this->response->data(array('farmId' => $dbFarm->ID, 'isNewFarm' => $bNew)); }
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'); }
public function GlobalVariableSet($ParamName, $ParamValue, $FarmRoleID = 0, $FarmID = 0, $ServerID = '', $RoleID = 0) { if (empty($FarmID) && empty($FarmRoleID) && empty($ServerID)) { $this->restrictAccess(Acl::RESOURCE_ENVADMINISTRATION_GLOBAL_VARIABLES); } try { if ($ServerID != '') { $DBServer = DBServer::LoadByID($ServerID); $DBFarmRole = $DBServer->GetFarmRoleObject(); $DBFarm = $DBFarmRole->GetFarmObject(); $scope = Scalr_Scripting_GlobalVariables::SCOPE_SERVER; $FarmRoleID = $DBFarmRole->ID; } else { if ($FarmRoleID != 0) { $DBFarmRole = DBFarmRole::LoadByID($FarmRoleID); $DBFarm = DBFarm::LoadByID($DBFarmRole->FarmID); $scope = Scalr_Scripting_GlobalVariables::SCOPE_FARMROLE; $ServerID = ''; } elseif ($FarmID != 0) { $DBFarm = DBFarm::LoadByID($FarmID); $scope = Scalr_Scripting_GlobalVariables::SCOPE_FARM; $FarmRoleID = 0; $ServerID = ''; } elseif ($RoleID != 0) { $DBRole = DBRole::loadById($RoleID); $scope = Scalr_Scripting_GlobalVariables::SCOPE_ROLE; $FarmRoleID = 0; $FarmID = 0; $ServerID = ''; } else { throw new Exception("FarmID or FarmRoleID should be specified"); } } if ($DBFarm) { if ($DBFarm->EnvID != $this->Environment->id) { throw new Exception("N"); } $this->user->getPermissions()->validate($DBFarm); } elseif ($DBRole) { if ($DBRole->envId != $this->Environment->id) { throw new Exception("N"); } $this->user->getPermissions()->validate($DBRole); } } catch (Exception $e) { throw new Exception(sprintf("FarmRole ID #%s not found", $FarmRoleID)); } $ParamName = $this->stripValue($ParamName); if (!$ParamName) { throw new Exception("Param name is required"); } $globalVariables = new Scalr_Scripting_GlobalVariables($this->Environment->clientId, $this->Environment->id, $scope); $globalVariables->setValues(array(array('name' => $ParamName, 'value' => $ParamValue)), $RoleID, $DBFarm->ID, $FarmRoleID, $ServerID); $response = $this->CreateInitialResponse(); $response->Result = true; return $response; }
public function xBuildAction() { $this->request->defineParams(array('farmId' => array('type' => 'int'), 'roles' => array('type' => 'json'), 'farm' => array('type' => 'json'), 'roleUpdate' => array('type' => 'int'))); $this->request->restrictAccess(Acl::RESOURCE_FARMS, Acl::PERM_FARMS_MANAGE); if (!$this->isFarmConfigurationValid($this->getParam('farmId'), $this->getParam('farm'), (array) $this->getParam('roles'))) { if ($this->errors['error_count'] != 0) { $this->response->failure(); $this->response->data(array('errors' => $this->errors)); return; } } $farm = $this->getParam('farm'); $client = Client::Load($this->user->getAccountId()); if ($this->getParam('farmId')) { $dbFarm = DBFarm::LoadByID($this->getParam('farmId')); $this->user->getPermissions()->validate($dbFarm); $dbFarm->isLocked(); if ($this->getParam('changed') && $dbFarm->changedTime && $this->getParam('changed') != $dbFarm->changedTime) { $userName = '******'; $changed = explode(' ', $this->getParam('changed')); $changedTime = intval($changed[1]); try { $user = new Scalr_Account_User(); $user->loadById($dbFarm->changedByUserId); $userName = $user->getEmail(); } catch (Exception $e) { } $this->response->failure(); $this->response->data(array('changedFailure' => sprintf('%s changed this farm at %s', $userName, Scalr_Util_DateTime::convertTz($changedTime)))); return; } $dbFarm->changedByUserId = $this->user->getId(); $dbFarm->changedTime = microtime(); } else { $this->user->getAccount()->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1); $dbFarm = new DBFarm(); $dbFarm->Status = FARM_STATUS::TERMINATED; $dbFarm->createdByUserId = $this->user->getId(); $dbFarm->createdByUserEmail = $this->user->getEmail(); $dbFarm->changedByUserId = $this->user->getId(); $dbFarm->changedTime = microtime(); } if ($this->getParam('farm')) { $dbFarm->Name = strip_tags($farm['name']); $dbFarm->RolesLaunchOrder = $farm['rolesLaunchOrder']; $dbFarm->Comments = trim(strip_tags($farm['description'])); } if (empty($dbFarm->Name)) { throw new Exception(_("Farm name required")); } $dbFarm->save(); $governance = new Scalr_Governance($this->getEnvironmentId()); if ($governance->isEnabled(Scalr_Governance::GENERAL_LEASE)) { $dbFarm->SetSetting(DBFarm::SETTING_LEASE_STATUS, 'Active'); } if (isset($farm['variables'])) { $variables = new Scalr_Scripting_GlobalVariables($this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARM); $variables->setValues($farm['variables'], 0, $dbFarm->ID, 0, '', false); } if (!$farm['timezone']) { $farm['timezone'] = date_default_timezone_get(); } $dbFarm->SetSetting(DBFarm::SETTING_TIMEZONE, $farm['timezone']); $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_ID, $farm['vpc_id']); $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_REGION, $farm['vpc_region']); if (!$dbFarm->GetSetting(DBFarm::SETTING_CRYPTO_KEY)) { $dbFarm->SetSetting(DBFarm::SETTING_CRYPTO_KEY, Scalr::GenerateRandomKey(40)); } $virtualFarmRoles = array(); $roles = $this->getParam('roles'); if (!empty($roles)) { foreach ($roles as $role) { if (strpos($role['farm_role_id'], "virtual_") !== false) { $dbRole = DBRole::loadById($role['role_id']); $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index'], $role['alias']); $virtualFarmRoles[$role['farm_role_id']] = $dbFarmRole->ID; } } } $usedPlatforms = array(); $dbFarmRolesList = array(); $newFarmRolesList = array(); $farmRoleVariables = new Scalr_Scripting_GlobalVariables($this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARMROLE); if (!empty($roles)) { foreach ($roles as $role) { if ($role['farm_role_id']) { if ($virtualFarmRoles[$role['farm_role_id']]) { $role['farm_role_id'] = $virtualFarmRoles[$role['farm_role_id']]; } $update = true; $dbFarmRole = DBFarmRole::LoadByID($role['farm_role_id']); $dbRole = DBRole::loadById($dbFarmRole->RoleID); $role['role_id'] = $dbFarmRole->RoleID; if ($dbFarmRole->Platform == SERVER_PLATFORMS::GCE) { $dbFarmRole->CloudLocation = $role['cloud_location']; } } else { $update = false; $dbRole = DBRole::loadById($role['role_id']); $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index']); } if ($dbRole->hasBehavior(ROLE_BEHAVIORS::RABBITMQ)) { $role['settings'][DBFarmRole::SETTING_SCALING_MAX_INSTANCES] = $role['settings'][DBFarmRole::SETTING_SCALING_MIN_INSTANCES]; } if ($dbFarmRole->NewRoleID) { continue; } if ($update) { $dbFarmRole->LaunchIndex = (int) $role['launch_index']; $dbFarmRole->Alias = $role['alias']; $dbFarmRole->Save(); } $usedPlatforms[$role['platform']] = 1; $oldRoleSettings = $dbFarmRole->GetAllSettings(); // Update virtual farm_role_id with actual value $scripts = (array) $role['scripting']; if (count($virtualFarmRoles) > 0) { array_walk_recursive($scripts, function (&$v, $k) use($virtualFarmRoles) { if (is_string($v)) { $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v); } }); array_walk_recursive($role['settings'], function (&$v, $k) use($virtualFarmRoles) { if (is_string($v)) { $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v); } }); } //Audit log start //!TODO Enable Audit log for Farm Builder // $auditLog = $this->getEnvironment()->auditLog; // $docRoleSettingsBefore = new FarmRoleSettingsDocument($oldRoleSettings); // $docRoleSettingsBefore['farmroleid'] = $dbFarmRole->ID; // $docRoleSettings = new FarmRoleSettingsDocument(array_merge((array)$role['scaling_settings'], (array)$role['settings'])); // $docRoleSettings['farmroleid'] = $dbFarmRole->ID; $dbFarmRole->ClearSettings("chef."); if (!empty($role['scaling_settings']) && is_array($role['scaling_settings'])) { foreach ($role['scaling_settings'] as $k => $v) { $dbFarmRole->SetSetting($k, $v, DBFarmRole::TYPE_CFG); } } foreach ($role['settings'] as $k => $v) { $dbFarmRole->SetSetting($k, $v, DBFarmRole::TYPE_CFG); } // $auditLog->log('Farm has been saved', array(AuditLogTags::TAG_UPDATE), $docRoleSettings, $docRoleSettingsBefore); // unset($docRoleSettings); // unset($docRoleSettingsBefore); //Audit log finish /****** Scaling settings ******/ $scalingManager = new Scalr_Scaling_Manager($dbFarmRole); $scalingManager->setFarmRoleMetrics(is_array($role['scaling']) ? $role['scaling'] : array()); //TODO: optimize this code... $this->db->Execute("DELETE FROM farm_role_scaling_times WHERE farm_roleid=?", array($dbFarmRole->ID)); // 5 = Time based scaling -> move to constants if ($role['scaling'][5]) { foreach ($role['scaling'][5] as $scal_period) { $chunks = explode(":", $scal_period['id']); $this->db->Execute("INSERT INTO farm_role_scaling_times SET\n farm_roleid\t\t= ?,\n start_time\t\t= ?,\n end_time\t\t= ?,\n days_of_week\t= ?,\n instances_count\t= ?\n ", array($dbFarmRole->ID, $chunks[0], $chunks[1], $chunks[2], $chunks[3])); } } /*****************/ /* Update role params */ $dbFarmRole->SetParameters((array) $role['params']); /* End of role params management */ /* Add script options to databse */ $dbFarmRole->SetScripts($scripts, (array) $role['scripting_params']); /* End of scripting section */ /* Add services configuration */ $dbFarmRole->SetServiceConfigPresets((array) $role['config_presets']); /* End of scripting section */ /* Add storage configuration */ //try { $dbFarmRole->getStorage()->setConfigs((array) $role['storages']['configs']); //} catch (FarmRoleStorageException $e) { // $errors[] = array('farm_role_id' => 1, 'tab' => 'storage', 'error' => $e->getMessage()); //} $farmRoleVariables->setValues($role['variables'], $dbFarmRole->GetRoleID(), $dbFarm->ID, $dbFarmRole->ID, '', false); Scalr_Helpers_Dns::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); foreach (Scalr_Role_Behavior::getListForFarmRole($dbFarmRole) as $behavior) { $behavior->onFarmSave($dbFarm, $dbFarmRole); } /** * Platfrom specified updates */ if ($dbFarmRole->Platform == SERVER_PLATFORMS::EC2) { Modules_Platforms_Ec2_Helpers_Ebs::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); Modules_Platforms_Ec2_Helpers_Eip::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); Modules_Platforms_Ec2_Helpers_Elb::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); } if (in_array($dbFarmRole->Platform, array(SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::CLOUDSTACK))) { Modules_Platforms_Cloudstack_Helpers_Cloudstack::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); } $dbFarmRolesList[] = $dbFarmRole; $newFarmRolesList[] = $dbFarmRole->ID; } } if (!$this->getParam('roleUpdate')) { foreach ($dbFarm->GetFarmRoles() as $dbFarmRole) { if (!$dbFarmRole->NewRoleID && !in_array($dbFarmRole->ID, $newFarmRolesList)) { $dbFarmRole->Delete(); } } } if ($usedPlatforms[SERVER_PLATFORMS::CLOUDSTACK]) { Modules_Platforms_Cloudstack_Helpers_Cloudstack::farmSave($dbFarm, $dbFarmRolesList); } if ($usedPlatforms[SERVER_PLATFORMS::EC2]) { Modules_Platforms_Ec2_Helpers_Ec2::farmSave($dbFarm, $dbFarmRolesList); } if ($usedPlatforms[SERVER_PLATFORMS::EUCALYPTUS]) { Modules_Platforms_Eucalyptus_Helpers_Eucalyptus::farmSave($dbFarm, $dbFarmRolesList); } $dbFarm->save(); if (!$client->GetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED)) { $client->SetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED, time()); } $this->response->success('Farm successfully saved'); $this->response->data(array('farmId' => $dbFarm->ID)); }
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; }
/** * @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'); }
public function GlobalVariableSet($ParamName, $ParamValue, $FarmRoleID = 0, $FarmID = 0, $ServerID = '', $RoleID = 0) { if (empty($FarmID) && empty($FarmRoleID) && empty($ServerID)) { $this->restrictAccess(Acl::RESOURCE_GLOBAL_VARIABLES_ENVIRONMENT); } try { if ($ServerID != '') { $DBServer = DBServer::LoadByID($ServerID); $DBFarmRole = $DBServer->GetFarmRoleObject(); $DBFarm = $DBFarmRole->GetFarmObject(); $scope = ScopeInterface::SCOPE_SERVER; $FarmRoleID = $DBFarmRole->ID; } else { if ($FarmRoleID != 0) { $DBFarmRole = DBFarmRole::LoadByID($FarmRoleID); $DBFarm = DBFarm::LoadByID($DBFarmRole->FarmID); $scope = ScopeInterface::SCOPE_FARMROLE; $ServerID = ''; } elseif ($FarmID != 0) { $DBFarm = DBFarm::LoadByID($FarmID); $scope = ScopeInterface::SCOPE_FARM; $FarmRoleID = 0; $ServerID = ''; } elseif ($RoleID != 0) { $DBRole = DBRole::loadById($RoleID); $scope = ScopeInterface::SCOPE_ROLE; $FarmRoleID = 0; $FarmID = 0; $ServerID = ''; } else { throw new Exception("You must specify al least one of the following arguments: FarmID, FarmRoleID, RoleID or ServerID."); } } if ($DBFarm) { if ($DBFarm->EnvID != $this->Environment->id) { throw new Exception(sprintf("Farm ID #%s is not found.", $FarmID)); } $this->user->getPermissions()->validate($DBFarm); } elseif ($DBRole) { if ($DBRole->envId != $this->Environment->id) { throw new Exception(sprintf("Role ID #%s is not found.", $RoleID)); } $this->user->getPermissions()->validate($DBRole); } } catch (Exception $e) { throw new Exception($e->getMessage()); } $ParamName = $this->stripValue($ParamName); if (!$ParamName) { throw new Exception("Param name is required"); } $globalVariables = new Scalr_Scripting_GlobalVariables($this->Environment->clientId, $this->Environment->id, $scope); $globalVariables->doNotValidateNameCaseSensitivity = true; $globalVariables->setValues(array(array('name' => $ParamName, 'value' => $ParamValue)), $RoleID, $DBFarm->ID, $FarmRoleID, $ServerID); $response = $this->CreateInitialResponse(); $response->Result = true; return $response; }
/** * Creates clone for the farm * * @param string $name The name of the farm * @param Scalr_Account_User $user The user object * @param int $envId The identifier of the environment * @return DBFarm Returns clone */ public function cloneFarm($name = false, Scalr_Account_User $user, $envId) { $account = $user->getAccount(); $account->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1); $definition = $this->getDefinition(); if (!$name) { $template = ""; if (!preg_match('/^(.*?)\\(clone \\#([0-9]*)\\)$/si', $definition->name)) { $name = $definition->name; } else { preg_match('/^(.*?)\\(clone \\#([0-9]*)\\)$/si', $definition->name, $matches); $name = trim($matches[1]); } $name = preg_replace('/[^A-Za-z0-9_\\. -]+/', '', $name); $lastUsedIndex = $this->DB->GetOne('SELECT MAX(CAST((SUBSTR(@p:=SUBSTRING_INDEX(name, \'#\', -1), 1, LENGTH(@p) - 1)) AS UNSIGNED)) as lastUsedCloneNumber FROM farms WHERE name REGEXP \'' . str_replace('.', '\\.', $name) . ' \\\\(clone #[0-9]+\\\\)\' AND env_id = ?', array($envId)); $name = $name . ' (clone #' . ($lastUsedIndex + 1) . ')'; } $dbFarm = self::create($name, $user, $envId); $dbFarm->createdByUserId = $user->id; $dbFarm->createdByUserEmail = $user->getEmail(); $dbFarm->RolesLaunchOrder = $definition->rolesLaunchOrder; $dbFarm->teamId = $definition->teamId; $dbFarm->SetSetting(DBFarm::SETTING_TIMEZONE, $definition->settings[DBFarm::SETTING_TIMEZONE]); $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_ID, $definition->settings[DBFarm::SETTING_EC2_VPC_ID]); $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_REGION, $definition->settings[DBFarm::SETTING_EC2_VPC_REGION]); $dbFarm->SetSetting(DBFarm::SETTING_SZR_UPD_REPOSITORY, $definition->settings[DBFarm::SETTING_SZR_UPD_REPOSITORY]); $dbFarm->SetSetting(DBFarm::SETTING_SZR_UPD_SCHEDULE, $definition->settings[DBFarm::SETTING_SZR_UPD_SCHEDULE]); $dbFarm->SetSetting(DBFarm::SETTING_LEASE_STATUS, $definition->settings[DBFarm::SETTING_LEASE_STATUS]); $variables = new Scalr_Scripting_GlobalVariables($dbFarm->ClientID, $envId, Scalr_Scripting_GlobalVariables::SCOPE_FARM); $variables->setValues($definition->globalVariables, 0, $dbFarm->ID, 0); foreach ($definition->roles as $index => $role) { $dbFarmRole = $dbFarm->AddRole(DBRole::loadById($role->roleId), $role->platform, $role->cloudLocation, $index + 1, $role->alias); $oldRoleSettings = $dbFarmRole->GetAllSettings(); $dbFarmRole->applyDefinition($role, true); $newSettings = $dbFarmRole->GetAllSettings(); // Platform specified updates if ($dbFarmRole->Platform == SERVER_PLATFORMS::EC2) { \Scalr\Modules\Platforms\Ec2\Helpers\EbsHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $newSettings); \Scalr\Modules\Platforms\Ec2\Helpers\EipHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $newSettings); \Scalr\Modules\Platforms\Ec2\Helpers\ElbHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $newSettings); } if (in_array($dbFarmRole->Platform, array(SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::CLOUDSTACK))) { CloudstackHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $newSettings); } $dbFarmRolesList[] = $dbFarmRole; $usedPlatforms[$role->platform] = 1; } $dbFarm->save(); return $dbFarm; }
/** * Creates clone for the farm * * @param string $name The name of the farm * @param Scalr_Account_User $user The user object * @param int $envId The identifier of the environment * @return DBFarm Returns clone */ public function cloneFarm($name = false, Scalr_Account_User $user, $envId) { $account = $user->getAccount(); $account->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1); $definition = $this->getDefinition(); if (!$name) { $template = ""; if (!stristr($definition->name, "clone")) { $template = $definition->name . ' (clone #%s)'; $i = 1; } else { preg_match("/^(.*?)\\(clone \\#([0-9]*)\\)\$/si", $definition->name, $matches); $template = trim($matches[1]) . " (clone #%s)"; $i = $matches[2] + 1; } while (true) { $name = sprintf($template, $i); if (!$this->DB->GetOne("SELECT id FROM farms WHERE name = ? AND env_id = ? LIMIT 1", array($name, $this->EnvID))) { break; } else { $i++; } } } $dbFarm = self::create($name, $user, $envId); $dbFarm->createdByUserId = $user->id; $dbFarm->createdByUserEmail = $user->getEmail(); $dbFarm->RolesLaunchOrder = $definition->rolesLaunchOrder; $dbFarm->SetSetting(DBFarm::SETTING_TIMEZONE, $definition->settings[DBFarm::SETTING_TIMEZONE]); $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_ID, $definition->settings[DBFarm::SETTING_EC2_VPC_ID]); $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_REGION, $definition->settings[DBFarm::SETTING_EC2_VPC_REGION]); $dbFarm->SetSetting(DBFarm::SETTING_SZR_UPD_REPOSITORY, $definition->settings[DBFarm::SETTING_SZR_UPD_REPOSITORY]); $dbFarm->SetSetting(DBFarm::SETTING_SZR_UPD_SCHEDULE, $definition->settings[DBFarm::SETTING_SZR_UPD_SCHEDULE]); $dbFarm->SetSetting(DBFarm::SETTING_LEASE_STATUS, $definition->settings[DBFarm::SETTING_LEASE_STATUS]); $variables = new Scalr_Scripting_GlobalVariables($dbFarm->ClientID, $envId, Scalr_Scripting_GlobalVariables::SCOPE_FARM); $variables->setValues($definition->globalVariables, 0, $dbFarm->ID, 0); foreach ($definition->roles as $index => $role) { $dbFarmRole = $dbFarm->AddRole(DBRole::loadById($role->roleId), $role->platform, $role->cloudLocation, $index + 1, $role->alias); $oldRoleSettings = $dbFarmRole->GetAllSettings(); $dbFarmRole->applyDefinition($role, true); $newSettings = $dbFarmRole->GetAllSettings(); Scalr_Helpers_Dns::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $newSettings); // Platfrom specified updates if ($dbFarmRole->Platform == SERVER_PLATFORMS::EC2) { \Scalr\Modules\Platforms\Ec2\Helpers\EbsHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $newSettings); \Scalr\Modules\Platforms\Ec2\Helpers\EipHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $newSettings); \Scalr\Modules\Platforms\Ec2\Helpers\ElbHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $newSettings); } if (in_array($dbFarmRole->Platform, array(SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::CLOUDSTACK))) { CloudstackHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $newSettings); } $dbFarmRolesList[] = $dbFarmRole; $usedPlatforms[$role->platform] = 1; } if ($usedPlatforms[SERVER_PLATFORMS::EC2]) { \Scalr\Modules\Platforms\Ec2\Helpers\Ec2Helper::farmSave($dbFarm, $dbFarmRolesList); } if ($usedPlatforms[SERVER_PLATFORMS::EUCALYPTUS]) { \Scalr\Modules\Platforms\Eucalyptus\Helpers\EucalyptusHelper::farmSave($dbFarm, $dbFarmRolesList); } if ($usedPlatforms[SERVER_PLATFORMS::CLOUDSTACK]) { CloudstackHelper::farmSave($dbFarm, $dbFarmRolesList); } $dbFarm->save(); return $dbFarm; }
public function xBuildAction() { $this->request->defineParams(array('farmId' => array('type' => 'int'), 'roles' => array('type' => 'json'), 'farm' => array('type' => 'json'), 'roleUpdate' => array('type' => 'int'), 'launch' => array('type' => 'bool'))); if (!$this->isFarmConfigurationValid($this->getParam('farmId'), $this->getParam('farm'), (array) $this->getParam('roles'))) { if ($this->errors['error_count'] != 0) { $this->response->failure(); $this->response->data(array('errors' => $this->errors)); return; } } $farm = $this->getParam('farm'); $client = Client::Load($this->user->getAccountId()); if ($this->getParam('farmId')) { $dbFarm = DBFarm::LoadByID($this->getParam('farmId')); $this->user->getPermissions()->validate($dbFarm); $this->request->restrictFarmAccess($dbFarm, Acl::PERM_FARMS_MANAGE); $dbFarm->isLocked(); if ($this->getParam('changed') && $dbFarm->changedTime && $this->getParam('changed') != $dbFarm->changedTime) { $userName = '******'; $changed = explode(' ', $this->getParam('changed')); $changedTime = intval($changed[1]); try { $user = new Scalr_Account_User(); $user->loadById($dbFarm->changedByUserId); $userName = $user->getEmail(); } catch (Exception $e) { } $this->response->failure(); $this->response->data(array('changedFailure' => sprintf('%s changed this farm at %s', $userName, Scalr_Util_DateTime::convertTz($changedTime)))); return; } $dbFarm->changedByUserId = $this->user->getId(); $dbFarm->changedTime = microtime(); $bNew = false; } else { $this->request->restrictFarmAccess(null, Acl::PERM_FARMS_MANAGE); $this->user->getAccount()->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1); $dbFarm = new DBFarm(); $dbFarm->ClientID = $this->user->getAccountId(); $dbFarm->EnvID = $this->getEnvironmentId(); $dbFarm->Status = FARM_STATUS::TERMINATED; $dbFarm->createdByUserId = $this->user->getId(); $dbFarm->createdByUserEmail = $this->user->getEmail(); $dbFarm->changedByUserId = $this->user->getId(); $dbFarm->changedTime = microtime(); $bNew = true; } if ($this->getParam('farm')) { $dbFarm->Name = $this->request->stripValue($farm['name']); $dbFarm->RolesLaunchOrder = $farm['rolesLaunchOrder']; $dbFarm->Comments = $this->request->stripValue($farm['description']); } if (empty($dbFarm->Name)) { throw new Exception(_("Farm name required")); } if ($bNew) { $dbFarm->teamId = is_numeric($farm['teamOwner']) && $farm['teamOwner'] > 0 ? $farm['teamOwner'] : NULL; } else { if ($dbFarm->createdByUserId == $this->user->getId() || $this->user->isAccountOwner() || $this->request->isFarmAllowed($dbFarm, Acl::PERM_FARMS_CHANGE_OWNERSHIP)) { if (is_numeric($farm['owner']) && $farm['owner'] != $dbFarm->createdByUserId) { $user = (new Scalr_Account_User())->loadById($farm['owner']); $dbFarm->createdByUserId = $user->getId(); $dbFarm->createdByUserEmail = $user->getEmail(); // TODO: move to subclass \Farm\Setting\OwnerHistory $history = unserialize($dbFarm->GetSetting(DBFarm::SETTING_OWNER_HISTORY)); if (!is_array($history)) { $history = []; } $history[] = ['newId' => $user->getId(), 'newEmail' => $user->getEmail(), 'changedById' => $this->user->getId(), 'changedByEmail' => $this->user->getEmail(), 'dt' => date('Y-m-d H:i:s')]; $dbFarm->SetSetting(DBFarm::SETTING_OWNER_HISTORY, serialize($history)); } $dbFarm->teamId = is_numeric($farm['teamOwner']) && $farm['teamOwner'] > 0 ? $farm['teamOwner'] : NULL; } } $dbFarm->save(); $governance = new Scalr_Governance($this->getEnvironmentId()); if (!$this->getParam('farmId') && $governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE)) { $dbFarm->SetSetting(DBFarm::SETTING_LEASE_STATUS, 'Active'); // for created farm } if (isset($farm['variables'])) { $variables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARM); $variables->setValues(is_array($farm['variables']) ? $farm['variables'] : [], 0, $dbFarm->ID, 0, '', false, true); } if (!$farm['timezone']) { $farm['timezone'] = date_default_timezone_get(); } $dbFarm->SetSetting(DBFarm::SETTING_TIMEZONE, $farm['timezone']); $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_ID, $farm['vpc_id']); $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_REGION, $farm['vpc_region']); $dbFarm->SetSetting(DBFarm::SETTING_SZR_UPD_REPOSITORY, $farm[DBFarm::SETTING_SZR_UPD_REPOSITORY]); $dbFarm->SetSetting(DBFarm::SETTING_SZR_UPD_SCHEDULE, $farm[DBFarm::SETTING_SZR_UPD_SCHEDULE]); if (!$dbFarm->GetSetting(DBFarm::SETTING_CRYPTO_KEY)) { $dbFarm->SetSetting(DBFarm::SETTING_CRYPTO_KEY, Scalr::GenerateRandomKey(40)); } if ($this->getContainer()->analytics->enabled) { //Cost analytics project must be set for the Farm object $dbFarm->setProject(!empty($farm['projectId']) ? $farm['projectId'] : null); } $virtualFarmRoles = array(); $roles = $this->getParam('roles'); if (!empty($roles)) { foreach ($roles as $role) { if (strpos($role['farm_role_id'], "virtual_") !== false) { $dbRole = DBRole::loadById($role['role_id']); $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index'], $role['alias']); $virtualFarmRoles[$role['farm_role_id']] = $dbFarmRole->ID; } } } $usedPlatforms = array(); $dbFarmRolesList = array(); $newFarmRolesList = array(); $farmRoleVariables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARMROLE); if (!empty($roles)) { foreach ($roles as $role) { if ($role['farm_role_id']) { if ($virtualFarmRoles[$role['farm_role_id']]) { $role['farm_role_id'] = $virtualFarmRoles[$role['farm_role_id']]; } $update = true; $dbFarmRole = DBFarmRole::LoadByID($role['farm_role_id']); $dbRole = DBRole::loadById($dbFarmRole->RoleID); $role['role_id'] = $dbFarmRole->RoleID; if ($dbFarmRole->Platform == SERVER_PLATFORMS::GCE) { $dbFarmRole->CloudLocation = $role['cloud_location']; } } else { $update = false; $dbRole = DBRole::loadById($role['role_id']); $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index']); } if ($dbRole->hasBehavior(ROLE_BEHAVIORS::RABBITMQ)) { $role['settings'][DBFarmRole::SETTING_SCALING_MAX_INSTANCES] = $role['settings'][DBFarmRole::SETTING_SCALING_MIN_INSTANCES]; } if ($dbFarmRole->NewRoleID) { continue; } if ($update) { $dbFarmRole->LaunchIndex = (int) $role['launch_index']; $dbFarmRole->Alias = $role['alias']; $dbFarmRole->Save(); } $usedPlatforms[$role['platform']] = 1; $oldRoleSettings = $dbFarmRole->GetAllSettings(); // Update virtual farm_role_id with actual value $scripts = (array) $role['scripting']; if (count($virtualFarmRoles) > 0) { array_walk_recursive($scripts, function (&$v, $k) use($virtualFarmRoles) { if (is_string($v)) { $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v); } }); array_walk_recursive($role['settings'], function (&$v, $k) use($virtualFarmRoles) { if (is_string($v)) { $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v); } }); } $dbFarmRole->ClearSettings("chef."); if (!empty($role['scaling_settings']) && is_array($role['scaling_settings'])) { foreach ($role['scaling_settings'] as $k => $v) { $dbFarmRole->SetSetting($k, $v, DBFarmRole::TYPE_CFG); } } foreach ($role['settings'] as $k => $v) { $dbFarmRole->SetSetting($k, $v, DBFarmRole::TYPE_CFG); } /****** Scaling settings ******/ $scalingManager = new Scalr_Scaling_Manager($dbFarmRole); $scalingManager->setFarmRoleMetrics(is_array($role['scaling']) ? $role['scaling'] : array()); //TODO: optimize this code... $this->db->Execute("DELETE FROM farm_role_scaling_times WHERE farm_roleid=?", array($dbFarmRole->ID)); // 5 = Time based scaling -> move to constants if ($role['scaling'][5]) { foreach ($role['scaling'][5] as $scal_period) { $chunks = explode(":", $scal_period['id']); $this->db->Execute("INSERT INTO farm_role_scaling_times SET\n farm_roleid\t\t= ?,\n start_time\t\t= ?,\n end_time\t\t= ?,\n days_of_week\t= ?,\n instances_count\t= ?\n ", array($dbFarmRole->ID, $chunks[0], $chunks[1], $chunks[2], $chunks[3])); } } /*****************/ /* Update role params */ $dbFarmRole->SetParameters((array) $role['params']); /* End of role params management */ /* Add script options to databse */ $dbFarmRole->SetScripts($scripts, (array) $role['scripting_params']); /* End of scripting section */ /* Add services configuration */ $dbFarmRole->SetServiceConfigPresets((array) $role['config_presets']); /* End of scripting section */ /* Add storage configuration */ if (isset($role['storages'])) { if (isset($role['storages']['configs'])) { $dbFarmRole->getStorage()->setConfigs($role['storages']['configs']); } } $farmRoleVariables->setValues(is_array($role['variables']) ? $role['variables'] : [], $dbFarmRole->GetRoleID(), $dbFarm->ID, $dbFarmRole->ID, '', false, true); foreach (Scalr_Role_Behavior::getListForFarmRole($dbFarmRole) as $behavior) { $behavior->onFarmSave($dbFarm, $dbFarmRole); } /** * Platform specified updates */ if ($dbFarmRole->Platform == SERVER_PLATFORMS::EC2) { \Scalr\Modules\Platforms\Ec2\Helpers\EbsHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); \Scalr\Modules\Platforms\Ec2\Helpers\EipHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); \Scalr\Modules\Platforms\Ec2\Helpers\ElbHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); } if (in_array($dbFarmRole->Platform, array(SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::CLOUDSTACK))) { Scalr\Modules\Platforms\Cloudstack\Helpers\CloudstackHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); } $dbFarmRolesList[] = $dbFarmRole; $newFarmRolesList[] = $dbFarmRole->ID; } } if (!$this->getParam('roleUpdate')) { foreach ($dbFarm->GetFarmRoles() as $dbFarmRole) { if (!$dbFarmRole->NewRoleID && !in_array($dbFarmRole->ID, $newFarmRolesList)) { $dbFarmRole->Delete(); } } } $dbFarm->save(); if (!$client->GetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED)) { $client->SetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED, time()); } if ($this->request->isFarmAllowed($dbFarm, Acl::PERM_FARMS_LAUNCH_TERMINATE) && $this->getParam('launch')) { $this->user->getPermissions()->validate($dbFarm); $dbFarm->isLocked(); Scalr::FireEvent($dbFarm->ID, new FarmLaunchedEvent(true, $this->user->id)); $this->response->success('Farm successfully saved and launched'); } else { $this->response->success('Farm successfully saved'); } $this->response->data(array('farmId' => $dbFarm->ID, 'isNewFarm' => $bNew)); }
/** * Creates clone for the farm * * @param string|bool $name The name of the farm * @param Scalr_Account_User $user The user object * @param int $envId The identifier of the environment * @return DBFarm Returns clone */ public function cloneFarm($name = false, Scalr_Account_User $user, $envId) { $account = $user->getAccount(); $account->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1); $definition = $this->getDefinition(); if (!$name) { $template = ""; if (!preg_match('/^(.*?)\\(clone \\#([0-9]*)\\)$/si', $definition->name)) { $name = $definition->name; } else { preg_match('/^(.*?)\\(clone \\#([0-9]*)\\)$/si', $definition->name, $matches); $name = trim($matches[1]); } $name = preg_replace('/[^A-Za-z0-9_\\. -]+/', '', $name); $lastUsedIndex = $this->DB->GetOne('SELECT MAX(CAST((SUBSTR(@p:=SUBSTRING_INDEX(name, \'#\', -1), 1, LENGTH(@p) - 1)) AS UNSIGNED)) as lastUsedCloneNumber FROM farms WHERE name REGEXP \'' . str_replace('.', '\\.', $name) . ' \\\\(clone #[0-9]+\\\\)\' AND env_id = ?', array($envId)); $name = $name . ' (clone #' . ($lastUsedIndex + 1) . ')'; } $dbFarm = self::create($name, $user, $envId); $dbFarm->RolesLaunchOrder = $definition->rolesLaunchOrder; $dbFarm->SetSetting(Entity\FarmSetting::TIMEZONE, $definition->settings[Entity\FarmSetting::TIMEZONE]); $dbFarm->SetSetting(Entity\FarmSetting::EC2_VPC_ID, $definition->settings[Entity\FarmSetting::EC2_VPC_ID]); $dbFarm->SetSetting(Entity\FarmSetting::EC2_VPC_REGION, $definition->settings[Entity\FarmSetting::EC2_VPC_REGION]); $dbFarm->SetSetting(Entity\FarmSetting::SZR_UPD_REPOSITORY, $definition->settings[Entity\FarmSetting::SZR_UPD_REPOSITORY]); $dbFarm->SetSetting(Entity\FarmSetting::SZR_UPD_SCHEDULE, $definition->settings[Entity\FarmSetting::SZR_UPD_SCHEDULE]); $dbFarm->SetSetting(Entity\FarmSetting::LEASE_STATUS, $definition->settings[Entity\FarmSetting::LEASE_STATUS]); if ($definition->settings[Entity\FarmSetting::PROJECT_ID]) { $dbFarm->SetSetting(Entity\FarmSetting::PROJECT_ID, $definition->settings[Entity\FarmSetting::PROJECT_ID]); } $variables = new Scalr_Scripting_GlobalVariables($dbFarm->ClientID, $envId, ScopeInterface::SCOPE_FARM); $variables->setValues($definition->globalVariables, 0, $dbFarm->ID, 0); $this->cloneFarmRoles($dbFarm); $this->DB->Execute("\n INSERT INTO farm_teams (farm_id, team_id)\n SELECT ? AS farm_id, team_id\n FROM `farm_teams`\n WHERE farm_id = ?\n ", [$dbFarm->ID, $this->ID]); $dbFarm->save(); return $dbFarm; }
public function xSaveVariablesAction() { $this->request->restrictAccess(Acl::RESOURCE_GENERAL_GLOBAL_VARIABLES); $this->request->defineParams(array('variables' => array('type' => 'json'))); $vars = new Scalr_Scripting_GlobalVariables($this->getEnvironmentId()); $result = $vars->setValues($this->getParam('variables')); if ($result === true) { $this->response->success('Variables saved'); } else { $this->response->failure(); $this->response->data(array('errors' => array('variables' => $result))); } }