Beispiel #1
0
 /**
  * Save metric.
  *
  * @param  string $name
  * @param  string $retrieveMethod
  * @param  string $calcFunction
  * @param  int    $metricId       optional
  * @param  string $filePath       optional
  * @param  bool   $isInvert       optional
  * @throws Exception
  * @throws Scalr_Exception_Core
  * @throws Scalr_Exception_InsufficientPermissions
  * @throws \Scalr\Exception\ModelException
  */
 public function xSaveAction($name, $retrieveMethod, $calcFunction = null, $metricId = null, $filePath = null, $isInvert = false)
 {
     $this->request->restrictAccess(Acl::RESOURCE_GENERAL_CUSTOM_SCALING_METRICS, Acl::PERM_GENERAL_CUSTOM_SCALING_METRICS_MANAGE);
     $validator = new Validator();
     if ($metricId) {
         /* @var $metric Entity\ScalingMetric */
         $metric = Entity\ScalingMetric::findPk($metricId);
         if (!$metric) {
             throw new Scalr_UI_Exception_NotFound();
         }
         $this->user->getPermissions()->validate($metric);
     } else {
         $metric = new Entity\ScalingMetric();
         $metric->accountId = $this->user->getAccountId();
         $metric->envId = $this->getEnvironmentId();
         $metric->alias = 'custom';
         $metric->algorithm = Entity\ScalingMetric::ALGORITHM_SENSOR;
     }
     if (!preg_match('/^' . Entity\ScalingMetric::NAME_REGEXP . '$/', $name)) {
         $validator->addError('name', 'Metric name should be both alphanumeric and greater than 5 chars');
     }
     if ($retrieveMethod == Entity\ScalingMetric::RETRIEVE_METHOD_URL_REQUEST) {
         $validator->addErrorIf($validator->validateUrl($filePath) !== true, 'filePath', 'Invalid URL');
     } else {
         $validator->addErrorIf($validator->validateNotEmpty($calcFunction) !== true, 'calcFunction', 'Calculation function is required');
     }
     $criteria = [];
     $criteria[] = ['name' => $name];
     if ($metricId) {
         $criteria[] = ['id' => ['$ne' => $metricId]];
     }
     if (Entity\ScalingMetric::findOne($criteria)) {
         $validator->addError('name', 'Metric with the same name already exists');
     }
     if ($validator->isValid($this->response)) {
         $metric->name = $name;
         $metric->filePath = $filePath;
         $metric->retrieveMethod = $retrieveMethod;
         $metric->calcFunction = $calcFunction;
         $metric->isInvert = $isInvert;
         $metric->save();
         $this->response->success('Scaling metric has been successfully saved.');
         $this->response->data(['metric' => get_object_vars($metric)]);
     }
 }
Beispiel #2
0
 /**
  * Save metric.
  *
  * @param string $name
  * @param string $retrieveMethod
  * @param string $calcFunction
  * @param int    $metricId       optional
  * @param string $filePath       optional
  * @throws Exception
  * @throws Scalr_Exception_Core
  * @throws Scalr_Exception_InsufficientPermissions
  * @throws \Scalr\Exception\ModelException
  */
 public function xSaveAction($name, $retrieveMethod, $calcFunction, $metricId = null, $filePath = null)
 {
     $this->request->restrictAccess(Acl::RESOURCE_GENERAL_CUSTOM_SCALING_METRICS);
     $validator = new Validator();
     if ($metricId) {
         /* @var \Scalr\Model\Entity\ScalingMetric $metric */
         $metric = Entity\ScalingMetric::findPk($metricId);
         if (!$metric) {
             throw new Scalr_UI_Exception_NotFound();
         }
         $this->user->getPermissions()->validate($metric);
     } else {
         $metric = new Entity\ScalingMetric();
         $metric->accountId = $this->user->getAccountId();
         $metric->envId = $this->getEnvironmentId();
         $metric->alias = 'custom';
         $metric->algorithm = Entity\ScalingMetric::ALGORITHM_SENSOR;
     }
     if (!preg_match('/^[A-Za-z0-9]{5,}$/', $name)) {
         $validator->addError('name', 'Metric name should be alphanumeric and greater than 5 chars');
     }
     $criteria = [];
     $criteria[] = ['name' => $name];
     if ($metricId) {
         $criteria[] = ['id' => ['$ne' => $metricId]];
     }
     if (Entity\ScalingMetric::findOne($criteria)) {
         $validator->addError('name', 'Metric with the same name already exist');
     }
     if ($validator->isValid($this->response)) {
         $metric->name = $name;
         $metric->filePath = $filePath;
         $metric->retrieveMethod = $retrieveMethod;
         $metric->calcFunction = $calcFunction;
         $metric->save();
         $this->response->success('Scaling metric successfully saved');
         $this->response->data(['metric' => get_object_vars($metric)]);
     }
 }
