Пример #1
0
 /**
  * {@inheritdoc}
  * @see Scalr\Tests\TestCase::tearDownAfterClass()
  */
 public static function tearDownAfterClass()
 {
     foreach (static::$testData as $rec) {
         if ($rec['class'] === Farm::class) {
             $entry = $rec['pk'];
             $farm = Farm::findPk(...$entry);
             /* @var $farm Farm */
             if (!empty($farm)) {
                 try {
                     \Scalr::FireEvent($farm->id, new FarmTerminatedEvent(false, false, false, false, true, static::$user->id));
                     foreach ($farm->servers as $server) {
                         try {
                             $dbServer = Server::findPk($server->serverId);
                             /* @var $dbServer Server */
                             $dbServer->terminate(Server::TERMINATE_REASON_FARM_TERMINATED, true, static::$user);
                         } catch (Exception $e) {
                             \Scalr::logException($e);
                         }
                         $server->delete();
                     }
                 } catch (Exception $e) {
                     \Scalr::logException($e);
                 }
             }
         }
     }
     parent::tearDownAfterClass();
 }
Пример #2
0
 /**
  * Gets specified Farm taking into account both scope and authentication token
  *
  * @param   string  $farmId              Numeric identifier of the Farm
  * @param   string  $permission optional Permission identifier
  *
  * @return  Farm    Returns the Farm Entity on success
  * @throws  ApiErrorException
  */
 public function getFarm($farmId, $permission = null)
 {
     /* @var $farm Farm */
     $farm = Farm::findPk($farmId);
     if (!$farm) {
         throw new ApiErrorException(404, ErrorMessage::ERR_OBJECT_NOT_FOUND, "Requested Farm either does not exist or is not owned by your environment.");
     }
     $this->checkPermissions($farm, $permission);
     return $farm;
 }
Пример #3
0
 /**
  * @return Entity\Farm
  * @throws Exception
  */
 public function __getNewFarmObject()
 {
     if (!$this->__newFarmObject) {
         if ($this->ID) {
             $this->__newFarmObject = Entity\Farm::findPk($this->ID);
         }
         if (!$this->__newFarmObject) {
             throw new Exception('Farm object is not found');
         }
     }
     return $this->__newFarmObject;
 }
Пример #4
0
 /**
  * Gets specified Farm taking into account both scope and authentication token
  *
  * @param   string  $farmId              Numeric identifier of the Farm
  * @param   string  $permission optional Permission identifier
  *
  * @return  Farm    Returns the Farm Entity on success
  * @throws  ApiErrorException
  */
 public function getFarm($farmId, $permission = null)
 {
     /* @var $farm Farm */
     $farm = Farm::findPk($farmId);
     if (!$farm) {
         throw new ApiErrorException(404, ErrorMessage::ERR_OBJECT_NOT_FOUND, "Requested Farm either does not exist or is not owned by your environment.");
     }
     if (!$this->hasPermissions($farm)) {
         //Checks entity level write access permissions
         throw new ApiErrorException(403, ErrorMessage::ERR_PERMISSION_VIOLATION, "Insufficient permissions");
     }
     $this->checkPermissions($farm, $permission);
     return $farm;
 }
Пример #5
0
 /**
  * Covert object to array (without public/private keys)
  *
  * @param SshKey $key
  * @return array
  */
 public function getSshKeyObject($key)
 {
     /* @var $farm Farm */
     return ['id' => $key->id, 'type' => $key->type, 'cloudKeyName' => $key->cloudKeyName, 'platform' => $key->platform, 'cloudLocation' => $key->cloudLocation, 'farmId' => $key->farmId, 'farmName' => $key->farmId && ($farm = Farm::findPk($key->farmId)) ? $farm->name : '', 'status' => $key->isUsed() ? 'In use' : 'Not used'];
 }
