Since: 5.4.0 (12.02.2015)
Author: Vitaliy Demidov (vitaliy@scalr.com)
Inheritance: extends Scalr\Api\Rest\Controller\AbstractController
Exemple #1
0
 protected function _os($from, $to, $action)
 {
     if ($action == self::ACT_CONVERT_TO_OBJECT) {
         $to->os = !empty($from->osId) ? ['id' => $from->osId] : null;
     } else {
         if ($action == self::ACT_CONVERT_TO_ENTITY) {
             $osId = ApiController::getBareId($from, 'os');
             if (!empty($osId)) {
                 if (!is_string($osId) || !preg_match('/^' . Entity\Os::ID_REGEXP . '$/', $osId)) {
                     throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, "Invalid identifier of the OS");
                 }
                 $to->osId = $osId;
             } else {
                 $to->osId = null;
             }
         } else {
             if ($action == self::ACT_GET_FILTER_CRITERIA) {
                 if (empty($from->os) || !preg_match('/^' . Entity\Os::ID_REGEXP . '$/', $from->os)) {
                     throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, "Invalid identifier of the OS");
                 }
                 return [['osId' => $from->os]];
             }
         }
     }
 }
Exemple #2
0
 /**
  * Gets a new Instance of the adapter
  *
  * @param   string|CloudCredentials|object  $name   The name of the adapter, or CloudCredentials entity, or cloud credentials data
  *
  * @return  ApiEntityAdapter    Returns the instance of cloud credentials adapter
  *
  * @throws  ApiErrorException
  */
 public function adapter($name, array $transform = null)
 {
     if (is_object($name)) {
         //
         $property = $name instanceof $this->entityClass ? static::$entityDescriminator : static::$objectDiscriminator;
         $value = empty($transform) ? $name->{$property} : $transform[$name->{$property}];
         switch (true) {
             case PlatformFactory::isOpenstack($value, true):
                 $value = SERVER_PLATFORMS::OPENSTACK;
                 break;
             case PlatformFactory::isCloudstack($value):
                 $value = SERVER_PLATFORMS::CLOUDSTACK;
                 break;
             case PlatformFactory::isRackspace($value):
                 $value = SERVER_PLATFORMS::RACKSPACE;
                 break;
         }
         if (!isset(static::$inheritanceMap[$value])) {
             throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, "Unknown cloud '{$value}'");
         }
         $class = empty(static::$inheritanceMap) ? $value : static::$inheritanceMap[$value];
         $name = empty(static::$inheritedNamespace) ? $class : static::$inheritedNamespace . "\\{$class}";
     }
     return parent::adapter($name);
 }
Exemple #3
0
 /**
  * Gets describe result
  *
  * @param   array    $criteria      Default search criteria
  * @param   callable $findCallback  optional Find method. Default value: find
  * @return  ListResultEnvelope      Returns describe result
  */
 public function getDescribeResult($criteria = null, $findCallback = null)
 {
     $data = [];
     foreach ($this->find($criteria, $findCallback) as $item) {
         $data[] = $item;
     }
     return $this->controller->resultList($data, $this->getInnerIterator()->totalNumber);
 }
Exemple #4
0
 public function _script($from, $to, $action)
 {
     switch ($action) {
         case static::ACT_CONVERT_TO_OBJECT:
             /* @var $from ScriptVersion */
             $to->script = ['id' => $from->scriptId];
             break;
         case static::ACT_CONVERT_TO_ENTITY:
             /* @var $to ScriptVersion */
             $to->scriptId = ApiController::getBareId($from, 'script');
             break;
         case static::ACT_GET_FILTER_CRITERIA:
             return [['scriptId' => ApiController::getBareId($from, 'script')]];
     }
 }