Beispiel #3
0
 /**
  * @param string $id
  * @param string $status
  * @param string $name
  * @param string $family
  * @param string $generation
  * @param string $version
  * @throws Exception
  */
 public function xSaveAction($id, $status, $name, $family, $generation, $version = '')
 {
     $os = Os::findPk($id);
     if (!$os) {
         $os = new Os();
         $os->isSystem = 0;
         $os->id = $id;
     }
     $validator = new Validator();
     $validator->validate($id, 'id', Validator::NOEMPTY);
     $validator->validate($name, 'name', Validator::NOEMPTY);
     $validator->validate($family, 'family', Validator::NOEMPTY);
     $validator->validate($generation, 'generation', Validator::NOEMPTY);
     //check by name, family, generation,version
     $criteria = [];
     $criteria[] = ['name' => $name];
     $criteria[] = ['family' => $family];
     $criteria[] = ['generation' => $generation];
     $criteria[] = ['version' => $version];
     if ($os->id) {
         $criteria[] = ['id' => ['$ne' => $os->id]];
     }
     if (Os::findOne($criteria)) {
         $validator->addError('name', 'Operating system with such name, family, generation and version already exists');
     }
     if (!$validator->isValid($this->response)) {
         return;
     }
     $os->status = $status;
     if ($os->isSystem != 1) {
         $os->name = $name;
         $os->family = $family;
         $os->generation = $generation;
         $os->version = $version;
     }
     $os->save();
     $result = get_object_vars($os);
     $result['used'] = $os->getUsed();
     $this->response->data(['os' => $os]);
     $this->response->success('Operating system successfully saved');
 }
Beispiel #4
0
 /**
  * @param int $id
  * @param string $url
  * @param string $username
  * @param string $authKey
  * @param string $vUsername
  * @param string $vAuthKey
  * @throws Exception
  */
 public function xSaveAction($id, $url, $username, $authKey, $vUsername, $vAuthKey)
 {
     if (!$this->canManageServers()) {
         throw new Scalr_Exception_InsufficientPermissions();
     }
     if (!$id) {
         $server = new ChefServer();
         $server->setScope($this->request->getScope(), $this->user->getAccountId(), $this->getEnvironmentId(true));
     } else {
         $server = ChefServer::findPk($id);
         if (!$this->canEditServer($server)) {
             throw new Scalr_Exception_Core('Insufficient permissions to edit chef server at this scope');
         }
     }
     $validator = new Validator();
     $validator->validate($url, 'url', Validator::NOEMPTY);
     //check url unique within current scope
     $criteria = [];
     $criteria[] = ['url' => $url];
     if ($server->id) {
         $criteria[] = ['id' => ['$ne' => $server->id]];
     }
     switch ($this->request->getScope()) {
         case ChefServer::SCOPE_ENVIRONMENT:
             $criteria[] = ['level' => ChefServer::LEVEL_ENVIRONMENT];
             $criteria[] = ['envId' => $server->envId];
             $criteria[] = ['accountId' => $server->accountId];
             break;
         case ChefServer::SCOPE_ACCOUNT:
             $criteria[] = ['level' => ChefServer::LEVEL_ACCOUNT];
             $criteria[] = ['envId' => null];
             $criteria[] = ['accountId' => $server->accountId];
             break;
         case ChefServer::SCOPE_SCALR:
             $criteria[] = ['level' => ChefServer::LEVEL_SCALR];
             $criteria[] = ['envId' => null];
             $criteria[] = ['accountId' => null];
             break;
     }
     if (ChefServer::findOne($criteria)) {
         $validator->addError('url', 'Url must be unique within current scope');
     }
     if (!$validator->isValid($this->response)) {
         return;
     }
     $authKey = str_replace("\r\n", "\n", $authKey);
     $vAuthKey = str_replace("\r\n", "\n", $vAuthKey);
     $server->url = $url;
     $server->username = $username;
     $server->vUsername = $vUsername;
     $server->authKey = $this->getCrypto()->encrypt($authKey);
     $server->vAuthKey = $this->getCrypto()->encrypt($vAuthKey);
     $chef = Scalr_Service_Chef_Client::getChef($server->url, $server->username, $authKey);
     $response = $chef->listCookbooks();
     $chef2 = Scalr_Service_Chef_Client::getChef($server->url, $server->vUsername, $vAuthKey);
     $clientName = 'scalr-temp-client-' . rand(10000, 99999);
     $response = $chef2->createClient($clientName);
     $response2 = $chef->removeClient($clientName);
     $server->save();
     $this->response->data(array('server' => $this->getServerData($server)));
     $this->response->success('Chef server successfully saved');
 }
