Author: Vlad Dobrovolskiy (v.dobrovolskiy@scalr.com)
Inheritance: extends Scalr\Model\AbstractEntity
Exemplo n.º 1
0
 /**
  * Gets Team entity
  *
  * @return Team|null
  */
 public function getTeam()
 {
     if (!empty($this->teamId) && empty($this->_team)) {
         $this->_team = Team::findPk($this->teamId);
     }
     return $this->_team;
 }
Exemplo n.º 2
0
 /**
  * Gets Team entity
  *
  * @param string $teamId Unique identifier of the Team
  *
  * @return Team
  * @throws  ApiErrorException
  */
 public function getTeam($teamId)
 {
     /* @var $team Team */
     $team = Team::findOne(array_merge($this->getDefaultCriteria(), [['id' => $teamId]]));
     if (empty($team)) {
         throw new ApiErrorException(404, ErrorMessage::ERR_OBJECT_NOT_FOUND, "Requested Team either does not exist or is not owned by your account.");
     }
     return $team;
 }
Exemplo n.º 3
0
 /**
  * {@inheritdoc}
  * @see ApiEntityAdapter::validateEntity()
  */
 public function validateEntity($entity)
 {
     if (!$entity instanceof Team) {
         throw new InvalidArgumentException(sprintf("First argument must be instance of %s", Team::class));
     }
     if (empty($entity->name)) {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_STRUCTURE, "Missed property name");
     }
     if (Team::findOne([['accountId' => $entity->accountId], ['name' => $entity->name], ['id' => ['$ne' => $entity->id]]])) {
         throw new ApiErrorException(409, ErrorMessage::ERR_UNICITY_VIOLATION, "Team with name '{$entity->name}' already exists in this account");
     }
     $this->validateTeamName($entity->name);
     if (empty($entity->accountRoleId)) {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_STRUCTURE, "Missed property defaultAclRole");
     }
     if (!(is_string($entity->accountRoleId) && preg_match('/^' . AclRole::ACL_ROLE_ID_REGEXP . '$/', $entity->accountRoleId))) {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, "Invalid identifier of the ACL Role");
     }
     if (empty(AclRole::findOne([['accountRoleId' => $entity->accountRoleId], ['accountId' => $entity->accountId]]))) {
         throw new ApiErrorException(404, ErrorMessage::ERR_INVALID_VALUE, "ACL Role with ID: '{$entity->accountRoleId}' is not found in this account.");
     }
 }
Exemplo n.º 4
0
 /**
  * {@inheritdoc}
  * @see ApiEntityAdapter::validateEntity()
  */
 public function validateEntity($entity)
 {
     if (!$entity instanceof TeamEnvs) {
         throw new InvalidArgumentException(sprintf("First argument must be instance of %s", Team::class));
     }
     if (empty($entity->teamId)) {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_STRUCTURE, "Missed property team.id");
     }
     $teamId = $entity->teamId;
     if (!is_numeric($teamId)) {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, "Invalid team identifier");
     }
     /* @var $team Team */
     $team = Team::findOne([['id' => $teamId], ['accountId' => $this->controller->getUser()->accountId]]);
     if (empty($team)) {
         throw new ApiErrorException(404, ErrorMessage::ERR_OBJECT_NOT_FOUND, sprintf("Requested team %s do not exist in this account", $teamId));
     }
     if (!empty(TeamEnvs::findOne([['envId' => $entity->envId], ['teamId' => $teamId]]))) {
         throw new ApiErrorException(409, ErrorMessage::ERR_UNICITY_VIOLATION, sprintf("Team %s already exists in this environment", $teamId));
     }
     /* @var  $teamAdapter TeamAdapter */
     $teamAdapter = $this->controller->adapter('team');
     $teamAdapter->validateTeamName($team->name);
 }