Exemple #5
0
 public function _defaultAclRole($from, $to, $action)
 {
     switch ($action) {
         case static::ACT_CONVERT_TO_OBJECT:
             /* @var $from Team */
             $to->defaultAclRole = ['id' => $from->accountRoleId];
             break;
         case static::ACT_CONVERT_TO_ENTITY:
             /* @var $to Team */
             $to->accountRoleId = ApiController::getBareId($from, 'defaultAclRole');
             break;
         case static::ACT_GET_FILTER_CRITERIA:
             return [['accountRoleId' => ApiController::getBareId($from, 'defaultAclRole')]];
     }
 }
 public function _costCenter($from, $to, $action)
 {
     switch ($action) {
         case static::ACT_CONVERT_TO_OBJECT:
             /* @var $from ProjectEntity */
             $to->costCenter = ['id' => $from->ccId];
             break;
         case static::ACT_CONVERT_TO_ENTITY:
             /* @var $to ProjectEntity */
             $to->ccId = ApiController::getBareId($from, 'costCenter');
             break;
         case static::ACT_GET_FILTER_CRITERIA:
             return [['ccId' => ApiController::getBareId(json_decode(json_encode($from)), 'costCenter')]];
     }
 }
 public function _defaultAclRole($from, $to, $action)
 {
     switch ($action) {
         case static::ACT_CONVERT_TO_OBJECT:
             /* @var $from TeamEnvs */
             $to->defaultAclRole = ['id' => $from->getTeam()->accountRoleId];
             break;
         case static::ACT_CONVERT_TO_ENTITY:
             /* @var $to TeamEnvs */
             // now its only Team property
             throw new ApiNotImplementedErrorException('Adjustment the default ACL Role for the Environment has not been implemented yet.');
         case static::ACT_GET_FILTER_CRITERIA:
             $aclRoleId = ApiController::getBareId($from, 'defaultAclRole');
             $team = new Team();
             $envTeam = new TeamEnvs();
             return [AbstractEntity::STMT_FROM => "\n                        JOIN {$team->table('t')} ON {$team->columnId('t')} = {$envTeam->columnTeamId()}\n                            AND {$team->columnAccountRoleId('t')} = " . $team->qstr('accountRoleId', $aclRoleId) . "\n                    "];
     }
 }
Exemple #8
0
 public function _costCenter($from, $to, $action)
 {
     switch ($action) {
         case static::ACT_CONVERT_TO_OBJECT:
             /* @var $from Environment */
             $to->costCenter = $from->getProperty(EnvironmentProperty::SETTING_CC_ID);
             break;
         case static::ACT_CONVERT_TO_ENTITY:
             /* @var $to Environment */
             $ccId = ApiController::getBareId($from, 'costCenter');
             if (empty($ccId)) {
                 throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, "Missed property costCenter");
             }
             $this->controller->getCostCenter($ccId);
             $to->setProperty(EnvironmentProperty::SETTING_CC_ID, $ccId);
             break;
         case static::ACT_GET_FILTER_CRITERIA:
             $env = new Environment();
             $envProperty = new EnvironmentProperty();
             return [AbstractEntity::STMT_FROM => "\n                         JOIN {$envProperty->table('cep')} ON {$env->columnId()} = {$envProperty->columnEnvId('cep')}\n                            AND {$envProperty->columnName('cep')} = " . $envProperty->qstr('name', EnvironmentProperty::SETTING_CC_ID) . "\n                    ", AbstractEntity::STMT_WHERE => "{$envProperty->columnValue('cep')} = " . $envProperty->qstr('value', $from->costCenter)];
     }
 }