Пример #6
0
 /**
  * {@inheritdoc}
  * @see ApiEntityAdapter::validateEntity()
  */
 public function validateEntity($entity)
 {
     if (!$entity instanceof Farm) {
         throw new InvalidArgumentException(sprintf("First argument must be instance of Scalr\\Model\\Entity\\Farm class"));
     }
     if ($entity->id !== null) {
         if (!Farm::findPk($entity->id)) {
             throw new ApiErrorException(404, ErrorMessage::ERR_OBJECT_NOT_FOUND, sprintf("Could not find out the Farm with ID: %d", $entity->id));
         }
     } else {
         if (empty($entity->name)) {
             throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_STRUCTURE, "Missed property name");
         }
         $criteria = $this->controller->getScopeCriteria();
         $criteria[] = ['name' => $entity->name];
         if (count(Farm::find($criteria))) {
             throw new ApiErrorException(409, ErrorMessage::ERR_UNICITY_VIOLATION, "Farm with name '{$entity->name}' already exists");
         }
     }
     if (!empty($entity->settings[FarmSetting::EC2_VPC_REGION])) {
         $region = $entity->settings[FarmSetting::EC2_VPC_REGION];
         $vpcId = $entity->settings[FarmSetting::EC2_VPC_ID];
         if (!in_array($region, Aws::getCloudLocations())) {
             throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, "Unknown VPC region");
         }
         $gov = new Scalr_Governance($this->controller->getEnvironment()->id);
         $vpcGovernanceRegions = $gov->getValue(SERVER_PLATFORMS::EC2, Scalr_Governance::AWS_VPC, 'regions');
         if (isset($vpcGovernanceRegions)) {
             if (!array_key_exists($region, $vpcGovernanceRegions)) {
                 $regions = array_keys($vpcGovernanceRegions);
                 throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, sprintf("Only %s %s allowed according to governance settings", ...count($regions) > 1 ? [implode(', ', $regions), 'regions are'] : [array_shift($regions), 'region is']));
             }
             $vpcGovernanceIds = $vpcGovernanceRegions[$region]['ids'];
             if (!empty($vpcGovernanceIds) && !in_array($vpcId, $vpcGovernanceIds)) {
                 throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, sprintf("Only %s %s allowed according to governance settings", ...count($vpcGovernanceIds) > 1 ? [implode(', ', $vpcGovernanceIds), 'vpcs are'] : [array_shift($vpcGovernanceIds), 'vpc is']));
             }
         }
         $found = null;
         /* @var $vpc VpcData */
         //TODO rewrite aws service usage
         foreach ($this->controller->getContainer()->aws($region, $this->controller->getEnvironment())->ec2->vpc->describe() as $vpc) {
             if ($vpcId == $vpc->vpcId) {
                 $found = $vpc;
             }
         }
         if (empty($found)) {
             throw new ApiErrorException(400, ErrorMessage::ERR_OBJECT_NOT_FOUND, "Could not find out the VPC with ID '{$vpcId}' in region '{$region}'");
         }
     } else {
         if (!empty($entity->settings[FarmSetting::EC2_VPC_ID])) {
             throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_STRUCTURE, "Missed property vpc.region");
         }
     }
     if (\Scalr::config('scalr.analytics.enabled')) {
         if (isset($entity->settings[FarmSetting::PROJECT_ID])) {
             if (!$this->controller->getContainer()->analytics->projects->get($entity->settings[FarmSetting::PROJECT_ID])) {
                 throw new ApiErrorException(403, ErrorMessage::ERR_PERMISSION_VIOLATION, "The project is not allowed for you");
             }
         } else {
             throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_STRUCTURE, "Missed property project");
         }
     }
     if (!$this->controller->hasPermissions($entity, true)) {
         //Checks entity level write access permissions
         throw new ApiErrorException(403, ErrorMessage::ERR_PERMISSION_VIOLATION, "Insufficient permissions");
     }
 }
Пример #7
0
 /**
  * Asserts post farm response
  *
  * @param ApiTestResponse $response
  * @param array           $data
  */
 public function assertPostFarms(ApiTestResponse $response, $data)
 {
     $this->assertEquals(201, $response->status, $this->printResponseError($response));
     $farmId = $response->getBody()->data->id;
     /* @var $farm Farm */
     $farm = Farm::findPk($farmId);
     $this->assertNotEmpty($farm);
     $this->farmToDelete($farmId);
     $this->assertObjectEqualsEntity($data, $farm);
 }