Beispiel #5
0
 /**
  * @param string $url
  * @param string $endpointId
  * @throws Exception
  */
 public function xSaveAction($url, $endpointId = null)
 {
     if (!$endpointId) {
         $endpoint = new WebhookEndpoint();
         $endpoint->setScope($this->request->getScope(), $this->user->getAccountId(), $this->getEnvironmentId(true));
         $endpoint->securityKey = Scalr::GenerateRandomKey(64);
     } else {
         $endpoint = WebhookEndpoint::findPk($endpointId);
         if (!$this->canEditEndpoint($endpoint)) {
             throw new Scalr_Exception_Core('Insufficient permissions to edit endpoint at this scope');
         }
     }
     $validator = new Validator();
     $validator->validate($url, 'url', Validator::URL);
     //check url unique within current level
     $criteria = [];
     $criteria[] = ['url' => $url];
     if ($endpoint->endpointId) {
         $criteria[] = ['endpointId' => ['$ne' => $endpoint->endpointId]];
     }
     switch ($this->request->getScope()) {
         case WebhookEndpoint::SCOPE_ENVIRONMENT:
             $criteria[] = ['level' => WebhookEndpoint::LEVEL_ENVIRONMENT];
             $criteria[] = ['envId' => $endpoint->envId];
             $criteria[] = ['accountId' => $endpoint->accountId];
             break;
         case WebhookEndpoint::SCOPE_ACCOUNT:
             $criteria[] = ['level' => WebhookEndpoint::LEVEL_ACCOUNT];
             $criteria[] = ['envId' => null];
             $criteria[] = ['accountId' => $endpoint->accountId];
             break;
         case WebhookEndpoint::SCOPE_SCALR:
             $criteria[] = ['level' => WebhookEndpoint::LEVEL_SCALR];
             $criteria[] = ['envId' => null];
             $criteria[] = ['accountId' => null];
             break;
     }
     if (WebhookEndpoint::findOne($criteria)) {
         $validator->addError('url', 'Endpoint url must be unique within current scope');
     }
     if (!$validator->isValid($this->response)) {
         return;
     }
     if ($endpoint->url != $url) {
         $endpoint->isValid = false;
         $endpoint->url = $url;
     }
     ////temporarily disable url validation per Igor`s request(see also webhooks/endpoints/view.js)
     $endpoint->isValid = true;
     $endpoint->save();
     $this->response->success('Endpoint successfully saved');
     $this->response->data(array('endpoint' => array('endpointId' => $endpoint->endpointId, 'url' => $endpoint->url, 'isValid' => $endpoint->isValid, 'validationToken' => $endpoint->validationToken, 'securityKey' => $endpoint->securityKey, 'scope' => $endpoint->getScope())));
 }
Beispiel #6
0
 /**
  * xSaveAction
  *
  * @param string $ccId
  * @param string $projectId
  * @param string $name
  * @param string $description
  * @param string $billingCode
  * @param string $leadEmail
  * @param int $shared
  * @param int $accountId optional
  * @param bool $checkAccountAccessToCc optional
  * @param bool $grantAccountAccessToCc optional
  * @throws Scalr_Exception_InsufficientPermissions
  */
 public function xSaveAction($ccId, $projectId, $name, $description, $billingCode, $leadEmail, $shared, $accountId = null, $checkAccountAccessToCc = true, $grantAccountAccessToCc = false)
 {
     $validator = new Validator();
     $validator->validate($name, 'name', Validator::NOEMPTY);
     if ($projectId) {
         $project = $this->getContainer()->analytics->projects->get($projectId);
         if (!$project) {
             throw new Scalr_UI_Exception_NotFound();
         }
     } else {
         $project = new ProjectEntity();
         $project->createdById = $this->user->id;
         $project->createdByEmail = $this->user->getEmail();
         $cc = $this->getContainer()->analytics->ccs->get($ccId);
         if (!$cc) {
             $validator->addError('ccId', 'Cost center ID should be set');
         }
         $project->ccId = $ccId;
     }
     if ($shared == ProjectEntity::SHARED_WITHIN_ACCOUNT) {
         $project->shared = ProjectEntity::SHARED_WITHIN_ACCOUNT;
         $project->accountId = $accountId;
     } elseif ($shared == ProjectEntity::SHARED_WITHIN_CC) {
         $project->shared = ProjectEntity::SHARED_WITHIN_CC;
         $project->accountId = null;
     } else {
         throw new Scalr_UI_Exception_NotFound();
     }
     if (!$validator->isValid($this->response)) {
         return;
     }
     if ($project->shared == ProjectEntity::SHARED_WITHIN_ACCOUNT) {
         if (!AccountCostCenterEntity::findOne([['accountId' => $project->accountId], ['ccId' => $ccId]])) {
             if ($checkAccountAccessToCc) {
                 $this->response->data(['ccIsNotAllowedToAccount' => true]);
                 $this->response->failure();
                 return;
             } elseif ($grantAccountAccessToCc) {
                 //give account access to cc
                 $accountCcEntity = new AccountCostCenterEntity($project->accountId, $ccId);
                 $accountCcEntity->save();
             }
         }
     }
     $project->name = $name;
     $this->db->BeginTrans();
     try {
         $project->save();
         //NOTE please take into account the presence of the usage->createHostedScalrAccountCostCenter() method
         $project->saveProperty(ProjectPropertyEntity::NAME_BILLING_CODE, $billingCode);
         $project->saveProperty(ProjectPropertyEntity::NAME_DESCRIPTION, $description);
         $project->saveProperty(ProjectPropertyEntity::NAME_LEAD_EMAIL, $leadEmail);
         $this->db->CommitTrans();
     } catch (Exception $e) {
         $this->db->RollbackTrans();
         throw $e;
     }
     $this->response->data(['project' => $this->getProjectData($project)]);
     $this->response->success('Project has been successfully saved');
 }