Exemple #9
0
 /**
  * Configures cloud credentials
  *
  * @param   int     $envId  Environment ID
  * @param   string  $cloud  Cloud platform name
  *
  * @return  ResultEnvelope
  *
  * @throws ApiErrorException
  * @throws ModelException
  */
 public function attachCredentialsAction($envId, $cloud)
 {
     if (!$this->getUser()->canManageAcl()) {
         $this->checkPermissions(Acl::RESOURCE_ENV_CLOUDS_ENVIRONMENT);
     }
     $env = $this->getEnv($envId);
     $object = $this->request->getJsonBody();
     $cloudCredentialsId = ApiController::getBareId($object, 'id');
     if (empty($cloudCredentialsId)) {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_STRUCTURE, "Missed property cloudCredentials.id");
     }
     $cloudCredentials = $this->getCloudCredentials($cloudCredentialsId);
     if ($cloudCredentials->envId != $envId && $cloudCredentials->getScope() == ScopeInterface::SCOPE_ENVIRONMENT) {
         throw new ApiErrorException(404, ErrorMessage::ERR_OBJECT_NOT_FOUND, "Cloud credentials '{$cloudCredentialsId}' not found!");
     }
     if ($cloud != $cloudCredentials->cloud) {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, "Cloud Credentials mismatch");
     }
     $prevCloudCredentials = $env->keychain($cloud);
     if (isset($prevCloudCredentials->id)) {
         if ($prevCloudCredentials->id == $cloudCredentialsId) {
             return $this->result($this->getCloudCredsController()->adapter($prevCloudCredentials)->toData($prevCloudCredentials));
         }
         switch ($cloud) {
             case SERVER_PLATFORMS::EC2:
                 $checkEnvIsEmpty = $cloudCredentials->properties[Entity\CloudCredentialsProperty::AWS_ACCOUNT_ID] != $prevCloudCredentials->properties[Entity\CloudCredentialsProperty::AWS_ACCOUNT_ID];
                 break;
             case SERVER_PLATFORMS::GCE:
                 $checkEnvIsEmpty = $cloudCredentials->properties[Entity\CloudCredentialsProperty::GCE_PROJECT_ID] != $prevCloudCredentials->properties[Entity\CloudCredentialsProperty::GCE_PROJECT_ID];
                 break;
             default:
                 $checkEnvIsEmpty = false;
                 break;
         }
         if ($checkEnvIsEmpty && (count(Entity\Server::find([['envId' => $envId], ['platform' => $cloud]])) || count(Entity\Image::find([['envId' => $envId], ['platform' => $cloud]])))) {
             throw new ApiErrorException(409, ErrorMessage::ERR_OBJECT_IN_USE, "Cloud Credentials are used");
         }
     }
     $cloudCredentials->bindEnvironment($envId)->save();
     return $this->result($this->getCloudCredsController()->adapter($cloudCredentials)->toData($cloudCredentials));
 }
Exemple #10
0
 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) . ")"];
     }
 }
Exemple #11
0
 /**
  * Gets a new Instance of the adapter
  *
  * @param   string|FarmRoleScalingMetric|object $name                The name of the adapter or FarmRoleScalingMetric entity or farm role scaling metric data
  * @param   string                              $scope      optional The scope of the adapter
  * @param   string                              $version    optional The version of the adapter
  *
  * @return ApiEntityAdapter
  *
  * @throws ApiErrorException
  */
 public function adapter($name, $scope = null, $version = null)
 {
     if (is_object($name)) {
         $object = $name;
         if ($object instanceof FarmRoleScalingMetric) {
             $name = ScalingRuleAdapter::$ruleTypeMap[$object->metric->alias];
         } else {
             $name = $this->getBareId($object, 'ruleType');
             if (!$name) {
                 throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_STRUCTURE, 'Missed property ruleType');
             }
             if (!in_array($name, ScalingRuleAdapter::$ruleTypeMap)) {
                 throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, 'Unexpected ruleType value');
             }
         }
         $name = static::$scalingRuleNamespace . "\\" . $name;
     }
     return parent::adapter($name, $scope, $version);
 }
Exemple #12
0
 /**
  * Permissions won't check if object has environment scope and role Acl::RESOURCE_ANALYTICS_ACCOUNT
  * {@inheritdoc}
  * @see ApiController::checkPermissions()
  */
 public function checkPermissions(...$args)
 {
     if ($this->getScope() === ScopeInterface::SCOPE_ENVIRONMENT && isset($args[0]) && $args[0] == Acl::RESOURCE_ANALYTICS_ACCOUNT && empty($args[1])) {
         return;
     }
     parent::checkPermissions(...$args);
 }