Пример #8
0
 /**
  * @param int $farmId
  * @param int $farmRoleId optional
  * @param string $serverId optional
  * @param int $scriptId optional
  * @param string $scriptPath optional
  * @param int $scriptIsSync
  * @param int $scriptTimeout
  * @param int $scriptVersion
  * @param array $scriptParams optional
  * @param int $shortcutId optional
  * @param int $editShortcut optional
  * @throws Exception
  */
 public function xExecuteAction($farmId, $farmRoleId = 0, $serverId = '', $scriptId = 0, $scriptPath = '', $scriptIsSync, $scriptTimeout, $scriptVersion, array $scriptParams = [], $shortcutId = null, $editShortcut = null)
 {
     $this->request->restrictAccess(Acl::RESOURCE_SCRIPTS_ENVIRONMENT, Acl::PERM_SCRIPTS_ENVIRONMENT_EXECUTE);
     if ($serverId) {
         $dbServer = DBServer::LoadByID($serverId);
         $this->user->getPermissions()->validate($dbServer);
         $target = Script::TARGET_INSTANCE;
         $serverId = $dbServer->serverId;
         $farmRoleId = $dbServer->farmRoleId;
         $farmId = $dbServer->farmId;
     } else {
         if ($farmRoleId) {
             $dbFarmRole = DBFarmRole::LoadByID($farmRoleId);
             $this->user->getPermissions()->validate($dbFarmRole);
             $target = Script::TARGET_ROLE;
             $farmRoleId = $dbFarmRole->ID;
             $farmId = $dbFarmRole->FarmID;
         } else {
             if (!$farmId) {
                 $target = Script::TARGET_ALL;
             } else {
                 $dbFarm = DBFarm::LoadByID($farmId);
                 $this->user->getPermissions()->validate($dbFarm);
                 $target = Script::TARGET_FARM;
                 $farmId = $dbFarm->ID;
             }
         }
     }
     if ($farmId) {
         $this->request->checkPermissions(Entity\Farm::findPk($farmId), Acl::PERM_FARMS_SERVERS);
     }
     if ($scriptId) {
         $script = Script::findPk($scriptId);
         /* @var $script Script */
         if (!$script) {
             throw new Scalr_UI_Exception_NotFound();
         }
         $script->checkPermission($this->user, $this->getEnvironmentId());
     } elseif (!$scriptPath) {
         throw new Scalr_Exception_Core('scriptId or scriptPath should be set');
     }
     if (!$scriptTimeout) {
         $scriptTimeout = $scriptIsSync == 1 ? Scalr::config('scalr.script.timeout.sync') : Scalr::config('scalr.script.timeout.async');
     }
     $executeScript = true;
     if ($shortcutId && ($target != Script::TARGET_INSTANCE || $target != Script::TARGET_ALL)) {
         if ($shortcutId == -1) {
             $shortcut = new ScriptShortcut();
             $shortcut->farmId = $farmId;
         } else {
             $shortcut = ScriptShortcut::findPk($shortcutId);
             /* @var $shortcut ScriptShortcut */
             if (!$shortcut) {
                 throw new Scalr_UI_Exception_NotFound();
             }
             if ($editShortcut == 1) {
                 $executeScript = false;
             }
         }
         $shortcut->farmRoleId = $farmRoleId == 0 ? NULL : $farmRoleId;
         if ($scriptId) {
             $shortcut->scriptId = $scriptId;
             $shortcut->scriptPath = '';
         } else {
             $shortcut->scriptPath = $scriptPath;
             $shortcut->scriptId = NULL;
         }
         $shortcut->isSync = $scriptIsSync;
         $shortcut->version = $scriptVersion;
         $shortcut->timeout = $scriptTimeout;
         $shortcut->params = $scriptParams;
         $shortcut->save();
     }
     if ($executeScript) {
         switch ($target) {
             case Script::TARGET_FARM:
                 $servers = $this->db->GetAll("\n                        SELECT server_id\n                        FROM servers\n                        WHERE is_scalarized = 1 AND status IN (?,?) AND farm_id=?", [SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, $farmId]);
                 break;
             case Script::TARGET_ROLE:
                 $servers = $this->db->GetAll("\n                        SELECT server_id\n                        FROM servers\n                        WHERE is_scalarized = 1 AND status IN (?,?) AND farm_roleid=?", [SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, $farmRoleId]);
                 break;
             case Script::TARGET_INSTANCE:
                 $servers = $this->db->GetAll("\n                        SELECT server_id\n                        FROM servers\n                        WHERE is_scalarized = 1 AND status IN (?,?) AND server_id=?", [SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, $serverId]);
                 break;
             case Script::TARGET_ALL:
                 $sql = "\n                        SELECT s.server_id\n                        FROM servers s\n                        JOIN farms f ON f.id = s.farm_id\n                        WHERE s.is_scalarized = 1\n                        AND s.status IN (?,?)\n                        AND s.env_id = ?\n                        AND " . $this->request->getFarmSqlQuery(Acl::PERM_FARMS_SERVERS);
                 $args = [SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, $this->getEnvironmentId()];
                 $servers = $this->db->GetAll($sql, $args);
                 break;
         }
         $scriptSettings = array('version' => $scriptVersion, 'timeout' => $scriptTimeout, 'issync' => $scriptIsSync, 'params' => serialize($scriptParams));
         if ($scriptId) {
             $scriptSettings['scriptid'] = $scriptId;
             $scriptSettings['type'] = Scalr_Scripting_Manager::ORCHESTRATION_SCRIPT_TYPE_SCALR;
         } else {
             $scriptSettings['script_path'] = $scriptPath;
             $scriptSettings['type'] = Scalr_Scripting_Manager::ORCHESTRATION_SCRIPT_TYPE_LOCAL;
         }
         $serializer = Scalr_Messaging_JsonSerializer::getInstance();
         $cryptoTool = \Scalr::getContainer()->srzcrypto;
         // send message to start executing task (starts script)
         if (count($servers) > 0) {
             foreach ($servers as $server) {
                 $DBServer = DBServer::LoadByID($server['server_id']);
                 $msg = new Scalr_Messaging_Msg_ExecScript("Manual");
                 $msg->setServerMetaData($DBServer);
                 $script = Scalr_Scripting_Manager::prepareScript($scriptSettings, $DBServer);
                 if ($script) {
                     $DBServer->executeScript($script, $msg);
                     $this->auditLog("script.execute", $script, $DBServer);
                     $manualLog = new OrchestrationLogManualScript($script['execution_id'], $msg->serverId);
                     $manualLog->userId = $this->getUser()->getId();
                     $manualLog->userEmail = $this->getUser()->getEmail();
                     $manualLog->added = new DateTime('now', new DateTimeZone('UTC'));
                     $manualLog->save();
                 }
             }
         }
         $this->response->success('Script execution has been queued and will occur on the selected instance(s) within a couple of minutes.');
     } else {
         $this->response->success('Script shortcut successfully saved');
     }
 }