Beispiel #7
0
 /**
  * @param string $cloudLocation
  * @param string $availabilityZone
  * @param int    $size
  * @param string $snapshotId
  * @param bool   $encrypted
  * @param string $kmsKeyId
  * @param string $type
  * @param int    $iops
  * @param string $serverId
  * @param bool   $mount
  * @param string $mountPoint
  */
 public function xCreateAction($cloudLocation, $availabilityZone, $size, $snapshotId = null, $encrypted = false, $kmsKeyId = null, $type = 'standard', $iops = null, $serverId = null, $mount = false, $mountPoint = null)
 {
     $this->request->restrictAccess(Acl::RESOURCE_AWS_VOLUMES, Acl::PERM_AWS_VOLUMES_MANAGE);
     $aws = $this->getEnvironment()->aws($cloudLocation);
     $decision = $this->getFilteringDecision();
     $validator = new Validator();
     if (empty($serverId) && $decision->mode == CloudResourceScopeMode::MODE_MANAGED_FARMS) {
         $validator->addError('serverId', 'Your permissions do not allow you to create EBS volume without attaching it to the Server.');
     }
     if ($encrypted && $kmsKeyId) {
         $kmsKey = $aws->kms->key->describe($kmsKeyId);
         if (!$kmsKey->enabled) {
             $validator->addError('kmsKeyId', 'This KMS Key is disabled, please choose another one.');
         }
     }
     if (!$validator->isValid($this->response)) {
         return;
     }
     $req = new CreateVolumeRequestData($availabilityZone, $size);
     if ($snapshotId) {
         $req->snapshotId = $snapshotId;
     }
     if ($encrypted) {
         $req->encrypted = true;
         if ($kmsKeyId) {
             $req->kmsKeyId = $kmsKeyId;
         }
     }
     if (in_array($type, [CreateVolumeRequestData::VOLUME_TYPE_STANDARD, CreateVolumeRequestData::VOLUME_TYPE_GP2, CreateVolumeRequestData::VOLUME_TYPE_IO1, CreateVolumeRequestData::VOLUME_TYPE_ST1, CreateVolumeRequestData::VOLUME_TYPE_SC1])) {
         $req->volumeType = $type;
         if ($type == CreateVolumeRequestData::VOLUME_TYPE_IO1) {
             $req->iops = $iops ? $iops : 100;
         }
     }
     $info = $aws->ec2->volume->create($req);
     if ($serverId) {
         //TODO You can attach only volume in available state
         $attempts = 6;
         while ($info->status != 'available' && $attempts--) {
             sleep(2);
             $info = $aws->ec2->volume->describe($info->volumeId)->get(0);
         }
         $this->attachVolumeToServer($info);
     } else {
         //Creates tags for the AWS resource
         $aws->ec2->tag->create($info->volumeId, $this->getEnvironment()->getAwsTags());
     }
     $this->response->success('EBS volume has been successfully created');
     $this->response->data(array('data' => array('volumeId' => $info->volumeId)));
 }