Exemple #13
0
 /**
  * Throws an exception if the user does not have sufficient permissions for projects
  * If the argument just one we will checks all the existing variants of access to projects
  * checkPermissions(int $roleId, string $permissionId = null)
  *
  * @param ...$args
  * @throws ApiInsufficientPermissionsException
  */
 public function checkPermissions(...$args)
 {
     if (isset($args[0]) && $args[0] == Acl::RESOURCE_ANALYTICS_PROJECTS_ACCOUNT && empty($args[1])) {
         if (!($this->hasPermissions(...$args) || $this->hasPermissions(Acl::RESOURCE_OWN_FARMS, Acl::PERM_FARMS_CREATE) || $this->hasPermissions(Acl::RESOURCE_FARMS, Acl::PERM_FARMS_PROJECTS) || $this->hasPermissions(Acl::RESOURCE_TEAM_FARMS, Acl::PERM_FARMS_PROJECTS) || $this->hasPermissions(Acl::RESOURCE_OWN_FARMS, Acl::PERM_FARMS_PROJECTS))) {
             throw new ApiInsufficientPermissionsException(isset($args[2]) ? $args[2] : null);
         }
     } else {
         parent::checkPermissions(...$args);
     }
 }
Exemple #14
0
 /**
  * Setups given instance configuration to specified farm role
  *
  * @param   FarmRole    $role       Configurable farm role
  * @param   object      $instance   Instance configuration
  *
  * @throws ApiErrorException
  */
 public static function setupInstanceConfiguration(FarmRole $role, $instance)
 {
     if (empty($instance->instanceConfigurationType)) {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_STRUCTURE, 'Missed property instance.instanceConfigurationType');
     }
     switch ($instance->instanceConfigurationType) {
         case FarmRoles::AWS_INSTANCE_CONFIGURATION:
             if (isset($instance->instanceType)) {
                 $type = ApiController::getBareId($instance, 'instanceType');
                 $role->settings[FarmRoleSetting::AWS_INSTANCE_TYPE] = $type;
             }
             if (isset($instance->ebsOptimized)) {
                 $role->settings[FarmRoleSetting::AWS_EBS_OPTIMIZED] = $instance->ebsOptimized;
             }
             break;
         default:
             throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, 'Unknown instanceConfigurationType');
     }
 }
Exemple #15
0
 protected function _category($from, $to, $action)
 {
     if ($action == self::ACT_CONVERT_TO_OBJECT) {
         $to->category = !empty($from->catId) ? ['id' => $from->catId] : null;
     } else {
         if ($action == self::ACT_CONVERT_TO_ENTITY) {
             $categoryId = ApiController::getBareId($from, 'category');
             if (!empty($categoryId)) {
                 if (!is_int($categoryId)) {
                     throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, "Invalid identifier of the category");
                 }
                 $to->catId = $categoryId;
             } else {
                 $to->catId = null;
             }
         } else {
             if ($action == self::ACT_GET_FILTER_CRITERIA) {
                 if (empty($from->category)) {
                     throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, "Invalid identifier of the category");
                 }
                 return [['catId' => ApiController::getBareId($from, 'category')]];
             }
         }
     }
 }