Exemplo n.º 5
0
 public function applyGlobalVarsToValue($value)
 {
     if (empty($this->globalVariablesCache)) {
         $formats = \Scalr::config("scalr.system.global_variables.format");
         $at = new Entity\Account\Team();
         $ft = new Entity\FarmTeam();
         $teams = Entity\Account\Team::find([\Scalr\Model\AbstractEntity::STMT_FROM => "{$at->table()} JOIN {$ft->table()} ON {$ft->columnTeamId} = {$at->columnId}", \Scalr\Model\AbstractEntity::STMT_WHERE => "{$ft->columnFarmId} = '{$this->ID}'"])->map(function ($t) {
             return $t->name;
         });
         $systemVars = array('env_id' => $this->EnvID, 'env_name' => $this->GetEnvironmentObject()->name, 'farm_team' => join(",", $teams), 'farm_id' => $this->ID, 'farm_name' => $this->Name, 'farm_hash' => $this->Hash, 'farm_owner_email' => $this->createdByUserEmail);
         if (\Scalr::getContainer()->analytics->enabled) {
             $projectId = $this->GetSetting(Entity\FarmSetting::PROJECT_ID);
             if ($projectId) {
                 $project = ProjectEntity::findPk($projectId);
                 /* @var $project ProjectEntity */
                 $systemVars['project_id'] = $projectId;
                 $systemVars['project_bc'] = $project->getProperty(ProjectPropertyEntity::NAME_BILLING_CODE);
                 $systemVars['project_name'] = $project->name;
                 $ccId = $project->ccId;
             }
             if ($ccId) {
                 $cc = CostCentreEntity::findPk($ccId);
                 if ($cc) {
                     /* @var $cc CostCentreEntity */
                     $systemVars['cost_center_id'] = $ccId;
                     $systemVars['cost_center_bc'] = $cc->getProperty(CostCentrePropertyEntity::NAME_BILLING_CODE);
                     $systemVars['cost_center_name'] = $cc->name;
                 } else {
                     throw new Exception("Cost center {$ccId} not found");
                 }
             }
         }
         // Get list of Server system vars
         foreach ($systemVars as $name => $val) {
             $name = "SCALR_" . strtoupper($name);
             $val = trim($val);
             if (isset($formats[$name])) {
                 $val = @sprintf($formats[$name], $val);
             }
             $this->globalVariablesCache[$name] = $val;
         }
         // Add custom variables
         $gv = new Scalr_Scripting_GlobalVariables($this->ClientID, $this->EnvID, ScopeInterface::SCOPE_FARM);
         $vars = $gv->listVariables(0, $this->ID);
         foreach ($vars as $v) {
             $this->globalVariablesCache[$v['name']] = $v['value'];
         }
     }
     //Parse variable
     $keys = array_keys($this->globalVariablesCache);
     $keys = array_map(function ($item) {
         return '{' . $item . '}';
     }, $keys);
     $values = array_values($this->globalVariablesCache);
     $retval = str_replace($keys, $values, $value);
     // Strip undefined variables & return value
     return preg_replace("/{[A-Za-z0-9_-]+}/", "", $retval);
 }
Exemplo n.º 6
0
 /**
  * Gets default search criteria according current account
  *
  * @return  array   Returns array of the search criteria
  */
 private function getDefaultCriteria()
 {
     $criteria = [['accountId' => $this->getUser()->getAccountId()]];
     $user = $this->getUser();
     if (!$user->canManageAcl()) {
         $env = new Account\Environment();
         $teamEnv = new Account\TeamEnvs();
         $team = new Account\Team();
         $teamUser = new Account\TeamUser();
         $criteria = array_merge($criteria, [AbstractEntity::STMT_DISTINCT => true, AbstractEntity::STMT_FROM => " {$env->table()}\n                    JOIN  {$teamEnv->table('te')} ON  {$teamEnv->columnEnvId('te')}  =  {$env->columnId()}\n                    JOIN  {$team->table('at')} ON  {$team->columnId('at')}  = {$teamEnv->columnTeamId('te')}\n                    JOIN  {$teamUser->table('tu')}  ON  {$teamUser->columnTeamId('tu')} = {$team->columnId('at')}\n                ", AbstractEntity::STMT_WHERE => "{$teamUser->columnUserId('tu')}  = " . $teamUser->qstr('userId', $user->id) . " AND  {$team->columnAccountId('at')}  = " . $team->qstr('accountId', $user->getAccountId())]);
     }
     return $criteria;
 }
