isNameUsed() public static méthode

Check if given name is used on scalr, account or environment scopes
public static isNameUsed ( string $name, integer $accountId, integer $envId, integer $ignoreRoleId = null ) : boolean
$name string Role's name to check
$accountId integer Identifier of account
$envId integer Identifier of environment
$ignoreRoleId integer Role id to ignore
Résultat boolean Returns TRUE if a such name has been already used on scalr or account (or environment) scopes
Exemple #1
0
 /**
  * @param   string      $platform
  * @param   string      $cloudLocation
  * @param   string      $cloudServerId
  * @param   string      $name
  * @param   bool        $createImage
  * @throws  Exception
  */
 public function xInitiateImportAction($platform, $cloudLocation, $cloudServerId, $name, $createImage = false)
 {
     if (!Role::isValidName($name)) {
         throw new Exception(_("Name is incorrect"));
     }
     if (!$createImage) {
         $this->request->restrictAccess(Acl::RESOURCE_ROLES_ENVIRONMENT, Acl::PERM_ROLES_ENVIRONMENT_MANAGE);
     }
     if (!$createImage && Role::isNameUsed($name, $this->user->getAccountId(), $this->getEnvironmentId())) {
         throw new Exception('Selected role name is already used. Please select another one.');
     }
     $cryptoKey = Scalr::GenerateRandomKey(40);
     $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_ROLE_NAME => $name, SERVER_PROPERTIES::SZR_IMPORTING_OBJECT => $createImage ? BundleTask::BUNDLETASK_OBJECT_IMAGE : BundleTask::BUNDLETASK_OBJECT_ROLE, SERVER_PROPERTIES::SZR_KEY => $cryptoKey, SERVER_PROPERTIES::SZR_KEY_TYPE => SZR_KEY_TYPE::PERMANENT, SERVER_PROPERTIES::SZR_VESION => "0.14.0", SERVER_PROPERTIES::SZR_IMPORTING_VERSION => 2, SERVER_PROPERTIES::SZR_IMPORTING_STEP => 1, SERVER_PROPERTIES::LAUNCHED_BY_ID => $this->user->id, SERVER_PROPERTIES::LAUNCHED_BY_EMAIL => $this->user->getEmail()));
     $platformObj = PlatformFactory::NewPlatform($platform);
     $availZone = null;
     $osType = '';
     if ($platform == SERVER_PLATFORMS::EC2) {
         $client = $this->environment->aws($cloudLocation)->ec2;
         $r = $client->instance->describe($cloudServerId);
         $instance = $r->get(0)->instancesSet->get(0);
         $availZone = $instance->placement->availabilityZone;
         $osType = $instance->platform == 'windows' ? 'windows' : 'linux';
         $creInfo->SetProperties(array(EC2_SERVER_PROPERTIES::REGION => $cloudLocation, EC2_SERVER_PROPERTIES::INSTANCE_ID => $cloudServerId, EC2_SERVER_PROPERTIES::AMIID => $instance->imageId, EC2_SERVER_PROPERTIES::AVAIL_ZONE => $instance->placement->availabilityZone));
     } else {
         if ($platform == SERVER_PLATFORMS::GCE) {
             $gce = $platformObj->getClient($this->environment);
             $result = $gce->instances->get($this->environment->keychain(SERVER_PLATFORMS::GCE)->properties[CloudCredentialsProperty::GCE_PROJECT_ID], $cloudLocation, $cloudServerId);
             $creInfo->SetProperties(array(GCE_SERVER_PROPERTIES::SERVER_NAME => $cloudServerId, GCE_SERVER_PROPERTIES::CLOUD_LOCATION => $cloudLocation));
         } else {
             if ($platform == SERVER_PLATFORMS::AZURE) {
                 //$this->getEnvironment()->azure()->compute->virtualMachine->getInstanceViewInfo()
                 // $r->properties->osProfile->linuxConfiguration != NULL
             } else {
                 if (PlatformFactory::isOpenstack($platform)) {
                     $creInfo->SetProperties(array(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION => $cloudLocation, OPENSTACK_SERVER_PROPERTIES::SERVER_ID => $cloudServerId));
                 } else {
                     if (PlatformFactory::isCloudstack($platform)) {
                         $creInfo->SetProperties(array(CLOUDSTACK_SERVER_PROPERTIES::CLOUD_LOCATION => $cloudLocation, CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID => $cloudServerId));
                     }
                 }
             }
         }
     }
     $dbServer = DBServer::Create($creInfo, true);
     $dbServer->osType = $osType;
     $ips = $platformObj->GetServerIPAddresses($dbServer);
     $dbServer->localIp = $ips['localIp'];
     $dbServer->remoteIp = $ips['remoteIp'];
     $dbServer->cloudLocation = $cloudLocation;
     if ($platform == SERVER_PLATFORMS::GCE) {
         $dbServer->cloudLocationZone = $cloudLocation;
     } else {
         $dbServer->cloudLocationZone = $availZone;
     }
     $dbServer->Save();
     $this->response->data(array('command' => $this->getSzrCmd($dbServer), 'installCommand' => $this->getInstallCmd($dbServer), 'osType' => $dbServer->osType, 'serverId' => $dbServer->serverId));
 }