Exemple #16
0
 public function _trigger($from, $to, $action)
 {
     switch ($action) {
         case static::ACT_CONVERT_TO_OBJECT:
             /* @var $from RoleScript */
             switch ($from->eventName) {
                 case '*':
                     $to->trigger = ['triggerType' => static::TRIGGER_ALL_EVENTS];
                     break;
                 default:
                     $to->trigger = ['triggerType' => static::TRIGGER_SINGLE_EVENT, 'event' => ['id' => $from->eventName]];
                     break;
             }
             break;
         case static::ACT_CONVERT_TO_ENTITY:
             /* @var $to RoleScript */
             if (empty($from->trigger->triggerType)) {
                 throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_STRUCTURE, "Missed trigger type");
             }
             switch ($from->trigger->triggerType) {
                 case static::TRIGGER_ALL_EVENTS:
                     $to->eventName = '*';
                     break;
                 case static::TRIGGER_SINGLE_EVENT:
                     if (!($event = ApiController::getBareId($from->trigger, 'event'))) {
                         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_STRUCTURE, "Missed property trigger:id");
                     }
                     $to->eventName = $event;
                     break;
                 default:
                     throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, "Unexpected trigger type");
             }
             break;
         case static::ACT_GET_FILTER_CRITERIA:
             return [['eventName' => $from->trigger]];
     }
 }
Exemple #17
0
 /**
  * Save data for x-usedIn endpoints
  *
  * @param string   $url        api url
  * @param stdClass $object     api object
  * @param string   $nameEntity name api entity
  */
 protected function saveUrlData($url, $object, $nameEntity)
 {
     $part = null;
     $pointer =& self::$data;
     foreach (explode('/', trim($url, '/')) as $part) {
         if (!isset($pointer[$part])) {
             $pointer[$part] = [];
         }
         $pointer =& $pointer[$part];
     }
     if (isset($this->paramMap[$part][$nameEntity])) {
         $param = $this->paramMap[$part][$nameEntity];
         $id = ApiController::getBareId($object, $param);
         $object = (array) $object;
         if (!empty($id)) {
             $pointer[$id] = $object;
         } else {
             if (isset($object[$param])) {
                 $pointer = array_flip($object[$param]);
             }
         }
     }
 }
Exemple #18
0
 /**
  * Deletes farm's global variable
  *
  * @param   int     $farmId Numeric identifier of the Farm
  * @param   string  $name   Name of variable
  *
  * @return  ResultEnvelope
  *
  * @throws  ApiErrorException
  * @throws  ModelException
  */
 public function deleteVariableAction($farmId, $name)
 {
     parent::checkPermissions(Acl::RESOURCE_GLOBAL_VARIABLES_ENVIRONMENT, Acl::PERM_GLOBAL_VARIABLES_ENVIRONMENT_MANAGE);
     $this->getFarm($farmId, Acl::PERM_FARMS_MANAGE);
     $fetch = $this->getGlobalVariable($farmId, $name, $this->getVariableInstance());
     $variable = FarmGlobalVariable::findPk($farmId, $name);
     if (empty($fetch)) {
         throw new ApiErrorException(404, ErrorMessage::ERR_OBJECT_NOT_FOUND, "Requested Global Variable does not exist.");
     } else {
         if (empty($variable)) {
             throw new ApiErrorException(403, ErrorMessage::ERR_SCOPE_VIOLATION, "You can only delete Global Variables declared in Farm scope.");
         }
     }
     $variable->delete();
     return $this->result(null);
 }
Exemple #19
0
 protected function _launchedBy($from, $to, $action)
 {
     switch ($action) {
         case static::ACT_CONVERT_TO_OBJECT:
             /* @var $from Server */
             $to->launchedBy = ['id' => $from->properties[Server::LAUNCHED_BY_ID]];
             break;
         case static::ACT_CONVERT_TO_ENTITY:
             /* @var $to Server */
             $launchedBy = ApiController::getBareId($from, 'launchedBy');
             if (!isset($launchedBy)) {
                 throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_STRUCTURE, "Missed launchedBy.id property");
             }
             $to->properties[Server::LAUNCHED_BY_ID] = $launchedBy;
             break;
         case static::ACT_GET_FILTER_CRITERIA:
             $entity = new Server();
             return $entity->getSettingCriteria(Server::LAUNCHED_BY_ID, ApiController::getBareId($from, 'launchedBy'));
     }
 }