Exemplo n.º 7
0
 public function _teamOwner($from, $to, $action)
 {
     switch ($action) {
         case static::ACT_CONVERT_TO_OBJECT:
             /* @var $from Farm */
             $to->teamOwner = ['id' => $from->teamId];
             break;
         case static::ACT_CONVERT_TO_ENTITY:
             /* @var $to Farm */
             $teamOwner = ApiController::getBareId($from, 'teamOwner');
             $user = $this->controller->getUser();
             if (!empty($to->createdById) && $to->teamId != $teamOwner) {
                 $this->controller->checkPermissions($to, Acl::PERM_FARMS_CHANGE_OWNERSHIP);
             }
             if (!empty($teamOwner)) {
                 $team = Team::findOne([['id' => $teamOwner], ['accountId' => $user->getAccountId()]]);
                 /* @var $team Team */
                 if (!($team && ($user->inTeam($teamOwner) || $user->canManageAcl()))) {
                     throw new ApiErrorException(404, ErrorMessage::ERR_OBJECT_NOT_FOUND, "Requested Team either does not exist or you do not have access to it.");
                 }
             }
             $to->teamId = $teamOwner;
             break;
         case static::ACT_GET_FILTER_CRITERIA:
             $teamOwner = ApiController::getBareId($from, 'teamOwner');
             return [['teamId' => $teamOwner]];
             break;
     }
 }
Exemplo n.º 8
0
 public function _teams($from, $to, $action)
 {
     switch ($action) {
         case static::ACT_CONVERT_TO_OBJECT:
             /* @var $from Farm */
             /* @var $team Team */
             foreach ($from->getTeams() as $team) {
                 $to->teams[] = ['id' => $team->id];
             }
             break;
         case static::ACT_CONVERT_TO_ENTITY:
             /* @var $to Farm */
             $newTeams = [];
             $newTeamIds = [];
             $user = $this->controller->getUser();
             foreach ($from->teams as $teamFk) {
                 $team = new Team();
                 $team->id = ApiController::getBareId($teamFk);
                 $newTeams[] = $team;
                 $newTeamIds[] = $team->id;
             }
             $currentTeamIds = [];
             foreach ($to->getTeams() as $team) {
                 $currentTeamIds[] = $team->id;
             }
             sort($newTeamIds);
             sort($currentTeamIds);
             if ($newTeamIds != $currentTeamIds) {
                 //filter out the Teams to which the User has no access
                 $teams = empty($newTeams) ? [] : Team::find([['id' => ['$in' => $newTeamIds]], ['accountId' => $user->getAccountId()]]);
                 if (count($teams) != count($newTeamIds)) {
                     throw new ApiErrorException(404, ErrorMessage::ERR_OBJECT_NOT_FOUND, "Requested Team(s) either does not exist or Farm has no access to it.");
                 }
                 $to->setTeams($newTeams);
             }
             break;
         case static::ACT_GET_FILTER_CRITERIA:
             $team = ApiController::getBareId($from, 'teams');
             $farm = new Farm();
             $farmTeam = new FarmTeam();
             return [AbstractEntity::STMT_FROM => "\n                        JOIN {$farmTeam->table('ft')} ON {$farmTeam->columnFarmId('ft')} = {$farm->columnId()}\n                            AND {$farmTeam->columnTeamId('ft')} = " . $farmTeam->qstr('teamId', $team) . "\n                    "];
     }
 }
