Ejemplo n.º 1
0
Archivo: Os.php Proyecto: scalr/scalr
 /**
  * Fetches detailed info about the Os
  *
  * @param    string $osId Unique identifier of the Os
  * @return \Scalr\Api\DataType\ResultEnvelope
  * @throws ApiErrorException
  */
 public function fetchAction($osId)
 {
     $os = Entity\Os::findPk($osId);
     if (!$os) {
         throw new ApiErrorException(404, ErrorMessage::ERR_OBJECT_NOT_FOUND, "Unable to find requested OS");
     }
     return $this->result($this->adapter('os')->toData($os));
 }
Ejemplo n.º 2
0
Archivo: Os.php Proyecto: scalr/scalr
 /**
  * @param string $id
  * @throws Exception
  */
 public function xRemoveAction($id)
 {
     $os = Os::findPk($id);
     if (!$os) {
         throw new Scalr_Exception_Core('Operating system not found');
     }
     if ($os->isSystem == 1) {
         throw new Scalr_Exception_Core('This Operating system can\'t be removed');
     }
     if ($os->getUsed()) {
         throw new Scalr_Exception_Core('Operating system is in use and can\'t be removed');
     }
     $os->delete();
     $this->response->success("Operating system successfully removed");
 }
Ejemplo n.º 3
0
Archivo: Role.php Proyecto: scalr/scalr
 /**
  * Gets the Os entity which corresponds to the Role
  *
  * @return  Os          Returns the Os entity which corresponds to the Role.
  *                      If OS has not been defined it will return NULL.
  * @throws  \Exception
  */
 public function getOs()
 {
     if (!$this->_os) {
         $this->_os = Os::findPk($this->osId);
     }
     return $this->_os;
 }
Ejemplo n.º 4
0
 /**
  * {@inheritdoc}
  * @see \Scalr\Api\DataType\ApiEntityAdapter::validateEntity()
  */
 public function validateEntity($entity)
 {
     if (!$entity instanceof Entity\Role) {
         throw new \InvalidArgumentException(sprintf("First argument must be instance of Scalr\\Model\\Entity\\Role class"));
     }
     if ($entity->id !== null) {
         if (!is_integer($entity->id)) {
             throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, "Invalid value of the identifier");
         }
         //Checks if the role does exist
         if (!Entity\Role::findPk($entity->id)) {
             throw new ApiErrorException(404, ErrorMessage::ERR_OBJECT_NOT_FOUND, sprintf("Could not find out the Role with ID: %d", $entity->id));
         }
     }
     //Is this a new Role
     if (!$entity->id) {
         $entity->addedByEmail = $this->controller->getUser()->email;
         $entity->addedByUserId = $this->controller->getUser()->id;
     }
     if (!$entity::isValidName($entity->name)) {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, "Invalid name of the Role");
     }
     $entity->description = $entity->description ?: '';
     $this->validateString($entity->description, 'Invalid description');
     if (!$this->controller->hasPermissions($entity, true)) {
         //Checks entity level write access permissions
         throw new ApiErrorException(403, ErrorMessage::ERR_PERMISSION_VIOLATION, "Insufficient permissions");
     }
     //We only allow to either create or modify Environment Scope Roles
     if ($entity->getScope() !== $this->controller->getScope()) {
         throw new ApiErrorException(403, ErrorMessage::ERR_SCOPE_VIOLATION, sprintf("Invalid scope"));
     }
     //Checks the Role Category
     if (!empty($entity->catId)) {
         //Tries to find out the specified Role category
         $category = Entity\RoleCategory::findPk($entity->catId);
         if ($category instanceof Entity\RoleCategory) {
             //Checks if the specified RoleCategory either shared or belongs to User's scope.
             if ($category->getScope() !== ScopeInterface::SCOPE_SCALR && $category->envId !== $this->controller->getEnvironment()->id) {
                 throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, "The specified category isn't owned by your environment.");
             }
         } else {
             throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, "The Role category does not exist");
         }
     } else {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_STRUCTURE, "Role category should be provided with the request.");
     }
     if (empty($entity->osId)) {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_STRUCTURE, "Missed property 'os.id'");
     }
     //Tries to find out the specified OS
     if (empty(Entity\Os::findPk($entity->osId))) {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, "OS with id '{$entity->osId}' not found.");
     }
 }