Пример #9
0
 /**
  * Checks whether Farm can be accessed by user
  *
  * @param       int         $farmId   ID of Farm
  * @param       int         $envId    ID of Environment
  * @param       string      $perm     optional Name of permission
  * @return      boolean     Returns true if access is granted
  */
 public function hasAccessFarm($farmId, $envId, $perm = null)
 {
     /* @var Farm $farm */
     $farm = Farm::findPk($farmId);
     if (!$farm) {
         return false;
     }
     if ($farm->envId != $envId) {
         return false;
     }
     $superposition = $this->getAclRolesByEnvironment($envId);
     $result = $superposition->isAllowed(Acl::RESOURCE_FARMS, $perm);
     if (!$result && $farm->teamId && $this->inTeam($farm->teamId)) {
         $result = $superposition->isAllowed(Acl::RESOURCE_TEAM_FARMS, $perm);
     }
     if (!$result && $farm->createdById && $this->id == $farm->createdById) {
         $result = $superposition->isAllowed(Acl::RESOURCE_OWN_FARMS, $perm);
     }
     return $result;
 }
Пример #10
0
 /**
  * {@inheritdoc}
  * @see \Scalr\DataType\AccessPermissionsInterface::hasAccessPermissions()
  */
 public function hasAccessPermissions($user, $environment = null, $modify = null)
 {
     if (empty($environment)) {
         return false;
     }
     if ($environment->id != $this->envId) {
         return false;
     }
     return $this->farmId ? Farm::findPk($this->farmId)->hasAccessPermissions($user, $environment) : true;
 }