Exemplo n.º 9
0
Arquivo: Farm.php Projeto: scalr/scalr
 /**
  * Searches farms by criteria and selecting and initiating their Teams
  *
  * @param    array        $criteria     optional The search criteria.
  * @param    array        $group        optional The group by looks like [property1, ...], by default groups by `id`
  * @param    array        $order        optional The results order looks like [property1 => true|false, ... ]
  * @param    int          $limit        optional The records limit
  * @param    int          $offset       optional The offset
  * @param    bool         $countRecords optional True to calculate total number of the records without limit
  *
  * @return   ArrayCollection|Farm[] Returns collection of the entities.
  *
  * @throws \Scalr\Exception\ModelException
  */
 public static function findWithTeams(array $criteria = null, array $group = null, array $order = null, $limit = null, $offset = null, $countRecords = null)
 {
     $farm = new Farm();
     /* @var $farms Farm[] */
     $farms = [];
     if (!isset($group)) {
         $group = ['id'];
     }
     $collection = $farm->result(AbstractEntity::RESULT_ENTITY_COLLECTION)->find($criteria, $group, $order, $limit, $offset, $countRecords);
     /* @var $farm Farm */
     foreach ($collection as $farm) {
         $farms[$farm->id] = $farm;
     }
     $team = new Team();
     $farmTeam = new FarmTeam();
     $stmt = "\n            SELECT {$team->fields()}, {$farmTeam->fields('ft', true)}\n            FROM {$team->table()}\n            JOIN {$farmTeam->table('ft')} ON {$farmTeam->columnTeamId('ft')} = {$team->columnId()}\n              AND {$farmTeam->columnFarmId('ft')} IN ('" . implode("', '", array_keys($farms)) . "')\n        ";
     foreach ($team->db()->Execute($stmt) as $row) {
         $team = new Team();
         $team->load($row);
         $farmTeam->load($row, 'ft');
         $farms[$farmTeam->farmId]->_teams[$team->id] = $team;
     }
     return $collection;
 }