Ejemplo n.º 5
0
 /**
  * {@inheritdoc}
  * @see \Scalr\Api\DataType\ApiEntityAdapter::validateEntity()
  */
 public function validateEntity($entity)
 {
     if (!$entity instanceof Entity\Image) {
         throw new \InvalidArgumentException(sprintf("First argument must be instance of Scalr\\Model\\Entity\\Image class"));
     }
     if ($entity->hash !== null) {
         //Checks if the image does exist
         if (!Entity\Image::findPk($entity->hash)) {
             throw new ApiErrorException(404, ErrorMessage::ERR_OBJECT_NOT_FOUND, sprintf("Could not find out the Image with ID: %d", $entity->hash));
         }
     } else {
         $image = Entity\Image::findOne([['id' => $entity->id], ['platform' => $entity->platform], ['cloudLocation' => (string) $entity->cloudLocation], ['$or' => [['accountId' => null], ['$and' => [['accountId' => $entity->accountId], ['$or' => [['envId' => null], ['envId' => $entity->envId]]]]]]]]);
         if ($image) {
             throw new ApiErrorException(409, ErrorMessage::ERR_UNICITY_VIOLATION, "This Image has already been registered in Scalr");
         }
     }
     //Is this a new Image
     if (!$entity->hash) {
         $entity->createdByEmail = $this->controller->getUser()->email;
         $entity->createdById = $this->controller->getUser()->id;
     }
     if (!Entity\Role::isValidName($entity->name)) {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, "Invalid name of the Image");
     }
     if (empty($entity->architecture)) {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_STRUCTURE, "Missed property 'architecture'");
     }
     if (!$this->controller->hasPermissions($entity, true)) {
         //Checks entity level write access permissions
         throw new ApiErrorException(403, ErrorMessage::ERR_PERMISSION_VIOLATION, "Insufficient permissions");
     }
     //We only allow to either create or modify Environment Scope Roles
     if ($entity->getScope() !== $this->controller->getScope()) {
         throw new ApiErrorException(403, ErrorMessage::ERR_SCOPE_VIOLATION, sprintf("Invalid scope"));
     }
     if (empty($entity->osId)) {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_STRUCTURE, "Missed property 'os.id'");
     }
     //Tries to find out the specified OS
     if (empty(Entity\Os::findPk($entity->osId))) {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, "OS with id '{$entity->osId}' not found.");
     }
     if (empty($entity->platform)) {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_STRUCTURE, "Missed property platform");
     }
     if (!isset(SERVER_PLATFORMS::GetList()[$entity->platform])) {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_STRUCTURE, "Unexpected platform value");
     }
 }