Пример #11
0
 /**
  * {@inheritdoc}
  * @see AccessPermissionsInterface::hasAccessPermissions()
  */
 public function hasAccessPermissions($user, $environment = null, $modify = null)
 {
     /* @var $farm Farm */
     $farm = Farm::findPk($this->farmId);
     return $environment ? $farm->envId == $environment->id : $user->hasAccessToEnvironment($farm->envId);
 }
Пример #12
0
 /**
  * xMoveProjectsAction
  *
  * @param JsonData $projects Projects that should be moved
  * @throws AnalyticsException
  * @throws Exception
  * @throws \Scalr\Exception\ModelException
  */
 public function xMoveProjectsAction(JsonData $projects = null)
 {
     $envChange = [];
     $accountChange = [];
     $projectChange = [];
     $ccEntityCache = [];
     $collisions = [];
     foreach ($projects as $project) {
         $projectEntity = ProjectEntity::findPk($project['projectId']);
         /* @var $projectEntity ProjectEntity */
         if (empty($ccEntity)) {
             $ccEntity = $projectEntity->getCostCenter();
         }
         if ($ccEntity->ccId == $project['ccId']) {
             continue;
         }
         if (empty($ccEntityCache[$project['ccId']])) {
             $newCcEntity = CostCentreEntity::findPk($project['ccId']);
             /* @var $newCcEntity CostCentreEntity */
             if (!$newCcEntity) {
                 throw new Exception(sprintf("Cost center with id %s has not been found.", $project['ccId']), 404);
             }
             $ccEntityCache[$project['ccId']] = $newCcEntity->ccId;
         }
         $farms[$projectEntity->projectId] = $projectEntity->getFarmsList();
         foreach ($farms[$projectEntity->projectId] as $farmId => $farmName) {
             $farmEntity = Farm::findPk($farmId);
             /* @var $farmEntity Farm */
             if (empty($accountChange[$farmEntity->accountId])) {
                 $accountCss = AccountCostCenterEntity::findOne([['accountId' => $farmEntity->accountId], ['ccId' => $newCcEntity->ccId]]);
                 if (!$accountCss) {
                     $accountChange[$farmEntity->accountId] = $newCcEntity->ccId;
                 }
             }
             if (empty($envChange[$farmEntity->envId])) {
                 $project['name'] = $projectEntity->name;
                 $envChange[$farmEntity->envId] = $project;
             } else {
                 if ($envChange[$farmEntity->envId]['ccId'] != $project['ccId']) {
                     if (!in_array($projectEntity->name, $collisions)) {
                         $collisions[] = $projectEntity->name;
                     }
                     if (!in_array($envChange[$farmEntity->envId]['name'], $collisions)) {
                         $collisions[] = $envChange[$farmEntity->envId]['name'];
                     }
                     continue;
                 }
             }
         }
         $projectEntity->ccId = $project['ccId'];
         $projectChange[$projectEntity->projectId] = $projectEntity;
     }
     $remainningEnvs = [];
     $projectsCount = count($projectChange);
     if ($projectsCount) {
         if (isset($ccEntity)) {
             $envList = $ccEntity->getEnvironmentsList();
             foreach ($envList as $envId => $name) {
                 if (isset($envChange[$envId])) {
                     $ccProjects = $this->getContainer()->analytics->projects->getUsedInEnvironment($envId);
                     foreach ($ccProjects as $project) {
                         /* @var $project ProjectEntity */
                         if (!isset($farms[$project->projectId])) {
                             $farms[$project->projectId] = $project->getFarmsList();
                         }
                         if (count($farms[$project->projectId]) > 0 && !isset($projectChange[$project->projectId])) {
                             if (!in_array($envId, $remainningEnvs)) {
                                 $remainningEnvs[] = $envId;
                             }
                         }
                     }
                 }
             }
         }
         $this->db->BeginTrans();
         try {
             foreach ($accountChange as $accountId => $ccId) {
                 $accountCss = new AccountCostCenterEntity($accountId, $ccId);
                 $accountCss->save();
             }
             if (empty($remainningEnvs) && empty($collisions)) {
                 foreach ($envChange as $envId => $data) {
                     $envProp = EnvironmentProperty::findOne([['envId' => $envId], ['name' => EnvironmentProperty::SETTING_CC_ID]]);
                     /* @var $envProp EnvironmentProperty */
                     $envProp->value = $data['ccId'];
                     $envProp->save();
                 }
             }
             foreach ($projectChange as $project) {
                 /* @var $project ProjectEntity */
                 $project->save();
             }
             $this->db->CommitTrans();
         } catch (Exception $e) {
             $this->db->RollbackTrans();
             throw $e;
         }
     }
     if (count($collisions) > 0) {
         $this->response->warning(sprintf("%d Project%s %s been moved however collision occurred. Projects '%s' are used in the Farms from the same Environment however they have been moved to different Cost Centers.", $projectsCount, $projectsCount > 1 ? 's' : '', $projectsCount > 1 ? 'have' : 'has', implode("', '", $collisions)));
     } else {
         if (count($remainningEnvs) > 0) {
             $this->response->warning(sprintf("%d Project%s %s been moved however some Projects don't correspond to Cost Centers assigned to Environments '%s'.", $projectsCount, $projectsCount > 1 ? 's' : '', $projectsCount > 1 ? 'have' : 'has', implode("', '", $remainningEnvs)));
         } else {
             $this->response->success(sprintf("%d Project%s %s been moved to other Cost Center.", $projectsCount, $projectsCount > 1 ? 's' : '', $projectsCount > 1 ? 'have' : 'has'));
         }
     }
 }