Exemplo n.º 10
0
 /**
  * @param   string  $query
  * @throws  Scalr_Exception_Core
  */
 public function xSearchResourcesAction($query)
 {
     if (trim($query) == '') {
         $this->response->data(['data' => []]);
         return;
     }
     $environments = $this->request->getScope() == ScopeInterface::SCOPE_ACCOUNT ? array_map(function ($r) {
         return $r['id'];
     }, $this->user->getEnvironments()) : [$this->getEnvironmentId()];
     $f = new Entity\Farm();
     $s = new Entity\Server();
     $fr = new Entity\FarmRole();
     $e = new Entity\Account\Environment();
     $at = new Entity\Account\Team();
     $sp = new Entity\Server\Property();
     $farmSql = [];
     $serverSql = [];
     $queryEnc = "%{$query}%";
     foreach ($environments as $envId) {
         $acl = $this->user->getAclRolesByEnvironment($envId);
         $isTermporaryServerPerm = $acl->isAllowed(Acl::RESOURCE_IMAGES_ENVIRONMENT, Acl::PERM_IMAGES_ENVIRONMENT_BUILD) || $acl->isAllowed(Acl::RESOURCE_IMAGES_ENVIRONMENT, Acl::PERM_IMAGES_ENVIRONMENT_IMPORT);
         if ($acl->isAllowed(Acl::RESOURCE_FARMS)) {
             $farmSql[] = "{$f->columnEnvId} = {$envId}";
             if ($isTermporaryServerPerm) {
                 $serverSql[] = "{$s->columnEnvId} = {$envId}";
             } else {
                 $serverSql[] = "{$s->columnEnvId} = {$envId} AND {$s->columnFarmId} IS NOT NULL";
             }
         } else {
             $q = [];
             if ($acl->isAllowed(Acl::RESOURCE_TEAM_FARMS)) {
                 $t = array_map(function ($t) {
                     return $t['id'];
                 }, $this->user->getTeams());
                 if (count($t)) {
                     $q[] = "{$f->columnTeamId} IN (" . join(',', $t) . ")";
                 }
             }
             if ($acl->isAllowed(Acl::RESOURCE_OWN_FARMS)) {
                 $q[] = "{$f->columnCreatedById} = {$this->user->getId()}";
             }
             if (count($q)) {
                 $farmSql[] = "{$f->columnEnvId} = {$envId} AND (" . join(" OR ", $q) . ")";
             }
             if ($isTermporaryServerPerm) {
                 $q[] = "{$s->columnStatus} IN ('" . Entity\Server::STATUS_IMPORTING . "', '" . Entity\Server::STATUS_TEMPORARY . "') AND {$s->columnFarmId} IS NULL";
             }
             if (count($q)) {
                 $serverSql[] = "{$s->columnEnvId} = {$envId} AND (" . join(" OR ", $q) . ")";
             }
         }
     }
     $farms = [];
     if (count($farmSql)) {
         $farmStmt = $this->db->Execute("\n                SELECT {$f->columnId} AS id, {$f->columnName} AS name, {$f->columnEnvId} AS envId, {$f->columnStatus} AS status,\n                {$f->columnAdded} AS added, {$f->columnCreatedByEmail} AS createdByEmail, {$at->columnName} AS teamName, {$e->columnName} AS `envName`\n                FROM {$f->table()}\n                LEFT JOIN {$at->table()} ON {$at->columnId} = {$f->columnTeamId}\n                LEFT JOIN {$e->table()} ON {$f->columnEnvId} = {$e->columnId}\n                WHERE ({$f->columnName} LIKE ?) AND (" . join(" OR ", $farmSql) . ")", [$queryEnc]);
         while ($farm = $farmStmt->FetchRow()) {
             $farm['status'] = Entity\Farm::getStatusName($farm['status']);
             $farm['added'] = Scalr_Util_DateTime::convertTz($farm['added'], 'M j, Y H:i');
             $farms[] = ['entityName' => 'farm', 'envId' => $farm['envId'], 'envName' => $farm['envName'], 'matchField' => 'Name', 'matchValue' => $farm['name'], 'data' => $farm];
         }
     }
     $servers = [];
     if (count($serverSql)) {
         $serverStmt = $this->db->Execute("\n                SELECT {$s->columnServerId} AS serverId, {$s->columnFarmId} AS farmId, {$s->columnFarmRoleId} AS farmRoleId,\n                {$s->columnEnvId} AS envId, {$s->columnPlatform} AS platform, {$s->columnInstanceTypeName} AS instanceTypeName,\n                {$s->columnStatus} AS status, {$s->columnCloudLocation} AS cloudLocation, {$s->columnRemoteIp} AS publicIp,\n                {$s->columnLocalIp} AS privateIp, {$s->columnAdded} AS added, {$f->columnName} AS farmName,\n                {$fr->columnAlias} AS farmRoleName, {$e->columnName} AS `envName`, {$fr->columnRoleId} AS roleId,\n                {$sp->columnValue('sp1', 'hostname')}\n                FROM {$s->table()}\n                LEFT JOIN {$f->table()} ON {$f->columnId} = {$s->columnFarmId}\n                LEFT JOIN {$fr->table()} ON {$fr->columnId} = {$s->columnFarmRoleId}\n                LEFT JOIN {$e->table()} ON {$e->columnId} = {$s->columnEnvId}\n                LEFT JOIN {$sp->table('sp1')} ON {$sp->columnServerId('sp1')} = {$s->columnServerId} AND {$sp->columnName('sp1')} = ?\n                WHERE ({$s->columnRemoteIp} LIKE ? OR {$s->columnLocalIp} LIKE ? OR {$sp->columnValue('sp1')} LIKE ?) AND (" . join(" OR ", $serverSql) . ")\n                GROUP BY {$s->columnServerId}", [Scalr_Role_Behavior::SERVER_BASE_HOSTNAME, $queryEnc, $queryEnc, $queryEnc]);
         $names = ['publicIp' => 'Public IP', 'privateIp' => 'Private IP', 'hostname' => 'Hostname'];
         while ($server = $serverStmt->FetchRow()) {
             $server['added'] = Scalr_Util_DateTime::convertTz($server['added'], 'M j, Y H:i');
             if (strstr($server['publicIp'], $query)) {
                 $m = 'publicIp';
             } else {
                 if (strstr($server['privateIp'], $query)) {
                     $m = 'privateIp';
                 } else {
                     $m = 'hostname';
                 }
             }
             $servers[] = ['entityName' => 'server', 'envId' => $server['envId'], 'envName' => $server['envName'], 'matchField' => $names[$m], 'matchValue' => $server[$m], 'data' => $server];
         }
     }
     $this->response->data(['data' => array_merge($farms, $servers)]);
 }
Exemplo n.º 11
0
 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));
 }