Beispiel #8
0
 /**
  * @param int $id
  * @param string $name
  * @param string $description
  * @param int $isSync
  * @param bool $allowScriptParameters
  * @param int $envId optional
  * @param int $timeout optional
  * @param int $version
  * @param RawData $content
  * @param string $tags
  * @param string $uploadType optional
  * @param string $uploadUrl optional
  * @param FileUploadData $uploadFile optional
  * @param bool $checkScriptParameters optional
  * @throws Scalr_UI_Exception_NotFound
  * @throws Scalr_Exception_InsufficientPermissions
  * @throws Exception
  */
 public function xSaveAction($id, $name, $description, $isSync = 0, $allowScriptParameters = false, $envId = NULL, $timeout = NULL, $version, RawData $content, $tags, $uploadType = NULL, $uploadUrl = NULL, FileUploadData $uploadFile = NULL, $checkScriptParameters = false)
 {
     $this->request->restrictAccess('SCRIPTS', 'MANAGE');
     $validator = new Validator();
     $validator->validate($name, 'name', Validator::NOEMPTY);
     if ($uploadType && $uploadType == 'URL') {
         $validator->validate($uploadUrl, 'uploadUrl', Validator::URL);
         if (!$validator->isValid($this->response)) {
             return;
         }
     }
     if ($uploadType) {
         $content = false;
         if ($uploadType == 'URL') {
             $content = @file_get_contents($uploadUrl);
             $validator->validate($content, 'uploadUrl', Validator::NOEMPTY, [], 'Invalid source');
         } else {
             if ($uploadType == 'File') {
                 $content = $uploadFile;
                 $validator->validate($content, 'uploadFile', Validator::NOEMPTY, [], 'Invalid source');
             } else {
                 $validator->addError('uploadType', 'Invalid source for script');
             }
         }
     }
     $envId = $this->getEnvironmentId(true);
     $content = str_replace("\r\n", "\n", $content);
     $tagsResult = [];
     foreach (explode(',', $tags) as $t) {
         $t = trim($t);
         if ($t) {
             if (!preg_match('/^[a-zA-Z0-9-]{3,10}$/', $t)) {
                 $validator->addError('tags', sprintf('Invalid name for tag: %s', $t));
             }
             $tagsResult[] = $t;
         }
     }
     $tags = $tagsResult;
     $criteria = [];
     $criteria[] = ['name' => $name];
     if ($id) {
         $criteria[] = ['id' => ['$ne' => $id]];
     }
     switch ($this->request->getScope()) {
         case Script::SCOPE_ENVIRONMENT:
             $criteria[] = ['envId' => $envId];
             $criteria[] = ['accountId' => $this->user->getAccountId()];
             break;
         case Script::SCOPE_ACCOUNT:
             $criteria[] = ['envId' => null];
             $criteria[] = ['accountId' => $this->user->getAccountId()];
             break;
         case Script::SCOPE_SCALR:
             $criteria[] = ['envId' => null];
             $criteria[] = ['accountId' => null];
             break;
     }
     if (Script::findOne($criteria)) {
         $validator->addError('name', 'Script name must be unique within current scope');
     }
     if (!$validator->isValid($this->response)) {
         return;
     }
     /* @var $script Script */
     if ($id) {
         $script = Script::findPk($id);
         if (!$script) {
             throw new Scalr_UI_Exception_NotFound();
         }
         $script->checkPermission($this->user, $envId);
         if (!$script->accountId && $this->user->getType() != Scalr_Account_User::TYPE_SCALR_ADMIN) {
             throw new Scalr_Exception_InsufficientPermissions();
         }
         if (!$script->envId && $this->request->getScope() == ScopeInterface::SCOPE_ENVIRONMENT) {
             throw new Scalr_Exception_InsufficientPermissions();
         }
     } else {
         $script = new Script();
         $script->accountId = $this->user->getAccountId() ?: NULL;
         $script->createdById = $this->user->getId();
         $script->createdByEmail = $this->user->getEmail();
         $script->envId = $envId;
         $version = 1;
     }
     //check variables in script content
     if (!$id && $checkScriptParameters && !$allowScriptParameters) {
         $scriptHasParameters = Script::hasVariables($content);
         if (!$scriptHasParameters) {
             /* @var $scriptVersion ScriptVersion */
             foreach ($script->getVersions() as $scriptVersion) {
                 if ($scriptVersion->version != $version) {
                     $scriptHasParameters = Script::hasVariables($scriptVersion->content);
                     if ($scriptHasParameters) {
                         break;
                     }
                 }
             }
         }
         if ($scriptHasParameters) {
             $this->response->data(['showScriptParametersConfirmation' => true]);
             $this->response->failure();
             return;
         }
     }
     $script->name = $name;
     $script->description = $description;
     $script->timeout = $timeout ? $timeout : NULL;
     $script->isSync = $isSync == 1 ? 1 : 0;
     $script->allowScriptParameters = $allowScriptParameters ? 1 : 0;
     $script->os = !strncmp($content, '#!cmd', strlen('#!cmd')) || !strncmp($content, '#!powershell', strlen('#!powershell')) ? Script::OS_WINDOWS : Script::OS_LINUX;
     $script->save();
     $scriptVersion = NULL;
     if ($version) {
         $scriptVersion = $script->getVersion($version);
     }
     if (!$scriptVersion && $script->getLatestVersion()->content !== $content) {
         $scriptVersion = new ScriptVersion();
         $scriptVersion->scriptId = $script->id;
         $scriptVersion->version = $script->getLatestVersion()->version + 1;
     }
     if ($scriptVersion) {
         $scriptVersion->changedById = $this->user->getId();
         $scriptVersion->changedByEmail = $this->user->getEmail();
         $scriptVersion->content = $content;
         $scriptVersion->save();
     }
     if ($this->user->getAccountId()) {
         Tag::setTags($tags, $this->user->getAccountId(), Tag::RESOURCE_SCRIPT, $script->id);
     }
     $this->response->success('Script successfully saved');
     $this->response->data(['script' => array_merge($this->getScript($script), $this->getScriptInfo($script))]);
 }
Beispiel #9
0
 /**
  * @param $password
  * @param $cpassword
  * @param $securityIpWhitelist
  */
 public function xSecuritySaveAction($password, $cpassword, $securityIpWhitelist)
 {
     $validator = new Validator();
     $validator->validate($password, 'password', Validator::NOEMPTY);
     $validator->validate($cpassword, 'cpassword', Validator::NOEMPTY);
     $validator->addErrorIf($password && $cpassword && $password != $cpassword, ['password', 'cpassword'], 'Two passwords are not equal');
     $subnets = array();
     $securityIpWhitelist = trim($securityIpWhitelist);
     if ($securityIpWhitelist) {
         $whitelist = explode(',', $securityIpWhitelist);
         foreach ($whitelist as $mask) {
             $sub = Scalr_Util_Network::convertMaskToSubnet($mask);
             if ($sub) {
                 $subnets[] = $sub;
             } else {
                 $validator->addError('securityIpWhitelist', sprintf('Not valid mask: %s', $mask));
             }
         }
     }
     if (count($subnets) && !Scalr_Util_Network::isIpInSubnets($this->request->getRemoteAddr(), $subnets)) {
         $validator->addError('securityIpWhitelist', 'New IP access whitelist doesn\'t correspond your current IP address');
     }
     if ($validator->isValid($this->response)) {
         $updateSession = false;
         if ($password != '******') {
             $this->user->updatePassword($password);
             $updateSession = true;
         }
         $this->user->setVar(Scalr_Account_User::VAR_SECURITY_IP_WHITELIST, count($subnets) ? serialize($subnets) : '');
         $this->user->save();
         if ($updateSession) {
             Scalr_Session::create($this->user->getId());
         }
         $this->response->success('Security settings successfully updated');
     }
 }