Ejemplo n.º 6
0
 /**
  * @param   int         $roleId
  * @param   string      $name
  * @param   string      $description
  * @param   string      $osId
  * @param   int         $catId
  * @param   bool        $isQuickStart
  * @param   bool        $isDeprecated
  * @param   bool        $isScalarized
  * @param   JsonData    $behaviors
  * @param   JsonData    $images
  * @param   JsonData    $scripts
  * @param   JsonData    $variables
  * @param   JsonData    $chef
  * @param   JsonData    $environments
  * @throws  Exception
  * @throws  Scalr_Exception_Core
  * @throws  Scalr_Exception_InsufficientPermissions
  */
 public function xSaveAction($roleId = 0, $name, $description, $osId, $catId, $isQuickStart = false, $isDeprecated = false, $isScalarized = true, JsonData $behaviors, JsonData $images, JsonData $scripts, JsonData $variables, JsonData $chef, JsonData $environments)
 {
     $this->request->restrictAccess('ROLES', 'MANAGE');
     $accountId = $this->user->getAccountId() ?: NULL;
     if (!Role::isValidName($name)) {
         throw new Exception(_("Role name is incorrect"));
     }
     if (Role::isNameUsed($name, $accountId, $this->getEnvironmentId(true), $roleId)) {
         throw new Exception('Selected role name is already used. Please select another one.');
     }
     if (!$catId) {
         throw new Exception('Role category is required');
     }
     if ($roleId == 0) {
         if (!Os::findPk($osId)) {
             throw new Exception(sprintf('%s is not valid osId', $osId));
         }
         $role = new Role();
         $role->generation = 2;
         $role->origin = $this->user->isScalrAdmin() ? ROLE_TYPE::SHARED : ROLE_TYPE::CUSTOM;
         $role->accountId = $accountId;
         $role->envId = $this->getEnvironmentId(true);
         $role->name = $name;
         $role->catId = $catId;
         $role->osId = $osId;
         $role->isScalarized = $isScalarized ? 1 : 0;
         $role->addedByUserId = $this->user->getId();
         $role->addedByEmail = $this->user->getEmail();
         $role->setBehaviors((array) $behaviors);
         $role->save();
     } else {
         $role = Role::findPk($roleId);
         if (!$role) {
             throw new Scalr_Exception_Core(sprintf(_("Role ID#%s not found in database"), $roleId));
         }
         $this->request->checkPermissions($role, true);
         $role->name = $name;
         $role->catId = $catId;
     }
     $globalVariables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(true), ScopeInterface::SCOPE_ROLE);
     $globalVariables->setValues($variables, $role->id);
     foreach (RoleProperty::find([['roleId' => $role->id], ['name' => ['$like' => ['chef.%']]]]) as $prop) {
         $prop->delete();
     }
     foreach ($chef as $name => $value) {
         $prop = new RoleProperty();
         $prop->roleId = $role->id;
         $prop->name = $name;
         $prop->value = $value;
         $prop->save();
     }
     $role->description = $description;
     $role->isQuickStart = $isQuickStart;
     $role->isDeprecated = $isDeprecated;
     foreach ($images as $i) {
         if (isset($i['platform']) && isset($i['cloudLocation']) && isset($i['imageId'])) {
             $role->setImage($i['platform'], $i['cloudLocation'], $i['imageId'], $this->user->getId(), $this->user->getEmail());
         }
     }
     $role->setScripts((array) $scripts);
     $role->save();
     if ($this->request->getScope() == ScopeInterface::SCOPE_ACCOUNT) {
         foreach (RoleEnvironment::find([['roleId' => $roleId]]) as $re) {
             $re->delete();
         }
         $accountEnvironments = [];
         $allowedEnvironments = [];
         foreach (Environment::find([['accountId' => $this->user->getAccountId()]]) as $env) {
             $accountEnvironments[] = $env->id;
         }
         foreach ($environments as $e) {
             if ($e['enabled'] == 1 && in_array($e['id'], $accountEnvironments)) {
                 $allowedEnvironments[] = $e['id'];
             }
         }
         if (count($allowedEnvironments) < count($accountEnvironments)) {
             foreach ($allowedEnvironments as $id) {
                 $re = new RoleEnvironment();
                 $re->roleId = $role->id;
                 $re->envId = $id;
                 $re->save();
             }
         }
     }
     $this->response->data(['role' => $this->getInfo($role->id, true), 'categories' => $this->listRoleCategories(true)]);
     $this->response->success('Role saved');
 }
Ejemplo n.º 7
0
 /**
  * {@inheritdoc}
  * @see \Scalr\Api\DataType\ApiEntityAdapter::validateEntity()
  */
 public function validateEntity($entity)
 {
     if (!$entity instanceof Entity\Image) {
         throw new \InvalidArgumentException(sprintf("First argument must be instance of Scalr\\Model\\Entity\\Image class"));
     }
     if ($entity->hash !== null) {
         //Checks if the image does exist
         if (!Entity\Image::findPk($entity->hash)) {
             throw new ApiErrorException(404, ErrorMessage::ERR_OBJECT_NOT_FOUND, sprintf("Could not find out the Image with ID: %d", $entity->hash));
         }
     } else {
         $image = Entity\Image::findOne([['id' => $entity->id], ['$or' => [['envId' => $entity->envId], ['envId' => null]]], ['platform' => $entity->platform], ['cloudLocation' => $entity->cloudLocation]]);
         if ($image) {
             throw new ApiErrorException(409, ErrorMessage::ERR_UNICITY_VIOLATION, "This Image has already been registered in Scalr");
         }
     }
     //Is this a new Image
     if (!$entity->hash) {
         $entity->createdByEmail = $this->controller->getUser()->email;
         $entity->createdById = $this->controller->getUser()->id;
     }
     if (!Entity\Role::validateName($entity->name)) {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, "Invalid name of the Image");
     }
     $entity->architecture = $entity->architecture ?: 'x86_64';
     if (!in_array($entity->architecture, ['i386', 'x86_64'])) {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, "Invalid architecture of the Image.");
     }
     if (!$this->controller->hasPermissions($entity, true)) {
         //Checks entity level write access permissions
         throw new ApiErrorException(403, ErrorMessage::ERR_PERMISSION_VIOLATION, "Insufficient permissions");
     }
     //We only allow to either create or modify Environment Scope Roles
     if ($entity->getScope() !== ScopeInterface::SCOPE_ENVIRONMENT) {
         throw new ApiErrorException(403, ErrorMessage::ERR_SCOPE_VIOLATION, sprintf("Only %s scope is allowed.", ScopeInterface::SCOPE_ENVIRONMENT));
     }
     //Validates OS
     if (!empty($entity->osId)) {
         //Tries to find out the specified OS
         $os = Entity\Os::findPk($entity->osId);
         if (!$os instanceof Entity\Os) {
             throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, "Specified OS does not exist");
         }
     } else {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_STRUCTURE, "OS must be provided with the request.");
     }
 }