Exemplo n.º 12
0
 /**
  *
  * @return array
  */
 public function GetScriptingVars()
 {
     $dbFarmRole = $this->GetFarmRoleObject();
     $roleId = $dbFarmRole->RoleID;
     $dbRole = DBRole::loadById($roleId);
     $isDbMsr = $dbRole->getDbMsrBehavior();
     if ($isDbMsr) {
         $isMaster = $this->GetProperty(Scalr_Db_Msr::REPLICATION_MASTER);
     } else {
         $isMaster = $this->GetProperty(\SERVER_PROPERTIES::DB_MYSQL_MASTER);
     }
     $at = new Entity\Account\Team();
     $ft = new Entity\FarmTeam();
     $teams = join(",", Entity\Account\Team::find([\Scalr\Model\AbstractEntity::STMT_FROM => "{$at->table()} JOIN {$ft->table()} ON {$ft->columnTeamId} = {$at->columnId}", \Scalr\Model\AbstractEntity::STMT_WHERE => "{$ft->columnFarmId} = '{$this->farmId}'"])->map(function ($t) {
         return $t->name;
     }));
     $retval = array('image_id' => $dbRole->__getNewRoleObject()->getImage($this->platform, $dbFarmRole->CloudLocation)->imageId, 'external_ip' => $this->remoteIp, 'internal_ip' => $this->localIp, 'role_name' => $dbRole->name, 'isdbmaster' => $isMaster, 'instance_index' => $this->index, 'instance_farm_index' => $this->farmIndex, 'server_type' => $this->type, 'server_hostname' => $this->GetProperty(Scalr_Role_Behavior::SERVER_BASE_HOSTNAME), 'server_id' => $this->serverId, 'farm_id' => $this->farmId, 'farm_role_id' => $this->farmRoleId, 'farm_role_alias' => $this->GetFarmRoleObject()->Alias, 'farm_name' => $this->GetFarmObject()->Name, 'farm_hash' => $this->GetFarmObject()->Hash, 'farm_owner_email' => $this->GetFarmObject()->createdByUserEmail, 'farm_team' => $teams, 'behaviors' => implode(",", $dbRole->getBehaviors()), 'env_id' => $this->GetEnvironmentObject()->id, 'env_name' => $this->GetEnvironmentObject()->name, 'cloud_location' => $this->GetCloudLocation(), 'cloud_server_id' => $this->GetCloudServerID());
     if ($this->cloudLocationZone) {
         $retval['cloud_location_zone'] = $this->cloudLocationZone;
     }
     if ($this->platform == SERVER_PLATFORMS::EC2) {
         $retval['instance_id'] = $this->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID);
         $retval['ami_id'] = $this->GetProperty(EC2_SERVER_PROPERTIES::AMIID);
         $retval['region'] = $this->GetProperty(EC2_SERVER_PROPERTIES::REGION);
         $retval['avail_zone'] = $this->GetProperty(EC2_SERVER_PROPERTIES::AVAIL_ZONE);
         if ($dbFarmRole->GetSetting(Entity\FarmRoleSetting::AWS_ELB_ENABLED)) {
             $elbId = $dbFarmRole->GetSetting(Entity\FarmRoleSetting::AWS_ELB_ID);
             $retval['aws_elb_name'] = $elbId;
         }
     }
     if (\Scalr::getContainer()->analytics->enabled) {
         $ccId = $this->GetProperty(\SERVER_PROPERTIES::ENV_CC_ID);
         if ($ccId) {
             $cc = CostCentreEntity::findPk($ccId);
             if ($cc) {
                 /* @var $cc CostCentreEntity */
                 $retval['cost_center_id'] = $ccId;
                 $retval['cost_center_bc'] = $cc->getProperty(CostCentrePropertyEntity::NAME_BILLING_CODE);
                 $retval['cost_center_name'] = $cc->name;
             } else {
                 throw new Exception("Cost center {$ccId} not found");
             }
         }
         $projectId = $this->GetProperty(\SERVER_PROPERTIES::FARM_PROJECT_ID);
         if ($projectId) {
             $project = ProjectEntity::findPk($projectId);
             /* @var $project ProjectEntity */
             $retval['project_id'] = $projectId;
             $retval['project_bc'] = $project->getProperty(ProjectPropertyEntity::NAME_BILLING_CODE);
             $retval['project_name'] = $project->name;
         }
     }
     return $retval;
 }