Пример #13
0
 /**
  * @param int $farmId
  * @throws Scalr_Exception_InsufficientPermissions
  */
 public function xGetOwnerHistoryAction($farmId)
 {
     $dbFarm = DBFarm::LoadByID($farmId);
     $this->user->getPermissions()->validate($dbFarm);
     $this->request->checkPermissions($dbFarm->__getNewFarmObject(), Acl::PERM_FARMS_UPDATE);
     if ($dbFarm->ownerId == $this->user->getId() || $this->request->hasPermissions($dbFarm->__getNewFarmObject(), Acl::PERM_FARMS_CHANGE_OWNERSHIP)) {
         $data = array_map(function ($item) {
             $item['dtTm'] = Scalr_Util_DateTime::convertTz($item['dt']);
             return $item;
         }, Entity\FarmSetting::getOwnerHistory(Entity\Farm::findPk($farmId)));
         $this->response->data(['history' => $data]);
     } else {
         throw new Scalr_Exception_InsufficientPermissions();
     }
 }
Пример #14
0
 /**
  * Get Farm entity
  *
  * @return Farm|null    Returns the Farm entity which is associated with the Server or null otherwise
  */
 public function getFarm()
 {
     if (empty($this->_farm) && !empty($this->farmId)) {
         $this->_farm = Farm::findPk($this->farmId);
     }
     return $this->_farm;
 }