Ejemplo n.º 8
0
 /**
  * @param   string      $platform
  * @param   string      $architecture
  * @param   JsonData    $behaviors
  * @param   string      $name
  * @param   bool        $createImage
  * @param   string      $imageId
  * @param   string      $cloudLocation
  * @param   string      $osId
  * @param   integer     $hvm
  * @param   JsonData    $advanced
  * @param   JsonData    $chef
  * @throws  Exception
  */
 public function xBuildAction($platform, $architecture, JsonData $behaviors, $name = '', $createImage = false, $imageId, $cloudLocation, $osId, $hvm = 0, JsonData $advanced, JsonData $chef)
 {
     $this->request->restrictAccess(Acl::RESOURCE_FARMS_ROLES, Acl::PERM_FARMS_ROLES_CREATE);
     if (!\Scalr\Model\Entity\Role::validateName($name)) {
         throw new Exception(_("Name is incorrect"));
     }
     if (!$createImage && $this->db->GetOne("SELECT id FROM roles WHERE name=? AND (env_id IS NULL OR env_id = ?) LIMIT 1", array($name, $this->getEnvironmentId()))) {
         throw new Exception('Selected role name is already used. Please select another one.');
     }
     $behaviours = implode(",", array_values($behaviors->getArrayCopy()));
     $os = Os::findPk($osId);
     if (!$os) {
         throw new Exception('Operating system not found.');
     }
     // Create server
     $creInfo = new ServerCreateInfo($platform, null, 0, 0);
     $creInfo->clientId = $this->user->getAccountId();
     $creInfo->envId = $this->getEnvironmentId();
     $creInfo->farmId = 0;
     $creInfo->SetProperties(array(SERVER_PROPERTIES::SZR_IMPORTING_BEHAVIOR => $behaviours, SERVER_PROPERTIES::SZR_IMPORTING_IMAGE_ID => $imageId, SERVER_PROPERTIES::SZR_KEY => Scalr::GenerateRandomKey(40), SERVER_PROPERTIES::SZR_KEY_TYPE => SZR_KEY_TYPE::PERMANENT, SERVER_PROPERTIES::SZR_VESION => "0.13.0", SERVER_PROPERTIES::SZR_IMPORTING_MYSQL_SERVER_TYPE => "mysql", SERVER_PROPERTIES::SZR_DEV_SCALARIZR_BRANCH => $advanced['scalrbranch'], SERVER_PROPERTIES::ARCHITECTURE => $architecture, SERVER_PROPERTIES::SZR_IMPORTING_LEAVE_ON_FAIL => $advanced['dontterminatefailed'] == 'on' ? 1 : 0, SERVER_PROPERTIES::SZR_IMPORTING_CHEF_SERVER_ID => $chef['chef.server'], SERVER_PROPERTIES::SZR_IMPORTING_CHEF_ENVIRONMENT => $chef['chef.environment'], SERVER_PROPERTIES::SZR_IMPORTING_CHEF_ROLE_NAME => $chef['chef.role']));
     $dbServer = DBServer::Create($creInfo, true);
     $dbServer->status = SERVER_STATUS::TEMPORARY;
     $dbServer->imageId = $imageId;
     $dbServer->save();
     //Launch server
     $launchOptions = new Scalr_Server_LaunchOptions();
     $launchOptions->imageId = $imageId;
     $launchOptions->cloudLocation = $cloudLocation;
     $launchOptions->architecture = $architecture;
     $platformObj = PlatformFactory::NewPlatform($platform);
     switch ($platform) {
         case SERVER_PLATFORMS::ECS:
             $launchOptions->serverType = 10;
             if ($cloudLocation == 'all') {
                 $locations = array_keys($platformObj->getLocations($this->environment));
                 $launchOptions->cloudLocation = $locations[0];
             }
             //Network here:
             $osClient = $platformObj->getOsClient($this->environment, $launchOptions->cloudLocation);
             $networks = $osClient->network->listNetworks();
             $tenantId = $osClient->getConfig()->getAuthToken()->getTenantId();
             foreach ($networks as $network) {
                 if ($network->status == 'ACTIVE') {
                     if ($network->{"router:external"} != true) {
                         if ($tenantId == $network->tenant_id) {
                             $launchOptions->networks = array($network->id);
                             break;
                         }
                     }
                 }
             }
             break;
         case SERVER_PLATFORMS::IDCF:
             $launchOptions->serverType = 24;
             break;
         case SERVER_PLATFORMS::RACKSPACE:
             if ($os->family == 'ubuntu') {
                 $launchOptions->serverType = 1;
             } else {
                 $launchOptions->serverType = 3;
             }
             break;
         case SERVER_PLATFORMS::RACKSPACENG_US:
             $launchOptions->serverType = 3;
             break;
         case SERVER_PLATFORMS::RACKSPACENG_UK:
             $launchOptions->serverType = 3;
             break;
         case SERVER_PLATFORMS::EC2:
             if ($hvm == 1) {
                 $launchOptions->serverType = 'm3.xlarge';
                 $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
             } else {
                 if ($os->family == 'oel') {
                     $launchOptions->serverType = 'm3.large';
                     $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
                 } elseif ($os->family == 'rhel') {
                     $launchOptions->serverType = 'm3.large';
                     $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
                 } elseif ($os->family == 'scientific') {
                     $launchOptions->serverType = 'm3.large';
                     $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
                 } elseif ($os->family == 'debian' && $os->generation == '8') {
                     $launchOptions->serverType = 'm3.large';
                     $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
                 } elseif ($os->family == 'centos' && $os->generation == '7') {
                     $launchOptions->serverType = 'm3.large';
                     $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
                 } else {
                     $launchOptions->serverType = 'm3.large';
                 }
             }
             $launchOptions->userData = "#cloud-config\ndisable_root: false";
             break;
         case SERVER_PLATFORMS::GCE:
             $launchOptions->serverType = 'n1-standard-1';
             $location = null;
             $locations = array_keys($platformObj->getLocations($this->environment));
             while (count($locations) != 0) {
                 $location = array_shift($locations);
                 if (strstr($location, "us-")) {
                     break;
                 }
             }
             $launchOptions->cloudLocation = $locations[0];
             $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::GCE_STORAGE;
             break;
     }
     if ($advanced['servertype']) {
         $launchOptions->serverType = $advanced['servertype'];
     }
     if ($advanced['availzone']) {
         $launchOptions->availZone = $advanced['availzone'];
     }
     if ($advanced['region']) {
         $launchOptions->cloudLocation = $advanced['region'];
     }
     //Add Bundle task
     $creInfo = new ServerSnapshotCreateInfo($dbServer, $name, SERVER_REPLACEMENT_TYPE::NO_REPLACE);
     $bundleTask = BundleTask::Create($creInfo, true);
     if ($bundleType) {
         $bundleTask->bundleType = $bundleType;
     }
     $bundleTask->createdById = $this->user->id;
     $bundleTask->createdByEmail = $this->user->getEmail();
     $bundleTask->osFamily = $os->family;
     $bundleTask->object = $createImage ? BundleTask::BUNDLETASK_OBJECT_IMAGE : BundleTask::BUNDLETASK_OBJECT_ROLE;
     $bundleTask->cloudLocation = $launchOptions->cloudLocation;
     $bundleTask->save();
     $bundleTask->Log(sprintf("Launching temporary server (%s)", serialize($launchOptions)));
     $dbServer->SetProperty(SERVER_PROPERTIES::SZR_IMPORTING_BUNDLE_TASK_ID, $bundleTask->id);
     try {
         $platformObj->LaunchServer($dbServer, $launchOptions);
         $bundleTask->Log(_("Temporary server launched. Waiting for running state..."));
     } catch (Exception $e) {
         $bundleTask->SnapshotCreationFailed(sprintf(_("Unable to launch temporary server: %s"), $e->getMessage()));
     }
     $this->response->data(array('serverId' => $dbServer->serverId, 'bundleTaskId' => $bundleTask->id));
 }