Beispiel #10
0
 /**
  * @param RawData $password
  * @param RawData $cpassword
  * @param $securityIpWhitelist
  * @param RawData $currentPassword optional
  */
 public function xSecuritySaveAction(RawData $password, RawData $cpassword, $securityIpWhitelist, RawData $currentPassword = null)
 {
     $validator = new Validator();
     if ($password != '******') {
         $validator->addErrorIf(!$this->user->checkPassword($currentPassword), ['currentPassword'], 'Invalid password');
     }
     $validator->validate($password, 'password', Validator::NOEMPTY);
     $validator->validate($cpassword, 'cpassword', Validator::NOEMPTY);
     $validator->addErrorIf($password && $cpassword && $password != $cpassword, ['password', 'cpassword'], 'Two passwords are not equal');
     $subnets = array();
     $securityIpWhitelist = trim($securityIpWhitelist);
     if ($securityIpWhitelist) {
         $whitelist = explode(',', $securityIpWhitelist);
         foreach ($whitelist as $mask) {
             $sub = Scalr_Util_Network::convertMaskToSubnet($mask);
             if ($sub) {
                 $subnets[] = $sub;
             } else {
                 $validator->addError('securityIpWhitelist', sprintf('Not valid mask: %s', $mask));
             }
         }
     }
     if (count($subnets) && !Scalr_Util_Network::isIpInSubnets($this->request->getRemoteAddr(), $subnets)) {
         $validator->addError('securityIpWhitelist', 'New IP access whitelist doesn\'t correspond your current IP address');
     }
     if ($validator->isValid($this->response)) {
         $updateSession = false;
         if ($password != '******') {
             $this->user->updatePassword($password);
             $updateSession = true;
             // Send notification E-mail
             $this->getContainer()->mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/password_change_notification.eml', array('{{fullname}}' => $this->user->fullname ? $this->user->fullname : $this->user->getEmail()), $this->user->getEmail(), $this->user->fullname);
         }
         $this->user->setVar(Scalr_Account_User::VAR_SECURITY_IP_WHITELIST, count($subnets) ? serialize($subnets) : '');
         $this->user->save();
         if ($updateSession) {
             Scalr_Session::create($this->user->getId());
             $this->response->data(['specialToken' => Scalr_Session::getInstance()->getToken()]);
         }
         $this->response->success('Security settings successfully updated');
     }
 }
