public static function targetToData(OrchestrationRule $entity, $object) { /* @var $entity FarmRoleScript */ parent::targetToData($entity, $object); if ($entity->target == static::TARGET_VALUE_SPECIFIED_FARM_ROLE) { /* @var $entity FarmRoleScript */ $farmRole = new FarmRole(); $targets = new FarmRoleScriptingTarget(); /* @var $target FarmRole */ foreach (FarmRole::find([['farmId' => $entity->farmId], AbstractEntity::STMT_FROM => "{$farmRole->table()} JOIN {$targets->table('t')} ON {$targets->columnTarget('t')} = {$farmRole->columnAlias()}", AbstractEntity::STMT_WHERE => "{$targets->columnFarmRoleScriptId('t')} = {$targets->qstr('farmRoleScriptId', $entity->id)} AND {$targets->columnTargetType('t')} = {$targets->qstr('targetType', OrchestrationRule::TARGET_ROLES)}"]) as $target) { $object->target->roles[] = ['id' => $target->id]; } } }
/** * Returns prepared orchestration log data for response * * @param EntityIterator $logs List of Orchestration Log objects * @return array */ private function prepareOrchestrationLogData($logs) { $farmIds = []; $serverIds = []; $taskIds = []; $eventIds = []; $ids = []; foreach ($logs as $row) { /* @var $row OrchestrationLog */ $farmIds[] = $row->farmId; $serverIds[] = $row->serverId; if ($row->eventServerId) { $serverIds[] = $row->eventServerId; } if ($row->taskId) { $taskIds[] = $row->taskId; } if ($row->eventId) { $eventIds[] = $row->eventId; } if ($row->type == OrchestrationLog::TYPE_MANUAL) { $ids[] = $row->id; } } if (!empty($farmIds)) { $farms = Farm::find([['id' => ['$in' => array_unique($farmIds)]]]); foreach ($farms as $farm) { /* @var $farm Farm */ $farmData[$farm->id] = $farm->name; } } if (!empty($serverIds)) { $servers = Server::find([['serverId' => ['$in' => array_unique($serverIds)]]]); $farmRoleIds = []; $serverFarmIds = []; foreach ($servers as $server) { /* @var $server Server */ $serverData[$server->serverId]['serverIndex'] = $server->index; $farmRoleIds[$server->serverId] = $server->farmRoleId; $serverFarmIds[$server->serverId] = $server->farmId; } $farms = Farm::find([['id' => ['$in' => array_unique(array_values($serverFarmIds))]]]); foreach ($farms as $farm) { /* @var $farm Farm */ foreach ($serverFarmIds as $serverId => $farmId) { if ($farmId == $farm->id) { $serverData[$serverId]['farmName'] = $farm->name; $serverData[$serverId]['farmId'] = $farm->id; } } } $farmRoles = FarmRole::find([['id' => ['$in' => array_unique(array_values($farmRoleIds))]]]); foreach ($farmRoles as $farmRole) { /* @var $farmRole FarmRole */ foreach ($farmRoleIds as $serverId => $farmRoleId) { if ($farmRoleId == $farmRole->id) { $serverData[$serverId]['alias'] = $farmRole->alias; $serverData[$serverId]['farmRoleId'] = $farmRole->id; } } } } if (!empty($taskIds)) { $tasks = SchedulerTask::find([['id' => ['$in' => array_unique($taskIds)]]]); foreach ($tasks as $task) { /* @var $task SchedulerTask */ $taskData[$task->id] = $task->name; } } if (!empty($eventIds)) { $events = Event::find([['eventId' => ['$in' => array_unique($eventIds)]]]); foreach ($events as $event) { /* @var $event Event */ $eventData[$event->eventId] = $event->type; } } if (!empty($ids)) { $manualLogs = OrchestrationLogManualScript::find([['orchestrationLogId' => ['$in' => array_unique($ids)]]]); foreach ($manualLogs as $manualLog) { /* @var $manualLog OrchestrationLogManualScript */ $scriptData[$manualLog->orchestrationLogId] = $manualLog->userEmail; } } $data = []; foreach ($logs as $row) { /* @var $row OrchestrationLog */ $dataRow = get_object_vars($row); $dataRow['targetFarmName'] = isset($farmData[$row->farmId]) ? $farmData[$row->farmId] : null; $dataRow['targetFarmId'] = $row->farmId; $dataRow['targetServerId'] = $row->serverId; $dataRow['targetServerIndex'] = isset($serverData[$row->serverId]['serverIndex']) ? $serverData[$row->serverId]['serverIndex'] : null; $dataRow['targetFarmRoleId'] = isset($serverData[$row->serverId]['farmRoleId']) ? $serverData[$row->serverId]['farmRoleId'] : null; $dataRow['targetRoleName'] = isset($serverData[$row->serverId]['alias']) ? $serverData[$row->serverId]['alias'] : null; $dataRow['added'] = Scalr_Util_DateTime::convertTz($row->added); if (\Scalr::config('scalr.system.scripting.logs_storage') == 'scalr') { $dataRow['executionId'] = null; } if ($dataRow['message']) { $dataRow['message'] = nl2br(htmlspecialchars($dataRow['message'])); } if ($row->eventServerId) { $dataRow['eventFarmName'] = isset($serverData[$row->eventServerId]['farmName']) ? $serverData[$row->eventServerId]['farmName'] : null; $dataRow['eventFarmId'] = isset($serverData[$row->eventServerId]['farmId']) ? $serverData[$row->eventServerId]['farmId'] : null; $dataRow['eventFarmRoleId'] = isset($serverData[$row->eventServerId]['farmRoleId']) ? $serverData[$row->eventServerId]['farmRoleId'] : null; $dataRow['eventRoleName'] = isset($serverData[$row->eventServerId]['alias']) ? $serverData[$row->eventServerId]['alias'] : null; $dataRow['eventServerIndex'] = isset($serverData[$row->eventServerId]['serverIndex']) ? $serverData[$row->eventServerId]['serverIndex'] : null; } $dataRow['event'] = null; if ($row->taskId) { $dataRow['event'] = isset($taskData[$row->taskId]) ? $taskData[$row->taskId] : null; } if ($row->eventId) { $dataRow['event'] = isset($eventData[$row->eventId]) ? $eventData[$row->eventId] : null; } if ($row->type == OrchestrationLog::TYPE_MANUAL) { $dataRow['event'] = isset($scriptData[$row->id]) ? $scriptData[$row->id] : null; } $data[] = $dataRow; } return $data; }
public function _vpc($from, $to, $action) { switch ($action) { case static::ACT_CONVERT_TO_OBJECT: /* @var $from Farm */ $vpc = []; if (!empty($from->settings[FarmSetting::EC2_VPC_ID])) { $vpc['id'] = $from->settings[FarmSetting::EC2_VPC_ID]; } if (!empty($from->settings[FarmSetting::EC2_VPC_REGION])) { $vpc['region'] = $from->settings[FarmSetting::EC2_VPC_REGION]; } if (!empty($vpc)) { $to->vpc = (object) $vpc; } break; case static::ACT_CONVERT_TO_ENTITY: /* @var $to Farm */ $vpcId = ApiController::getBareId($from, 'vpc'); if (!is_string($vpcId)) { throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_STRUCTURE, "Missed vpc.id property"); } if ($to->status || FarmRole::find([['farmId' => $to->id], ['platform' => \SERVER_PLATFORMS::EC2]], null, null, null, null, true)->totalNumber) { throw new ApiErrorException(400, ErrorMessage::ERR_OBJECT_IN_USE, "To change VPC settings you must first stop farm and remove all EC2 farm-roles"); } $to->settings[FarmSetting::EC2_VPC_ID] = $vpcId; if (!empty($from->vpc->region)) { $to->settings[FarmSetting::EC2_VPC_REGION] = $from->vpc->region; } break; case static::ACT_GET_FILTER_CRITERIA: $farm = new Farm(); $farmSetting = new FarmSetting(); $vpcId = ApiController::getBareId($from, 'vpc'); return [AbstractEntity::STMT_FROM => $farm->table() . " LEFT JOIN " . $farmSetting->table() . " ON {$farmSetting->columnFarmId} = {$farm->columnId}", AbstractEntity::STMT_WHERE => "({$farmSetting->columnName} = '" . FarmSetting::EC2_VPC_ID . "' AND {$farmSetting->columnValue} = " . $farmSetting->qstr('value', $vpcId) . ")"]; } }
/** * @param string $platform Name of platform * @param string $cloudLocation Name of location * @param array $ids The list of the identifiers of the cloud instances * @param int $roleId optional Identifier of Role * @return array * @throws Exception */ public function checkStatus($platform, $cloudLocation, $ids, $roleId = null) { if (!in_array($platform, $this->allowedPlatforms)) { throw new Exception(sprintf("Platform '%s' is not supported", $platform)); } if (!$this->environment->isPlatformEnabled($platform)) { throw new Exception(sprintf("Platform '%s' is not enabled", $platform)); } if (empty($ids) || empty($ids[0])) { throw new Exception("You should provide at least one instanceId"); } $instances = PlatformFactory::NewPlatform($platform)->getOrphanedServers($this->getEnvironmentEntity(), $cloudLocation, $ids); $status = ['instances' => $instances]; $imageIds = array_unique(array_map(function ($item) { return $item->imageId; }, $instances)); if (count($imageIds) != 1) { $status['compatibility'] = ['success' => false]; return $status; } /* @var $instance OrphanedServer */ $instance = $instances[0]; $status['compatibility'] = ['success' => true]; // Check vpc compatibility if ($instance->vpcId && $instance->subnetId) { $gov = new Scalr_Governance($this->getEnvironmentId()); $vpcGovernanceRegions = $gov->getValue(SERVER_PLATFORMS::EC2, Scalr_Governance::AWS_VPC, 'regions'); if (isset($vpcGovernanceRegions)) { if (!array_key_exists($cloudLocation, $vpcGovernanceRegions)) { $status['compatibility']['success'] = false; $status['compatibility']['message'] = sprintf('Region <b>%s</b> is not allowed by the Governance.', $cloudLocation); } else { $vpcGovernanceIds = $vpcGovernanceRegions[$cloudLocation]['ids']; if (!empty($vpcGovernanceIds) && !in_array($instance->vpcId, $vpcGovernanceIds)) { $status['compatibility']['success'] = false; $status['compatibility']['message'] = sprintf('VPC <b>%s</b> is not allowed by the Governance.', $instance->vpcId); } else { $vpcGovernanceIds = $gov->getValue(SERVER_PLATFORMS::EC2, Scalr_Governance::AWS_VPC, 'ids'); /* @var $platformObject Ec2PlatformModule */ $platformObject = PlatformFactory::NewPlatform(SERVER_PLATFORMS::EC2); $subnet = $platformObject->listSubnets($this->getEnvironment(), $cloudLocation, $instance->vpcId, true, $instance->subnetId); if (isset($vpcGovernanceIds[$instance->vpcId])) { if (!empty($vpcGovernanceIds[$instance->vpcId]) && is_array($vpcGovernanceIds[$instance->vpcId]) && !in_array($instance->subnetId, $vpcGovernanceIds[$instance->vpcId])) { $status['compatibility']['success'] = false; $status['compatibility']['message'] = sprintf('Subnet <b>%s</b> is prohibited by the Governance.', $instance->subnetId); } else { if ($vpcGovernanceIds[$instance->vpcId] == "outbound-only" && $subnet['type'] != 'private') { $status['compatibility']['success'] = false; $status['compatibility']['message'] = 'Only private subnets are allowed by the Governance.'; } else { if ($vpcGovernanceIds[$instance->vpcId] == "full" && $subnet['type'] != 'public') { $status['compatibility']['success'] = false; $status['compatibility']['message'] = 'Only public subnets are allowed by the Governance.'; } } } } } } } } if (!$status['compatibility']['success']) { return $status; } $scopeCriteria = ['$or' => [['accountId' => null], ['$and' => [['accountId' => $this->getUser()->accountId], ['$or' => [['envId' => null], ['envId' => $this->getEnvironment()->id]]]]]]]; /* @var $image Entity\Image */ $image = Entity\Image::findOne([['platform' => $platform], ['cloudLocation' => $cloudLocation], ['id' => $instance->imageId], $scopeCriteria]); $status['image'] = ['success' => !!$image, 'data' => ['id' => $instance->imageId]]; if ($image) { if ($image->isScalarized) { $status['image']['success'] = false; $status['image']['isScalarized'] = true; return $status; } $status['image']['data'] = ['hash' => $image->hash, 'name' => $image->name, 'id' => $image->id, 'scope' => $image->getScope()]; $criteria = [['platform' => $platform], ['imageId' => $image->id]]; if (!($platform == SERVER_PLATFORMS::GCE || $platform == SERVER_PLATFORMS::AZURE)) { $criteria[] = ['cloudLocation' => $cloudLocation]; } $roleIds = []; foreach (Entity\RoleImage::find($criteria) as $ri) { $roleIds[] = $ri->roleId; } if (count($roleIds)) { $roles = Entity\Role::find([['id' => ['$in' => $roleIds]], ['isScalarized' => false], $scopeCriteria]); $status['role'] = ['availableRoles' => [], 'image' => Scalr_UI_Controller_Images::controller()->convertEntityToArray($image)]; $selectedRole = null; if (count($roles) == 1) { $selectedRole = $roles->current(); } else { if ($roleId && in_array($roleId, $roleIds)) { foreach ($roles as $role) { /* @var $role Entity\Role */ if ($role->id == $roleId) { $selectedRole = $role; break; } } } } foreach ($roles as $role) { /* @var $role Entity\Role */ $status['role']['availableRoles'][] = ['id' => $role->id, 'name' => $role->name, 'scope' => $role->getScope()]; } if ($selectedRole) { $status['role']['success'] = true; $status['role']['data'] = ['id' => $selectedRole->id, 'name' => $selectedRole->name, 'scope' => $selectedRole->getScope()]; $farms = []; $status['farmrole'] = ['instance' => ['instanceType' => $instance->instanceType, 'vpcId' => $instance->vpcId, 'subnetId' => $instance->subnetId, 'roleName' => $selectedRole->name]]; foreach (Entity\Farm::find([['envId' => $this->getEnvironment()->id], ['status' => FARM_STATUS::RUNNING]]) as $farm) { /* @var $farm Entity\Farm */ if ($this->request->hasPermissions($farm, Acl::PERM_FARMS_UPDATE) && $this->request->hasPermissions($farm, Acl::PERM_FARMS_SERVERS)) { // cloud specific (EC2) if ($farm->settings[Entity\FarmSetting::EC2_VPC_ID] == $instance->vpcId) { $farms[$farm->id] = ['id' => $farm->id, 'name' => $farm->name, 'farmroles' => []]; } } } foreach (Entity\FarmRole::find([['farmId' => ['$in' => array_keys($farms)]], ['roleId' => $selectedRole->id]]) as $farmRole) { /* @var $farmRole Entity\FarmRole */ if (isset($farms[$farmRole->farmId])) { if (!$instance->subnetId || $instance->subnetId && in_array($instance->subnetId, json_decode($farmRole->settings[Entity\FarmRoleSetting::AWS_VPC_SUBNET_ID]))) { $farms[$farmRole->farmId]['farmroles'][] = ['id' => $farmRole->id, 'name' => $farmRole->alias, 'tags' => $farmRole->getCloudTags(true)]; } } } $status['farmrole']['data'] = array_values($farms); $status['farmrole']['success'] = false; } else { if (count($roles) > 1) { $status['role']['success'] = false; } else { $status['role']['success'] = false; } } } else { $status['role']['success'] = false; $status['role']['image'] = Scalr_UI_Controller_Images::controller()->convertEntityToArray($image); } } return $status; }
/** * Get information about role * * @param int $roleId Identifier of role * @param bool $extended Get extended information about role * @param array $canAddImage Array of platform, cloudLocation to check if role has image in that location * @return array * @throws Exception * @throws Scalr_Exception_Core * @throws Scalr_Exception_InsufficientPermissions */ private function getInfo($roleId, $extended = false, $canAddImage = null) { /* @var $role Role */ $role = Role::findPk($roleId); if (!$role) { throw new Scalr_Exception_Core(sprintf(_("Role ID#%s not found in database"), $roleId)); } $this->request->checkPermissions($role); $usedBy = $role->getFarmsCount($this->user->getAccountId(), $this->getEnvironmentId(true)); $platforms = array_keys($role->fetchImagesArray()); $allPlatforms = array_flip(array_keys(SERVER_PLATFORMS::GetList())); usort($platforms, function ($a, $b) use($allPlatforms) { return $allPlatforms[$a] > $allPlatforms[$b] ? 1 : -1; }); $result = array('name' => $role->name, 'behaviors' => $role->getBehaviors(), 'id' => $role->id, 'accountId' => $role->accountId, 'envId' => $role->envId, 'catId' => $role->catId, 'status' => $usedBy > 0 ? 'In use' : 'Not used', 'scope' => $role->getScope(), 'os' => $role->getOs()->name, 'osId' => $role->osId, 'osFamily' => $role->getOs()->family, 'dtAdded' => $role->added ? Scalr_Util_DateTime::convertTz($role->added) : NULL, 'dtLastUsed' => $role->lastUsed ? Scalr_Util_DateTime::convertTz($role->lastUsed) : NULL, 'isQuickStart' => $role->isQuickStart, 'isDeprecated' => $role->isDeprecated, 'isScalarized' => $role->isScalarized, 'platforms' => $platforms, 'environments' => !empty($envs = $role->getAllowedEnvironments()) ? $this->db->GetCol("SELECT name FROM client_environments WHERE id IN(" . join(',', $envs) . ")") : []); if ($canAddImage) { try { $role->getImage($canAddImage['platform'], $canAddImage['cloudLocation']); $result['canAddImage'] = false; } catch (Exception $e) { $result['canAddImage'] = true; } } if ($extended) { $result['description'] = $role->description; $result['images'] = []; foreach (RoleImage::find([['roleId' => $role->id]]) as $image) { /* @var $image RoleImage */ $im = $image->getImage(); $ext = []; if ($im) { $ext = get_object_vars($im); $ext['software'] = $im->getSoftwareAsString(); } $result['images'][] = ['imageId' => $image->imageId, 'platform' => $image->platform, 'cloudLocation' => $image->cloudLocation, 'extended' => $ext]; } if ($result['status'] == 'In use' && $this->getEnvironmentId(true)) { $farms = []; $f = []; foreach (FarmRole::find([['roleId' => $role->id]]) as $farmRole) { /* @var $farmRole FarmRole */ $f[] = $farmRole->farmId; } $f = array_unique($f); if (count($f)) { foreach (Farm::find([['id' => ['$in' => $f]], ['envId' => $this->getEnvironmentId()]]) as $fm) { /* @var $fm Farm */ $farms[] = ['id' => $fm->id, 'name' => $fm->name]; } } $result['usedBy'] = ['farms' => $farms, 'cnt' => count($farms)]; } } return $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)); }
/** * {@inheritdoc} * @see AbstractEntity::__set() */ public function __set($name, $value) { switch ($name) { case 'targets': if (!is_array($value)) { $value = (array) $value; } /* @var $farmRole FarmRole */ foreach (FarmRole::find([['id' => ['$in' => $value]]]) as $farmRole) { $target = new FarmRoleScriptingTarget(); $target->farmRoleScriptId =& $this->id; $target->targetType = OrchestrationRule::TARGET_ROLES; $target->target = $farmRole->alias; $this->_targets[$farmRole->id] = $target; } if ($notFound = array_diff_key(array_flip($value), $this->_targets)) { throw new InvalidEntityConfigurationException("Invalid target. Not found Farm Roles with IDs: [" . implode(', ', array_keys($notFound)) . "]"); } break; default: parent::__set($name, $value); } }