Пример #15
0
 public function getFarm2($farmId)
 {
     $dbFarm = DBFarm::LoadByID($farmId);
     $this->user->getPermissions()->validate($dbFarm);
     $farmRoles = array();
     $variables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), ScopeInterface::SCOPE_FARM);
     $farmRoleVariables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), ScopeInterface::SCOPE_FARMROLE);
     foreach ($dbFarm->GetFarmRoles() as $dbFarmRole) {
         $scripts = $this->db->GetAll("\n                SELECT farm_role_scripts.*, scripts.name, scripts.os\n                FROM farm_role_scripts\n                LEFT JOIN scripts ON scripts.id = farm_role_scripts.scriptid\n                WHERE farm_roleid=? AND issystem='1'\n            ", array($dbFarmRole->ID));
         $scriptsObject = array();
         foreach ($scripts as $script) {
             if (!empty($script['scriptid']) && $script['script_type'] == Scalr_Scripting_Manager::ORCHESTRATION_SCRIPT_TYPE_SCALR || !empty($script['script_path']) && $script['script_type'] == Scalr_Scripting_Manager::ORCHESTRATION_SCRIPT_TYPE_LOCAL || !empty($script['params']) && $script['script_type'] == Scalr_Scripting_Manager::ORCHESTRATION_SCRIPT_TYPE_CHEF) {
                 $s = array('script_type' => $script['script_type'], 'script_id' => (int) $script['scriptid'], 'script' => $script['name'], 'os' => $script['os'], 'params' => unserialize($script['params']), 'target' => $script['target'], 'version' => (int) $script['version'], 'timeout' => $script['timeout'], 'isSync' => (int) $script['issync'], 'order_index' => $script['order_index'], 'event' => $script['event_name'], 'script_path' => $script['script_path'], 'run_as' => $script['run_as']);
                 if ($script['target'] == Script::TARGET_BEHAVIORS || $script['target'] == Script::TARGET_ROLES || $script['target'] == Script::TARGET_FARMROLES) {
                     switch ($script['target']) {
                         case $script['target'] == Script::TARGET_ROLES:
                             $varName = 'target_roles';
                             break;
                         case $script['target'] == Script::TARGET_FARMROLES:
                             $varName = 'target_farmroles';
                             break;
                         case $script['target'] == Script::TARGET_BEHAVIORS:
                             $varName = 'target_behaviors';
                             break;
                     }
                     $s[$varName] = array();
                     $r = $this->db->GetAll("SELECT `target` FROM farm_role_scripting_targets WHERE farm_role_script_id = ?", array($script['id']));
                     foreach ($r as $v) {
                         array_push($s[$varName], $v['target']);
                     }
                 }
                 $scriptsObject[] = $s;
             }
         }
         //Scripting params
         $scriptingParams = $this->db->Execute("\n                SELECT * FROM farm_role_scripting_params\n                WHERE farm_role_id = ? AND farm_role_script_id = '0'\n            ", array($dbFarmRole->ID));
         $sParams = array();
         while ($p = $scriptingParams->FetchRow()) {
             $sParams[] = array('hash' => $p['hash'], 'role_script_id' => $p['role_script_id'], 'params' => unserialize($p['params']));
         }
         $scalingManager = new Scalr_Scaling_Manager($dbFarmRole);
         $scaling = array();
         foreach ($scalingManager->getFarmRoleMetrics() as $farmRoleMetric) {
             $scaling[$farmRoleMetric->metricId] = $farmRoleMetric->getSettings();
         }
         $roleName = $dbFarmRole->GetRoleObject()->name;
         $storages = array('configs' => $dbFarmRole->getStorage()->getConfigs());
         foreach ($dbFarmRole->getStorage()->getVolumes() as $configKey => $config) {
             $storages['devices'][$configKey] = array();
             foreach ($config as $device) {
                 $info = array('farmRoleId' => $device->farmRoleId, 'placement' => $device->placement, 'serverIndex' => $device->serverIndex, 'storageId' => $device->storageId, 'storageConfigId' => $device->storageConfigId, 'status' => $device->status);
                 try {
                     $server = DBServer::LoadByFarmRoleIDAndIndex($device->farmRoleId, $device->serverIndex);
                     if ($server->status != SERVER_STATUS::TERMINATED) {
                         $info['serverId'] = $server->serverId;
                         $info['serverInstanceId'] = $server->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID);
                     }
                 } catch (Exception $e) {
                     $this->response->debugException($e);
                 }
                 $storages['devices'][$configKey][] = $info;
             }
         }
         $image = $dbFarmRole->GetRoleObject()->__getNewRoleObject()->getImage($dbFarmRole->Platform, $dbFarmRole->CloudLocation);
         $securityGroups = $this->getInitialSecurityGroupsList($dbFarmRole);
         $farmRoles[] = array('farm_role_id' => $dbFarmRole->ID, 'alias' => $dbFarmRole->Alias ? $dbFarmRole->Alias : $dbFarmRole->GetRoleObject()->name, 'role_id' => $dbFarmRole->RoleID, 'platform' => $dbFarmRole->Platform, 'os' => $dbFarmRole->GetRoleObject()->getOs()->name, 'os_family' => $dbFarmRole->GetRoleObject()->getOs()->family, 'os_generation' => $dbFarmRole->GetRoleObject()->getOs()->generation, 'os_version' => $dbFarmRole->GetRoleObject()->getOs()->version, 'osId' => $dbFarmRole->GetRoleObject()->getOs()->id, 'generation' => $dbFarmRole->GetRoleObject()->generation, 'group' => $dbFarmRole->GetRoleObject()->getCategoryName(), 'cat_id' => $dbFarmRole->GetRoleObject()->catId, 'isScalarized' => $dbFarmRole->GetRoleObject()->isScalarized, 'name' => $roleName, 'behaviors' => implode(",", $dbFarmRole->GetRoleObject()->getBehaviors()), 'scripting' => $scriptsObject, 'scripting_params' => $sParams, 'settings' => $dbFarmRole->GetAllSettings(), 'cloud_location' => $dbFarmRole->CloudLocation, 'launch_index' => (int) $dbFarmRole->LaunchIndex, 'scaling' => $scaling, 'image' => $image->getImage(), 'storages' => $storages, 'variables' => $farmRoleVariables->getValues($dbFarmRole->GetRoleID(), $dbFarm->ID, $dbFarmRole->ID), 'running_servers' => $dbFarmRole->GetRunningInstancesCount(), 'suspended_servers' => $dbFarmRole->GetSuspendedInstancesCount(), 'security_groups' => $securityGroups, 'hourly_rate' => $this->getInstanceTypeHourlyRate($dbFarmRole->Platform, $dbFarmRole->CloudLocation, $dbFarmRole->getInstanceType(), $dbFarmRole->GetRoleObject()->getOs()->family));
     }
     $vpc = array();
     if ($dbFarm->GetSetting(Entity\FarmSetting::EC2_VPC_ID)) {
         $vpc = array('id' => $dbFarm->GetSetting(Entity\FarmSetting::EC2_VPC_ID), 'region' => $dbFarm->GetSetting(Entity\FarmSetting::EC2_VPC_REGION));
     }
     /* @var $farm Entity\Farm */
     $farm = Entity\Farm::findPk($dbFarm->ID);
     // or implement AccessPermissionsInterface in DBFarm
     $farmOwnerEditable = $this->request->hasPermissions($farm, Acl::PERM_FARMS_CHANGE_OWNERSHIP) || $dbFarm->ownerId == $this->user->getId();
     $projectEditable = $this->user->isAccountOwner() || $this->request->hasPermissions($farm, Acl::PERM_FARMS_PROJECTS);
     $farmTeams = $farm->getTeams()->map(function ($team) {
         /* @var $ft Entity\Account\Team */
         return $team->name;
     });
     return array('farm' => array('name' => $dbFarm->Name, 'description' => $dbFarm->Comments, 'rolesLaunchOrder' => $dbFarm->RolesLaunchOrder, 'timezone' => $dbFarm->GetSetting(Entity\FarmSetting::TIMEZONE), 'variables' => $variables->getValues(0, $dbFarm->ID), 'vpc' => $vpc, 'status' => $dbFarm->Status, 'hash' => $dbFarm->Hash, 'owner' => $farmOwnerEditable ? $dbFarm->ownerId : ($dbFarm->ownerId ? Entity\Account\User::findPk($dbFarm->ownerId)->email : ''), 'ownerEditable' => $farmOwnerEditable, 'teamOwner' => $farmTeams, 'teamOwnerEditable' => $farmOwnerEditable, 'launchPermission' => $this->request->hasPermissions($farm, Acl::PERM_FARMS_LAUNCH_TERMINATE), 'projectEditable' => $projectEditable, Entity\FarmSetting::SZR_UPD_REPOSITORY => $dbFarm->GetSetting(Entity\FarmSetting::SZR_UPD_REPOSITORY), Entity\FarmSetting::SZR_UPD_SCHEDULE => $dbFarm->GetSetting(Entity\FarmSetting::SZR_UPD_SCHEDULE)), 'roles' => $farmRoles, 'lock' => $dbFarm->isLocked(false), 'changed' => $dbFarm->changedTime);
 }