public function xCheckCommunicationAction() { $dbServer = DBServer::LoadByID($this->getParam('serverId')); $this->user->getPermissions()->validate($dbServer); if ($dbServer->status != SERVER_STATUS::IMPORTING) { throw new Exception('Server is not in importing state'); } $inboundConnection = false; $outboundConnection = false; $row = $this->db->GetRow("SELECT * FROM messages WHERE server_id = ? AND type = ? LIMIT 1", array($dbServer->serverId, "in")); if ($row) { $inboundConnection = true; $outboundConnection = (bool) $dbServer->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_OUT_CONNECTION); if ($outboundConnection) { $behaviors = $dbServer->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_BEHAVIOR); } else { $connectionError = $dbServer->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_OUT_CONNECTION_ERROR); } $bundleTaskId = $this->db->GetOne("SELECT id FROM bundle_tasks WHERE server_id = ? ORDER BY dtadded DESC LIMIT 1", array($dbServer->serverId)); if ($bundleTaskId) { $bundleTask = BundleTask::LoadById($bundleTaskId); $osDetails = $bundleTask->getOsDetails(); $criteria = [['family' => $osDetails->family], ['generation' => $osDetails->generation], ['status' => Os::STATUS_ACTIVE]]; $os = Os::find($criteria); } } $this->response->data(array('inbound' => $inboundConnection, 'outbound' => $outboundConnection, 'connectionError' => $connectionError, 'bundleTaskId' => $bundleTaskId, 'behaviors' => $behaviors ? explode(',', $behaviors) : null, 'os' => isset($os) ? $os->getArrayCopy() : [], 'serverOs' => $osDetails ? $osDetails->name : '')); }
protected function run1($stage) { $stmt = ''; if (!$this->hasTableColumn('os', 'created')) { $bCreated = true; $this->console->out("Adding scalr.os.created column..."); $stmt .= ", ADD COLUMN `created` DATETIME NOT NULL COMMENT 'Created at timestamp' AFTER `is_system`"; } if (!$this->hasTableIndex('os', 'idx_created')) { $this->console->out("Adding idx_created index for scalr.os.created column..."); $stmt .= ", ADD INDEX `idx_created` (`created` ASC)"; } if (!empty($stmt)) { $this->db->Execute("ALTER TABLE `os` " . ltrim($stmt, ',')); } if (!empty($bCreated)) { $date = new \DateTime(); $date->modify('-1 hour'); $list = Os::find([['$or' => [['created' => null], ['created' => new \DateTime('0000-00-00 00:00:00')]]]]); foreach ($list as $os) { /* @var $os Os */ $os->created = $date; $os->save(); $date->modify('+1 second'); } } }
/** * 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)); }
/** * @param int $id * * @return DBRole * * @throws Exception */ public static function loadById($id) { $db = \Scalr::getDb(); $roleinfo = $db->GetRow("SELECT * FROM roles WHERE id=?", array($id)); if (!$roleinfo) { throw new Exception(sprintf(_("Role ID#%s not found in database"), $id)); } $DBRole = new DBRole($id); foreach (self::$FieldPropertyMap as $k => $v) { if (isset($roleinfo[$k])) { $DBRole->{$v} = $roleinfo[$k]; } } if (!$DBRole->__os) { $DBRole->__os = Os::findOne([['id' => $DBRole->osId]]); } return $DBRole; }
/** * @test */ public function testImagesFunctional() { $testName = str_replace('-', '', $this->getTestName()); $images = null; $uri = self::getUserApiUrl('/images'); do { $query = []; if (isset($images->pagination->next)) { $parts = parse_url($images->pagination->next); parse_str($parts['query'], $query); } $describe = $this->request($uri, Request::METHOD_GET, $query); $this->assertDescribeResponseNotEmpty($describe); $images = $describe->getBody(); foreach ($images->data as $image) { $this->assertImageObjectNotEmpty($image); if (strpos($image->name, $testName) !== false) { $delete = $this->request($uri . '/' . $image->id, Request::METHOD_DELETE); $this->assertEquals(200, $delete->response->getStatus()); } } } while (!empty($images->pagination->next)); // test create action $create = $this->request($uri, Request::METHOD_POST, [], ['scope' => 'invalid']); $this->assertErrorMessageContains($create, 400, ErrorMessage::ERR_INVALID_VALUE, 'Invalid scope'); $create = $this->request($uri, Request::METHOD_POST); $this->assertErrorMessageContains($create, 400, ErrorMessage::ERR_INVALID_STRUCTURE, 'Invalid body'); $create = $this->request($uri, Request::METHOD_POST, [], ['invalid' => 'value']); $this->assertErrorMessageContains($create, 400, ErrorMessage::ERR_INVALID_STRUCTURE, 'You are trying to set'); $create = $this->request($uri, Request::METHOD_POST, [], ['scope' => ScopeInterface::SCOPE_ENVIRONMENT, 'name' => 'invalidName^$&&']); $this->assertErrorMessageContains($create, 400, ErrorMessage::ERR_INVALID_VALUE, 'Invalid name of the Image'); $create = $this->request($uri, Request::METHOD_POST, [], ['scope' => ScopeInterface::SCOPE_ENVIRONMENT, 'architecture' => 'invalid', 'name' => $testName]); $this->assertErrorMessageContains($create, 400, ErrorMessage::ERR_INVALID_VALUE, 'Invalid architecture of the Image'); $create = $this->request($uri, Request::METHOD_POST, [], ['scope' => ScopeInterface::SCOPE_ENVIRONMENT, 'name' => $testName]); $this->assertErrorMessageContains($create, 400, ErrorMessage::ERR_INVALID_STRUCTURE, 'OS must be provided with the request'); $create = $this->request($uri, Request::METHOD_POST, [], ['scope' => ScopeInterface::SCOPE_ENVIRONMENT, 'name' => $testName, 'os' => ['id' => 'invalidOsId']]); $this->assertErrorMessageContains($create, 400, ErrorMessage::ERR_INVALID_VALUE, 'Specified OS does not exist'); $os = Os::findOne([['status' => Os::STATUS_ACTIVE]]); /* @var $os Os */ $env = \Scalr_Environment::init()->loadById(static::$testEnvId); $platform = \SERVER_PLATFORMS::EC2; if ($env->isPlatformEnabled($platform)) { $env->setPlatformConfig([$platform . '.is_enabled' => 0]); } $create = $this->request($uri, Request::METHOD_POST, [], ['scope' => ScopeInterface::SCOPE_ENVIRONMENT, 'name' => $testName, 'os' => ['id' => $os->id], 'cloudPlatform' => $platform]); $this->assertErrorMessageErrorEquals(ErrorMessage::ERR_INVALID_VALUE, $create); $this->assertErrorMessageStatusEquals(400, $create); $env->setPlatformConfig([$platform . '.is_enabled' => 1]); $create = $this->request($uri, Request::METHOD_POST, [], ['scope' => ScopeInterface::SCOPE_ENVIRONMENT, 'name' => $testName, 'os' => ['invalid'], 'cloudPlatform' => $platform]); $this->assertErrorMessageContains($create, 400, ErrorMessage::ERR_INVALID_VALUE, 'Invalid identifier of the OS'); $create = $this->request($uri, Request::METHOD_POST, [], ['scope' => ScopeInterface::SCOPE_ENVIRONMENT, 'name' => $testName, 'os' => ['id' => $os->id], 'cloudPlatform' => $platform]); $this->assertErrorMessageContains($create, 400, ErrorMessage::ERR_INVALID_VALUE, 'Unable to find the requested image on the cloud'); $region = null; $cloudImageId = null; foreach (Aws::getCloudLocations() as $cloudLocation) { $cloudImageId = $this->getNewImageId($env, $cloudLocation); if (!empty($cloudImageId)) { $region = $cloudLocation; break; } } $this->assertNotNull($cloudImageId); $this->assertNotNull($cloudLocation); $create = $this->request($uri, Request::METHOD_POST, [], ['scope' => ScopeInterface::SCOPE_ENVIRONMENT, 'name' => $testName, 'os' => $os->id, 'cloudPlatform' => $platform, 'cloudLocation' => $region, 'cloudImageId' => $cloudImageId]); $this->assertFetchResponseNotEmpty($create); $imageBody = $create->getBody(); $this->assertImageObjectNotEmpty($imageBody->data); $this->assertEquals(201, $create->response->getStatus()); $this->assertNotEmpty($imageBody->data->id); $this->assertEquals(ScopeInterface::SCOPE_ENVIRONMENT, $imageBody->data->scope); $this->assertEquals($testName, $imageBody->data->name); $this->assertEquals($os->id, $imageBody->data->os->id); $this->assertEquals($platform, $imageBody->data->cloudPlatform); $this->assertEquals($region, $imageBody->data->cloudLocation); $this->assertEquals($cloudImageId, $imageBody->data->cloudImageId); $create = $this->request($uri, Request::METHOD_POST, [], ['scope' => ScopeInterface::SCOPE_ENVIRONMENT, 'name' => $testName, 'os' => ['id' => $os->id], 'cloudPlatform' => $platform, 'cloudLocation' => $region, 'cloudImageId' => $cloudImageId]); $this->assertErrorMessageErrorEquals(ErrorMessage::ERR_UNICITY_VIOLATION, $create); $this->assertErrorMessageStatusEquals(409, $create); // test filtering $describe = $this->request($uri, Request::METHOD_GET, ['scope' => ScopeInterface::SCOPE_ENVIRONMENT]); $this->assertDescribeResponseNotEmpty($describe); foreach ($describe->getBody()->data as $data) { $this->assertImageObjectNotEmpty($data); $this->assertEquals(ScopeInterface::SCOPE_ENVIRONMENT, $data->scope); } $describe = $this->request($uri, Request::METHOD_GET, ['name' => $testName]); $this->assertDescribeResponseNotEmpty($describe); foreach ($describe->getBody()->data as $data) { $this->assertImageObjectNotEmpty($data); $this->assertEquals($testName, $data->name); } $describe = $this->request($uri, Request::METHOD_GET, ['id' => $imageBody->data->id]); $this->assertDescribeResponseNotEmpty($describe); foreach ($describe->getBody()->data as $data) { $this->assertImageObjectNotEmpty($data); $this->assertEquals($imageBody->data->id, $data->id); } $describe = $this->request($uri, Request::METHOD_GET, ['os' => $os->id]); $this->assertDescribeResponseNotEmpty($describe); foreach ($describe->getBody()->data as $data) { $this->assertImageObjectNotEmpty($data); $this->assertEquals($os->id, $data->os->id); } $describe = $this->request($uri, Request::METHOD_GET, ['os' => 'invalid*&^^%']); $this->assertErrorMessageContains($describe, 400, ErrorMessage::ERR_INVALID_VALUE, "Invalid identifier of the OS"); $describe = $this->request($uri, Request::METHOD_GET, ['cloudPlatform' => $platform, 'cloudLocation' => $region]); $this->assertDescribeResponseNotEmpty($describe); foreach ($describe->getBody()->data as $data) { $this->assertImageObjectNotEmpty($data); $this->assertEquals($platform, $data->cloudPlatform); $this->assertEquals($region, $data->cloudLocation); } $describe = $this->request($uri, Request::METHOD_GET, ['cloudLocation' => $region]); $this->assertErrorMessageErrorEquals(ErrorMessage::ERR_INVALID_STRUCTURE, $describe); $this->assertErrorMessageStatusEquals(400, $describe); $describe = $this->request($uri, Request::METHOD_GET, ['cloudImageId' => $cloudImageId]); $this->assertDescribeResponseNotEmpty($describe); foreach ($describe->getBody()->data as $data) { $this->assertImageObjectNotEmpty($data); $this->assertEquals($cloudImageId, $data->cloudImageId); } // test modify action $modify = $this->request($uri, Request::METHOD_PATCH, [], ['name' => $testName . 'modify']); $this->assertErrorMessageErrorEquals(ErrorMessage::ERR_ENDPOINT_NOT_FOUND, $modify); $this->assertErrorMessageStatusEquals(404, $modify); $modify = $this->request($uri . '/' . $imageBody->data->id, Request::METHOD_PATCH, [], ['invalid' => $testName . 'modify']); $this->assertErrorMessageErrorEquals(ErrorMessage::ERR_INVALID_STRUCTURE, $modify); $this->assertErrorMessageStatusEquals(400, $modify); $modify = $this->request($uri . '/' . $imageBody->data->id, Request::METHOD_PATCH, [], ['id' => $testName . 'modify']); $this->assertErrorMessageErrorEquals(ErrorMessage::ERR_INVALID_STRUCTURE, $modify); $this->assertErrorMessageStatusEquals(400, $modify); $modify = $this->request($uri . '/' . $imageBody->data->id, Request::METHOD_PATCH, [], ['scope' => $testName . 'modify']); $this->assertErrorMessageErrorEquals(ErrorMessage::ERR_INVALID_VALUE, $modify); $this->assertErrorMessageStatusEquals(400, $modify); $notFoundId = '11111111-1111-1111-1111-111111111111'; $modify = $this->request($uri . '/' . $notFoundId, Request::METHOD_PATCH, [], ['name' => $testName . 'modify']); $this->assertErrorMessageErrorEquals(ErrorMessage::ERR_OBJECT_NOT_FOUND, $modify); $this->assertErrorMessageStatusEquals(404, $modify); $entity = Image::findOne([['envId' => null], ['status' => Image::STATUS_ACTIVE]]); /* @var $entity Image */ $this->assertNotEmpty($entity); $notAccessibleId = $entity->hash; $modify = $this->request($uri . '/' . $notAccessibleId, Request::METHOD_PATCH, [], ['name' => $testName . 'modify']); $this->assertErrorMessageErrorEquals(ErrorMessage::ERR_SCOPE_VIOLATION, $modify); $this->assertErrorMessageStatusEquals(403, $modify); $create = $this->request($uri, Request::METHOD_POST, [], ['scope' => ScopeInterface::SCOPE_ENVIRONMENT, 'name' => $testName, 'os' => ['id' => $entity->osId], 'cloudPlatform' => $entity->platform, 'cloudLocation' => $entity->cloudLocation, 'cloudImageId' => $entity->id]); $this->assertErrorMessageErrorEquals(ErrorMessage::ERR_UNICITY_VIOLATION, $create); $this->assertErrorMessageStatusEquals(409, $create); // test fetch action $fetch = $this->request($uri . '/' . $notFoundId, Request::METHOD_GET); $this->assertErrorMessageErrorEquals(ErrorMessage::ERR_OBJECT_NOT_FOUND, $fetch); $this->assertErrorMessageStatusEquals(404, $fetch); $fetch = $this->request($uri . '/' . $imageBody->data->id, Request::METHOD_GET); $this->assertFetchResponseNotEmpty($fetch); $fetchBody = $fetch->getBody(); $this->assertImageObjectNotEmpty($fetchBody->data); $this->assertEquals($imageBody->data->id, $fetchBody->data->id); $fetch = $this->request($uri . '/' . $entity->hash, Request::METHOD_GET); $this->assertFetchResponseNotEmpty($fetch); $fetchBody = $fetch->getBody(); $this->assertImageObjectNotEmpty($fetchBody->data); $this->assertEquals($entity->hash, $fetchBody->data->id); $modify = $this->request($uri . '/' . $imageBody->data->id, Request::METHOD_PATCH, [], ['name' => $testName . 'modify']); $this->assertEquals(200, $modify->response->getStatus()); $this->assertImageObjectNotEmpty($modify->getBody()->data); $this->assertEquals($testName . 'modify', $modify->getBody()->data->name); // test copy action $copy = $this->request($uri . '/' . $imageBody->data->id . '/actions/copy', Request::METHOD_POST); $this->assertErrorMessageErrorEquals(ErrorMessage::ERR_INVALID_STRUCTURE, $copy); $this->assertErrorMessageStatusEquals(400, $copy); $copy = $this->request($uri . '/' . $imageBody->data->id . '/actions/copy', Request::METHOD_POST, [], ['cloudLocation' => 'invalid', 'cloudPlatform' => 'ec2']); $this->assertErrorMessageErrorEquals(ErrorMessage::ERR_INVALID_VALUE, $copy); $this->assertErrorMessageStatusEquals(400, $copy); $copy = $this->request($uri . '/' . $imageBody->data->id . '/actions/copy', Request::METHOD_POST, [], ['cloudLocation' => Aws::REGION_US_EAST_1, 'cloudPlatform' => 'gce']); $this->assertErrorMessageErrorEquals(ErrorMessage::ERR_INVALID_VALUE, $copy); $this->assertErrorMessageStatusEquals(400, $copy); $copy = $this->request($uri . '/' . $imageBody->data->id . '/actions/copy', Request::METHOD_POST, [], ['cloudLocation' => $region, 'cloudPlatform' => 'ec2']); $this->assertErrorMessageErrorEquals(ErrorMessage::ERR_BAD_REQUEST, $copy); $this->assertErrorMessageStatusEquals(400, $copy); $awsRegions = Aws::getCloudLocations(); $copyTo = null; foreach ($awsRegions as $awsRegion) { if ($awsRegion != $region) { $copyTo = $awsRegion; break; } } $this->assertNotNull($copyTo); $copy = $this->request($uri . '/' . $notAccessibleId . '/actions/copy', Request::METHOD_POST, [], ['cloudLocation' => $copyTo, 'cloudPlatform' => \SERVER_PLATFORMS::EC2]); $this->assertErrorMessageErrorEquals(ErrorMessage::ERR_SCOPE_VIOLATION, $copy); $this->assertErrorMessageStatusEquals(403, $copy); $copy = $this->request($uri . '/' . $imageBody->data->id . '/actions/copy', Request::METHOD_POST, [], ['cloudLocation' => $copyTo, 'cloudPlatform' => \SERVER_PLATFORMS::EC2]); $copyBody = $copy->getBody(); $this->assertEquals(202, $copy->response->getStatus()); $this->assertFetchResponseNotEmpty($copy); $this->assertImageObjectNotEmpty($copyBody->data); $this->assertEquals(\SERVER_PLATFORMS::EC2, $copyBody->data->cloudPlatform); $this->assertEquals($copyTo, $copyBody->data->cloudLocation); // test delete action $delete = $this->request($uri . '/' . $notFoundId, Request::METHOD_DELETE); $this->assertErrorMessageErrorEquals(ErrorMessage::ERR_OBJECT_NOT_FOUND, $delete); $this->assertErrorMessageStatusEquals(404, $delete); $delete = $this->request($uri . '/' . $entity->hash, Request::METHOD_DELETE); $this->assertErrorMessageErrorEquals(ErrorMessage::ERR_SCOPE_VIOLATION, $delete); $this->assertErrorMessageStatusEquals(403, $delete); $delete = $this->request($uri . '/' . $copyBody->data->id, Request::METHOD_DELETE); $this->assertEquals(200, $delete->response->getStatus()); $delete = $this->request($uri . '/' . $imageBody->data->id, Request::METHOD_DELETE); $this->assertEquals(200, $delete->response->getStatus()); }
protected function run8($stage) { $knownOses = []; //Retrieves the list of all known OSes foreach (Entity\Os::all() as $os) { /* @var $os Entity\Os */ $knownOses[$os->id] = $os; } $role = new Entity\Role(); //Trying to clarify the operating system of the Roles using Images which are associated with them. //If all Images have the same operating system it will be considered as acceptable for the Role at latter will be updated. $rs = $this->db->Execute("\n SELECT " . $role->fields('r', true) . ", GROUP_CONCAT(t.os_id) `osids`\n FROM roles r JOIN (\n SELECT DISTINCT ri.role_id, i.os_id\n FROM images i\n JOIN role_images ri ON i.id = ri.image_id\n AND i.platform = ri.platform\n AND i.cloud_location = ri.cloud_location\n ) t ON t.role_id = r.id\n WHERE r.os_id = ?\n GROUP BY r.id\n HAVING osids != r.os_id\n ", ['unknown-os']); if ($rs->RecordCount()) { $this->console->out("Found %d Roles the OS value of which can be filled from the Images. Updating...", $rs->RecordCount()); } while ($row = $rs->FetchRow()) { $role = new Entity\Role(); $role->load($row, 'r'); if (!empty($row['osids'])) { if (isset($knownOses[$row['osids']])) { //Updating OS value of the Role $role->osId = $row['osids']; $role->save(); } else { $this->console->warning("Role %s (%d) is associated with the Images with either different or unknown OS: %s", $role->name, $role->id, $row['osids']); } } } $image = new Entity\Image(); //Trying to clarify the operating sytem of the Images using Roles which are associated with them. $rs = $this->db->Execute("\n SELECT " . $image->fields('i', true) . ", GROUP_CONCAT(t.os_id) `osids`\n FROM images i JOIN (\n SELECT DISTINCT ri.image_id, ri.platform, ri.cloud_location, r.os_id\n FROM roles r\n JOIN role_images ri ON ri.role_id = r.id\n ) t ON t.image_id = i.id AND t.platform = i.platform AND t.cloud_location = i.cloud_location\n WHERE i.os_id = ?\n GROUP BY i.hash\n HAVING osids != i.os_id\n ", ['unknown-os']); if ($rs->RecordCount()) { $this->console->out("Found %d Images the OS value of which can be filled from the Roles. Updating...", $rs->RecordCount()); } while ($row = $rs->FetchRow()) { $image = new Entity\Image(); $image->load($row, 'i'); if (!empty($row['osids'])) { if (isset($knownOses[$row['osids']])) { //Updating OS value of the Image $image->osId = $row['osids']; $image->save(); } else { $this->console->warning("Image (%s) imageId: %s, platform: %s, cloudLocation: %s is associated with the Roles with either different or unknown OS: %s", $image->hash, $image->id, $image->platform, $image->cloudLocation, $row['osids']); } } } }
/** * @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)); }
/** * @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"); }
/** * @test */ public function testAccountRolesFunctional() { $db = \Scalr::getDb(); $testName = str_replace('-', '', static::getTestName()); $roles = null; $uri = self::getAccountApiUrl('/roles'); do { $query = []; if (isset($roles->pagination->next)) { $parts = parse_url($roles->pagination->next); parse_str($parts['query'], $query); } $describe = $this->request($uri, Request::METHOD_GET, $query); $this->assertDescribeResponseNotEmpty($describe); $this->assertNotEmpty($describe->getBody()); $roles = $describe->getBody(); foreach ($roles->data as $role) { $this->assertRolesObjectNotEmpty($role); if ($role->name == $testName) { $delete = $this->request($uri . '/' . $role->id, Request::METHOD_DELETE); $this->assertEquals(200, $delete->status); } } } while (!empty($roles->pagination->next)); // test create action $create = $this->request($uri, Request::METHOD_POST, [], ['scope' => 'invalid']); $this->assertErrorMessageContains($create, 400, ErrorMessage::ERR_INVALID_VALUE, 'Invalid scope'); $create = $this->request($uri, Request::METHOD_POST); $this->assertErrorMessageContains($create, 400, ErrorMessage::ERR_INVALID_STRUCTURE, 'Invalid body'); $create = $this->request($uri, Request::METHOD_POST, [], ['invalid' => 'value']); $this->assertErrorMessageContains($create, 400, ErrorMessage::ERR_INVALID_STRUCTURE, 'You are trying to set'); $create = $this->request($uri, Request::METHOD_POST, [], ['id' => 'value']); $this->assertErrorMessageContains($create, 400, ErrorMessage::ERR_INVALID_VALUE, 'Invalid name'); $create = $this->request($uri, Request::METHOD_POST, [], ['scope' => ScopeInterface::SCOPE_ACCOUNT, 'name' => 'invalidName^$&&']); $this->assertErrorMessageContains($create, 400, ErrorMessage::ERR_INVALID_VALUE, 'Invalid name of the Role'); $create = $this->request($uri, Request::METHOD_POST, [], ['scope' => ScopeInterface::SCOPE_ACCOUNT, 'name' => $testName, 'description' => 'invalidDesc<br/>']); $this->assertErrorMessageContains($create, 400, ErrorMessage::ERR_INVALID_VALUE, 'Invalid description'); $create = $this->request($uri, Request::METHOD_POST, [], ['scope' => ScopeInterface::SCOPE_ACCOUNT, 'name' => $testName]); $this->assertErrorMessageContains($create, 400, ErrorMessage::ERR_INVALID_STRUCTURE, 'Role category should be provided'); $create = $this->request($uri, Request::METHOD_POST, [], ['scope' => ScopeInterface::SCOPE_ACCOUNT, 'name' => $testName, 'category' => ['id' => 'not int']]); $this->assertErrorMessageContains($create, 400, ErrorMessage::ERR_INVALID_VALUE, 'Invalid identifier of the category'); $create = $this->request($uri, Request::METHOD_POST, [], ['scope' => ScopeInterface::SCOPE_ACCOUNT, 'name' => $testName, 'category' => ['id' => -1]]); $this->assertErrorMessageContains($create, 400, ErrorMessage::ERR_INVALID_VALUE, 'The Role category does not exist'); $rolesCat = RoleCategory::findOne(); /* @var $rolesCat RoleCategory */ $this->assertNotEmpty($rolesCat); $create = $this->request($uri, Request::METHOD_POST, [], ['scope' => ScopeInterface::SCOPE_ACCOUNT, 'name' => $testName, 'category' => ['id' => $rolesCat->id]]); $this->assertErrorMessageContains($create, 400, ErrorMessage::ERR_INVALID_STRUCTURE, "Missed property 'os.id'"); $os = Os::findOne([['status' => Os::STATUS_ACTIVE], ['family' => 'ubuntu'], ['generation' => '12.04']]); /* @var $os Os */ $this->assertNotEmpty($os); $create = $this->request($uri, Request::METHOD_POST, [], ['scope' => ScopeInterface::SCOPE_ACCOUNT, 'name' => $testName, 'category' => ['id' => $rolesCat->id], 'os' => ['id' => -1]]); $this->assertErrorMessageContains($create, 400, ErrorMessage::ERR_INVALID_VALUE, 'Invalid identifier of the OS'); $create = $this->request($uri, Request::METHOD_POST, [], ['scope' => ScopeInterface::SCOPE_ACCOUNT, 'name' => $testName, 'category' => ['id' => $rolesCat->id], 'os' => ['id' => 'invalid']]); $this->assertErrorMessageContains($create, 400, ErrorMessage::ERR_INVALID_VALUE, "OS with id 'invalid' not found."); $create = $this->request($uri, Request::METHOD_POST, [], ['scope' => ScopeInterface::SCOPE_ACCOUNT, 'name' => $testName, 'description' => $testName, 'category' => $rolesCat->id, 'os' => $os->id, 'quickStart' => true, 'deprecated' => true]); $body = $create->getBody(); $this->assertEquals(201, $create->response->getStatus()); $this->assertFetchResponseNotEmpty($create); $this->assertRolesObjectNotEmpty($body->data); $this->assertNotEmpty($body->data->id); $this->assertEquals($testName, $body->data->name); $this->assertEquals($testName, $body->data->description); $this->assertEquals(ScopeInterface::SCOPE_ACCOUNT, $body->data->scope); $this->assertEquals($rolesCat->id, $body->data->category->id); $this->assertEquals($os->id, $body->data->os->id); $this->assertEquals(true, $body->data->quickStart); $this->assertEquals(true, $body->data->deprecated); // test images actions $roleId = $body->data->id; $imagesUri = $uri . '/' . $roleId . '/images'; $images = null; do { $query = []; if (isset($images->pagination->next)) { $parts = parse_url($images->pagination->next); parse_str($parts['query'], $query); } $describeImages = $this->request($imagesUri, Request::METHOD_GET, $query); $this->assertDescribeResponseNotEmpty($describeImages); $images = $describeImages->getBody(); foreach ($images->data as $imageRole) { $this->assertRoleImageObjectNotEmpty($imageRole); $this->assertEquals($roleId, $imageRole->role->id); $image = Image::findPk($imageRole->image->id); /* @var $image Image */ if ($image->name == $testName) { $delete = $this->request($imagesUri . '/' . $imageRole->image->id, Request::METHOD_DELETE); $this->assertEquals(200, $delete->status); } } } while (!empty($images->pagination->next)); $env = \Scalr_Environment::init()->loadById(static::$testEnvId); $platform = \SERVER_PLATFORMS::EC2; if (!$env->isPlatformEnabled($platform)) { $env->setPlatformConfig([$platform . '.is_enabled' => 1]); } $region = null; $cloudImageId = null; foreach (Aws::getCloudLocations() as $cloudLocation) { $cloudImageId = $this->getNewImageId($env, $cloudLocation); if (!empty($cloudImageId)) { $region = $cloudLocation; break; } } $this->assertNotNull($cloudImageId); $this->assertNotNull($cloudLocation); $image = $this->createEntity(new Image(), ['accountId' => $this->getUser()->accountId, 'name' => $testName, 'osId' => $os->id, 'platform' => $platform, 'cloudLocation' => $region, 'id' => $cloudImageId, 'architecture' => 'x86_64', 'source' => Image::SOURCE_MANUAL, 'status' => Image::STATUS_ACTIVE]); $createRoleImage = $this->request($imagesUri, Request::METHOD_POST, [], ['role' => ['id' => $roleId + 10], 'image' => ['id' => $image->hash]]); $this->assertErrorMessageStatusEquals(400, $createRoleImage); $this->assertErrorMessageErrorEquals(ErrorMessage::ERR_INVALID_VALUE, $createRoleImage); $createRoleImage = $this->request($imagesUri, Request::METHOD_POST, [], ['role' => ['id' => $roleId]]); $this->assertErrorMessageStatusEquals(400, $createRoleImage); $this->assertErrorMessageErrorEquals(ErrorMessage::ERR_INVALID_STRUCTURE, $createRoleImage); $createRoleImage = $this->request($imagesUri, Request::METHOD_POST, [], ['role' => ['id' => $roleId], 'image' => ['id' => '11111111-1111-1111-1111-111111111111']]); $this->assertErrorMessageStatusEquals(404, $createRoleImage); $this->assertErrorMessageErrorEquals(ErrorMessage::ERR_INVALID_VALUE, $createRoleImage); $createRoleImage = $this->request($imagesUri, Request::METHOD_POST, [], ['role' => ['id' => $roleId], 'image' => ['id' => $image->hash]]); $createRoleImageBody = $createRoleImage->getBody(); $this->assertEquals(201, $createRoleImage->response->getStatus()); $this->assertFetchResponseNotEmpty($createRoleImage); $this->assertRoleImageObjectNotEmpty($createRoleImageBody->data); $createRoleImageError = $this->request($imagesUri, Request::METHOD_POST, [], ['role' => ['id' => $roleId], 'image' => ['id' => $image->hash]]); $this->assertErrorMessageStatusEquals(400, $createRoleImageError); $this->assertErrorMessageErrorEquals(ErrorMessage::ERR_BAD_REQUEST, $createRoleImageError); $fetchImage = $this->request($imagesUri . '/' . $createRoleImageBody->data->image->id, Request::METHOD_GET); $fetchImageBody = $fetchImage->getBody(); $this->assertEquals(200, $fetchImage->response->getStatus()); $this->assertFetchResponseNotEmpty($fetchImage); $this->assertImageObjectNotEmpty($fetchImageBody->data); $this->assertEquals($cloudImageId, $fetchImageBody->data->cloudImageId); $this->assertEquals($testName, $fetchImageBody->data->name); // test role images filtering $describeRoleImages = $this->request($imagesUri, Request::METHOD_GET, ['role' => $roleId]); $this->assertDescribeResponseNotEmpty($describeRoleImages); foreach ($describeRoleImages->getBody()->data as $data) { $this->assertRoleImageObjectNotEmpty($data); $this->assertEquals($roleId, $data->role->id); } $describeRoleImages = $this->request($imagesUri, Request::METHOD_GET, ['image' => $image->hash]); $this->assertDescribeResponseNotEmpty($describeRoleImages); foreach ($describeRoleImages->getBody()->data as $data) { $this->assertRoleImageObjectNotEmpty($data); $this->assertEquals($image->hash, $data->image->id); } $describeRoleImages = $this->request($imagesUri, Request::METHOD_GET, ['invalid' => 'value']); $this->assertErrorMessageContains($describeRoleImages, 400, ErrorMessage::ERR_INVALID_STRUCTURE, 'Unsupported filter'); $currentRole = Role::findPk($roleId); /* @var $currentRole Role */ $this->assertNotEmpty($currentRole); $adminImages = Image::find([['envId' => null], ['status' => Image::STATUS_ACTIVE], ['cloudLocation' => $region]]); $this->assertNotEmpty($adminImages); $adminImage = null; foreach ($adminImages as $aImage) { /* @var $aImage Image */ $imageOs = $aImage->getOs(); if (!empty($imageOs) && $imageOs->generation == $currentRole->getOs()->generation && $imageOs->family == $currentRole->getOs()->family) { $adminImage = $aImage; break; } } /* @var $adminImage Image */ $this->assertNotEmpty($adminImage); $this->assertNotEquals($createRoleImageBody->data->image->id, $adminImage->hash); $replaceImage = $this->request($imagesUri . '/' . $createRoleImageBody->data->image->id . '/actions/replace', Request::METHOD_POST, [], ['role' => $roleId, 'image' => $adminImage->hash]); $replaceImageBody = $replaceImage->getBody(); $this->assertEquals(200, $replaceImage->response->getStatus()); $this->assertFetchResponseNotEmpty($replaceImage); $this->assertRoleImageObjectNotEmpty($replaceImageBody->data); $this->assertEquals($adminImage->hash, $replaceImageBody->data->image->id); $deleteImage = $this->request($imagesUri . '/' . $replaceImageBody->data->image->id, Request::METHOD_DELETE); $this->assertEquals(200, $deleteImage->response->getStatus()); $delete = $this->request(static::getAccountApiUrl("images/{$image->hash}"), Request::METHOD_DELETE); $this->assertEquals(200, $delete->response->getStatus()); // test get action $notFoundRoleId = 10 + $db->GetOne("SELECT MAX(r.id) FROM roles r"); $get = $this->request($uri . '/' . $notFoundRoleId, Request::METHOD_GET); $this->assertErrorMessageContains($get, 404, ErrorMessage::ERR_OBJECT_NOT_FOUND, "The Role either does not exist or isn't in scope for the current Environment"); $get = $this->request($uri . '/' . $body->data->id, Request::METHOD_GET); $getBody = $get->getBody(); $this->assertEquals(200, $get->response->getStatus()); $this->assertFetchResponseNotEmpty($get); $this->assertRolesObjectNotEmpty($getBody->data); $this->assertEquals($body->data->id, $getBody->data->id); $this->assertEquals($testName, $getBody->data->name); $this->assertEquals($testName, $getBody->data->description); $this->assertEquals(ScopeInterface::SCOPE_ACCOUNT, $getBody->data->scope); $this->assertEquals($rolesCat->id, $getBody->data->category->id); $this->assertEquals($os->id, $getBody->data->os->id); // test filters $describe = $this->request($uri, Request::METHOD_GET, ['description' => $testName]); $this->assertErrorMessageContains($describe, 400, ErrorMessage::ERR_INVALID_STRUCTURE, 'Unsupported filter'); $describe = $this->request($uri, Request::METHOD_GET, ['scope' => 'wrong<br>']); $this->assertErrorMessageContains($describe, 400, ErrorMessage::ERR_INVALID_VALUE, 'Unexpected scope value'); $describe = $this->request($uri, Request::METHOD_GET, ['scope' => ScopeInterface::SCOPE_SCALR]); $this->assertDescribeResponseNotEmpty($describe); foreach ($describe->getBody()->data as $data) { $this->assertRolesObjectNotEmpty($data); } $describe = $this->request($uri, Request::METHOD_GET, ['scope' => ScopeInterface::SCOPE_ACCOUNT]); $this->assertDescribeResponseNotEmpty($describe); foreach ($describe->getBody()->data as $data) { $this->assertRolesObjectNotEmpty($data); $this->assertEquals(ScopeInterface::SCOPE_ACCOUNT, $data->scope); } $describe = $this->request($uri, Request::METHOD_GET, ['name' => $testName]); $this->assertDescribeResponseNotEmpty($describe); foreach ($describe->getBody()->data as $data) { $this->assertRolesObjectNotEmpty($data); $this->assertEquals($testName, $data->name); } $describe = $this->request($uri, Request::METHOD_GET, ['id' => $roleId]); $this->assertDescribeResponseNotEmpty($describe); foreach ($describe->getBody()->data as $data) { $this->assertRolesObjectNotEmpty($data); $this->assertEquals($roleId, $data->id); } $describe = $this->request($uri, Request::METHOD_GET, ['os' => $os->id]); $this->assertDescribeResponseNotEmpty($describe); foreach ($describe->getBody()->data as $data) { $this->assertRolesObjectNotEmpty($data); $this->assertEquals($os->id, $data->os->id); } $describe = $this->request($uri, Request::METHOD_GET, ['os' => 'invalid*&^^%']); $this->assertErrorMessageContains($describe, 400, ErrorMessage::ERR_INVALID_VALUE, "Invalid identifier of the OS"); $describe = $this->request($uri, Request::METHOD_GET, ['category' => $rolesCat->id]); $this->assertDescribeResponseNotEmpty($describe); foreach ($describe->getBody()->data as $data) { $this->assertRolesObjectNotEmpty($data); $this->assertEquals($rolesCat->id, $data->category->id); } $describe = $this->request($uri, Request::METHOD_GET, ['category' => '']); $this->assertErrorMessageContains($describe, 400, ErrorMessage::ERR_INVALID_VALUE, "Invalid identifier of the category"); // test modify action $modify = $this->request($uri . '/' . $body->data->id, Request::METHOD_PATCH); $this->assertErrorMessageContains($modify, 400, ErrorMessage::ERR_INVALID_STRUCTURE, 'Invalid body'); $modify = $this->request($uri . '/' . $body->data->id, Request::METHOD_PATCH, [], ['id' => 123]); $this->assertErrorMessageContains($modify, 400, ErrorMessage::ERR_INVALID_STRUCTURE); $modify = $this->request($uri . '/' . $body->data->id, Request::METHOD_PATCH, [], ['invalid' => 'err']); $this->assertErrorMessageContains($modify, 400, ErrorMessage::ERR_INVALID_STRUCTURE, 'You are trying to set'); $modify = $this->request($uri . '/' . $body->data->id, Request::METHOD_PATCH, [], ['scope' => 'environment']); $this->assertErrorMessageContains($modify, 400, ErrorMessage::ERR_INVALID_VALUE); $modify = $this->request($uri . '/' . $body->data->id, Request::METHOD_PATCH, [], ['description' => '']); $modifyBody = $modify->getBody(); $this->assertEquals(200, $modify->response->getStatus()); $this->assertFetchResponseNotEmpty($modify); $this->assertRolesObjectNotEmpty($modifyBody->data); $this->assertEquals($body->data->id, $modifyBody->data->id); $this->assertEquals($testName, $modifyBody->data->name); $this->assertEquals('', $modifyBody->data->description); $this->assertEquals(ScopeInterface::SCOPE_ACCOUNT, $modifyBody->data->scope); $this->assertEquals($rolesCat->id, $modifyBody->data->category->id); $this->assertEquals($os->id, $modifyBody->data->os->id); // test delete action $delete = $this->request(static::getAccountApiUrl("/roles/{$notFoundRoleId}"), Request::METHOD_DELETE); $this->assertErrorMessageContains($delete, 404, ErrorMessage::ERR_OBJECT_NOT_FOUND); $delete = $this->request($uri . '/' . $body->data->id, Request::METHOD_DELETE); $this->assertEquals(200, $delete->status); $db->Execute("INSERT INTO roles SET\n name = ?,\n dtadded = NOW(),\n env_id\t = NULL,\n client_id = NULL,\n generation = 2\n ", [$testName]); $insertedId = $db->_insertid(); $db->Execute("INSERT INTO role_images SET\n role_id = ?,\n platform = 'ec2',\n image_id = 'test'\n ", [$insertedId]); $delete = $this->request($uri . '/' . $insertedId, Request::METHOD_DELETE); $db->Execute("DELETE FROM roles WHERE name = ? AND id = ?", [$testName, $insertedId]); $this->assertErrorMessageContains($delete, 403, ErrorMessage::ERR_SCOPE_VIOLATION); }
/** * @param int $uiStorageTime optional * @return array */ public function getContext($uiStorageTime = 0) { $data = array(); if ($this->user) { $data['user'] = array('userId' => $this->user->getId(), 'clientId' => $this->user->getAccountId(), 'userName' => $this->user->getEmail(), 'gravatarHash' => $this->user->getGravatarHash(), 'envId' => $this->getEnvironment() ? $this->getEnvironmentId() : 0, 'envName' => $this->getEnvironment() ? $this->getEnvironment()->name : '', 'envVars' => '', 'type' => $this->user->getType(), 'settings' => [Scalr_Account_User::SETTING_UI_TIMEZONE => $this->user->getSetting(Scalr_Account_User::SETTING_UI_TIMEZONE), UserSetting::NAME_UI_ANNOUNCEMENT_TIME => $this->getUser()->getSetting(UserSetting::NAME_UI_ANNOUNCEMENT_TIME)]); if ($this->getEnvironment()) { $data['user']['envVars'] = $this->getEnvironment()->getPlatformConfigValue(Scalr_Environment::SETTING_UI_VARS); } else { if ($this->user->getAccountId()) { $data['user']['envVars'] = $this->user->getAccount()->getSetting(Scalr_Account::SETTING_UI_VARS); } } if ($uiStorageTime > 0 && $uiStorageTime < $this->user->getSetting(Scalr_Account_User::SETTING_UI_STORAGE_TIME) && !Scalr_Session::getInstance()->isVirtual()) { $data['user']['uiStorage'] = $this->user->getVar(Scalr_Account_User::VAR_UI_STORAGE); } $envVars = json_decode($data['user']['envVars'], true); $betaMode = $envVars && $envVars['beta'] == 1; if (!$this->user->isAdmin()) { $data['flags'] = []; if ($this->user->getAccountId() != 0) { $data['user']['userIsTrial'] = $this->user->getAccount()->getSetting(Scalr_Account::SETTING_IS_TRIAL) == '1' ? true : false; } $data['flags']['billingExists'] = \Scalr::config('scalr.billing.enabled'); $data['flags']['showDeprecatedFeatures'] = \Scalr::config('scalr.ui.show_deprecated_features'); $data['acl'] = $this->request->getAclRoles()->getAllowedArray(true); if (!$this->user->isAccountOwner()) { $data['user']['accountOwnerName'] = $this->user->getAccount()->getOwner()->getEmail(); } $data['environments'] = $this->user->getEnvironments(); if ($this->user->isAccountOwner()) { if (!$this->user->getAccount()->getSetting(Scalr_Account::SETTING_DATE_ENV_CONFIGURED)) { $data['flags']['needEnvConfig'] = true; } } if ($this->request->getScope() == 'environment') { $sql = "SELECT id, name FROM farms f WHERE env_id = ? AND " . $this->request->getFarmSqlQuery(); $args = [$this->getEnvironmentId()]; $sql .= " ORDER BY name"; $data['farms'] = $this->db->getAll($sql, $args); if ($this->getEnvironment() && $this->user->isTeamOwner()) { $data['user']['isTeamOwner'] = true; } } } $data['flags']['wikiUrl'] = \Scalr::config('scalr.ui.wiki_url'); $data['flags']['supportUrl'] = \Scalr::config('scalr.ui.support_url'); if ($data['flags']['supportUrl'] == '/core/support') { if ($this->user->isAdmin()) { unset($data['flags']['supportUrl']); } else { $data['flags']['supportUrl'] .= '?X-Requested-Token=' . Scalr_Session::getInstance()->getToken(); } } //OS $data['os'] = []; foreach (Os::find() as $os) { /* @var $os Os */ $data['os'][] = ['id' => $os->id, 'family' => $os->family, 'name' => $os->name, 'generation' => $os->generation, 'version' => $os->version, 'status' => $os->status]; } $data['defaults'] = (new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(true), ScopeInterface::SCOPE_ENVIRONMENT))->getUiDefaults(); $data['platforms'] = []; $allowedClouds = (array) \Scalr::config('scalr.allowed_clouds'); if ($this->user->getAccountId() == 263) { array_push($allowedClouds, SERVER_PLATFORMS::VERIZON); } $platforms = SERVER_PLATFORMS::getList(); if (!($this->request->getHeaderVar('Interface-Beta') || $betaMode)) { $platforms = array_intersect_key($platforms, array_flip($allowedClouds)); } $environment = $this->getEnvironment(); if (!empty($environment)) { $cloudsCredentials = $environment->cloudCredentialsList(array_keys($platforms)); } foreach ($platforms as $platform => $platformName) { if (!in_array($platform, $allowedClouds) && !$this->request->getHeaderVar('Interface-Beta') && !$betaMode) { continue; } $data['platforms'][$platform] = array('public' => PlatformFactory::isPublic($platform), 'enabled' => $this->user->isAdmin() || $this->request->getScope() != 'environment' ? true : isset($cloudsCredentials[$platform]) && $cloudsCredentials[$platform]->isEnabled(), 'name' => $platformName); if (!($this->user->isAdmin() || $this->request->getScope() != 'environment')) { if ($platform == SERVER_PLATFORMS::EC2 && $this->environment->status == Scalr_Environment::STATUS_INACTIVE && $this->environment->getPlatformConfigValue('system.auto-disable-reason')) { $data['platforms'][$platform]['config'] = array('autoDisabled' => true); } if (PlatformFactory::isOpenstack($platform) && $data['platforms'][$platform]['enabled']) { $ccProps = $cloudsCredentials[$platform]->properties; $data['platforms'][$platform]['config'] = [CloudCredentialsProperty::OPENSTACK_EXT_SECURITYGROUPS_ENABLED => $ccProps[CloudCredentialsProperty::OPENSTACK_EXT_SECURITYGROUPS_ENABLED], CloudCredentialsProperty::OPENSTACK_EXT_LBAAS_ENABLED => $ccProps[CloudCredentialsProperty::OPENSTACK_EXT_LBAAS_ENABLED], CloudCredentialsProperty::OPENSTACK_EXT_FLOATING_IPS_ENABLED => $ccProps[CloudCredentialsProperty::OPENSTACK_EXT_FLOATING_IPS_ENABLED], CloudCredentialsProperty::OPENSTACK_EXT_CINDER_ENABLED => $ccProps[CloudCredentialsProperty::OPENSTACK_EXT_CINDER_ENABLED], CloudCredentialsProperty::OPENSTACK_EXT_SWIFT_ENABLED => $ccProps[CloudCredentialsProperty::OPENSTACK_EXT_SWIFT_ENABLED]]; } } } $data['flags']['uiStorageTime'] = $this->user->getSetting(Scalr_Account_User::SETTING_UI_STORAGE_TIME); $data['flags']['uiStorage'] = $this->user->getVar(Scalr_Account_User::VAR_UI_STORAGE); $data['flags']['allowManageAnalytics'] = $this->user->getAccountId() && Scalr::isAllowedAnalyticsOnHostedScalrAccount($this->user->getAccountId()); $data['flags']['hostedScalr'] = (bool) Scalr::isHostedScalr(); $data['flags']['analyticsEnabled'] = $this->getContainer()->analytics->enabled; $data['flags']['apiEnabled'] = (bool) \Scalr::config('scalr.system.api.enabled'); $data['flags']['dnsGlobalEnabled'] = (bool) \Scalr::config('scalr.dns.global.enabled'); $data['flags']['allowBetaEbsTypes'] = SCALR_ID == 'gdp-aws-east'; $data['scope'] = $this->request->getScope(); if ($this->request->getScope() == 'environment') { $governance = new Scalr_Governance($this->getEnvironmentId()); $data['governance'] = $governance->getValues(true); } } if ($this->user) { $data['tags'] = Tag::getAll($this->user->getAccountId()); } $data['flags']['authMode'] = $this->getContainer()->config->get('scalr.auth_mode'); $data['flags']['recaptchaPublicKey'] = $this->getContainer()->config->get('scalr.ui.recaptcha.public_key'); $data['flags']['specialToken'] = Scalr_Session::getInstance()->getToken(); $data['flags']['loginWarning'] = $this->getContainer()->config->get('scalr.ui.login_warning'); return $data; }
/** * {@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"); } }
/** * @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'); }
/** * Fetches identifiers of the OSes which satisfy specified criteria * * @param string $family The family * @param string $generation optional The generation * @param string $version optional The version * @return array Returns array of the identifiers of the OSes which satisfy specified criteria */ public static function findIdsBy($family, $generation = null, $version = null) { $criteria = [['family' => $family]]; if ($generation) { $criteria[] = ['generation' => $generation]; } if ($version) { $criteria[] = ['version' => $version]; } $os = Os::find($criteria); $osIds = []; foreach ($os as $i) { /* @var $i Os */ array_push($osIds, $i->id); } return $osIds; }
/** * {@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."); } }
public function getContext($uiStorageTime = 0) { $data = array(); if ($this->user) { $data['user'] = array('userId' => $this->user->getId(), 'clientId' => $this->user->getAccountId(), 'userName' => $this->user->getEmail(), 'gravatarHash' => $this->user->getGravatarHash(), 'envId' => $this->getEnvironment() ? $this->getEnvironmentId() : 0, 'envName' => $this->getEnvironment() ? $this->getEnvironment()->name : '', 'envVars' => $this->getEnvironment() ? $this->getEnvironment()->getPlatformConfigValue(Scalr_Environment::SETTING_UI_VARS) : '', 'type' => $this->user->getType(), 'settings' => [Scalr_Account_User::VAR_SSH_CONSOLE_LAUNCHER => $this->user->getVar(Scalr_Account_User::VAR_SSH_CONSOLE_LAUNCHER)]); if ($uiStorageTime > 0 && $uiStorageTime < $this->user->getSetting(Scalr_Account_User::SETTING_UI_STORAGE_TIME) && !Scalr_Session::getInstance()->isVirtual()) { $data['user']['uiStorage'] = $this->user->getVar(Scalr_Account_User::VAR_UI_STORAGE); } $envVars = json_decode($data['user']['envVars'], true); $betaMode = $envVars && $envVars['beta'] == 1; if (!$this->user->isAdmin()) { $data['flags'] = []; if ($this->user->getAccountId() != 0) { $data['user']['userIsTrial'] = $this->user->getAccount()->getSetting(Scalr_Account::SETTING_IS_TRIAL) == '1' ? true : false; } $data['flags']['billingExists'] = \Scalr::config('scalr.billing.enabled'); $data['flags']['showDeprecatedFeatures'] = \Scalr::config('scalr.ui.show_deprecated_features'); $data['flags']['wikiUrl'] = \Scalr::config('scalr.ui.wiki_url'); $data['flags']['supportUrl'] = \Scalr::config('scalr.ui.support_url'); if ($data['flags']['supportUrl'] == '/core/support') { $data['flags']['supportUrl'] .= '?X-Requested-Token=' . Scalr_Session::getInstance()->getToken(); } $data['acl'] = $this->request->getAclRoles()->getAllowedArray(true); if (!$this->user->isAccountOwner()) { $data['user']['accountOwnerName'] = $this->user->getAccount()->getOwner()->getEmail(); } $data['environments'] = $this->user->getEnvironments(); if ($this->user->isAccountOwner()) { if (!$this->user->getAccount()->getSetting(Scalr_Account::SETTING_DATE_ENV_CONFIGURED)) { $data['flags']['needEnvConfig'] = true; } } if ($this->request->getScope() == 'environment') { $sql = 'SELECT id, name FROM farms WHERE env_id = ?'; $args = [$this->getEnvironmentId()]; list($sql, $args) = $this->request->prepareFarmSqlQuery($sql, $args); $sql .= ' ORDER BY name'; $data['farms'] = $this->db->getAll($sql, $args); if ($this->getEnvironment() && $this->user->isTeamOwner()) { $data['user']['isTeamOwner'] = true; } } } //OS $data['os'] = []; foreach (Os::find([['status' => Os::STATUS_ACTIVE]]) as $os) { /* @var $os Os */ $data['os'][] = ['id' => $os->id, 'family' => $os->family, 'name' => $os->name, 'generation' => $os->generation, 'version' => $os->version]; } $data['platforms'] = []; $allowedClouds = (array) \Scalr::config('scalr.allowed_clouds'); foreach (SERVER_PLATFORMS::getList() as $platform => $platformName) { if ($this->user->getAccountId() == 263) { array_push($allowedClouds, SERVER_PLATFORMS::VERIZON); } if (!in_array($platform, $allowedClouds) && !$this->request->getHeaderVar('Interface-Beta')) { continue; } $data['platforms'][$platform] = array('public' => PlatformFactory::isPublic($platform), 'enabled' => $this->user->isAdmin() || $this->request->getScope() != 'environment' ? true : !!$this->environment->isPlatformEnabled($platform), 'name' => $platformName); if (!($this->user->isAdmin() || $this->request->getScope() != 'environment')) { if ($platform == SERVER_PLATFORMS::EC2 && $this->environment->status == Scalr_Environment::STATUS_INACTIVE && $this->environment->getPlatformConfigValue('system.auto-disable-reason')) { $data['platforms'][$platform]['config'] = array('autoDisabled' => true); } if (PlatformFactory::isOpenstack($platform) && $data['platforms'][$platform]['enabled']) { $data['platforms'][$platform]['config'] = array(OpenstackPlatformModule::EXT_SECURITYGROUPS_ENABLED => PlatformFactory::NewPlatform($platform)->getConfigVariable(OpenstackPlatformModule::EXT_SECURITYGROUPS_ENABLED, $this->getEnvironment(), false), OpenstackPlatformModule::EXT_LBAAS_ENABLED => PlatformFactory::NewPlatform($platform)->getConfigVariable(OpenstackPlatformModule::EXT_LBAAS_ENABLED, $this->getEnvironment(), false), OpenstackPlatformModule::EXT_FLOATING_IPS_ENABLED => PlatformFactory::NewPlatform($platform)->getConfigVariable(OpenstackPlatformModule::EXT_FLOATING_IPS_ENABLED, $this->getEnvironment(), false), OpenstackPlatformModule::EXT_CINDER_ENABLED => PlatformFactory::NewPlatform($platform)->getConfigVariable(OpenstackPlatformModule::EXT_CINDER_ENABLED, $this->getEnvironment(), false), OpenstackPlatformModule::EXT_SWIFT_ENABLED => PlatformFactory::NewPlatform($platform)->getConfigVariable(OpenstackPlatformModule::EXT_SWIFT_ENABLED, $this->getEnvironment(), false)); } } } $data['flags']['uiStorageTime'] = $this->user->getSetting(Scalr_Account_User::SETTING_UI_STORAGE_TIME); $data['flags']['uiStorage'] = $this->user->getVar(Scalr_Account_User::VAR_UI_STORAGE); $data['flags']['allowManageAnalytics'] = (bool) Scalr::isAllowedAnalyticsOnHostedScalrAccount($this->environment->clientId); $data['scope'] = $this->request->getScope(); if ($this->request->getScope() == 'environment') { $governance = new Scalr_Governance($this->getEnvironmentId()); $data['governance'] = $governance->getValues(true); } } if ($this->user) { $data['tags'] = Tag::getAll($this->user->getAccountId()); } $data['flags']['authMode'] = $this->getContainer()->config->get('scalr.auth_mode'); $data['flags']['recaptchaPublicKey'] = $this->getContainer()->config->get('scalr.ui.recaptcha.public_key'); $data['flags']['specialToken'] = Scalr_Session::getInstance()->getToken(); $data['flags']['hostedScalr'] = (bool) Scalr::isHostedScalr(); $data['flags']['analyticsEnabled'] = $this->getContainer()->analytics->enabled; $data['flags']['apiEnabled'] = (bool) \Scalr::config('scalr.system.api.enabled'); return $data; }
/** * {@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."); } }
/** * 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; }
public function getOsDetails() { $retval = new stdClass(); switch ($this->osFamily) { case "windows": $retval->family = "windows"; if (strpos($this->osName, '2008Server') === 0) { $generation = '2008'; } elseif (strpos($this->osName, '2012Server') === 0) { $generation = '2012'; } $retval->generation = $generation; $retval->version = $this->osVersion; $retval->name = "Windows {$generation}"; if (substr($this->osName, -2) == 'R2') { $retval->name .= " R2"; } break; case "ubuntu": $retval->family = $this->osFamily; $retval->generation = $this->osVersion; $retval->version = $this->osVersion; $retval->name = "Ubuntu {$retval->version} " . ucfirst($this->osName); break; case "centos": $retval->family = $this->osFamily; $retval->generation = (int) substr($this->osVersion, 0, 1); $retval->version = $this->osVersion; $retval->name = "CentOS {$retval->version} Final"; break; case "amazon": $retval->family = $this->osFamily; $retval->generation = $this->osVersion; $retval->version = $this->osVersion; $retval->name = "Amazon Linux {$retval->version}"; break; case "oel": $retval->family = $this->osFamily; $retval->generation = (int) substr($this->osVersion, 0, 1); $retval->version = $this->osVersion; $retval->name = "Oracle Enterprise Linux Server {$this->osVersion}"; if ($retval->generation == 5) { $retval->name .= " Tikanga"; } elseif ($retval->generation == 6) { $retval->name .= " Santiago"; } break; case "redhat": $retval->family = $this->osFamily; $retval->generation = (int) substr($this->osVersion, 0, 1); $retval->version = $this->osVersion; $retval->name = "Redhat {$this->osVersion}"; if ($retval->generation == 5) { $retval->name .= " Tikanga"; } elseif ($retval->generation == 6) { $retval->name .= " Santiago"; } break; case "scientific": $retval->family = $this->osFamily; $retval->generation = (int) substr($this->osVersion, 0, 1); $retval->version = $this->osVersion; $retval->name = "Scientific {$this->osVersion}"; if ($retval->generation == 5) { $retval->name .= " Boron"; } elseif ($retval->generation == 6) { $retval->name .= " Carbon"; } break; case "debian": $retval->family = $this->osFamily; $retval->generation = (int) substr($this->osVersion, 0, 1); $retval->version = $this->osVersion; $retval->name = "Debian {$this->osVersion}"; if ($retval->generation == 5) { $retval->name .= " Lenny"; } elseif ($retval->generation == 6) { $retval->name .= " Squeeze"; } elseif ($retval->generation == 7) { $retval->name .= " Wheezy"; } break; default: $retval->generation = ''; $retval->version = ''; $retval->name = $this->osName; } $osIds = Os::findIdsBy($retval->family, $retval->generation, $retval->version); if (count($osIds) > 0) { $retval->id = $osIds[0]; } else { $osIds = Os::findIdsBy($retval->family, $retval->generation, NULL); if (count($osIds) > 0) { $retval->id = $osIds[0]; } else { $retval->id = Os::UNKNOWN_OS; } } return $retval; }
/** * @return Os * @throws \Exception */ public function getOs() { if (!$this->_os) { $this->_os = Os::findOne([['id' => $this->osId]]); } return $this->_os; }
/** * @param string $osFamily * @param string $osVersion */ public function xGetRoleImagesAction($osFamily, $osVersion) { $this->restrictAccess('IMAGES', 'MANAGE'); $data = []; $osIds = Os::findIdsBy($osFamily, null, $osVersion); foreach (Image::find([['$or' => [['envId' => $this->getEnvironmentId(true)], ['envId' => NULL]]], ['osId' => ['$in' => $osIds]], ['status' => Image::STATUS_ACTIVE]]) as $image) { /* @var $image Image */ $data[] = ['platform' => $image->platform, 'cloudLocation' => $image->cloudLocation, 'id' => $image->id, 'architecture' => $image->architecture, 'source' => $image->source, 'createdByEmail' => $image->createdByEmail, 'os_family' => $image->getOs()->family, 'os_generation' => $image->getOs()->generation, 'os_version' => $image->getOs()->version, 'os_id' => $image->getOs()->id, 'os' => $image->getOs()->name]; } $this->response->data(['images' => $data]); }