Beispiel #11
0
 /**
  * @param   string  $serverId
  * @param   string  $name
  * @param   string  $description
  * @param   bool    $createRole
  * @param   string  $scope
  * @param   string  $replaceRole
  * @param   bool    $replaceImage
  * @param   int     $rootVolumeSize
  * @param   string  $rootVolumeType
  * @param   int     $rootVolumeIops
  * @throws  Exception
  */
 public function xServerCreateSnapshotAction($serverId, $name = '', $description = '', $createRole = false, $scope = '', $replaceRole = '', $replaceImage = false, $rootVolumeSize = 0, $rootVolumeType = '', $rootVolumeIops = 0)
 {
     $this->request->restrictAccess(Acl::RESOURCE_IMAGES_ENVIRONMENT, Acl::PERM_IMAGES_ENVIRONMENT_MANAGE);
     $server = $this->getServerEntity($serverId);
     $this->request->checkPermissions($server, true);
     $farm = $server->getFarm();
     $role = $server->getFarmRole()->getRole();
     //Check for already running bundle on selected instance
     if ($this->db->GetOne("SELECT id FROM bundle_tasks WHERE server_id=? AND status NOT IN ('success', 'failed') LIMIT 1", array($server->serverId))) {
         throw new Exception(sprintf(_("Server '%s' is already synchonizing."), $server->serverId));
     }
     $validator = new Validator();
     $validator->addErrorIf(!Entity\Role::isValidName($name), 'name', "Role name is incorrect");
     $validator->addErrorIf(!in_array($replaceRole, ['farm', 'all', '']), 'replaceRole', 'Invalid value');
     $object = $createRole ? BundleTask::BUNDLETASK_OBJECT_ROLE : BundleTask::BUNDLETASK_OBJECT_IMAGE;
     $replaceType = SERVER_REPLACEMENT_TYPE::NO_REPLACE;
     $createScope = ScopeInterface::SCOPE_ENVIRONMENT;
     if ($createRole) {
         $this->request->restrictAccess(Acl::RESOURCE_ROLES_ENVIRONMENT, Acl::PERM_ROLES_ENVIRONMENT_MANAGE);
         if ($replaceRole == 'farm') {
             if ($farm->hasAccessPermissions($this->getUser(), $this->getEnvironment(), Acl::PERM_FARMS_UPDATE)) {
                 $replaceType = SERVER_REPLACEMENT_TYPE::REPLACE_FARM;
             } else {
                 $validator->addError('replaceRole', "You don't have permissions to update farm");
             }
         } else {
             if ($replaceRole == 'all') {
                 if ($this->request->isAllowed([Acl::RESOURCE_FARMS, Acl::RESOURCE_TEAM_FARMS, Acl::RESOURCE_OWN_FARMS], Acl::PERM_FARMS_UPDATE)) {
                     $replaceType = SERVER_REPLACEMENT_TYPE::REPLACE_ALL;
                 } else {
                     $validator->addError('replaceRole', "You don't have permissions to update farms");
                 }
             }
         }
         /* @var $existRole Entity\Role */
         $existRole = Entity\Role::findOne([['name' => $name], ['$or' => [['accountId' => null], ['$and' => [['accountId' => $this->getUser()->accountId], ['$or' => [['envId' => null], ['envId' => $this->getEnvironment()->id]]]]]]]]);
         if ($existRole) {
             if (empty($existRole->accountId)) {
                 $validator->addError('name', _("Selected role name is reserved and cannot be used for custom role"));
             } else {
                 if ($replaceType != SERVER_REPLACEMENT_TYPE::REPLACE_ALL) {
                     $validator->addError('name', _("Specified role name is already used by another role. You can use this role name only if you will replace old one on ALL your farms."));
                 } else {
                     if ($replaceType == SERVER_REPLACEMENT_TYPE::REPLACE_ALL && $existRole->id != $role->id) {
                         $validator->addError('name', _("Specified role name is already in use. You cannot replace a Role different from the one you are currently snapshotting."));
                     }
                 }
             }
         }
         if ($btId = BundleTask::getActiveTaskIdByName($name, $this->getUser()->accountId, $this->getEnvironment()->id)) {
             $validator->addError('name', sprintf("Specified role name is already reserved for BundleTask with ID: %d.", $btId));
         }
         if ($replaceType != SERVER_REPLACEMENT_TYPE::NO_REPLACE) {
             $chk = BundleTask::getActiveTaskIdByRoleId($role->id, $this->getEnvironment()->id, BundleTask::BUNDLETASK_OBJECT_ROLE);
             $validator->addErrorIf($chk, 'replaceRole', sprintf("Role is already synchronizing in BundleTask: %d.", $chk));
         }
     } else {
         $sc = $role->getScope();
         if ($replaceImage) {
             if ($sc == ScopeInterface::SCOPE_ENVIRONMENT && $this->request->isAllowed(Acl::RESOURCE_ROLES_ENVIRONMENT, Acl::PERM_ROLES_ENVIRONMENT_MANAGE) || $sc == ScopeInterface::SCOPE_ACCOUNT && $this->request->isAllowed(Acl::RESOURCE_ROLES_ACCOUNT, Acl::PERM_ROLES_ACCOUNT_MANAGE)) {
                 $replaceType = SERVER_REPLACEMENT_TYPE::REPLACE_ALL;
                 $chk = BundleTask::getActiveTaskIdByRoleId($role->id, $this->getEnvironment()->id, BundleTask::BUNDLETASK_OBJECT_IMAGE);
                 $validator->addErrorIf($chk, 'replaceImage', sprintf("Role is already synchronizing in BundleTask: %d.", $chk));
             } else {
                 $validator->addError('replaceImage', "You don't have permissions to replace image in role");
             }
         }
     }
     if ($scope && ($createRole || $scope != $createScope)) {
         if ($createRole) {
             $c = $scope == ScopeInterface::SCOPE_ENVIRONMENT && $this->request->isAllowed(Acl::RESOURCE_ROLES_ENVIRONMENT, Acl::PERM_ROLES_ENVIRONMENT_MANAGE) || $scope == ScopeInterface::SCOPE_ACCOUNT && $this->request->isAllowed(Acl::RESOURCE_ROLES_ACCOUNT, Acl::PERM_ROLES_ACCOUNT_MANAGE);
             $validator->addErrorIf(!$c, 'scope', sprintf("You don't have permissions to create role in scope %s", $scope));
         }
         $c = $scope == ScopeInterface::SCOPE_ENVIRONMENT && $this->request->isAllowed(Acl::RESOURCE_IMAGES_ENVIRONMENT, Acl::PERM_IMAGES_ENVIRONMENT_MANAGE) || $scope == ScopeInterface::SCOPE_ACCOUNT && $this->request->isAllowed(Acl::RESOURCE_IMAGES_ACCOUNT, Acl::PERM_IMAGES_ACCOUNT_MANAGE);
         $validator->addErrorIf(!$c, 'scope', sprintf("You don't have permissions to create image in scope %s", $scope));
         $createScope = $scope;
     }
     $image = $role->getImage($server->platform, $server->cloudLocation)->getImage();
     $rootBlockDevice = [];
     if ($server->platform == SERVER_PLATFORMS::EC2 && ($server->isVersionSupported('0.7') && $server->os == 'linux' || $image->isEc2HvmImage())) {
         if ($rootVolumeSize > 0) {
             $rootBlockDevice['size'] = $rootVolumeSize;
         }
         if (in_array($rootVolumeType, [CreateVolumeRequestData::VOLUME_TYPE_STANDARD, CreateVolumeRequestData::VOLUME_TYPE_GP2, CreateVolumeRequestData::VOLUME_TYPE_IO1, CreateVolumeRequestData::VOLUME_TYPE_SC1, CreateVolumeRequestData::VOLUME_TYPE_ST1])) {
             $rootBlockDevice['volume_type'] = $rootVolumeType;
             if ($rootVolumeType == CreateVolumeRequestData::VOLUME_TYPE_IO1 && $rootVolumeIops > 0) {
                 $rootBlockDevice['iops'] = $rootVolumeIops;
             }
         }
     }
     if (!$validator->isValid($this->response)) {
         return;
     }
     $ServerSnapshotCreateInfo = new ServerSnapshotCreateInfo(DBServer::LoadByID($server->serverId), $name, $replaceType, $object, $description, $rootBlockDevice);
     $BundleTask = BundleTask::Create($ServerSnapshotCreateInfo);
     $BundleTask->createdById = $this->user->id;
     $BundleTask->createdByEmail = $this->user->getEmail();
     $BundleTask->osId = $role->osId;
     $BundleTask->objectScope = $createScope;
     if ($role->getOs()->family == 'windows') {
         $BundleTask->osFamily = $role->getOs()->family;
         $BundleTask->osVersion = $role->getOs()->generation;
         $BundleTask->osName = '';
     } else {
         $BundleTask->osFamily = $role->getOs()->family;
         $BundleTask->osVersion = $role->getOs()->version;
         $BundleTask->osName = $role->getOs()->name;
     }
     if (in_array($role->getOs()->family, array('redhat', 'oel', 'scientific')) && $server->platform == SERVER_PLATFORMS::EC2) {
         $BundleTask->bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
     }
     $BundleTask->save();
     $this->response->data(['bundleTaskId' => $BundleTask->id]);
     $this->response->success("Bundle task successfully created.");
 }