Exemple #2
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');
 }
Exemple #3
0
 public function ServerImageCreate($ServerID, $RoleName)
 {
     $this->restrictAccess(Acl::RESOURCE_IMAGES_ENVIRONMENT, Acl::PERM_IMAGES_ENVIRONMENT_MANAGE);
     $this->restrictAccess(Acl::RESOURCE_ROLES_ENVIRONMENT, Acl::PERM_ROLES_ENVIRONMENT_MANAGE);
     $DBServer = DBServer::LoadByID($ServerID);
     // Validate client and server
     if ($DBServer->envId != $this->Environment->id) {
         throw new Exception(sprintf("Server ID #%s not found", $ServerID));
     }
     $this->user->getPermissions()->validate($DBServer);
     //Check for already running bundle on selected instance
     $chk = $this->DB->GetOne("SELECT id FROM bundle_tasks WHERE server_id=? AND status NOT IN ('success', 'failed') LIMIT 1", array($ServerID));
     if ($chk) {
         throw new Exception(sprintf(_("Server '%s' is already synchonizing."), $ServerID));
     }
     if (!Role::isValidName($RoleName)) {
         throw new Exception(_("Role name is incorrect"));
     }
     if (Role::isNameUsed($RoleName, $this->user->getAccountId(), $this->Environment->id)) {
         throw new Exception("Specified role name is already used by another role");
     }
     if ($btId = BundleTask::getActiveTaskIdByName($RoleName, $this->user->getAccountId(), $this->Environment->id)) {
         throw new Exception(sprintf("Specified role name is already reserved for BundleTask with ID: %d.", $btId));
     }
     $ServerSnapshotCreateInfo = new ServerSnapshotCreateInfo($DBServer, $RoleName, SERVER_REPLACEMENT_TYPE::NO_REPLACE, BundleTask::BUNDLETASK_OBJECT_ROLE, 'Bundled via API');
     $BundleTask = BundleTask::Create($ServerSnapshotCreateInfo);
     $BundleTask->createdById = $this->user->id;
     $BundleTask->createdByEmail = $this->user->getEmail();
     $BundleTask->save();
     $response = $this->CreateInitialResponse();
     $response->BundleTaskID = $BundleTask->id;
     return $response;
 }
Exemple #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 (!Role::isValidName($entity->name)) {
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, "Invalid name of the Role");
     }
     $envId = $this->controller->getScope() === ScopeInterface::SCOPE_ENVIRONMENT ? $this->controller->getEnvironment()->id : null;
     if (Role::isNameUsed($entity->name, $this->controller->getUser()->accountId, $envId, $entity->id)) {
         throw new ApiErrorException(409, ErrorMessage::ERR_UNICITY_VIOLATION, 'Selected role name is already used. Please select another one.');
     }
     $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}' is not found.");
     }
     if (empty($entity->isScalarized)) {
         if (!empty($entity->behaviors)) {
             throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_STRUCTURE, 'builtinAutomation property requires Scalr agent to be set');
         }
     } else {
         if (empty($entity->behaviors)) {
             throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_STRUCTURE, "Missed property builtinAutomation");
         }
     }
 }