Generates random key of specified length
public static GenerateRandomKey ( integer $length = 128 ) : string | ||
$length | integer | optional The length of the key |
return | string | Returns the random string of specified length |
public function xSaveAction($url, $endpointId = null) { if (!$endpointId) { $endpoint = new WebhookEndpoint(); $endpoint->level = WebhookEndpoint::LEVEL_ENVIRONMENT; $endpoint->accountId = $this->getEnvironment()->clientId; $endpoint->envId = $this->getEnvironmentId(); $endpoint->securityKey = Scalr::GenerateRandomKey(64); } else { $endpoint = WebhookEndpoint::findPk($endpointId); if ($endpoint->envId != $this->getEnvironmentId() || $endpoint->accountId != $this->getEnvironment()->clientId) { throw new Scalr_Exception_Core('Insufficient permissions to edit endpoint'); } } foreach (WebhookEndpoint::findByUrl($url) as $ep) { if ($ep->endpointId != $endpoint->endpointId && $ep->envId == $this->getEnvironmentId()) { $this->request->addValidationErrors('url', 'Endpoint url must be unique within environment'); break; } } if ($this->request->isValid()) { 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->data(array('endpoint' => array('endpointId' => $endpoint->endpointId, 'url' => $endpoint->url, 'isValid' => $endpoint->isValid, 'validationToken' => $endpoint->validationToken, 'securityKey' => $endpoint->securityKey))); } else { $this->response->data($this->request->getValidationErrors()); $this->response->failure(); } }
/** * Initializes ReportPayloadEntity object * * @param array $data Data array of params for uuid (Notification type, subject type, subject id) * @param array $payload Payload * @param string|DateTime|null $start optional Start date of the report (Y-m-d) * @return ReportPayloadEntity Returns ReportPayloadEntity object */ public static function init(array $data, $payload, $start = null) { $obj = new self(); $obj->created = $start instanceof DateTime ? clone $start : new DateTime($start ?: "now", new DateTimeZone('UTC')); $dataToHash = implode('|', $data) . '|' . $obj->created->format('Y-m-d'); $obj->uuid = $obj->type('uuid')->toPhp(substr(hash('sha1', $dataToHash, true), 0, 16)); $obj->secret = $obj->type('secret')->toPhp(hash('sha1', \Scalr::GenerateRandomKey(40), true)); $baseUrl = rtrim(\Scalr::getContainer()->config('scalr.endpoint.scheme') . "://" . \Scalr::getContainer()->config('scalr.endpoint.host'), '/'); $payload['reportUrl'] = $baseUrl . '#/public/report?uuid=' . $obj->uuid . '&secretHash=' . bin2hex((string) $obj->secret); $obj->payload = json_encode($payload); return $obj; }
/** * @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()))); }
public function xInitiateImportAction() { $this->request->defineParams(array('platform', 'cloudLocation', 'cloudServerId', 'roleName')); $validator = new Scalr_Validator(); if ($validator->validateNotEmpty($this->getParam('roleName')) !== true) { $err['roleName'] = 'Role name cannot be empty'; } if (strlen($this->getParam('roleName')) < 3) { $err['roleName'] = _("Role name should be greater than 3 chars"); } if (!preg_match("/^[A-Za-z0-9-]+\$/si", $this->getParam('roleName'))) { $err['roleName'] = _("Role name is incorrect"); } if ($this->db->GetOne("SELECT id FROM roles WHERE name=? AND (env_id = '0' OR env_id = ?) LIMIT 1", array($this->getParam('roleName'), $this->getEnvironmentId()))) { $err['roleName'] = 'Selected role name is already used. Please select another one.'; } $cryptoKey = Scalr::GenerateRandomKey(40); $creInfo = new ServerCreateInfo($this->getParam('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 => $this->getParam('roleName'), 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())); $platform = PlatformFactory::NewPlatform($this->getParam('platform')); if ($this->getParam('platform') == SERVER_PLATFORMS::EC2) { $client = $this->environment->aws($this->getParam('cloudLocation'))->ec2; $r = $client->instance->describe($this->getParam('cloudServerId')); $instance = $r->get(0)->instancesSet->get(0); $creInfo->SetProperties(array(EC2_SERVER_PROPERTIES::REGION => $this->getParam('cloudLocation'), EC2_SERVER_PROPERTIES::INSTANCE_ID => $this->getParam('cloudServerId'), EC2_SERVER_PROPERTIES::AMIID => $instance->imageId, EC2_SERVER_PROPERTIES::AVAIL_ZONE => $instance->placement->availabilityZone)); } else { if ($this->getParam('platform') == SERVER_PLATFORMS::GCE) { $gce = $platform->getClient($this->environment, $this->getParam('cloudLocation')); $result = $gce->instances->get($this->environment->getPlatformConfigValue(Modules_Platforms_GoogleCE::PROJECT_ID), $this->getParam('cloudLocation'), $this->getParam('cloudServerId')); $creInfo->SetProperties(array(GCE_SERVER_PROPERTIES::SERVER_ID => $result->id, GCE_SERVER_PROPERTIES::SERVER_NAME => $this->getParam('cloudServerId'), GCE_SERVER_PROPERTIES::CLOUD_LOCATION => $this->getParam('cloudLocation'))); } else { if (PlatformFactory::isOpenstack($this->getParam('platform'))) { $creInfo->SetProperties(array(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION => $this->getParam('cloudLocation'), OPENSTACK_SERVER_PROPERTIES::SERVER_ID => $this->getParam('cloudServerId'))); } else { if (PlatformFactory::isCloudstack($this->getParam('platform'))) { $creInfo->SetProperties(array(CLOUDSTACK_SERVER_PROPERTIES::CLOUD_LOCATION => $this->getParam('cloudLocation'), CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID => $this->getParam('cloudServerId'))); } } } } $dbServer = DBServer::Create($creInfo, true); $platform = PlatformFactory::NewPlatform($this->getParam('platform')); $ips = $platform->GetServerIPAddresses($dbServer); $dbServer->localIp = $ips['localIp']; $dbServer->remoteIp = $ips['remoteIp']; $dbServer->Save(); $this->response->data(array('command' => $this->getSzrCmd($dbServer), 'serverId' => $dbServer->serverId)); }
/** * @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::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.'); } $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); if ($platform == SERVER_PLATFORMS::EC2) { $client = $this->environment->aws($cloudLocation)->ec2; $r = $client->instance->describe($cloudServerId); $instance = $r->get(0)->instancesSet->get(0); $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::EUCALYPTUS) { $client = $this->environment->eucalyptus($cloudLocation)->ec2; $r = $client->instance->describe($cloudServerId); $instance = $r->get(0)->instancesSet->get(0); $creInfo->SetProperties(array(EUCA_SERVER_PROPERTIES::REGION => $cloudLocation, EUCA_SERVER_PROPERTIES::INSTANCE_ID => $cloudServerId, EUCA_SERVER_PROPERTIES::EMIID => $instance->imageId, EUCA_SERVER_PROPERTIES::AVAIL_ZONE => $instance->placement->availabilityZone)); } else { if ($platform == SERVER_PLATFORMS::GCE) { $gce = $platformObj->getClient($this->environment, $cloudLocation); $result = $gce->instances->get($this->environment->getPlatformConfigValue(GoogleCEPlatformModule::PROJECT_ID), $cloudLocation, $cloudServerId); $creInfo->SetProperties(array(GCE_SERVER_PROPERTIES::SERVER_NAME => $cloudServerId, GCE_SERVER_PROPERTIES::CLOUD_LOCATION => $cloudLocation)); } 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); $ips = $platformObj->GetServerIPAddresses($dbServer); $dbServer->localIp = $ips['localIp']; $dbServer->remoteIp = $ips['remoteIp']; $dbServer->Save(); $this->response->data(array('command' => $this->getSzrCmd($dbServer), 'serverId' => $dbServer->serverId)); }
/** * Performs upgrade literally for the stage ONE. * * Implementation of this method performs update steps needs to be taken * to accomplish upgrade successfully. * * If there are any error during an execution of this scenario it must * throw an exception. * * @param int $stage optional The stage number * @throws \Exception */ protected function run1($stage) { $observers = $this->db->Execute("SELECT * FROM farm_event_observers WHERE event_observer_name = 'MailEventObserver'"); while ($observer = $observers->FetchRow()) { $dbFarm = \DBFarm::LoadByID($observer['farmid']); // Create endpoint $endpointId = $this->db->GetOne("SELECT endpoint_id FROM webhook_endpoints WHERE env_id = ? AND url = ?", array($dbFarm->EnvID, 'SCALR_MAIL_SERVICE')); if ($endpointId) { $endpoint = WebhookEndpoint::findPk(bin2hex($endpointId)); } else { $endpoint = new WebhookEndpoint(); $endpoint->level = WebhookEndpoint::LEVEL_ENVIRONMENT; $endpoint->accountId = $dbFarm->ClientID; $endpoint->envId = $dbFarm->EnvID; $endpoint->securityKey = \Scalr::GenerateRandomKey(64); $endpoint->isValid = true; $endpoint->url = "SCALR_MAIL_SERVICE"; $endpoint->save(); } //Create webhook configuration $webhook = new WebhookConfig(); $webhook->level = WebhookConfig::LEVEL_ENVIRONMENT; $webhook->accountId = $dbFarm->ClientID; $webhook->envId = $dbFarm->EnvID; $webhook->name = "MailEventObserver(FarmID: {$dbFarm->ID})"; $webhook->postData = $this->db->GetOne("SELECT value FROM farm_event_observers_config WHERE `key` = ? AND observerid = ?", array('EventMailTo', $observer['id'])); $webhook->save(); //save endpoints $configEndpoint = new WebhookConfigEndpoint(); $configEndpoint->webhookId = $webhook->webhookId; $configEndpoint->setEndpoint($endpoint); $configEndpoint->save(); //save events $dbEvents = $this->db->Execute("SELECT * FROM farm_event_observers_config WHERE `key` LIKE '%Notify' AND observerid = ?", array($observer['id'])); while ($info = $dbEvents->FetchRow()) { preg_match('/On([A-Za-z0-9]+)Notify/si', $info['key'], $matches); $configEvent = new WebhookConfigEvent(); $configEvent->webhookId = $webhook->webhookId; $configEvent->eventType = $matches[1]; $configEvent->save(); } //save farms $configFarm = new WebhookConfigFarm(); $configFarm->webhookId = $webhook->webhookId; $configFarm->farmId = $dbFarm->ID; $configFarm->save(); } }
public static function create($name) { $account = Scalr_UI_Request::getInstance()->getUser()->getAccount(); $account->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1); $db = Core::GetDBInstance(); $dbFarm = new self(); $dbFarm->Status = FARM_STATUS::TERMINATED; $dbFarm->ClientID = $account->id; $dbFarm->EnvID = Scalr_UI_Request::getInstance()->getEnvironment()->id; $dbFarm->Name = $name; $dbFarm->RolesLaunchOrder = 0; $dbFarm->Comments = ""; $dbFarm->save(); $dbFarm->SetSetting(DBFarm::SETTING_CRYPTO_KEY, Scalr::GenerateRandomKey(40)); return $dbFarm; }
/** * Initializes a new farm * * TODO: Rewrite this terrible code. * * @param string $name The name of the farm * @param Scalr_Account_User $user The user * @param int $envId The identifier of the environment * @return DBFarm */ public static function create($name, Scalr_Account_User $user, $envId) { $account = $user->getAccount(); $account->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1); $dbFarm = new self(); $dbFarm->Status = FARM_STATUS::TERMINATED; $dbFarm->ClientID = $account->id; $dbFarm->EnvID = $envId; $dbFarm->createdByUserId = $user->getId(); $dbFarm->createdByUserEmail = $user->getEmail(); $dbFarm->changedByUserId = $user->getId(); $dbFarm->changedTime = microtime(); $dbFarm->Name = $name; $dbFarm->RolesLaunchOrder = 0; $dbFarm->Comments = ""; $dbFarm->save(); $dbFarm->SetSetting(DBFarm::SETTING_CRYPTO_KEY, Scalr::GenerateRandomKey(40)); return $dbFarm; }
/** * Data provider for testCrypto() */ public function providerTestCrypto() { self::initCrypto(); $cases = array(); // this cases doesn't work similar in python decrypt as php /* TODO: fix $cases[] = array("\n"); $cases[] = array("abracadabra\n"); $cases[] = array(" "); $cases[] = array(" \n"); $cases[] = array("abracadabra \n"); $cases[] = array(" abracadabra \n"); $cases[] = array("\t\n"); $cases[] = array(" foo "); */ // depends on block size (extended test = 256, short = 32) for ($i = 1; $i <= 32; $i++) { $cases[] = array(\Scalr::GenerateRandomKey($i)); } return $cases; }
/** * {@inheritdoc} * @see AbstractEntity::save() */ public function save() { $this->changed = microtime(); if (empty($this->id)) { $this->createdById = $this->changedById; $this->added = new DateTime(); $this->status = FARM_STATUS::TERMINATED; if (empty($this->settings[FarmSetting::TIMEZONE])) { $this->settings[FarmSetting::TIMEZONE] = date_default_timezone_get(); } $this->settings[FarmSetting::CRYPTO_KEY] = \Scalr::GenerateRandomKey(40); /* @var $governance Governance */ $governance = Governance::findPk($this->envId, Governance::CATEGORY_GENERAL, Governance::GENERAL_LEASE); if (!empty($governance) && $governance->enabled) { $this->settings[FarmSetting::LEASE_STATUS] = 'Active'; } //TODO: unused field $this->region = Aws::REGION_US_EAST_1; } parent::save(); if (!empty($this->_settings)) { $this->_settings->save(); } }
/** * {@inheritdoc} * @see ServerImportInterface::import() */ public function import($instanceId, $tags = []) { $instances = PlatformFactory::NewPlatform($this->farmRole->platform)->getOrphanedServers($this->farmRole->getFarm()->getEnvironment(), $this->farmRole->cloudLocation, [$instanceId]); if (count($instances) != 1) { throw new ValidationErrorException("Instance was not found"); } $this->orphaned = $instances[0]; $this->tags = $tags; $this->validate(); $farm = $this->farmRole->getFarm(); $server = $this->server = new Entity\Server(); try { $server->serverId = \Scalr::GenerateUID(false); // DBServer::Create, startWithLetter $server->platform = $this->farmRole->platform; $server->cloudLocation = $this->farmRole->cloudLocation; $server->accountId = $farm->accountId; $server->envId = $farm->envId; $server->farmId = $farm->id; $server->farmRoleId = $this->farmRole->id; $server->imageId = $this->orphaned->imageId; $server->status = Entity\Server::STATUS_RUNNING; $server->type = $this->orphaned->instanceType; $server->remoteIp = $this->orphaned->publicIp; $server->localIp = $this->orphaned->privateIp; $server->added = new DateTime(); $server->initialized = new DateTime(); // initialized is used in billing, so we set current time as start point $server->scalarized = 0; $server->setFreeFarmIndex(); $server->setFreeFarmRoleIndex(); $server->properties[Entity\Server::SZR_KEY] = \Scalr::GenerateRandomKey(40); $server->properties[Entity\Server::SZR_KEY_TYPE] = SZR_KEY_TYPE::ONE_TIME; $server->properties[Entity\Server::SZR_VESION] = ''; $server->properties[Entity\Server::LAUNCHED_BY_ID] = $this->user->id; $server->properties[Entity\Server::LAUNCHED_BY_EMAIL] = $this->user->email; $server->properties[Entity\Server::LAUNCH_REASON_ID] = DBServer::LAUNCH_REASON_IMPORT; $server->properties[Entity\Server::LAUNCH_REASON] = DBServer::getLaunchReason(DBServer::LAUNCH_REASON_IMPORT); $server->properties[Entity\Server::FARM_ROLE_ID] = $this->farmRole->id; $server->properties[Entity\Server::ROLE_ID] = $this->farmRole->roleId; $server->properties[Entity\Server::FARM_CREATED_BY_ID] = $farm->ownerId ?: $farm->settings[Entity\FarmSetting::CREATED_BY_ID]; $server->properties[Entity\Server::FARM_CREATED_BY_EMAIL] = $farm->ownerId ? Entity\Account\User::findPk($farm->ownerId)->email : $farm->settings[Entity\FarmSetting::CREATED_BY_EMAIL]; // projectId, ccId $projectId = $farm->settings[Entity\FarmSetting::PROJECT_ID]; $ccId = null; if (!empty($projectId)) { try { $projectEntity = ProjectEntity::findPk($projectId); if ($projectEntity instanceof ProjectEntity) { /* @var $projectEntity ProjectEntity */ $ccId = $projectEntity->ccId; } else { $projectId = null; } } catch (Exception $e) { $projectId = null; } } $server->properties[Entity\Server::FARM_PROJECT_ID] = $projectId; if (empty($ccId)) { $ccId = Entity\Account\Environment::findPk($farm->envId)->getProperty(Entity\Account\EnvironmentProperty::SETTING_CC_ID); } $server->properties[Entity\Server::ENV_CC_ID] = $ccId; if (!empty($server->getImage())) { $server->getImage()->update(['dtLastUsed' => new DateTime()]); } if (!empty($this->farmRole->getRole())) { $this->farmRole->getRole()->update(['lastUsed' => new DateTime()]); } $this->importServer(); $server->save(); $server->setTimeLog('ts_created'); $server->setTimeLog('ts_launched', time()); $history = $server->getHistory(); $history->markAsLaunched($server->properties[Entity\Server::LAUNCH_REASON], $server->properties[Entity\Server::LAUNCH_REASON_ID]); $history->update(['cloudServerId' => $this->orphaned->cloudServerId, 'scuCollecting' => 1]); $this->applyTags(); return $server; } catch (Exception $e) { if (!empty($server->serverId)) { // cleanup $server->deleteBy([['serverId' => $server->serverId]]); Entity\ServerProperty::deleteBy([['serverId' => $server->serverId]]); Entity\Server\History::deletePk($server->serverId); $this->db->Execute("DELETE FROM `servers_launch_timelog` WHERE server_id = ?", [$server->serverId]); } throw new ServerImportException(sprintf("Server create was failed with error: %s", $e->getMessage()), $e->getCode(), $e); } }
public function xBuildAction() { $this->request->defineParams(array('farmId' => array('type' => 'int'), 'roles' => array('type' => 'json'), 'farm' => array('type' => 'json'), 'roleUpdate' => array('type' => 'int'), 'launch' => array('type' => 'bool'))); if (!$this->isFarmConfigurationValid($this->getParam('farmId'), $this->getParam('farm'), (array) $this->getParam('roles'))) { if ($this->errors['error_count'] != 0) { $this->response->failure(); $this->response->data(array('errors' => $this->errors)); return; } } $farm = $this->getParam('farm'); $client = Client::Load($this->user->getAccountId()); if ($this->getParam('farmId')) { $dbFarm = DBFarm::LoadByID($this->getParam('farmId')); $this->user->getPermissions()->validate($dbFarm); $this->request->restrictFarmAccess($dbFarm, Acl::PERM_FARMS_MANAGE); $dbFarm->isLocked(); if ($this->getParam('changed') && $dbFarm->changedTime && $this->getParam('changed') != $dbFarm->changedTime) { $userName = '******'; $changed = explode(' ', $this->getParam('changed')); $changedTime = intval($changed[1]); try { $user = new Scalr_Account_User(); $user->loadById($dbFarm->changedByUserId); $userName = $user->getEmail(); } catch (Exception $e) { } $this->response->failure(); $this->response->data(array('changedFailure' => sprintf('%s changed this farm at %s', $userName, Scalr_Util_DateTime::convertTz($changedTime)))); return; } $dbFarm->changedByUserId = $this->user->getId(); $dbFarm->changedTime = microtime(); $bNew = false; } else { $this->request->restrictFarmAccess(null, Acl::PERM_FARMS_MANAGE); $this->user->getAccount()->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1); $dbFarm = new DBFarm(); $dbFarm->ClientID = $this->user->getAccountId(); $dbFarm->EnvID = $this->getEnvironmentId(); $dbFarm->Status = FARM_STATUS::TERMINATED; $dbFarm->createdByUserId = $this->user->getId(); $dbFarm->createdByUserEmail = $this->user->getEmail(); $dbFarm->changedByUserId = $this->user->getId(); $dbFarm->changedTime = microtime(); $bNew = true; } if ($this->getParam('farm')) { $dbFarm->Name = $this->request->stripValue($farm['name']); $dbFarm->RolesLaunchOrder = $farm['rolesLaunchOrder']; $dbFarm->Comments = $this->request->stripValue($farm['description']); } if (empty($dbFarm->Name)) { throw new Exception(_("Farm name required")); } if ($bNew) { $dbFarm->teamId = is_numeric($farm['teamOwner']) && $farm['teamOwner'] > 0 ? $farm['teamOwner'] : NULL; } else { if ($dbFarm->createdByUserId == $this->user->getId() || $this->user->isAccountOwner() || $this->request->isFarmAllowed($dbFarm, Acl::PERM_FARMS_CHANGE_OWNERSHIP)) { if (is_numeric($farm['owner']) && $farm['owner'] != $dbFarm->createdByUserId) { $user = (new Scalr_Account_User())->loadById($farm['owner']); $dbFarm->createdByUserId = $user->getId(); $dbFarm->createdByUserEmail = $user->getEmail(); // TODO: move to subclass \Farm\Setting\OwnerHistory $history = unserialize($dbFarm->GetSetting(DBFarm::SETTING_OWNER_HISTORY)); if (!is_array($history)) { $history = []; } $history[] = ['newId' => $user->getId(), 'newEmail' => $user->getEmail(), 'changedById' => $this->user->getId(), 'changedByEmail' => $this->user->getEmail(), 'dt' => date('Y-m-d H:i:s')]; $dbFarm->SetSetting(DBFarm::SETTING_OWNER_HISTORY, serialize($history)); } $dbFarm->teamId = is_numeric($farm['teamOwner']) && $farm['teamOwner'] > 0 ? $farm['teamOwner'] : NULL; } } $dbFarm->save(); $governance = new Scalr_Governance($this->getEnvironmentId()); if (!$this->getParam('farmId') && $governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE)) { $dbFarm->SetSetting(DBFarm::SETTING_LEASE_STATUS, 'Active'); // for created farm } if (isset($farm['variables'])) { $variables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARM); $variables->setValues(is_array($farm['variables']) ? $farm['variables'] : [], 0, $dbFarm->ID, 0, '', false, true); } if (!$farm['timezone']) { $farm['timezone'] = date_default_timezone_get(); } $dbFarm->SetSetting(DBFarm::SETTING_TIMEZONE, $farm['timezone']); $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_ID, $farm['vpc_id']); $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_REGION, $farm['vpc_region']); $dbFarm->SetSetting(DBFarm::SETTING_SZR_UPD_REPOSITORY, $farm[DBFarm::SETTING_SZR_UPD_REPOSITORY]); $dbFarm->SetSetting(DBFarm::SETTING_SZR_UPD_SCHEDULE, $farm[DBFarm::SETTING_SZR_UPD_SCHEDULE]); if (!$dbFarm->GetSetting(DBFarm::SETTING_CRYPTO_KEY)) { $dbFarm->SetSetting(DBFarm::SETTING_CRYPTO_KEY, Scalr::GenerateRandomKey(40)); } if ($this->getContainer()->analytics->enabled) { //Cost analytics project must be set for the Farm object $dbFarm->setProject(!empty($farm['projectId']) ? $farm['projectId'] : null); } $virtualFarmRoles = array(); $roles = $this->getParam('roles'); if (!empty($roles)) { foreach ($roles as $role) { if (strpos($role['farm_role_id'], "virtual_") !== false) { $dbRole = DBRole::loadById($role['role_id']); $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index'], $role['alias']); $virtualFarmRoles[$role['farm_role_id']] = $dbFarmRole->ID; } } } $usedPlatforms = array(); $dbFarmRolesList = array(); $newFarmRolesList = array(); $farmRoleVariables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARMROLE); if (!empty($roles)) { foreach ($roles as $role) { if ($role['farm_role_id']) { if ($virtualFarmRoles[$role['farm_role_id']]) { $role['farm_role_id'] = $virtualFarmRoles[$role['farm_role_id']]; } $update = true; $dbFarmRole = DBFarmRole::LoadByID($role['farm_role_id']); $dbRole = DBRole::loadById($dbFarmRole->RoleID); $role['role_id'] = $dbFarmRole->RoleID; if ($dbFarmRole->Platform == SERVER_PLATFORMS::GCE) { $dbFarmRole->CloudLocation = $role['cloud_location']; } } else { $update = false; $dbRole = DBRole::loadById($role['role_id']); $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index']); } if ($dbRole->hasBehavior(ROLE_BEHAVIORS::RABBITMQ)) { $role['settings'][DBFarmRole::SETTING_SCALING_MAX_INSTANCES] = $role['settings'][DBFarmRole::SETTING_SCALING_MIN_INSTANCES]; } if ($dbFarmRole->NewRoleID) { continue; } if ($update) { $dbFarmRole->LaunchIndex = (int) $role['launch_index']; $dbFarmRole->Alias = $role['alias']; $dbFarmRole->Save(); } $usedPlatforms[$role['platform']] = 1; $oldRoleSettings = $dbFarmRole->GetAllSettings(); // Update virtual farm_role_id with actual value $scripts = (array) $role['scripting']; if (count($virtualFarmRoles) > 0) { array_walk_recursive($scripts, function (&$v, $k) use($virtualFarmRoles) { if (is_string($v)) { $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v); } }); array_walk_recursive($role['settings'], function (&$v, $k) use($virtualFarmRoles) { if (is_string($v)) { $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v); } }); } $dbFarmRole->ClearSettings("chef."); if (!empty($role['scaling_settings']) && is_array($role['scaling_settings'])) { foreach ($role['scaling_settings'] as $k => $v) { $dbFarmRole->SetSetting($k, $v, DBFarmRole::TYPE_CFG); } } foreach ($role['settings'] as $k => $v) { $dbFarmRole->SetSetting($k, $v, DBFarmRole::TYPE_CFG); } /****** Scaling settings ******/ $scalingManager = new Scalr_Scaling_Manager($dbFarmRole); $scalingManager->setFarmRoleMetrics(is_array($role['scaling']) ? $role['scaling'] : array()); //TODO: optimize this code... $this->db->Execute("DELETE FROM farm_role_scaling_times WHERE farm_roleid=?", array($dbFarmRole->ID)); // 5 = Time based scaling -> move to constants if ($role['scaling'][5]) { foreach ($role['scaling'][5] as $scal_period) { $chunks = explode(":", $scal_period['id']); $this->db->Execute("INSERT INTO farm_role_scaling_times SET\n farm_roleid\t\t= ?,\n start_time\t\t= ?,\n end_time\t\t= ?,\n days_of_week\t= ?,\n instances_count\t= ?\n ", array($dbFarmRole->ID, $chunks[0], $chunks[1], $chunks[2], $chunks[3])); } } /*****************/ /* Update role params */ $dbFarmRole->SetParameters((array) $role['params']); /* End of role params management */ /* Add script options to databse */ $dbFarmRole->SetScripts($scripts, (array) $role['scripting_params']); /* End of scripting section */ /* Add services configuration */ $dbFarmRole->SetServiceConfigPresets((array) $role['config_presets']); /* End of scripting section */ /* Add storage configuration */ if (isset($role['storages'])) { if (isset($role['storages']['configs'])) { $dbFarmRole->getStorage()->setConfigs($role['storages']['configs']); } } $farmRoleVariables->setValues(is_array($role['variables']) ? $role['variables'] : [], $dbFarmRole->GetRoleID(), $dbFarm->ID, $dbFarmRole->ID, '', false, true); foreach (Scalr_Role_Behavior::getListForFarmRole($dbFarmRole) as $behavior) { $behavior->onFarmSave($dbFarm, $dbFarmRole); } /** * Platform specified updates */ if ($dbFarmRole->Platform == SERVER_PLATFORMS::EC2) { \Scalr\Modules\Platforms\Ec2\Helpers\EbsHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); \Scalr\Modules\Platforms\Ec2\Helpers\EipHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); \Scalr\Modules\Platforms\Ec2\Helpers\ElbHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); } if (in_array($dbFarmRole->Platform, array(SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::CLOUDSTACK))) { Scalr\Modules\Platforms\Cloudstack\Helpers\CloudstackHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); } $dbFarmRolesList[] = $dbFarmRole; $newFarmRolesList[] = $dbFarmRole->ID; } } if (!$this->getParam('roleUpdate')) { foreach ($dbFarm->GetFarmRoles() as $dbFarmRole) { if (!$dbFarmRole->NewRoleID && !in_array($dbFarmRole->ID, $newFarmRolesList)) { $dbFarmRole->Delete(); } } } $dbFarm->save(); if (!$client->GetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED)) { $client->SetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED, time()); } if ($this->request->isFarmAllowed($dbFarm, Acl::PERM_FARMS_LAUNCH_TERMINATE) && $this->getParam('launch')) { $this->user->getPermissions()->validate($dbFarm); $dbFarm->isLocked(); Scalr::FireEvent($dbFarm->ID, new FarmLaunchedEvent(true, $this->user->id)); $this->response->success('Farm successfully saved and launched'); } else { $this->response->success('Farm successfully saved'); } $this->response->data(array('farmId' => $dbFarm->ID, 'isNewFarm' => $bNew)); }
/** * @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_IMAGES_ENVIRONMENT, Acl::PERM_IMAGES_ENVIRONMENT_BUILD); 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.'); } $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::IDCF: $launchOptions->serverType = 24; break; case SERVER_PLATFORMS::RACKSPACENG_US: $launchOptions->serverType = 3; break; case SERVER_PLATFORMS::RACKSPACENG_UK: $launchOptions->serverType = 3; break; case SERVER_PLATFORMS::EC2: if ($cloudLocation == Aws::REGION_AP_NORTHEAST_2) { if ($hvm == 1 || $this->isHvmBundleTypeOs($os)) { $launchOptions->serverType = 't2.large'; $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM; } } else { if ($hvm == 1) { $launchOptions->serverType = "m3.xlarge"; $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM; } else { $launchOptions->serverType = "m3.large"; if ($this->isHvmBundleTypeOs($os)) { $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM; } if ($os->family == 'oel' && $os->generation == '5') { $launchOptions->serverType = "m1.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); $dbServer->Save(); $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 $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)); }
public static function GenerateAPIKeys() { $key = Scalr::GenerateRandomKey(); $sault = abs(crc32($key)); $keyid = dechex($sault) . dechex(time()); $ScalrKey = $key; $ScalrKeyID = $keyid; return array("id" => $ScalrKeyID, "key" => $ScalrKey); }
public function extendedInfoAction() { if (!$this->getParam('serverId')) { throw new Exception(_('Server not found')); } $dbServer = DBServer::LoadByID($this->getParam('serverId')); $this->user->getPermissions()->validate($dbServer); $info = PlatformFactory::NewPlatform($dbServer->platform)->GetServerExtendedInformation($dbServer); $form = array(array('xtype' => 'fieldcontainer', 'layout' => 'hbox', 'hideLabel' => true, 'items' => array(array('xtype' => 'fieldset', 'title' => 'General', 'height' => 218, 'flex' => 1, 'margin' => '0 3 0 0', 'labelWidth' => 240, 'items' => array(array('xtype' => 'displayfield', 'fieldLabel' => 'Server ID', 'width' => 380, 'value' => $dbServer->serverId), array('xtype' => 'displayfield', 'fieldLabel' => 'Platform', 'value' => $dbServer->platform), array('xtype' => 'displayfield', 'fieldLabel' => 'Remote IP', 'value' => $dbServer->remoteIp ? $dbServer->remoteIp : ''), array('xtype' => 'displayfield', 'fieldLabel' => 'Local IP', 'value' => $dbServer->localIp ? $dbServer->localIp : ''), array('xtype' => 'displayfield', 'fieldLabel' => 'Status', 'value' => $dbServer->status), array('xtype' => 'displayfield', 'fieldLabel' => 'Index', 'value' => $dbServer->index), array('xtype' => 'displayfield', 'fieldLabel' => 'Added at', 'value' => Scalr_Util_DateTime::convertTz($dbServer->dateAdded))))))); /***** Scalr agent *****/ if ($dbServer->status == SERVER_STATUS::RUNNING) { try { $updateClient = new Scalr_Net_Scalarizr_UpdateClient($dbServer); $status = $updateClient->getStatus(); } catch (Exception $e) { $oldUpdClient = stristr($e->getMessage(), "Method not found"); $error = $e->getMessage(); } if ($status) { $items = array(array('xtype' => 'displayfield', 'fieldLabel' => 'Scalarizr status', 'value' => $status->service_status == 'running' ? "<span style='color:green;'>Running</span>" : "<span style='color:red;'>" . ucfirst($status->service_status) . "</span>"), array('xtype' => 'displayfield', 'fieldLabel' => 'Version', 'value' => $status->installed), array('xtype' => 'displayfield', 'fieldLabel' => 'Repository', 'value' => ucfirst($status->repository)), array('xtype' => 'displayfield', 'fieldLabel' => 'Last update', 'value' => Scalr_Util_DateTime::convertTz($status->executed_at)), array('xtype' => 'displayfield', 'fieldLabel' => 'Last update status', 'value' => $status->error ? "<span style='color:red;'>Error: " . nl2br($status->error) . "</span>" : "<span style='color:green;'>Success</span>"), array('xtype' => 'displayfield', 'fieldLabel' => 'Next update', 'value' => $status->installed != $status->candidate ? "Update to <b>{$status->candidate}</b> scheduled on <b>" . Scalr_Util_DateTime::convertTz($status->scheduled_on) . "</b>" : "Scalarizr is up to date"), array('xtype' => 'displayfield', 'fieldLabel' => 'Schedule', 'value' => $status->schedule), array('xtype' => 'fieldcontainer', 'layout' => 'hbox', 'hideLabel' => true, 'items' => array(array('xtype' => 'button', 'itemId' => 'updateSzrBtn', 'text' => 'Update scalarizr now', 'disabled' => $status->installed == $status->candidate, 'flex' => 1, 'margin' => $this->getParam('beta') == 1 ? '0 3 0 0' : '0 0 0 0'), array('xtype' => 'button', 'itemId' => 'restartSzrBtn', 'text' => 'Restart scalarizr', 'flex' => 1)))); } else { if ($oldUpdClient) { $items = array(array('xtype' => 'button', 'itemId' => 'upgradeUpdClientBtn', 'text' => 'Upgrade scalarizr upd-client', 'flex' => 1)); } else { $items = array(array('xtype' => 'displayfield', 'hideLabel' => true, 'value' => "<span style='color:red;'>Scalarizr status is not available: {$error}</span>")); } } $form[0]['items'][] = array('xtype' => 'fieldset', 'labelWidth' => 240, 'flex' => 1, 'title' => 'Scalr agent status', 'items' => $items); } /***** Scalr agent *****/ $it = array(); if (is_array($info) && count($info)) { foreach ($info as $name => $value) { $it[] = array('xtype' => 'displayfield', 'fieldLabel' => $name, 'value' => $value); } } else { $it[] = array('xtype' => 'displayfield', 'hideLabel' => true, 'value' => 'Platform specific details not available for this server'); } $form[] = array('xtype' => 'fieldset', 'labelWidth' => 240, 'title' => 'Platform specific details', 'collapsible' => true, 'collapsed' => false, 'items' => $it); /* <tr> <td width="20%">CloudWatch monitoring:</td> <td>{if $info->instancesSet->item->monitoring->state == 'enabled'} <a href="/aws_cw_monitor.php?ObjectId={$info->instancesSet->item->instanceId}&Object=InstanceId&NameSpace=AWS/EC2">{$info->instancesSet->item->monitoring->state}</a> (<a href="aws_ec2_cw_manage.php?action=Disable&iid={$info->instancesSet->item->instanceId}®ion={$smarty.request.region}">Disable</a>) {else} {$info->instancesSet->item->monitoring->state} (<a href="aws_ec2_cw_manage.php?action=Enable&iid={$info->instancesSet->item->instanceId}®ion={$smarty.request.region}">Enable</a>) {/if} </td> </tr> --> {include file="inc/intable_footer.tpl" color="Gray"} */ if (count($dbServer->GetAllProperties())) { $it = array(); foreach ($dbServer->GetAllProperties() as $name => $value) { $it[] = array('xtype' => 'displayfield', 'fieldLabel' => $name, 'value' => $value); } $form[] = array('xtype' => 'fieldset', 'title' => 'Scalr internal server properties', 'collapsible' => true, 'collapsed' => true, 'labelWidth' => 220, 'items' => $it); } if (!$dbServer->IsSupported('0.5')) { $authKey = $dbServer->GetKey(); if (!$authKey) { $authKey = Scalr::GenerateRandomKey(40); $dbServer->SetProperty(SERVER_PROPERTIES::SZR_KEY, $authKey); } $dbServer->SetProperty(SERVER_PROPERTIES::SZR_KEY_TYPE, SZR_KEY_TYPE::PERMANENT); $form[] = array('xtype' => 'fieldset', 'title' => 'Upgrade from ami-scripts to scalarizr', 'labelWidth' => 220, 'items' => array('xtype' => 'textarea', 'hideLabel' => true, 'readOnly' => true, 'anchor' => '-20', 'value' => sprintf("wget " . CONFIG::$HTTP_PROTO . "://" . CONFIG::$EVENTHANDLER_URL . "/storage/scripts/amiscripts-to-scalarizr.py && python amiscripts-to-scalarizr.py -s %s -k %s -o queryenv-url=%s -o messaging_p2p.producer_url=%s", $dbServer->serverId, $authKey, CONFIG::$HTTP_PROTO . "://" . CONFIG::$EVENTHANDLER_URL . "/query-env", CONFIG::$HTTP_PROTO . "://" . CONFIG::$EVENTHANDLER_URL . "/messaging"))); } $this->response->page('ui/servers/extendedinfo.js', $form); }
public function xBuildAction() { $this->request->defineParams(array('platform' => array('type' => 'string'), 'architecture' => array('type' => 'string'), 'behaviors' => array('type' => 'json'), 'roleName' => array('type' => 'string'), 'imageId' => array('type' => 'string'), 'location' => array('type' => 'string'), 'mysqlServerType' => array('type' => 'string'), 'devScalarizrBranch' => array('type' => 'string'))); if (strlen($this->getParam('roleName')) < 3) { throw new Exception(_("Role name should be greater than 3 chars")); } if (!preg_match("/^[A-Za-z0-9-]+\$/si", $this->getParam('roleName'))) { throw new Exception(_("Role name is incorrect")); } $chkRoleId = $this->db->GetOne("SELECT id FROM roles WHERE name=? AND (env_id = '0' OR env_id = ?)", array($this->getParam('roleName'), $this->getEnvironmentId())); if ($chkRoleId) { if (!$this->db->GetOne("SELECT id FROM roles_queue WHERE role_id=?", array($chkRoleId))) { throw new Exception('Selected role name is already used. Please select another one.'); } } $imageId = $this->getParam('imageId'); if ($this->getParam('platform') == SERVER_PLATFORMS::RACKSPACE) { $imageId = str_replace('lon', '', $imageId); } $behaviours = implode(",", array_values($this->getParam('behaviors'))); // Create server $creInfo = new ServerCreateInfo($this->getParam('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_KEY => Scalr::GenerateRandomKey(40), SERVER_PROPERTIES::SZR_KEY_TYPE => SZR_KEY_TYPE::PERMANENT, SERVER_PROPERTIES::SZR_VESION => "0.6", SERVER_PROPERTIES::SZR_IMPORTING_MYSQL_SERVER_TYPE => $this->getParam('mysqlServerType'), SERVER_PROPERTIES::SZR_DEV_SCALARIZR_BRANCH => $this->getParam('devScalarizrBranch'))); $dbServer = DBServer::Create($creInfo, true); $dbServer->status = SERVER_STATUS::TEMPORARY; $dbServer->save(); //Launch server $launchOptions = new Scalr_Server_LaunchOptions(); $launchOptions->imageId = $imageId; $launchOptions->cloudLocation = $this->getParam('location'); $launchOptions->architecture = $this->getParam('architecture'); switch ($this->getParam('platform')) { case SERVER_PLATFORMS::RACKSPACE: $launchOptions->serverType = 1; break; case SERVER_PLATFORMS::EC2: $launchOptions->serverType = 'm1.small'; $launchOptions->userData = "#cloud-config\ndisable_root: false"; break; } if ($this->getParam('serverType')) { $launchOptions->serverType = $this->getParam('serverType'); } if ($this->getParam('availZone')) { $launchOptions->availZone = $this->getParam('availZone'); } //Add Bundle task $creInfo = new ServerSnapshotCreateInfo($dbServer, $this->getParam('roleName'), SERVER_REPLACEMENT_TYPE::NO_REPLACE); $bundleTask = BundleTask::Create($creInfo, true); $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 { PlatformFactory::NewPlatform($this->getParam('platform'))->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('bundleTaskId' => $bundleTask->id)); }
public function xBuildAction() { $this->request->defineParams(array('farmId' => array('type' => 'int'), 'roles' => array('type' => 'json'), 'farm' => array('type' => 'json'), 'roleUpdate' => array('type' => 'int'))); $this->request->restrictAccess(Acl::RESOURCE_FARMS, Acl::PERM_FARMS_MANAGE); if (!$this->isFarmConfigurationValid($this->getParam('farmId'), $this->getParam('farm'), (array) $this->getParam('roles'))) { if ($this->errors['error_count'] != 0) { $this->response->failure(); $this->response->data(array('errors' => $this->errors)); return; } } $farm = $this->getParam('farm'); $client = Client::Load($this->user->getAccountId()); if ($this->getParam('farmId')) { $dbFarm = DBFarm::LoadByID($this->getParam('farmId')); $this->user->getPermissions()->validate($dbFarm); $dbFarm->isLocked(); if ($this->getParam('changed') && $dbFarm->changedTime && $this->getParam('changed') != $dbFarm->changedTime) { $userName = '******'; $changed = explode(' ', $this->getParam('changed')); $changedTime = intval($changed[1]); try { $user = new Scalr_Account_User(); $user->loadById($dbFarm->changedByUserId); $userName = $user->getEmail(); } catch (Exception $e) { } $this->response->failure(); $this->response->data(array('changedFailure' => sprintf('%s changed this farm at %s', $userName, Scalr_Util_DateTime::convertTz($changedTime)))); return; } $dbFarm->changedByUserId = $this->user->getId(); $dbFarm->changedTime = microtime(); } else { $this->user->getAccount()->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1); $dbFarm = new DBFarm(); $dbFarm->Status = FARM_STATUS::TERMINATED; $dbFarm->createdByUserId = $this->user->getId(); $dbFarm->createdByUserEmail = $this->user->getEmail(); $dbFarm->changedByUserId = $this->user->getId(); $dbFarm->changedTime = microtime(); } if ($this->getParam('farm')) { $dbFarm->Name = strip_tags($farm['name']); $dbFarm->RolesLaunchOrder = $farm['rolesLaunchOrder']; $dbFarm->Comments = trim(strip_tags($farm['description'])); } if (empty($dbFarm->Name)) { throw new Exception(_("Farm name required")); } $dbFarm->save(); $governance = new Scalr_Governance($this->getEnvironmentId()); if ($governance->isEnabled(Scalr_Governance::GENERAL_LEASE)) { $dbFarm->SetSetting(DBFarm::SETTING_LEASE_STATUS, 'Active'); } if (isset($farm['variables'])) { $variables = new Scalr_Scripting_GlobalVariables($this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARM); $variables->setValues($farm['variables'], 0, $dbFarm->ID, 0, '', false); } if (!$farm['timezone']) { $farm['timezone'] = date_default_timezone_get(); } $dbFarm->SetSetting(DBFarm::SETTING_TIMEZONE, $farm['timezone']); $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_ID, $farm['vpc_id']); $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_REGION, $farm['vpc_region']); if (!$dbFarm->GetSetting(DBFarm::SETTING_CRYPTO_KEY)) { $dbFarm->SetSetting(DBFarm::SETTING_CRYPTO_KEY, Scalr::GenerateRandomKey(40)); } $virtualFarmRoles = array(); $roles = $this->getParam('roles'); if (!empty($roles)) { foreach ($roles as $role) { if (strpos($role['farm_role_id'], "virtual_") !== false) { $dbRole = DBRole::loadById($role['role_id']); $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index'], $role['alias']); $virtualFarmRoles[$role['farm_role_id']] = $dbFarmRole->ID; } } } $usedPlatforms = array(); $dbFarmRolesList = array(); $newFarmRolesList = array(); $farmRoleVariables = new Scalr_Scripting_GlobalVariables($this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARMROLE); if (!empty($roles)) { foreach ($roles as $role) { if ($role['farm_role_id']) { if ($virtualFarmRoles[$role['farm_role_id']]) { $role['farm_role_id'] = $virtualFarmRoles[$role['farm_role_id']]; } $update = true; $dbFarmRole = DBFarmRole::LoadByID($role['farm_role_id']); $dbRole = DBRole::loadById($dbFarmRole->RoleID); $role['role_id'] = $dbFarmRole->RoleID; if ($dbFarmRole->Platform == SERVER_PLATFORMS::GCE) { $dbFarmRole->CloudLocation = $role['cloud_location']; } } else { $update = false; $dbRole = DBRole::loadById($role['role_id']); $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index']); } if ($dbRole->hasBehavior(ROLE_BEHAVIORS::RABBITMQ)) { $role['settings'][DBFarmRole::SETTING_SCALING_MAX_INSTANCES] = $role['settings'][DBFarmRole::SETTING_SCALING_MIN_INSTANCES]; } if ($dbFarmRole->NewRoleID) { continue; } if ($update) { $dbFarmRole->LaunchIndex = (int) $role['launch_index']; $dbFarmRole->Alias = $role['alias']; $dbFarmRole->Save(); } $usedPlatforms[$role['platform']] = 1; $oldRoleSettings = $dbFarmRole->GetAllSettings(); // Update virtual farm_role_id with actual value $scripts = (array) $role['scripting']; if (count($virtualFarmRoles) > 0) { array_walk_recursive($scripts, function (&$v, $k) use($virtualFarmRoles) { if (is_string($v)) { $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v); } }); array_walk_recursive($role['settings'], function (&$v, $k) use($virtualFarmRoles) { if (is_string($v)) { $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v); } }); } //Audit log start //!TODO Enable Audit log for Farm Builder // $auditLog = $this->getEnvironment()->auditLog; // $docRoleSettingsBefore = new FarmRoleSettingsDocument($oldRoleSettings); // $docRoleSettingsBefore['farmroleid'] = $dbFarmRole->ID; // $docRoleSettings = new FarmRoleSettingsDocument(array_merge((array)$role['scaling_settings'], (array)$role['settings'])); // $docRoleSettings['farmroleid'] = $dbFarmRole->ID; $dbFarmRole->ClearSettings("chef."); if (!empty($role['scaling_settings']) && is_array($role['scaling_settings'])) { foreach ($role['scaling_settings'] as $k => $v) { $dbFarmRole->SetSetting($k, $v, DBFarmRole::TYPE_CFG); } } foreach ($role['settings'] as $k => $v) { $dbFarmRole->SetSetting($k, $v, DBFarmRole::TYPE_CFG); } // $auditLog->log('Farm has been saved', array(AuditLogTags::TAG_UPDATE), $docRoleSettings, $docRoleSettingsBefore); // unset($docRoleSettings); // unset($docRoleSettingsBefore); //Audit log finish /****** Scaling settings ******/ $scalingManager = new Scalr_Scaling_Manager($dbFarmRole); $scalingManager->setFarmRoleMetrics(is_array($role['scaling']) ? $role['scaling'] : array()); //TODO: optimize this code... $this->db->Execute("DELETE FROM farm_role_scaling_times WHERE farm_roleid=?", array($dbFarmRole->ID)); // 5 = Time based scaling -> move to constants if ($role['scaling'][5]) { foreach ($role['scaling'][5] as $scal_period) { $chunks = explode(":", $scal_period['id']); $this->db->Execute("INSERT INTO farm_role_scaling_times SET\n farm_roleid\t\t= ?,\n start_time\t\t= ?,\n end_time\t\t= ?,\n days_of_week\t= ?,\n instances_count\t= ?\n ", array($dbFarmRole->ID, $chunks[0], $chunks[1], $chunks[2], $chunks[3])); } } /*****************/ /* Update role params */ $dbFarmRole->SetParameters((array) $role['params']); /* End of role params management */ /* Add script options to databse */ $dbFarmRole->SetScripts($scripts, (array) $role['scripting_params']); /* End of scripting section */ /* Add services configuration */ $dbFarmRole->SetServiceConfigPresets((array) $role['config_presets']); /* End of scripting section */ /* Add storage configuration */ //try { $dbFarmRole->getStorage()->setConfigs((array) $role['storages']['configs']); //} catch (FarmRoleStorageException $e) { // $errors[] = array('farm_role_id' => 1, 'tab' => 'storage', 'error' => $e->getMessage()); //} $farmRoleVariables->setValues($role['variables'], $dbFarmRole->GetRoleID(), $dbFarm->ID, $dbFarmRole->ID, '', false); Scalr_Helpers_Dns::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); foreach (Scalr_Role_Behavior::getListForFarmRole($dbFarmRole) as $behavior) { $behavior->onFarmSave($dbFarm, $dbFarmRole); } /** * Platfrom specified updates */ if ($dbFarmRole->Platform == SERVER_PLATFORMS::EC2) { Modules_Platforms_Ec2_Helpers_Ebs::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); Modules_Platforms_Ec2_Helpers_Eip::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); Modules_Platforms_Ec2_Helpers_Elb::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); } if (in_array($dbFarmRole->Platform, array(SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::CLOUDSTACK))) { Modules_Platforms_Cloudstack_Helpers_Cloudstack::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); } $dbFarmRolesList[] = $dbFarmRole; $newFarmRolesList[] = $dbFarmRole->ID; } } if (!$this->getParam('roleUpdate')) { foreach ($dbFarm->GetFarmRoles() as $dbFarmRole) { if (!$dbFarmRole->NewRoleID && !in_array($dbFarmRole->ID, $newFarmRolesList)) { $dbFarmRole->Delete(); } } } if ($usedPlatforms[SERVER_PLATFORMS::CLOUDSTACK]) { Modules_Platforms_Cloudstack_Helpers_Cloudstack::farmSave($dbFarm, $dbFarmRolesList); } if ($usedPlatforms[SERVER_PLATFORMS::EC2]) { Modules_Platforms_Ec2_Helpers_Ec2::farmSave($dbFarm, $dbFarmRolesList); } if ($usedPlatforms[SERVER_PLATFORMS::EUCALYPTUS]) { Modules_Platforms_Eucalyptus_Helpers_Eucalyptus::farmSave($dbFarm, $dbFarmRolesList); } $dbFarm->save(); if (!$client->GetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED)) { $client->SetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED, time()); } $this->response->success('Farm successfully saved'); $this->response->data(array('farmId' => $dbFarm->ID)); }
/** * {@inheritdoc} * @see AbstractEntity::save() */ public function save() { $this->changed = microtime(); $db = $this->db(); try { $db->BeginTrans(); if (empty($this->id)) { $this->ownerId = $this->changedById; $this->settings[FarmSetting::CREATED_BY_ID] = $this->ownerId; $this->settings[FarmSetting::CREATED_BY_EMAIL] = User::findPk($this->ownerId)->email; $this->added = new DateTime(); $this->status = FARM_STATUS::TERMINATED; if (empty($this->settings[FarmSetting::TIMEZONE])) { $this->settings[FarmSetting::TIMEZONE] = date_default_timezone_get(); } $this->settings[FarmSetting::CRYPTO_KEY] = \Scalr::GenerateRandomKey(40); /* @var $governance Governance */ $governance = Governance::findPk($this->envId, Governance::CATEGORY_GENERAL, Governance::GENERAL_LEASE); if (!empty($governance) && $governance->enabled) { $this->settings[FarmSetting::LEASE_STATUS] = 'Active'; } //TODO: unused field $this->region = Aws::REGION_US_EAST_1; } parent::save(); if (!empty($this->_settings)) { $this->_settings->save(); } if (isset($this->_teamsChanged)) { $this->saveTeams($this->_teams); $this->_teamsChanged = false; } $db->CommitTrans(); } catch (Exception $e) { $db->RollbackTrans(); throw $e; } }
/** * {@inheritdoc} * @see \Scalr\Model\Type\GeneratedValueTypeInterface::generateValue() */ public function generateValue($entity = null) { return \Scalr::GenerateRandomKey(40); }
/** * @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)); }
public function dashboardAction() { if (!$this->request->isAllowed(Acl::RESOURCE_FARMS_SERVERS) && !$this->request->isAllowed(Acl::RESOURCE_FARMS_ROLES, Acl::PERM_FARMS_ROLES_CREATE)) { throw new Scalr_Exception_InsufficientPermissions(); } if (!$this->getParam('serverId')) { throw new Exception(_('Server not found')); } $dbServer = DBServer::LoadByID($this->getParam('serverId')); $this->user->getPermissions()->validate($dbServer); $data = array(); $p = PlatformFactory::NewPlatform($dbServer->platform); $info = $p->GetServerExtendedInformation($dbServer); if (is_array($info) && count($info)) { $data['cloudProperties'] = $info; if ($dbServer->platform == SERVER_PLATFORMS::OPENSTACK) { $client = $p->getOsClient($this->environment, $dbServer->GetCloudLocation()); $iinfo = $client->servers->getServerDetails($dbServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::SERVER_ID)); $data['raw_server_info'] = $iinfo; } } try { $dbRole = $dbServer->GetFarmRoleObject()->GetRoleObject(); } catch (Exception $e) { } $r_dns = $this->db->GetOne("SELECT value FROM farm_role_settings WHERE farm_roleid=? AND `name`=? LIMIT 1", array($dbServer->farmRoleId, DBFarmRole::SETTING_EXCLUDE_FROM_DNS)); $conf = $this->getContainer()->config->get('scalr.load_statistics.connections.plotter'); try { if ($dbServer->farmRoleId != 0) { $hostNameFormat = $dbServer->GetFarmRoleObject()->GetSetting(Scalr_Role_Behavior::ROLE_BASE_HOSTNAME_FORMAT); $hostnameDebug = !empty($hostNameFormat) ? $dbServer->applyGlobalVarsToValue($hostNameFormat) : ''; } } catch (Exception $e) { } if ($dbServer->farmId != 0) { $hash = $dbServer->GetFarmObject()->Hash; } $data['general'] = array('server_id' => $dbServer->serverId, 'hostname_debug' => urlencode($hostnameDebug), 'hostname' => $dbServer->GetProperty(Scalr_Role_Behavior::SERVER_BASE_HOSTNAME), 'farm_id' => $dbServer->farmId, 'farm_name' => $dbServer->farmId ? $dbServer->GetFarmObject()->Name : "", 'farm_roleid' => $dbServer->farmRoleId, 'farm_hash' => $hash, 'role_id' => isset($dbRole) ? $dbRole->id : null, 'platform' => $dbServer->platform, 'cloud_location' => $dbServer->GetCloudLocation(), 'role' => array('name' => isset($dbRole) ? $dbRole->name : 'unknown', 'platform' => $dbServer->platform), 'os' => array('title' => isset($dbRole) ? $dbRole->os : 'unknown', 'family' => isset($dbRole) ? $dbRole->osFamily : 'unknown'), 'behaviors' => isset($dbRole) ? $dbRole->getBehaviors() : array(), 'status' => $dbServer->status, 'initDetailsSupported' => $dbServer->IsSupported("0.7.181"), 'index' => $dbServer->index, 'local_ip' => $dbServer->localIp, 'remote_ip' => $dbServer->remoteIp, 'instType' => PlatformFactory::NewPlatform($dbServer->platform)->GetServerFlavor($dbServer), 'addedDate' => Scalr_Util_DateTime::convertTz($dbServer->dateAdded), 'excluded_from_dns' => !$dbServer->GetProperty(SERVER_PROPERTIES::EXCLUDE_FROM_DNS) && !$r_dns ? false : true, 'is_locked' => $dbServer->GetProperty(EC2_SERVER_PROPERTIES::IS_LOCKED) ? 1 : 0, 'cloud_server_id' => $dbServer->GetCloudServerID(), 'monitoring_host_url' => "{$conf['scheme']}://{$conf['host']}:{$conf['port']}", 'debug' => $p->debugLog); $szrInitFailed = $this->db->GetOne("SELECT value FROM server_properties WHERE server_id=? AND `name`=? LIMIT 1", array($dbServer->serverId, SERVER_PROPERTIES::SZR_IS_INIT_FAILED)); if ($szrInitFailed && in_array($dbServer->status, array(SERVER_STATUS::INIT, SERVER_STATUS::PENDING))) { $data['general']['isInitFailed'] = 1; } if ($dbServer->GetProperty(SERVER_PROPERTIES::LAUNCH_ERROR)) { $data['general']['launch_error'] = 1; } if ($dbServer->status == SERVER_STATUS::RUNNING) { $rebooting = $this->db->GetOne("SELECT value FROM server_properties WHERE server_id=? AND `name`=? LIMIT 1", array($dbServer->serverId, SERVER_PROPERTIES::REBOOTING)); if ($rebooting) { $data['general']['status'] = "Rebooting"; } $subStatus = $dbServer->GetProperty(SERVER_PROPERTIES::SUB_STATUS); if ($subStatus) { $data['general']['status'] = ucfirst($subStatus); } } $status = $this->getServerStatus($dbServer, true); if ($status) { $data['scalarizr'] = $status; } $internalProperties = $dbServer->GetAllProperties(); if (!empty($internalProperties)) { $data['internalProperties'] = $internalProperties; } if (!$dbServer->IsSupported('0.5')) { $baseurl = $this->getContainer()->config('scalr.endpoint.scheme') . "://" . $this->getContainer()->config('scalr.endpoint.host'); $authKey = $dbServer->GetKey(); if (!$authKey) { $authKey = Scalr::GenerateRandomKey(40); $dbServer->SetProperty(SERVER_PROPERTIES::SZR_KEY, $authKey); } $dbServer->SetProperty(SERVER_PROPERTIES::SZR_KEY_TYPE, SZR_KEY_TYPE::PERMANENT); $data['updateAmiToScalarizr'] = sprintf("wget " . $baseurl . "/storage/scripts/amiscripts-to-scalarizr.py && python amiscripts-to-scalarizr.py -s %s -k %s -o queryenv-url=%s -o messaging_p2p.producer_url=%s", $dbServer->serverId, $authKey, $baseurl . "/query-env", $baseurl . "/messaging"); } $this->response->page('ui/servers/dashboard.js', $data, array('ui/servers/actionsmenu.js', 'ui/monitoring/window.js')); }
public function LaunchServer(DBServer $DBServer, \Scalr_Server_LaunchOptions $launchOptions = null) { $environment = $DBServer->GetEnvironmentObject(); $ccProps = $environment->keychain(SERVER_PLATFORMS::GCE)->properties; $governance = new \Scalr_Governance($environment->id); $rootDeviceSettings = null; $ssdDisks = array(); $scopes = ["https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/devstorage.full_control"]; if (!$launchOptions) { $launchOptions = new \Scalr_Server_LaunchOptions(); $DBRole = $DBServer->GetFarmRoleObject()->GetRoleObject(); $launchOptions->imageId = $DBRole->__getNewRoleObject()->getImage(\SERVER_PLATFORMS::GCE, $DBServer->GetProperty(\GCE_SERVER_PROPERTIES::CLOUD_LOCATION))->imageId; $launchOptions->serverType = $DBServer->GetFarmRoleObject()->GetSetting(Entity\FarmRoleSetting::INSTANCE_TYPE); $launchOptions->cloudLocation = $DBServer->GetFarmRoleObject()->CloudLocation; $userData = $DBServer->GetCloudUserData(); $launchOptions->architecture = 'x86_64'; $networkName = $DBServer->GetFarmRoleObject()->GetSetting(Entity\FarmRoleSetting::GCE_NETWORK); $subnet = $DBServer->GetFarmRoleObject()->GetSetting(Entity\FarmRoleSetting::GCE_SUBNET); $onHostMaintenance = $DBServer->GetFarmRoleObject()->GetSetting(Entity\FarmRoleSetting::GCE_ON_HOST_MAINTENANCE); $osType = $DBRole->getOs()->family == 'windows' ? 'windows' : 'linux'; $rootDevice = json_decode($DBServer->GetFarmRoleObject()->GetSetting(\Scalr_Role_Behavior::ROLE_BASE_ROOT_DEVICE_CONFIG), true); if ($rootDevice && $rootDevice['settings']) { $rootDeviceSettings = $rootDevice['settings']; } $storage = new FarmRoleStorage($DBServer->GetFarmRoleObject()); $volumes = $storage->getVolumesConfigs($DBServer); if (!empty($volumes)) { foreach ($volumes as $volume) { if ($volume->type == FarmRoleStorageConfig::TYPE_GCE_EPHEMERAL) { array_push($ssdDisks, $volume); } } } if ($governance->isEnabled(\Scalr_Governance::CATEGORY_GENERAL, \Scalr_Governance::GENERAL_HOSTNAME_FORMAT)) { $hostNameFormat = $governance->getValue(\Scalr_Governance::CATEGORY_GENERAL, \Scalr_Governance::GENERAL_HOSTNAME_FORMAT); } else { $hostNameFormat = $DBServer->GetFarmRoleObject()->GetSetting(\Scalr_Role_Behavior::ROLE_BASE_HOSTNAME_FORMAT); } $hostname = !empty($hostNameFormat) ? $DBServer->applyGlobalVarsToValue($hostNameFormat) : ''; if ($hostname != '') { $DBServer->SetProperty(\Scalr_Role_Behavior::SERVER_BASE_HOSTNAME, $hostname); } $userScopes = json_decode($DBServer->GetFarmRoleObject()->GetSetting(Entity\FarmRoleSetting::GCE_INSTANCE_PERMISSIONS)); if (!empty($userScopes) && is_array($userScopes)) { $scopes = array_merge($scopes, $userScopes); } } else { $userData = array(); $networkName = 'default'; $osType = 'linux'; $hostname = ''; } if (!$onHostMaintenance) { $onHostMaintenance = 'MIGRATE'; } if ($DBServer->status == \SERVER_STATUS::TEMPORARY) { $keyName = "SCALR-ROLESBUILDER-" . SCALR_ID; } else { $keyName = "FARM-{$DBServer->farmId}-" . SCALR_ID; } $sshKey = (new SshKey())->loadGlobalByName($DBServer->envId, \SERVER_PLATFORMS::GCE, "", $keyName); if (!$sshKey) { $sshKey = new SshKey(); $keys = $sshKey->generateKeypair(); if ($keys['public']) { $sshKey->farmId = $DBServer->farmId; $sshKey->envId = $DBServer->envId; $sshKey->type = SshKey::TYPE_GLOBAL; $sshKey->platform = \SERVER_PLATFORMS::GCE; $sshKey->cloudLocation = ""; $sshKey->cloudKeyName = $keyName; $sshKey->save(); $publicKey = $keys['public']; } else { throw new Exception("Scalr unable to generate ssh keypair"); } } else { $publicKey = $sshKey->publicKey; } $gce = $this->getClient($environment); $projectId = $ccProps[Entity\CloudCredentialsProperty::GCE_PROJECT_ID]; // Check firewall $firewalls = $gce->firewalls->listFirewalls($projectId); $firewallFound = false; foreach ($firewalls->getItems() as $f) { if ($f->getName() == 'scalr-system') { $firewallFound = true; break; } } // Create scalr firewall if (!$firewallFound) { $firewall = new \Google_Service_Compute_Firewall(); $firewall->setName('scalr-system'); $firewall->setNetwork($this->getObjectUrl($networkName, 'networks', $projectId)); //Get scalr IP-pool IP list and set source ranges $firewall->setSourceRanges(\Scalr::config('scalr.aws.ip_pool')); // Set ports $tcp = new \Google_Service_Compute_FirewallAllowed(); $tcp->setIPProtocol('tcp'); $tcp->setPorts(array('1-65535')); $udp = new \Google_Service_Compute_FirewallAllowed(); $udp->setIPProtocol('udp'); $udp->setPorts(array('1-65535')); $firewall->setAllowed(array($tcp, $udp)); // Set target tags $firewall->setTargetTags(array('scalr')); $gce->firewalls->insert($projectId, $firewall); } $instance = new \Google_Service_Compute_Instance(); $instance->setKind("compute#instance"); // Set scheduling $scheduling = new \Google_Service_Compute_Scheduling(); $scheduling->setAutomaticRestart(true); $scheduling->setOnHostMaintenance($onHostMaintenance); $instance->setScheduling($scheduling); $accessConfig = new \Google_Service_Compute_AccessConfig(); $accessConfig->setName("External NAT"); $accessConfig->setType("ONE_TO_ONE_NAT"); $network = new \Google_Service_Compute_NetworkInterface(); $network->setNetwork($this->getObjectUrl($networkName, 'networks', $projectId)); if (!empty($subnet)) { $network->setSubnetwork($this->getObjectUrl($subnet, 'subnetworks', $projectId, $DBServer->GetFarmRoleObject()->GetSetting(Entity\FarmRoleSetting::GCE_REGION))); } $network->setAccessConfigs(array($accessConfig)); $instance->setNetworkInterfaces(array($network)); $serviceAccount = new \Google_Service_Compute_ServiceAccount(); $serviceAccount->setEmail("default"); $serviceAccount->setScopes($scopes); $instance->setServiceAccounts(array($serviceAccount)); if ($launchOptions->cloudLocation != 'x-scalr-custom') { $availZone = $launchOptions->cloudLocation; } else { $location = $DBServer->GetFarmRoleObject()->GetSetting(Entity\FarmRoleSetting::GCE_CLOUD_LOCATION); $availZones = array(); if (stristr($location, "x-scalr-custom")) { $zones = explode("=", $location); foreach (explode(":", $zones[1]) as $zone) { if ($zone != "") { array_push($availZones, $zone); } } } sort($availZones); $availZones = array_reverse($availZones); $servers = $DBServer->GetFarmRoleObject()->GetServersByFilter(array("status" => array(\SERVER_STATUS::RUNNING, \SERVER_STATUS::INIT, \SERVER_STATUS::PENDING))); $availZoneDistribution = array(); foreach ($servers as $cDbServer) { if ($cDbServer->serverId != $DBServer->serverId) { $availZoneDistribution[$cDbServer->GetProperty(\GCE_SERVER_PROPERTIES::CLOUD_LOCATION)]++; } } $sCount = 1000000; foreach ($availZones as $zone) { if ((int) $availZoneDistribution[$zone] <= $sCount) { $sCount = (int) $availZoneDistribution[$zone]; $availZone = $zone; } } $aZones = implode(",", $availZones); // Available zones $dZones = ""; // Zones distribution foreach ($availZoneDistribution as $zone => $num) { $dZones .= "({$zone}:{$num})"; } } $instance->setZone($this->getObjectUrl($availZone, 'zones', $projectId)); $instance->setMachineType($this->getObjectUrl($launchOptions->serverType, 'machineTypes', $projectId, $availZone)); //Create root disk $image = $this->getObjectUrl($launchOptions->imageId, 'images', $projectId); $disks = array(); $diskName = "root-{$DBServer->serverId}"; $initializeParams = new \Google_Service_Compute_AttachedDiskInitializeParams(); $initializeParams->sourceImage = $image; $initializeParams->diskName = $diskName; if ($rootDeviceSettings) { $initializeParams->diskType = $this->getObjectUrl($rootDeviceSettings[FarmRoleStorageConfig::SETTING_GCE_PD_TYPE] ? $rootDeviceSettings[FarmRoleStorageConfig::SETTING_GCE_PD_TYPE] : 'pd-standard', 'diskTypes', $projectId, $availZone); $initializeParams->diskSizeGb = $rootDeviceSettings[FarmRoleStorageConfig::SETTING_GCE_PD_SIZE]; } $attachedDisk = new \Google_Service_Compute_AttachedDisk(); $attachedDisk->setKind("compute#attachedDisk"); $attachedDisk->setBoot(true); $attachedDisk->setMode("READ_WRITE"); $attachedDisk->setType("PERSISTENT"); $attachedDisk->setDeviceName("root"); $attachedDisk->setAutoDelete(true); $attachedDisk->setInitializeParams($initializeParams); array_push($disks, $attachedDisk); if (count($ssdDisks) > 0) { foreach ($ssdDisks as $disk) { $attachedDisk = new \Google_Service_Compute_AttachedDisk(); $attachedDisk->setKind("compute#attachedDisk"); $attachedDisk->setBoot(false); $attachedDisk->setMode("READ_WRITE"); $attachedDisk->setType("SCRATCH"); $attachedDisk->setDeviceName(str_replace("google-", "", $disk->name)); $attachedDisk->setInterface('SCSI'); $attachedDisk->setAutoDelete(true); $initializeParams = new \Google_Service_Compute_AttachedDiskInitializeParams(); $initializeParams->diskType = $this->getObjectUrl('local-ssd', 'diskTypes', $projectId, $availZone); $attachedDisk->setInitializeParams($initializeParams); array_push($disks, $attachedDisk); } } $instance->setDisks($disks); $instance->setName($DBServer->serverId); $tags = array('scalr', "env-{$DBServer->envId}"); if ($DBServer->farmId) { $tags[] = "farm-{$DBServer->farmId}"; } if ($DBServer->farmRoleId) { $tags[] = "farmrole-{$DBServer->farmRoleId}"; } $gTags = new \Google_Service_Compute_Tags(); $gTags->setItems($tags); $instance->setTags($gTags); $metadata = new \Google_Service_Compute_Metadata(); $items = array(); // Set user data $uData = ''; foreach ($userData as $k => $v) { $uData .= "{$k}={$v};"; } $uData = trim($uData, ";"); if ($uData) { $item = new \Google_Service_Compute_MetadataItems(); $item->setKey('scalr'); $item->setValue($uData); $items[] = $item; } if ($osType == 'windows') { // Add Windows credentials $item = new \Google_Service_Compute_MetadataItems(); $item->setKey("gce-initial-windows-user"); $item->setValue("scalr"); $items[] = $item; $item = new \Google_Service_Compute_MetadataItems(); $item->setKey("gce-initial-windows-password"); $item->setValue(\Scalr::GenerateRandomKey(16) . rand(0, 9)); $items[] = $item; } else { // Add SSH Key $item = new \Google_Service_Compute_MetadataItems(); $item->setKey("sshKeys"); $item->setValue("scalr:{$publicKey}"); $items[] = $item; } //Set hostname if ($hostname != '') { $item = new \Google_Service_Compute_MetadataItems(); $item->setKey("hostname"); $item->setValue($hostname); $items[] = $item; } $metadata->setItems($items); $instance->setMetadata($metadata); try { $result = $gce->instances->insert($projectId, $availZone, $instance); } catch (Exception $e) { $json = json_decode($e->getMessage()); if (!empty($json->error->message)) { $message = $json->error->message; } else { $message = $e->getMessage(); } throw new Exception(sprintf(_("Cannot launch new instance. %s (%s, %s)"), $message, $image, $launchOptions->serverType)); } if ($result->id) { $instanceTypeInfo = $this->getInstanceType($launchOptions->serverType, $environment, $availZone); /* @var $instanceTypeInfo CloudInstanceType */ $DBServer->SetProperties([\GCE_SERVER_PROPERTIES::PROVISIONING_OP_ID => $result->name, \GCE_SERVER_PROPERTIES::SERVER_NAME => $DBServer->serverId, \GCE_SERVER_PROPERTIES::CLOUD_LOCATION => $availZone, \GCE_SERVER_PROPERTIES::CLOUD_LOCATION_ZONE => $availZone, \SERVER_PROPERTIES::ARCHITECTURE => $launchOptions->architecture, 'debug.region' => $result->region, 'debug.zone' => $result->zone, \SERVER_PROPERTIES::INFO_INSTANCE_VCPUS => $instanceTypeInfo ? $instanceTypeInfo->vcpus : null]); $DBServer->setOsType($osType); $DBServer->cloudLocation = $availZone; $DBServer->cloudLocationZone = $availZone; $DBServer->imageId = $launchOptions->imageId; $DBServer->update(['type' => $launchOptions->serverType, 'instanceTypeName' => $launchOptions->serverType]); // we set server history here $DBServer->getServerHistory()->update(['cloudServerId' => $DBServer->serverId]); return $DBServer; } else { throw new Exception(sprintf(_("Cannot launch new instance. %s (%s, %s)"), serialize($result), $launchOptions->imageId, $launchOptions->serverType)); } }
/** * {@inheritdoc} * @see \Scalr\Modules\PlatformModuleInterface::LaunchServer() */ public function LaunchServer(DBServer $DBServer, \Scalr_Server_LaunchOptions $launchOptions = null) { $config = \Scalr::getContainer()->config; $environment = $DBServer->GetEnvironmentObject(); $governance = new \Scalr_Governance($environment->id); if (!$launchOptions) { $launchOptions = new \Scalr_Server_LaunchOptions(); $DBRole = $DBServer->GetFarmRoleObject()->GetRoleObject(); $launchOptions->imageId = $DBRole->__getNewRoleObject()->getImage($this->platform, $DBServer->GetCloudLocation())->imageId; $launchOptions->serverType = $DBServer->GetFarmRoleObject()->GetSetting(Entity\FarmRoleSetting::INSTANCE_TYPE); $launchOptions->cloudLocation = $DBServer->GetFarmRoleObject()->CloudLocation; $launchOptions->userData = $DBServer->GetCloudUserData(); $launchOptions->userData['region'] = $launchOptions->cloudLocation; $launchOptions->userData['vzc.adminpassword'] = \Scalr::GenerateRandomKey(20); $launchOptions->userData['platform'] = \SERVER_PLATFORMS::VERIZON; // Apply tags $launchOptions->userData = array_merge($DBServer->getOpenstackTags(), $launchOptions->userData); $launchOptions->networks = @json_decode($DBServer->GetFarmRoleObject()->GetSetting(Entity\FarmRoleSetting::OPENSTACK_NETWORKS)); $gevernanceNetworks = $governance->getValue($this->platform, 'openstack.networks'); if (count($launchOptions->networks) == 0 && $gevernanceNetworks) { $launchOptions->networks = $gevernanceNetworks[$launchOptions->cloudLocation]; } foreach ($launchOptions->userData as $k => $v) { if (!$v) { unset($launchOptions->userData[$k]); } } $launchOptions->architecture = 'x86_64'; $isWindows = $DBServer->osType == 'windows' || $DBRole->getOs()->family == 'windows'; $customUserData = $DBServer->GetFarmRoleObject()->GetSetting('base.custom_user_data'); $serverNameFormat = $governance->getValue($DBServer->platform, \Scalr_Governance::OPENSTACK_INSTANCE_NAME_FORMAT); if (!$serverNameFormat) { $serverNameFormat = $DBServer->GetFarmRoleObject()->GetSetting(\Scalr_Role_Behavior::ROLE_INSTANCE_NAME_FORMAT); } } else { $launchOptions->userData = array(); $customUserData = false; if (!$launchOptions->networks) { $launchOptions->networks = array(); } $isWindows = $DBServer->osType == 'windows'; } $client = $this->getOsClient($environment, $launchOptions->cloudLocation); // Prepare user data $u_data = ""; foreach ($launchOptions->userData as $k => $v) { $u_data .= "{$k}={$v};"; } $u_data = trim($u_data, ";"); if ($customUserData) { $repos = $DBServer->getScalarizrRepository(); $extProperties["user_data"] = base64_encode(str_replace(array('{SCALR_USER_DATA}', '{RPM_REPO_URL}', '{DEB_REPO_URL}'), array($u_data, $repos['rpm_repo_url'], $repos['deb_repo_url']), $customUserData)); } $personality = new PersonalityList(); if ($isWindows) { $personality->append(new Personality('C:\\Program Files\\Scalarizr\\etc\\private.d\\.user-data', base64_encode($u_data))); } else { $personality->append(new Personality('/etc/scalr/private.d/.user-data', base64_encode($u_data))); } //TODO: newtorks $networks = new NetworkList(); foreach ((array) $launchOptions->networks as $network) { if ($network) { $networks->append(new Network($network)); } } //$osUserData = null; $osPersonality = null; $userDataMethod = 'meta-data'; $osPersonality = null; $userDataMethod = $config->defined("scalr.{$this->platform}.user_data_method") ? $config("scalr.{$this->platform}.user_data_method") : null; if (!$userDataMethod || $userDataMethod == 'both' || $userDataMethod == 'personality') { $osPersonality = $personality; } if (!$userDataMethod || $userDataMethod == 'both' || $userDataMethod == 'meta-data' || $isWindows) { $osUserData = $launchOptions->userData; } $serverName = $serverNameFormat ? $DBServer->applyGlobalVarsToValue($serverNameFormat) : $DBServer->serverId; try { $result = $client->servers->createServer($serverName, $launchOptions->serverType, $launchOptions->imageId, null, $osUserData, $osPersonality, $networks, $extProperties); $instanceTypeInfo = $this->getInstanceType($launchOptions->serverType, $environment, $launchOptions->cloudLocation); /* @var $instanceTypeInfo CloudInstanceType */ $DBServer->SetProperties([\OPENSTACK_SERVER_PROPERTIES::SERVER_ID => $result->id, \OPENSTACK_SERVER_PROPERTIES::IMAGE_ID => $launchOptions->imageId, \OPENSTACK_SERVER_PROPERTIES::ADMIN_PASS => $launchOptions->userData['vzc.adminpassword'] ? $launchOptions->userData['vzc.adminpassword'] : $result->adminPass, \OPENSTACK_SERVER_PROPERTIES::NAME => $DBServer->serverId, \SERVER_PROPERTIES::ARCHITECTURE => $launchOptions->architecture, \OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION => $launchOptions->cloudLocation, \SERVER_PROPERTIES::SYSTEM_USER_DATA_METHOD => $userDataMethod, \SERVER_PROPERTIES::INFO_INSTANCE_VCPUS => $instanceTypeInfo ? $instanceTypeInfo->vcpus : null]); if ($DBServer->farmRoleId) { $ipPool = $DBServer->GetFarmRoleObject()->GetSetting(Entity\FarmRoleSetting::OPENSTACK_IP_POOL); if ($ipPool) { $DBServer->SetProperty(\SERVER_PROPERTIES::SYSTEM_IGNORE_INBOUND_MESSAGES, 1); } } $params = ['type' => $launchOptions->serverType]; if ($instanceTypeInfo) { $params['instanceTypeName'] = $instanceTypeInfo->name; } $DBServer->setOsType($isWindows ? 'windows' : 'linux'); $DBServer->cloudLocation = $launchOptions->cloudLocation; $DBServer->cloudLocationZone = ""; // Not supported by openstack $DBServer->imageId = $launchOptions->imageId; $DBServer->update($params); // we set server history here $DBServer->getServerHistory()->update(['cloudServerId' => $result->id]); return $DBServer; } catch (\Exception $e) { throw new \Exception(sprintf(_("Cannot launch new instance. %s"), $e->getMessage())); } }
public function getSwiftSignerUrl($path, $platform, $cloudLocation) { $expires = time() + 3600; $method = 'GET'; $rs = $this->environment->openstack($platform, $cloudLocation); $basePath = $rs->swift->getEndpointUrl(); $objectPath = explode("/v1/", $basePath); $stringToSign = "{$method}\n{$expires}\n/v1/{$objectPath[1]}/{$path}"; $response = $rs->swift->describeService(); $key = $response->getHeader('X-Account-Meta-Temp-Url-Key'); if (!$key) { $key = Scalr::GenerateRandomKey(32); $rs->swift->updateService(array('_headers' => array('X-Account-Meta-Temp-URL-Key' => $key))); } $signature = urlencode(hash_hmac("sha1", utf8_encode($stringToSign), $key)); return "{$basePath}/{$path}?temp_url_sig={$signature}&temp_url_expires={$expires}"; }
public function xBuildAction() { $this->request->restrictAccess(Acl::RESOURCE_FARMS_ROLES, Acl::PERM_FARMS_ROLES_CREATE); $this->request->defineParams(array('platform' => array('type' => 'string'), 'architecture' => array('type' => 'string'), 'behaviors' => array('type' => 'json'), 'roleName' => array('type' => 'string'), 'imageId' => array('type' => 'string'), 'location' => array('type' => 'string'), 'advanced' => array('type' => 'json'), 'chef' => array('type' => 'json'))); if (strlen($this->getParam('roleName')) < 3) { throw new Exception(_("Role name should be greater than 3 chars")); } if (!preg_match("/^[A-Za-z0-9-]+\$/si", $this->getParam('roleName'))) { throw new Exception(_("Role name is incorrect")); } $chkRoleId = $this->db->GetOne("SELECT id FROM roles WHERE name=? AND (env_id = '0' OR env_id = ?) LIMIT 1", array($this->getParam('roleName'), $this->getEnvironmentId())); if ($chkRoleId) { if (!$this->db->GetOne("SELECT id FROM roles_queue WHERE role_id=? LIMIT 1", array($chkRoleId))) { throw new Exception('Selected role name is already used. Please select another one.'); } } $imageId = $this->getParam('imageId'); $advanced = $this->getParam('advanced'); $chef = $this->getParam('chef'); $behaviours = implode(",", array_values($this->getParam('behaviors'))); // Create server $creInfo = new ServerCreateInfo($this->getParam('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 => $this->getParam('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->save(); //Launch server $launchOptions = new Scalr_Server_LaunchOptions(); $launchOptions->imageId = $imageId; $launchOptions->cloudLocation = $this->getParam('cloud_location'); $launchOptions->architecture = $this->getParam('architecture'); $platform = PlatformFactory::NewPlatform($this->getParam('platform')); switch ($this->getParam('platform')) { case SERVER_PLATFORMS::ECS: $launchOptions->serverType = 10; break; case SERVER_PLATFORMS::IDCF: $launchOptions->serverType = 24; break; case SERVER_PLATFORMS::RACKSPACE: if ($this->getParam('osfamily') == '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 ($this->getParam('hvm') == 1) { $launchOptions->serverType = 'm3.xlarge'; $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM; } else { if ($this->getParam('osfamily') == 'oel') { $launchOptions->serverType = 'm1.large'; $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM; } elseif ($this->getParam('osfamily') == 'rhel') { $launchOptions->serverType = 'm1.large'; $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM; } elseif ($this->getParam('osfamily') == 'scientific') { $launchOptions->serverType = 'm1.large'; $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM; } else { $launchOptions->serverType = 'm1.small'; } } $launchOptions->userData = "#cloud-config\ndisable_root: false"; break; case SERVER_PLATFORMS::GCE: $launchOptions->serverType = 'n1-standard-1'; $locations = array_keys($platform->getLocations()); $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, $this->getParam('roleName'), 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 = $this->getParam('osfamily'); $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 { $platform->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)); }
private function saveGroupRulesAzure($platform, $cloudLocation, $groupData, $rules, $action, $extraParams) { $azure = $this->environment->azure(); foreach ($rules['rules'] as $rule) { if ($action == 'add') { $createSecurityRule = new CreateSecurityRule($rule['ipProtocol'] == '*' ? $rule['ipProtocol'] : ucfirst($rule['ipProtocol']), '*', $rule['fromPort'] == $rule['toPort'] ? $rule['fromPort'] : $rule['fromPort'] . '-' . $rule['toPort'], $rule['cidrIp'], '*', 'Allow', $rule['priority'], SecurityRuleProperties::DIRECTION_INBOUND, $rule['comment']); $azure->network->securityRule->create($this->environment->cloudCredentials(SERVER_PLATFORMS::AZURE)->properties[Entity\CloudCredentialsProperty::AZURE_SUBSCRIPTION_ID], $extraParams['resourceGroup'], $groupData['id'], 'scalr-' . \Scalr::GenerateRandomKey(20), $createSecurityRule); } else { $azure->network->securityRule->delete($this->environment->cloudCredentials(SERVER_PLATFORMS::AZURE)->properties[Entity\CloudCredentialsProperty::AZURE_SUBSCRIPTION_ID], $extraParams['resourceGroup'], $groupData['id'], $rule['id']); } } }
public function dashboardAction() { if (!$this->request->isAllowed(Acl::RESOURCE_FARMS_SERVERS) && !$this->request->isAllowed(Acl::RESOURCE_FARMS_ROLES, Acl::PERM_FARMS_ROLES_CREATE)) { throw new Scalr_Exception_InsufficientPermissions(); } if (!$this->getParam('serverId')) { throw new Exception(_('Server not found')); } $dbServer = DBServer::LoadByID($this->getParam('serverId')); $this->user->getPermissions()->validate($dbServer); $data = array(); $info = PlatformFactory::NewPlatform($dbServer->platform)->GetServerExtendedInformation($dbServer); if (is_array($info) && count($info)) { $data['cloudProperties'] = $info; } try { $dbRole = $dbServer->GetFarmRoleObject()->GetRoleObject(); } catch (Exception $e) { } $r_dns = $this->db->GetOne("SELECT value FROM farm_role_settings WHERE farm_roleid=? AND `name`=? LIMIT 1", array($dbServer->farmRoleId, DBFarmRole::SETTING_EXCLUDE_FROM_DNS)); $data['general'] = array('server_id' => $dbServer->serverId, 'farm_id' => $dbServer->farmId, 'farm_role_id' => $dbServer->farmRoleId, 'role_id' => isset($dbRole) ? $dbRole->id : null, 'platform' => $dbServer->platform, 'cloud_location' => $dbServer->GetCloudLocation(), 'role' => array('name' => isset($dbRole) ? $dbRole->name : 'unknown', 'platform' => $dbServer->platform), 'os' => array('title' => isset($dbRole) ? $dbRole->os : 'unknown', 'family' => isset($dbRole) ? $dbRole->osFamily : 'unknown'), 'behaviors' => isset($dbRole) ? $dbRole->getBehaviors() : array(), 'status' => $dbServer->status, 'index' => $dbServer->index, 'local_ip' => $dbServer->localIp, 'remote_ip' => $dbServer->remoteIp, 'instType' => PlatformFactory::NewPlatform($dbServer->platform)->GetServerFlavor($dbServer), 'addedDate' => Scalr_Util_DateTime::convertTz($dbServer->dateAdded), 'excluded_from_dns' => !$dbServer->GetProperty(SERVER_PROPERTIES::EXCLUDE_FROM_DNS) && !$r_dns ? false : true, 'is_locked' => $dbServer->GetProperty(EC2_SERVER_PROPERTIES::IS_LOCKED) ? 1 : 0, 'cloud_server_id' => $dbServer->GetCloudServerID()); if ($dbServer->status == SERVER_STATUS::RUNNING) { $rebooting = $this->db->GetOne("SELECT value FROM server_properties WHERE server_id=? AND `name`=? LIMIT 1", array($dbServer->serverId, SERVER_PROPERTIES::REBOOTING)); if ($rebooting) { $data['general']['status'] = "Rebooting"; } $subStatus = $dbServer->GetProperty(SERVER_PROPERTIES::SUB_STATUS); if ($subStatus) { $data['general']['status'] = ucfirst($subStatus); } } if ($dbServer->status == SERVER_STATUS::RUNNING && $dbServer->GetProperty(SERVER_PROPERTIES::SUB_STATUS) != 'stopped' && ($dbServer->IsSupported('0.8') && $dbServer->osType == 'linux' || $dbServer->IsSupported('0.19') && $dbServer->osType == 'windows')) { try { $port = $dbServer->GetProperty(SERVER_PROPERTIES::SZR_UPDC_PORT); if (!$port) { $port = 8008; } $updateClient = new Scalr_Net_Scalarizr_UpdateClient($dbServer, $port, \Scalr::config('scalr.system.instances_connection_timeout')); $scalarizr = $updateClient->getStatus(); } catch (Exception $e) { $oldUpdClient = stristr($e->getMessage(), "Method not found"); $error = $e->getMessage(); } if ($scalarizr) { $data['scalarizr'] = array('status' => $scalarizr->service_status, 'version' => $scalarizr->installed, 'candidate' => $scalarizr->candidate, 'repository' => ucfirst($scalarizr->repository), 'lastUpdate' => array('date' => $scalarizr->executed_at ? Scalr_Util_DateTime::convertTz($scalarizr->executed_at) : "", 'error' => nl2br($scalarizr->error)), 'nextUpdate' => $scalarizr->installed != $scalarizr->candidate ? "Update to <b>{$scalarizr->candidate}</b> scheduled on <b>" . Scalr_Util_DateTime::convertTz($scalarizr->scheduled_on) . "</b>" : "Scalarizr is up to date", 'fullInfo' => $scalarizr); } else { if ($oldUpdClient) { $data['scalarizr'] = array('status' => 'upgradeUpdClient'); } else { $data['scalarizr'] = array('status' => 'statusNotAvailable', 'error' => "<span style='color:red;'>Scalarizr status is not available: {$error}</span>"); } } } $internalProperties = $dbServer->GetAllProperties(); if (!empty($internalProperties)) { $data['internalProperties'] = $internalProperties; } if (!$dbServer->IsSupported('0.5')) { $baseurl = $this->getContainer()->config('scalr.endpoint.scheme') . "://" . $this->getContainer()->config('scalr.endpoint.host'); $authKey = $dbServer->GetKey(); if (!$authKey) { $authKey = Scalr::GenerateRandomKey(40); $dbServer->SetProperty(SERVER_PROPERTIES::SZR_KEY, $authKey); } $dbServer->SetProperty(SERVER_PROPERTIES::SZR_KEY_TYPE, SZR_KEY_TYPE::PERMANENT); $data['updateAmiToScalarizr'] = sprintf("wget " . $baseurl . "/storage/scripts/amiscripts-to-scalarizr.py && python amiscripts-to-scalarizr.py -s %s -k %s -o queryenv-url=%s -o messaging_p2p.producer_url=%s", $dbServer->serverId, $authKey, $baseurl . "/query-env", $baseurl . "/messaging"); } $this->response->page('ui/servers/dashboard.js', $data, array('ui/servers/actionsmenu.js', 'ui/monitoring/window.js')); }
public function xBuildAction() { $this->request->defineParams(array('farmId' => array('type' => 'int'), 'roles' => array('type' => 'json'), 'farm' => array('type' => 'json'), 'roleUpdate' => array('type' => 'int'))); $Validator = new Validator(); $cloudFoundryStack = array(); $nginxFound = 0; foreach ($this->getParam('roles') as $role) { $dbRole = DBRole::loadById($role['role_id']); if (!$dbRole->getImageId($role['platform'], $role['cloud_location'])) { throw new Exception(sprintf(_("Role '%s' is not available in %s on %s"), $dbRole->name, $role['platform'], $role['cloud_location'])); } // Validate deployments $appId = $role[Scalr_Role_Behavior::ROLE_DM_APPLICATION_ID]; if ($appId) { $application = Scalr_Dm_Application::init()->loadById($appId); $this->user->getPermissions()->validate($application); if (!$role[Scalr_Role_Behavior::ROLE_DM_REMOTE_PATH]) { throw new Exception(sprintf("Remote path reuired for deployment on role '%s'", $dbRole->name)); } } //-- CloudFoundryStuff if ($dbRole->hasBehavior(ROLE_BEHAVIORS::CF_CLOUD_CONTROLLER)) { $cloudFoundryStack[ROLE_BEHAVIORS::CF_CLOUD_CONTROLLER] = true; } if ($dbRole->hasBehavior(ROLE_BEHAVIORS::CF_DEA)) { $cloudFoundryStack[ROLE_BEHAVIORS::CF_DEA] = true; } if ($dbRole->hasBehavior(ROLE_BEHAVIORS::CF_HEALTH_MANAGER)) { $cloudFoundryStack[ROLE_BEHAVIORS::CF_HEALTH_MANAGER] = true; } if ($dbRole->hasBehavior(ROLE_BEHAVIORS::CF_ROUTER)) { $cloudFoundryStack[ROLE_BEHAVIORS::CF_ROUTER] = true; } if ($dbRole->hasBehavior(ROLE_BEHAVIORS::CF_SERVICE)) { $cloudFoundryStack[ROLE_BEHAVIORS::CF_SERVICE] = true; } if ($dbRole->hasBehavior(ROLE_BEHAVIORS::NGINX)) { $nginxFound++; } //-- End CloudFoundry stuff if ($dbRole->hasBehavior(ROLE_BEHAVIORS::RABBITMQ)) { $role['settings'][DBFarmRole::SETTING_SCALING_MAX_INSTANCES] = $role['settings'][DBFarmRole::SETTING_SCALING_MIN_INSTANCES]; $role['settings'][Scalr_Role_Behavior_RabbitMQ::ROLE_NODES_RATIO] = (int) $role['settings'][Scalr_Role_Behavior_RabbitMQ::ROLE_NODES_RATIO]; if ($role['settings'][Scalr_Role_Behavior_RabbitMQ::ROLE_NODES_RATIO] < 1 || $role['settings'][Scalr_Role_Behavior_RabbitMQ::ROLE_NODES_RATIO] > 100) { throw new Exception(sprintf("Nodes ratio for RabbitMq role '%s' should be between 1 and 100", $dbRole->name)); } } if ($dbRole->hasBehavior(ROLE_BEHAVIORS::MONGODB)) { if ($role['settings'][Scalr_Role_Behavior_MongoDB::ROLE_DATA_STORAGE_ENGINE] == 'ebs') { if ($role['settings'][Scalr_Role_Behavior_MongoDB::ROLE_DATA_STORAGE_EBS_SIZE] < 10 || $role['settings'][Scalr_Role_Behavior_MongoDB::ROLE_DATA_STORAGE_EBS_SIZE] > 1000) { throw new Exception(sprintf("EBS size for mongoDB role should be between 10 and 1000 GB", $dbRole->name)); } } } /* Validate scaling */ $minCount = (int) $role['settings'][DBFarmRole::SETTING_SCALING_MIN_INSTANCES]; if (!$minCount && $minCount != 0) { $minCount = 1; } if ($minCount < 0 || $minCount > 400) { throw new Exception(sprintf(_("Min instances for '%s' must be a number between 1 and 400"), $dbRole->name)); } $maxCount = (int) $role['settings'][DBFarmRole::SETTING_SCALING_MAX_INSTANCES]; if (!$maxCount) { $maxCount = 1; } if ($maxCount < 1 || $maxCount > 400) { throw new Exception(sprintf(_("Max instances for '%s' must be a number between 1 and 400"), $dbRole->name)); } if ($maxCount < $minCount) { throw new Exception(sprintf(_("Max instances should be greater or equal than Min instances for role '%s'"), $dbRole->name)); } if (isset($role['settings'][DBFarmRole::SETTING_SCALING_POLLING_INTERVAL]) && $role['settings'][DBFarmRole::SETTING_SCALING_POLLING_INTERVAL] > 0) { $polling_interval = (int) $role['settings'][DBFarmRole::SETTING_SCALING_POLLING_INTERVAL]; } else { $polling_interval = 2; } if ($polling_interval < 1 || $polling_interval > 50) { throw new Exception(sprintf(_("Polling interval for role '%s' must be a number between 1 and 50"), $dbRole->name)); } /** Validate platform specified settings **/ switch ($role['platform']) { case SERVER_PLATFORMS::EC2: Modules_Platforms_Ec2_Helpers_Ebs::farmValidateRoleSettings($role['settings'], $dbRole->name); Modules_Platforms_Ec2_Helpers_Eip::farmValidateRoleSettings($role['settings'], $dbRole->name); Modules_Platforms_Ec2_Helpers_Elb::farmValidateRoleSettings($role['settings'], $dbRole->name); if ($dbRole->hasBehavior(ROLE_BEHAVIORS::MYSQL)) { if ($role['settings'][DBFarmRole::SETTING_MYSQL_DATA_STORAGE_ENGINE] == MYSQL_STORAGE_ENGINE::EBS) { if ($dbRole->generation != 2) { if ($role['settings'][DBFarmRole::SETTING_AWS_AVAIL_ZONE] == "" || $role['settings'][DBFarmRole::SETTING_AWS_AVAIL_ZONE] == "x-scalr-diff" || stristr($role['settings'][DBFarmRole::SETTING_AWS_AVAIL_ZONE], 'x-scalr-custom')) { throw new Exception(sprintf(_("Requirement for EBS MySQL data storage is specific 'Placement' parameter for role '%s'"), $dbRole->name)); } } } } if ($dbRole->getDbMsrBehavior()) { if ($role['settings'][Scalr_Db_Msr::DATA_STORAGE_ENGINE] == MYSQL_STORAGE_ENGINE::EPH) { if (!$role['settings'][Scalr_Db_Msr::DATA_STORAGE_EPH_DISK]) { throw new Exception(sprintf(_("Ephemeral disk settings is required for role '%s'"), $dbRole->name)); } } } if ($role['settings'][DBFarmRole::SETTING_AWS_AVAIL_ZONE] == 'x-scalr-custom=') { throw new Exception(sprintf(_("Availability zone for role \"%s\" should be selected"), $dbRole->name)); } break; case SERVER_PLATFORMS::RDS: Modules_Platforms_Rds_Helpers_Rds::farmValidateRoleSettings($role['settings'], $dbRole->name); break; case SERVER_PLATFORMS::EUCALYPTUS: Modules_Platforms_Eucalyptus_Helpers_Eucalyptus::farmValidateRoleSettings($role['settings'], $dbRole->name); break; case SERVER_PLATFORMS::CLOUDSTACK: Modules_Platforms_Cloudstack_Helpers_Cloudstack::farmValidateRoleSettings($role['settings'], $dbRole->name); break; case SERVER_PLATFORMS::RACKSPACE: Modules_Platforms_Rackspace_Helpers_Rackspace::farmValidateRoleSettings($role['settings'], $dbRole->name); break; } Scalr_Helpers_Dns::farmValidateRoleSettings($role['settings'], $dbRole->name); } //Validate ClouFoundry stuff if (!empty($cloudFoundryStack)) { if (!$cloudFoundryStack[ROLE_BEHAVIORS::CF_CLOUD_CONTROLLER]) { throw new Exception("CF CloudContoller role required for CloudFoundry stack. Please add All-in-one CF or separate CCHM role to farm"); } if (!$cloudFoundryStack[ROLE_BEHAVIORS::CF_HEALTH_MANAGER]) { throw new Exception("CF HealthManager role required for CloudFoundry stack. Please add All-in-one CF or separate CCHM role to farm"); } if (!$cloudFoundryStack[ROLE_BEHAVIORS::CF_ROUTER]) { throw new Exception("CF Router role required for CloudFoundry stack. Please add All-in-one CF or separate CF Router role to farm"); } if (!$cloudFoundryStack[ROLE_BEHAVIORS::CF_DEA]) { throw new Exception("CF DEA role required for CloudFoundry stack. Please add All-in-one CF or separate CF DEA role to farm"); } if (!$nginxFound) { throw new Exception("Nginx load balancer role required for CloudFoundry stack. Please add it to the farm"); } if ($cloudFoundryStack[ROLE_BEHAVIORS::CF_CLOUD_CONTROLLER] > 1) { throw new Exception("CloudFoundry stack can work only with ONE CF CloudController role. Please leave only one CloudController role in farm"); } if ($cloudFoundryStack[ROLE_BEHAVIORS::CF_HEALTH_MANAGER] > 1) { throw new Exception("CloudFoundry stack can work only with ONE CF HealthManager role. Please leave only one HealthManager role in farm"); } if ($nginxFound > 1) { throw new Exception("CloudFoundry stack can work only with ONE nginx role. Please leave only one nginx role in farm"); } } $client = Client::Load($this->user->getAccountId()); if ($this->getParam('farmId')) { $dbFarm = DBFarm::LoadByID($this->getParam('farmId')); $this->user->getPermissions()->validate($dbFarm); } else { $this->user->getAccount()->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1); $dbFarm = new DBFarm(); $dbFarm->Status = FARM_STATUS::TERMINATED; } if ($this->getParam('farm')) { $farm = $this->getParam('farm'); $dbFarm->Name = strip_tags($farm['name']); $dbFarm->RolesLaunchOrder = $farm['roles_launch_order']; $dbFarm->Comments = trim(strip_tags($farm['description'])); } if (!$Validator->IsNotEmpty($dbFarm->Name)) { throw new Exception(_("Farm name required")); } $dbFarm->save(); if (!$dbFarm->GetSetting(DBFarm::SETTING_CRYPTO_KEY)) { $dbFarm->SetSetting(DBFarm::SETTING_CRYPTO_KEY, Scalr::GenerateRandomKey(40)); } $usedPlatforms = array(); $dbFarmRolesList = array(); $newFarmRolesList = array(); foreach ($this->getParam('roles') as $role) { if ($role['farm_role_id']) { $update = true; $dbFarmRole = DBFarmRole::LoadByID($role['farm_role_id']); $dbRole = DBRole::loadById($dbFarmRole->RoleID); $role['role_id'] = $dbFarmRole->RoleID; } else { $update = false; $dbRole = DBRole::loadById($role['role_id']); $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index']); } if ($dbRole->hasBehavior(ROLE_BEHAVIORS::RABBITMQ)) { $role['settings'][DBFarmRole::SETTING_SCALING_MAX_INSTANCES] = $role['settings'][DBFarmRole::SETTING_SCALING_MIN_INSTANCES]; } if ($dbFarmRole->NewRoleID) { continue; } if ($update) { $dbFarmRole->LaunchIndex = (int) $role['launch_index']; $dbFarmRole->Save(); } $usedPlatforms[$role['platform']] = 1; $oldRoleSettings = $dbFarmRole->GetAllSettings(); foreach ($role['scaling_settings'] as $k => $v) { $dbFarmRole->SetSetting($k, $v); } foreach ($role['settings'] as $k => $v) { $dbFarmRole->SetSetting($k, $v); } /****** Scaling settings ******/ $scalingManager = new Scalr_Scaling_Manager($dbFarmRole); $scalingManager->setFarmRoleMetrics($role['scaling']); //TODO: optimize this code... $this->db->Execute("DELETE FROM farm_role_scaling_times WHERE farm_roleid=?", array($dbFarmRole->ID)); // 5 = Time based scaling -> move to constants if ($role['scaling'][5]) { foreach ($role['scaling'][5] as $scal_period) { $chunks = explode(":", $scal_period['id']); $this->db->Execute("INSERT INTO farm_role_scaling_times SET\n\t\t\t\t\t\tfarm_roleid\t\t= ?,\n\t\t\t\t\t\tstart_time\t\t= ?,\n\t\t\t\t\t\tend_time\t\t= ?,\n\t\t\t\t\t\tdays_of_week\t= ?,\n\t\t\t\t\t\tinstances_count\t= ?\n\t\t\t\t\t", array($dbFarmRole->ID, $chunks[0], $chunks[1], $chunks[2], $chunks[3])); } } /*****************/ /* Update role params */ $dbFarmRole->SetParameters($role['params']); /* End of role params management */ /* Add script options to databse */ $dbFarmRole->SetScripts($role['scripting']); /* End of scripting section */ /* Add services configuration */ $dbFarmRole->SetServiceConfigPresets($role['config_presets']); /* End of scripting section */ Scalr_Helpers_Dns::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); foreach (Scalr_Role_Behavior::getListForFarmRole($dbFarmRole) as $behavior) { $behavior->onFarmSave($dbFarm, $dbFarmRole); } /** * Platfrom specified updates */ if ($dbFarmRole->Platform == SERVER_PLATFORMS::EC2) { Modules_Platforms_Ec2_Helpers_Ebs::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); Modules_Platforms_Ec2_Helpers_Eip::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); Modules_Platforms_Ec2_Helpers_Elb::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); } $dbFarmRolesList[] = $dbFarmRole; $newFarmRolesList[] = $dbFarmRole->ID; } if (!$this->getParam('roleUpdate')) { foreach ($dbFarm->GetFarmRoles() as $dbFarmRole) { if (!$dbFarmRole->NewRoleID && !in_array($dbFarmRole->ID, $newFarmRolesList)) { $dbFarmRole->Delete(); } } } if ($usedPlatforms[SERVER_PLATFORMS::CLOUDSTACK]) { Modules_Platforms_Cloudstack_Helpers_Cloudstack::farmSave($dbFarm, $dbFarmRolesList); } if ($usedPlatforms[SERVER_PLATFORMS::EC2]) { Modules_Platforms_Ec2_Helpers_Ec2::farmSave($dbFarm, $dbFarmRolesList); } if ($usedPlatforms[SERVER_PLATFORMS::EUCALYPTUS]) { Modules_Platforms_Eucalyptus_Helpers_Eucalyptus::farmSave($dbFarm, $dbFarmRolesList); } $dbFarm->save(); if (!$client->GetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED)) { $client->SetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED, time()); } $this->response->success('Farm successfully saved'); $this->response->data(array('farmId' => $dbFarm->ID)); }
public function xBuildAction() { $this->request->defineParams(array('farmId' => array('type' => 'int'), 'roles' => array('type' => 'json'), 'rolesToRemove' => array('type' => 'json'), 'farm' => array('type' => 'json'), 'launch' => array('type' => 'bool'))); if (!$this->isFarmConfigurationValid($this->getParam('farmId'), $this->getParam('farm'), (array) $this->getParam('roles'))) { if ($this->errors['error_count'] != 0) { $this->response->failure(); $this->response->data(array('errors' => $this->errors)); return; } } $farm = $this->getParam('farm'); $client = Client::Load($this->user->getAccountId()); if ($this->getParam('farmId')) { $dbFarm = DBFarm::LoadByID($this->getParam('farmId')); $this->user->getPermissions()->validate($dbFarm); $this->request->checkPermissions($dbFarm->__getNewFarmObject(), Acl::PERM_FARMS_UPDATE); $dbFarm->isLocked(); if ($this->getParam('changed') && $dbFarm->changedTime && $this->getParam('changed') != $dbFarm->changedTime) { $userName = '******'; $changed = explode(' ', $this->getParam('changed')); $changedTime = intval($changed[1]); try { $user = new Scalr_Account_User(); $user->loadById($dbFarm->changedByUserId); $userName = $user->getEmail(); } catch (Exception $e) { } $this->response->failure(); $this->response->data(array('changedFailure' => sprintf('%s changed this farm at %s', $userName, Scalr_Util_DateTime::convertTz($changedTime)))); return; } else { if ($this->getParam('changed')) { $this->checkFarmConfigurationIntegrity($this->getParam('farmId'), $this->getParam('farm'), (array) $this->getParam('roles'), (array) $this->getParam('rolesToRemove')); } } $dbFarm->changedByUserId = $this->user->getId(); $dbFarm->changedTime = microtime(); if ($this->getContainer()->analytics->enabled) { $projectId = $farm['projectId']; if (empty($projectId)) { $ccId = $dbFarm->GetEnvironmentObject()->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID); if (!empty($ccId)) { //Assigns Project automatically only if it is the one withing the Cost Center $projects = ProjectEntity::findByCcId($ccId); if (count($projects) == 1) { $projectId = $projects->getArrayCopy()[0]->projectId; } } } if (!empty($projectId) && $dbFarm->GetSetting(Entity\FarmSetting::PROJECT_ID) != $projectId) { $this->request->checkPermissions($dbFarm->__getNewFarmObject(), Acl::PERM_FARMS_PROJECTS); } } $bNew = false; } else { $this->request->restrictAccess(Acl::RESOURCE_OWN_FARMS, Acl::PERM_FARMS_CREATE); $this->user->getAccount()->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1); $dbFarm = new DBFarm(); $dbFarm->ClientID = $this->user->getAccountId(); $dbFarm->EnvID = $this->getEnvironmentId(); $dbFarm->Status = FARM_STATUS::TERMINATED; $dbFarm->ownerId = $this->user->getId(); $dbFarm->changedByUserId = $this->user->getId(); $dbFarm->changedTime = microtime(); $bNew = true; } if ($this->getParam('farm')) { $dbFarm->Name = $this->request->stripValue($farm['name']); $dbFarm->RolesLaunchOrder = $farm['rolesLaunchOrder']; $dbFarm->Comments = $this->request->stripValue($farm['description']); } if (empty($dbFarm->Name)) { throw new Exception(_("Farm name required")); } $setFarmTeams = false; if ($bNew) { $setFarmTeams = true; } else { if ($dbFarm->ownerId == $this->user->getId() || $this->request->hasPermissions($dbFarm->__getNewFarmObject(), Acl::PERM_FARMS_CHANGE_OWNERSHIP)) { if (is_numeric($farm['owner']) && $farm['owner'] != $dbFarm->ownerId) { $dbFarm->ownerId = $farm['owner']; $f = Entity\Farm::findPk($dbFarm->ID); Entity\FarmSetting::addOwnerHistory($f, User::findPk($farm['owner']), User::findPk($this->user->getId())); $f->save(); } $setFarmTeams = true; } } $dbFarm->save(); if ($setFarmTeams && is_array($farm['teamOwner'])) { /* @var $f Entity\Farm */ $f = Entity\Farm::findPk($dbFarm->ID); $f->setTeams(empty($farm['teamOwner']) ? [] : Entity\Account\Team::find([['name' => ['$in' => $farm['teamOwner']]], ['accountId' => $this->getUser()->accountId]])); $f->save(); } if ($bNew) { $dbFarm->SetSetting(Entity\FarmSetting::CREATED_BY_ID, $this->user->getId()); $dbFarm->SetSetting(Entity\FarmSetting::CREATED_BY_EMAIL, $this->user->getEmail()); } $governance = new Scalr_Governance($this->getEnvironmentId()); if (!$this->getParam('farmId') && $governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE)) { $dbFarm->SetSetting(Entity\FarmSetting::LEASE_STATUS, 'Active'); // for created farm } if (isset($farm['variables'])) { $variables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), ScopeInterface::SCOPE_FARM); $variables->setValues(is_array($farm['variables']) ? $farm['variables'] : [], 0, $dbFarm->ID, 0, '', false, true); } if (!$farm['timezone']) { $farm['timezone'] = date_default_timezone_get(); } $dbFarm->SetSetting(Entity\FarmSetting::TIMEZONE, $farm['timezone']); $dbFarm->SetSetting(Entity\FarmSetting::EC2_VPC_ID, isset($farm["vpc_id"]) ? $farm['vpc_id'] : null); $dbFarm->SetSetting(Entity\FarmSetting::EC2_VPC_REGION, isset($farm["vpc_id"]) ? $farm['vpc_region'] : null); $dbFarm->SetSetting(Entity\FarmSetting::SZR_UPD_REPOSITORY, $farm[Entity\FarmSetting::SZR_UPD_REPOSITORY]); $dbFarm->SetSetting(Entity\FarmSetting::SZR_UPD_SCHEDULE, $farm[Entity\FarmSetting::SZR_UPD_SCHEDULE]); if (!$dbFarm->GetSetting(Entity\FarmSetting::CRYPTO_KEY)) { $dbFarm->SetSetting(Entity\FarmSetting::CRYPTO_KEY, Scalr::GenerateRandomKey(40)); } if ($this->getContainer()->analytics->enabled) { //Cost analytics project must be set for the Farm object $dbFarm->setProject(!empty($farm['projectId']) ? $farm['projectId'] : null); } $virtualFarmRoles = array(); $roles = $this->getParam('roles'); if (!empty($roles)) { foreach ($roles as $role) { if (strpos($role['farm_role_id'], "virtual_") !== false) { $dbRole = DBRole::loadById($role['role_id']); $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index'], $role['alias']); $virtualFarmRoles[$role['farm_role_id']] = $dbFarmRole->ID; } } } $usedPlatforms = array(); $farmRoleVariables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), ScopeInterface::SCOPE_FARMROLE); if (!empty($roles)) { foreach ($roles as $role) { if ($role['farm_role_id']) { if (isset($virtualFarmRoles[$role['farm_role_id']])) { $role['farm_role_id'] = $virtualFarmRoles[$role['farm_role_id']]; } $update = true; $dbFarmRole = DBFarmRole::LoadByID($role['farm_role_id']); $dbRole = DBRole::loadById($dbFarmRole->RoleID); $role['role_id'] = $dbFarmRole->RoleID; if ($dbFarmRole->Platform == SERVER_PLATFORMS::GCE) { $dbFarmRole->CloudLocation = $role['cloud_location']; } } else { /** TODO: Remove because will be handled with virtual_ **/ $update = false; $dbRole = DBRole::loadById($role['role_id']); $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index']); } if ($dbRole->hasBehavior(ROLE_BEHAVIORS::RABBITMQ)) { $role['settings'][Entity\FarmRoleSetting::SCALING_MAX_INSTANCES] = $role['settings'][Entity\FarmRoleSetting::SCALING_MIN_INSTANCES]; } if ($update) { $dbFarmRole->LaunchIndex = (int) $role['launch_index']; $dbFarmRole->Alias = $role['alias']; $dbFarmRole->Save(); } $usedPlatforms[$role['platform']] = 1; $oldRoleSettings = $dbFarmRole->GetAllSettings(); // Update virtual farm_role_id with actual value $scripts = (array) $role['scripting']; if (!empty($virtualFarmRoles)) { array_walk_recursive($scripts, function (&$v, $k) use($virtualFarmRoles) { if (is_string($v)) { $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v); } }); array_walk_recursive($role['settings'], function (&$v, $k) use($virtualFarmRoles) { if (is_string($v)) { $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v); } }); } $dbFarmRole->ClearSettings("chef."); if (!empty($role['scaling_settings']) && is_array($role['scaling_settings'])) { foreach ($role['scaling_settings'] as $k => $v) { $dbFarmRole->SetSetting($k, $v, Entity\FarmRoleSetting::TYPE_CFG); } } foreach ($role['settings'] as $k => $v) { $dbFarmRole->SetSetting($k, $v, Entity\FarmRoleSetting::TYPE_CFG); } /****** Scaling settings ******/ $scalingManager = new Scalr_Scaling_Manager($dbFarmRole); $scalingManager->setFarmRoleMetrics(is_array($role['scaling']) ? $role['scaling'] : array()); //TODO: optimize this code... $this->db->Execute("DELETE FROM farm_role_scaling_times WHERE farm_roleid=?", array($dbFarmRole->ID)); // 5 = Time based scaling -> move to constants if (!empty($role['scaling'][Entity\ScalingMetric::METRIC_DATE_AND_TIME_ID])) { foreach ($role['scaling'][Entity\ScalingMetric::METRIC_DATE_AND_TIME_ID] as $scal_period) { $chunks = explode(":", $scal_period['id']); $this->db->Execute("INSERT INTO farm_role_scaling_times SET\n farm_roleid\t\t= ?,\n start_time\t\t= ?,\n end_time\t\t= ?,\n days_of_week\t= ?,\n instances_count\t= ?\n ", array($dbFarmRole->ID, $chunks[0], $chunks[1], $chunks[2], $chunks[3])); } } /*****************/ /* Add script options to databse */ $dbFarmRole->SetScripts($scripts, (array) $role['scripting_params']); /* End of scripting section */ /* Add storage configuration */ if (isset($role['storages']['configs'])) { $dbFarmRole->getStorage()->setConfigs($role['storages']['configs'], false); } $farmRoleVariables->setValues(is_array($role['variables']) ? $role['variables'] : [], $dbFarmRole->GetRoleID(), $dbFarm->ID, $dbFarmRole->ID, '', false, true); foreach (Scalr_Role_Behavior::getListForFarmRole($dbFarmRole) as $behavior) { $behavior->onFarmSave($dbFarm, $dbFarmRole); } /** * Platform specified updates */ if ($dbFarmRole->Platform == SERVER_PLATFORMS::EC2) { \Scalr\Modules\Platforms\Ec2\Helpers\EbsHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); \Scalr\Modules\Platforms\Ec2\Helpers\EipHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); if ($role['settings']['aws.elb.remove']) { $this->request->restrictAccess(Acl::RESOURCE_AWS_ELB, Acl::PERM_AWS_ELB_MANAGE); } \Scalr\Modules\Platforms\Ec2\Helpers\ElbHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); } if (in_array($dbFarmRole->Platform, array(SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::CLOUDSTACK))) { Scalr\Modules\Platforms\Cloudstack\Helpers\CloudstackHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']); } } } $rolesToRemove = $this->getParam('rolesToRemove'); if (!empty($rolesToRemove)) { $currentFarmRoles = Entity\FarmRole::find([['farmId' => $dbFarm->ID], ['id' => ['$in' => $rolesToRemove]]]); /* @var $farmRole Entity\FarmRole */ foreach ($currentFarmRoles as $farmRole) { $farmRole->delete(); } } $dbFarm->save(); if (!$client->GetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED)) { $client->SetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED, time()); } if ($this->request->hasPermissions($dbFarm->__getNewFarmObject(), Acl::PERM_FARMS_LAUNCH_TERMINATE) && $this->getParam('launch')) { $this->user->getPermissions()->validate($dbFarm); $dbFarm->isLocked(); Scalr::FireEvent($dbFarm->ID, new FarmLaunchedEvent(true, $this->user->id)); $this->response->success('Farm successfully saved and launched'); } else { $this->response->success('Farm successfully saved'); } $this->response->data(array('farmId' => $dbFarm->ID, 'isNewFarm' => $bNew)); }