Beispiel #12
0
 /**
  * @param int $id
  * @param string $name
  * @param string $description
  * @param int $isSync
  * @param int $envId optional
  * @param int $timeout optional
  * @param int $version
  * @param RawData $content
  * @param string $tags
  * @param string $uploadType optional
  * @param string $uploadUrl optional
  * @param FileUploadData $uploadFile optional
  * @throws Scalr_UI_Exception_NotFound
  * @throws Scalr_Exception_InsufficientPermissions
  * @throws Exception
  */
 public function xSaveAction($id, $name, $description, $isSync = 0, $envId = 2, $timeout = NULL, $version, RawData $content, $tags, $uploadType = NULL, $uploadUrl = NULL, FileUploadData $uploadFile = NULL)
 {
     $this->request->restrictAccess(Acl::RESOURCE_ADMINISTRATION_SCRIPTS, Acl::PERM_ADMINISTRATION_SCRIPTS_MANAGE);
     $validator = new Validator();
     $validator->validate($name, 'name', Validator::NOEMPTY);
     if ($uploadType) {
         $content = false;
         if ($uploadType == 'URL') {
             $content = @file_get_contents($uploadUrl);
             $validator->validate($content, 'uploadUrl', Validator::NOEMPTY, [], 'Invalid source');
         } else {
             if ($uploadType == 'File') {
                 $content = $uploadFile;
                 $validator->validate($content, 'uploadFile', Validator::NOEMPTY, [], 'Invalid source');
             } else {
                 $validator->addError('uploadType', 'Invalid source for script');
             }
         }
     }
     $content = str_replace("\r\n", "\n", $content);
     $tagsResult = [];
     foreach (explode(',', $tags) as $t) {
         $t = trim($t);
         if ($t) {
             if (!preg_match('/^[a-zA-Z0-9-]{3,10}$/', $t)) {
                 $validator->addError('tags', sprintf('Invalid name for tag: %s', $t));
             }
             $tagsResult[] = $t;
         }
     }
     $tags = $tagsResult;
     if (!$validator->isValid($this->response)) {
         return;
     }
     /* @var Script $script */
     if ($id) {
         $script = Script::findPk($id);
         if (!$script) {
             throw new Scalr_UI_Exception_NotFound();
         }
         $script->checkPermission($this->user, $this->getEnvironmentId(true));
         if (!$script->accountId && $this->user->getType() != Scalr_Account_User::TYPE_SCALR_ADMIN) {
             throw new Scalr_Exception_InsufficientPermissions();
         }
     } else {
         $script = new Script();
         $script->accountId = $this->user->getAccountId() ? $this->user->getAccountId() : NULL;
         $script->createdById = $this->user->getId();
         $script->createdByEmail = $this->user->getEmail();
         $version = 1;
     }
     if ($this->user->isScalrAdmin()) {
         $envId = NULL;
     } else {
         if (!in_array($envId, array_map(function ($e) {
             return $e['id'];
         }, $this->user->getEnvironments()))) {
             $envId = NULL;
         }
     }
     $script->name = $name;
     $script->description = $description;
     $script->timeout = $timeout ? $timeout : NULL;
     $script->isSync = $isSync == 1 ? 1 : 0;
     $script->envId = $envId;
     $script->os = !strncmp($content, '#!cmd', strlen('#!cmd')) || !strncmp($content, '#!powershell', strlen('#!powershell')) ? Script::OS_WINDOWS : Script::OS_LINUX;
     $script->save();
     $scriptVersion = NULL;
     if ($version) {
         $scriptVersion = $script->getVersion($version);
     }
     if (!$scriptVersion && $script->getLatestVersion()->content !== $content) {
         $scriptVersion = new ScriptVersion();
         $scriptVersion->scriptId = $script->id;
         $scriptVersion->version = $script->getLatestVersion()->version + 1;
     }
     if ($scriptVersion) {
         $scriptVersion->changedById = $this->user->getId();
         $scriptVersion->changedByEmail = $this->user->getEmail();
         $scriptVersion->content = $content;
         $scriptVersion->save();
     }
     if ($this->user->getAccountId()) {
         Tag::setTags($tags, $this->user->getAccountId(), Tag::RESOURCE_SCRIPT, $script->id);
     }
     $this->response->success('Script successfully saved');
 }