getPlatformConfigValue() public method

Gets client_environment_properties value.
public getPlatformConfigValue ( string $key, boolean $encrypted = true, string $group = '' ) : mixed
$key string Property name.
$encrypted boolean optional This value is ignored and never taken into account
$group string optional Group name.
return mixed Returns config value on success or NULL if value does not exist.
Example #1
0
 public function GetServersList(Scalr_Environment $environment, $region, $skipCache = false)
 {
     if (!$region) {
         return array();
     }
     if (!$this->instancesListCache[$environment->id][$region] || $skipCache) {
         $EC2Client = Scalr_Service_Cloud_Aws::newEc2($region, $environment->getPlatformConfigValue(self::PRIVATE_KEY), $environment->getPlatformConfigValue(self::CERTIFICATE));
         try {
             $results = $EC2Client->DescribeInstances();
             $results = $results->reservationSet;
         } catch (Exception $e) {
             throw new Exception(sprintf("Cannot get list of servers for platfrom ec2: %s", $e->getMessage()));
         }
         if ($results->item) {
             if ($results->item->reservationId) {
                 $this->instancesListCache[$environment->id][$region][(string) $results->item->instancesSet->item->instanceId] = (string) $results->item->instancesSet->item->instanceState->name;
             } else {
                 foreach ($results->item as $item) {
                     $this->instancesListCache[$environment->id][$region][(string) $item->instancesSet->item->instanceId] = (string) $item->instancesSet->item->instanceState->name;
                 }
             }
         }
     }
     return $this->instancesListCache[$environment->id][$region];
 }
 /**
  * Gets the list of available locations
  *
  * @return  array Returns the list of available locations looks like array(location => description)
  */
 public function getLocations(\Scalr_Environment $environment = null)
 {
     $retval = array(Aws::REGION_US_EAST_1 => 'us-east-1 (N. Virginia)', Aws::REGION_US_WEST_1 => 'us-west-1 (N. California)', Aws::REGION_US_WEST_2 => 'us-west-2 (Oregon)', Aws::REGION_EU_WEST_1 => 'eu-west-1 (Ireland)', Aws::REGION_EU_CENTRAL_1 => 'eu-central-1 (Frankfurt)', Aws::REGION_SA_EAST_1 => 'sa-east-1 (Sao Paulo)', Aws::REGION_AP_SOUTHEAST_1 => 'ap-southeast-1 (Singapore)', Aws::REGION_AP_SOUTHEAST_2 => 'ap-southeast-2 (Sydney)', Aws::REGION_AP_NORTHEAST_1 => 'ap-northeast-1 (Tokyo)');
     if ($environment instanceof \Scalr_Environment && $this instanceof Ec2PlatformModule) {
         if ($environment->getPlatformConfigValue(Ec2PlatformModule::ACCOUNT_TYPE) == Ec2PlatformModule::ACCOUNT_TYPE_GOV_CLOUD) {
             return [Aws::REGION_US_GOV_WEST_1 => 'us-gov-west-1 (GovCloud US)'];
         }
         if ($environment->getPlatformConfigValue(Ec2PlatformModule::ACCOUNT_TYPE) == Ec2PlatformModule::ACCOUNT_TYPE_CN_CLOUD) {
             return [Aws::REGION_CN_NORTH_1 => 'cn-north-1 (China)'];
         }
     } else {
         // For admin (when no environment defined) we need to show govcloud and chinacloud locations to be able to manage images.
         $retval = array_merge($retval, [Aws::REGION_CN_NORTH_1 => 'cn-north-1 (China)', Aws::REGION_US_GOV_WEST_1 => 'us-gov-west-1 (GovCloud US)']);
     }
     return $retval;
 }
Example #3
0
 private function getCloudStackDetails($platform)
 {
     $params["{$platform}.is_enabled"] = true;
     $params[CloudstackPlatformModule::API_URL] = $this->env->getPlatformConfigValue("{$platform}." . CloudstackPlatformModule::API_URL);
     $params[CloudstackPlatformModule::API_KEY] = $this->env->getPlatformConfigValue("{$platform}." . CloudstackPlatformModule::API_KEY);
     $params[CloudstackPlatformModule::SECRET_KEY] = $this->env->getPlatformConfigValue("{$platform}." . CloudstackPlatformModule::SECRET_KEY);
     return $params;
 }
 /**
  * Gets the list of available locations
  *
  * @return  array Returns the list of available locations looks like array(location => description)
  */
 public function getLocations(\Scalr_Environment $environment = null)
 {
     if ($environment instanceof \Scalr_Environment && $this instanceof Ec2PlatformModule) {
         if ($environment->getPlatformConfigValue(Ec2PlatformModule::ACCOUNT_TYPE) == Ec2PlatformModule::ACCOUNT_TYPE_GOV_CLOUD) {
             return array(Aws::REGION_US_GOV_WEST_1 => 'AWS / us-gov-west-1 (GovCloud US)');
         }
     }
     return array(Aws::REGION_US_EAST_1 => 'AWS / us-east-1 (N. Virginia)', Aws::REGION_US_WEST_1 => 'AWS / us-west-1 (N. California)', Aws::REGION_US_WEST_2 => 'AWS / us-west-2 (Oregon)', Aws::REGION_EU_WEST_1 => 'AWS / eu-west-1 (Ireland)', Aws::REGION_SA_EAST_1 => 'AWS / sa-east-1 (Sao Paulo)', Aws::REGION_AP_SOUTHEAST_1 => 'AWS / ap-southeast-1 (Singapore)', Aws::REGION_AP_SOUTHEAST_2 => 'AWS / ap-southeast-2 (Sydney)', Aws::REGION_AP_NORTHEAST_1 => 'AWS / ap-northeast-1 (Tokyo)');
 }
Example #5
0
 public function eucalyptusAction()
 {
     $params = array();
     $rows = $this->db->GetAll('SELECT * FROM client_environment_properties WHERE env_id = ? AND name LIKE "eucalyptus.%" AND `group` != "" GROUP BY `group`', $this->env->id);
     foreach ($rows as $value) {
         $cloud = $value['group'];
         $params[$cloud] = array(Modules_Platforms_Eucalyptus::ACCOUNT_ID => $this->env->getPlatformConfigValue(Modules_Platforms_Eucalyptus::ACCOUNT_ID, true, $cloud), Modules_Platforms_Eucalyptus::ACCESS_KEY => $this->env->getPlatformConfigValue(Modules_Platforms_Eucalyptus::ACCESS_KEY, true, $cloud), Modules_Platforms_Eucalyptus::EC2_URL => $this->env->getPlatformConfigValue(Modules_Platforms_Eucalyptus::EC2_URL, true, $cloud), Modules_Platforms_Eucalyptus::S3_URL => $this->env->getPlatformConfigValue(Modules_Platforms_Eucalyptus::S3_URL, true, $cloud), Modules_Platforms_Eucalyptus::SECRET_KEY => $this->env->getPlatformConfigValue(Modules_Platforms_Eucalyptus::SECRET_KEY, true, $cloud) != '' ? '******' : false, Modules_Platforms_Eucalyptus::PRIVATE_KEY => $this->env->getPlatformConfigValue(Modules_Platforms_Eucalyptus::PRIVATE_KEY, true, $cloud) != '' ? 'Uploaded' : '', Modules_Platforms_Eucalyptus::CLOUD_CERTIFICATE => $this->env->getPlatformConfigValue(Modules_Platforms_Eucalyptus::CLOUD_CERTIFICATE, true, $cloud) != '' ? 'Uploaded' : '', Modules_Platforms_Eucalyptus::CERTIFICATE => $this->env->getPlatformConfigValue(Modules_Platforms_Eucalyptus::CERTIFICATE, true, $cloud) != '' ? 'Uploaded' : '');
     }
     $this->response->page('ui/account2/environments/platform/eucalyptus.js', array('env' => array('id' => $this->env->id, 'name' => $this->env->name), 'params' => $params));
 }
Example #6
0
 /**
  * {@inheritdoc}
  * @see \Scalr\Modules\PlatformModuleInterface::hasCloudPrices()
  */
 public function hasCloudPrices(\Scalr_Environment $env)
 {
     if (!$this->container->analytics->enabled) {
         return false;
     }
     $url = $env->getPlatformConfigValue(static::API_URL);
     if (empty($url)) {
         return false;
     }
     return $this->container->analytics->prices->hasPriceForUrl(\SERVER_PLATFORMS::NIMBULA, $url) ?: $url;
 }
Example #7
0
 public function getClient(Scalr_Environment $environment, $cloudLocation)
 {
     $client = new Google_Client();
     $client->setApplicationName("Scalr GCE");
     $client->setScopes(array('https://www.googleapis.com/auth/compute'));
     $key = base64_decode($environment->getPlatformConfigValue(self::KEY));
     $client->setAssertionCredentials(new Google_AssertionCredentials($environment->getPlatformConfigValue(self::SERVICE_ACCOUNT_NAME), array('https://www.googleapis.com/auth/compute'), $key));
     $client->setUseObjects(true);
     $client->setClientId($environment->getPlatformConfigValue(self::CLIENT_ID));
     $gce = new Google_ComputeService($client);
     //**** Store access token ****//
     $jsonAccessToken = $environment->getPlatformConfigValue(self::ACCESS_TOKEN);
     $accessToken = @json_decode($jsonAccessToken);
     if ($accessToken && $accessToken->created + $accessToken->expires_in > time()) {
         $client->setAccessToken($jsonAccessToken);
     } else {
         $gce->zones->listZones($environment->getPlatformConfigValue(self::PROJECT_ID));
         $token = $client->getAccessToken();
         $environment->setPlatformConfig(array(self::ACCESS_TOKEN => $token));
     }
     return $gce;
 }
Example #8
0
 public function BuildRestServer($request)
 {
     try {
         $Reflect = new ReflectionObject($this);
         if ($Reflect->hasMethod($request['Action'])) {
             //Authenticate
             if ($request['AuthType'] == 'ldap') {
                 $this->AuthenticateLdap($request);
             } else {
                 if ($request['AuthVersion'] == 2) {
                     $this->AuthenticateRESTv2($request);
                 } elseif ($request['AuthVersion'] == 3) {
                     $this->AuthenticateRESTv3($request);
                 } else {
                     $this->AuthenticateREST($request);
                 }
                 if ($this->user->getSetting(Scalr_Account_User::SETTING_API_ENABLED) != 1) {
                     throw new Exception(_("Your API keys are currently disabled. You can enable access at Settings > API access."));
                 }
                 //Check IP Addresses
                 if ($this->user->getSetting(Scalr_Account_User::SETTING_API_IP_WHITELIST)) {
                     $ips = explode(",", $this->user->getSetting(Scalr_Account_User::SETTING_API_IP_WHITELIST));
                     if (!$this->IPAccessCheck($ips)) {
                         throw new Exception(sprintf(_("Access to the API is not allowed from your IP '%s'"), $_SERVER['REMOTE_ADDR']));
                     }
                 }
             }
             //Check limit
             if ($this->Environment->getPlatformConfigValue(Scalr_Environment::SETTING_API_LIMIT_ENABLED, false) == 1) {
                 $hour = $this->Environment->getPlatformConfigValue(Scalr_Environment::SETTING_API_LIMIT_HOUR, false);
                 $limit = $this->Environment->getPlatformConfigValue(Scalr_Environment::SETTING_API_LIMIT_REQPERHOUR, false);
                 $usage = $this->Environment->getPlatformConfigValue(Scalr_Environment::SETTING_API_LIMIT_USAGE, false);
                 if ($usage >= $limit && $hour == date("YmdH")) {
                     $reset = 60 - (int) date("i");
                     header("HTTP/1.0 429 Too Many Requests");
                     exit;
                     //throw new Exception(sprintf("Hourly API requests limit (%s) exceeded. Limit will be reset within %s minutes", $limit, $reset));
                 }
                 if (date("YmdH") > $hour) {
                     $hour = date("YmdH");
                     $usage = 0;
                 }
                 $this->Environment->setPlatformConfig(array(Scalr_Environment::SETTING_API_LIMIT_USAGE => $usage + 1, Scalr_Environment::SETTING_API_LIMIT_HOUR => $hour), false);
             }
             //Execute API call
             $ReflectMethod = $Reflect->getMethod($request['Action']);
             $args = array();
             foreach ($ReflectMethod->getParameters() as $param) {
                 if (!$param->isOptional() && !isset($request[$param->getName()])) {
                     throw new Exception(sprintf("Missing required parameter '%s'", $param->getName()));
                 } else {
                     if ($param->isArray()) {
                         $args[$param->getName()] = (array) $request[$param->getName()];
                     } else {
                         $args[$param->getName()] = $request[$param->getName()];
                     }
                 }
             }
             $result = $ReflectMethod->invokeArgs($this, $args);
             $this->LastTransactionID = $result->TransactionID;
             // Create response
             $DOMDocument = new DOMDocument('1.0', 'UTF-8');
             $DOMDocument->loadXML("<{$request['Action']}Response></{$request['Action']}Response>");
             $this->ObjectToXML($result, $DOMDocument->documentElement, $DOMDocument);
             $retval = $DOMDocument->saveXML();
         } else {
             throw new Exception(sprintf("Action '%s' is not defined", $request['Action']));
         }
     } catch (Exception $e) {
         if (!$this->LastTransactionID) {
             $this->LastTransactionID = Scalr::GenerateUID();
         }
         $retval = "<?xml version=\"1.0\"?>\n" . "<Error>\n" . "\t<TransactionID>{$this->LastTransactionID}</TransactionID>\n" . "\t<Message>{$e->getMessage()}</Message>\n" . "</Error>\n";
     }
     if (isset($this->user)) {
         $this->LogRequest($this->LastTransactionID, $request['Action'], $_SERVER['REMOTE_ADDR'], $request, $retval);
     }
     header("Content-type: text/xml");
     header("Content-length: " . strlen($retval));
     header("Access-Control-Allow-Origin: *");
     print $retval;
 }
Example #9
0
 /**
  * @return Scalr_Service_Cloud_Rackspace_CS
  */
 private function getRsClient(Scalr_Environment $environment, $cloudLocation)
 {
     return Scalr_Service_Cloud_Rackspace::newRackspaceCS($environment->getPlatformConfigValue(self::USERNAME, true, $cloudLocation), $environment->getPlatformConfigValue(self::API_KEY, true, $cloudLocation), $cloudLocation);
 }
 /**
  * Gets endpoint url for private cloud
  *
  * @param \Scalr_Environment $env       The scalr environment object
  * @param string             $group     optional The group name for eucaliptus
  * @return string Returns endpoint url for cloudstack.
  */
 public function getEndpointUrl(\Scalr_Environment $env, $group = null)
 {
     return $env->getPlatformConfigValue($this->platform . "." . self::API_URL);
 }
Example #11
0
 private function saveOpenstack()
 {
     $pars = array();
     $enabled = false;
     $platform = $this->getParam('platform');
     $bNew = !$this->env->isPlatformEnabled($platform);
     if (!$bNew) {
         $oldUrl = $this->env->getPlatformConfigValue($this->getOpenStackOption('KEYSTONE_URL'));
     }
     if ($this->getParam("{$platform}_is_enabled")) {
         $enabled = true;
         $pars[$this->getOpenStackOption('KEYSTONE_URL')] = trim($this->checkVar(OpenstackPlatformModule::KEYSTONE_URL, 'string', 'KeyStone URL required'));
         $pars[$this->getOpenStackOption('SSL_VERIFYPEER')] = trim($this->checkVar(OpenstackPlatformModule::SSL_VERIFYPEER, 'int'));
         $pars[$this->getOpenStackOption('USERNAME')] = $this->checkVar(OpenstackPlatformModule::USERNAME, 'string', 'Username required');
         $pars[$this->getOpenStackOption('PASSWORD')] = $this->checkVar(OpenstackPlatformModule::PASSWORD, 'password', '', '', false, $platform);
         $pars[$this->getOpenStackOption('API_KEY')] = $this->checkVar(OpenstackPlatformModule::API_KEY, 'string');
         $pars[$this->getOpenStackOption('IDENTITY_VERSION')] = OpenStackConfig::parseIdentityVersion($pars[$this->getOpenStackOption('KEYSTONE_URL')]);
         if ($platform == SERVER_PLATFORMS::ECS) {
             $pars[$this->getOpenStackOption('TENANT_NAME')] = $this->checkVar(OpenstackPlatformModule::TENANT_NAME, 'password', '', '', false, $platform);
         } else {
             $pars[$this->getOpenStackOption('TENANT_NAME')] = $this->checkVar(OpenstackPlatformModule::TENANT_NAME, 'string');
         }
         if (empty($this->checkVarError) && empty($pars[$this->getOpenStackOption('PASSWORD')]) && empty($pars[$this->getOpenStackOption('API_KEY')])) {
             $this->checkVarError['api_key'] = $this->checkVarError['password'] = '******';
         }
     }
     /* @var $config Yaml */
     $config = $this->env->getContainer()->config;
     if (isset($platform) && $config->defined("scalr.{$platform}.use_proxy") && $config("scalr.{$platform}.use_proxy") && in_array($config('scalr.connections.proxy.use_on'), ['both', 'scalr'])) {
         $pars['proxySettings'] = $config('scalr.connections.proxy');
     } else {
         $pars['proxySettings'] = null;
     }
     if (count($this->checkVarError)) {
         $this->response->failure();
         $this->response->data(array('errors' => $this->checkVarError));
     } else {
         if ($this->getParam($platform . "_is_enabled")) {
             $os = new OpenStack(new OpenStackConfig($pars[$this->getOpenStackOption('USERNAME')], $pars[$this->getOpenStackOption('KEYSTONE_URL')], 'fake-region', $pars[$this->getOpenStackOption('API_KEY')], null, null, $pars[$this->getOpenStackOption('PASSWORD')], $pars[$this->getOpenStackOption('TENANT_NAME')], $pars[$this->getOpenStackOption('IDENTITY_VERSION')], $pars['proxySettings']));
             //It throws an exception on failure
             $zones = $os->listZones();
             $zone = array_shift($zones);
             $os = new OpenStack(new OpenStackConfig($pars[$this->getOpenStackOption('USERNAME')], $pars[$this->getOpenStackOption('KEYSTONE_URL')], $zone->name, $pars[$this->getOpenStackOption('API_KEY')], null, null, $pars[$this->getOpenStackOption('PASSWORD')], $pars[$this->getOpenStackOption('TENANT_NAME')], $pars[$this->getOpenStackOption('IDENTITY_VERSION')], $pars['proxySettings']));
             // Check SG Extension
             $pars[$this->getOpenStackOption('EXT_SECURITYGROUPS_ENABLED')] = (int) $os->servers->isExtensionSupported(ServersExtension::securityGroups());
             // Check Floating Ips Extension
             $pars[$this->getOpenStackOption('EXT_FLOATING_IPS_ENABLED')] = (int) $os->servers->isExtensionSupported(ServersExtension::floatingIps());
             // Check Cinder Extension
             $pars[$this->getOpenStackOption('EXT_CINDER_ENABLED')] = (int) $os->hasService('volume');
             // Check Swift Extension
             $pars[$this->getOpenStackOption('EXT_SWIFT_ENABLED')] = (int) $os->hasService('object-store');
             // Check LBaas Extension
             $pars[$this->getOpenStackOption('EXT_LBAAS_ENABLED')] = !in_array($platform, array(SERVER_PLATFORMS::RACKSPACENG_US, SERVER_PLATFORMS::RACKSPACENG_UK)) && $os->hasService('network') ? (int) $os->network->isExtensionSupported('lbaas') : 0;
         }
         $this->db->BeginTrans();
         try {
             $this->env->enablePlatform($platform, $enabled);
             if ($enabled) {
                 $this->env->setPlatformConfig($pars);
                 if ($this->getContainer()->analytics->enabled && ($bNew || $oldUrl !== $pars[$this->getOpenStackOption('KEYSTONE_URL')])) {
                     $this->getContainer()->analytics->notifications->onCloudAdd($platform, $this->env, $this->user);
                 }
             } else {
                 $this->env->setPlatformConfig(array("{$platform}." . OpenstackPlatformModule::AUTH_TOKEN => false));
             }
             if (!$this->user->getAccount()->getSetting(Scalr_Account::SETTING_DATE_ENV_CONFIGURED)) {
                 $this->user->getAccount()->setSetting(Scalr_Account::SETTING_DATE_ENV_CONFIGURED, time());
             }
             $this->response->success('Cloud credentials have been ' . ($enabled ? 'saved' : 'removed from Scalr'));
             $this->response->data(array('enabled' => $enabled));
         } catch (Exception $e) {
             $this->db->RollbackTrans();
             throw new Exception(_('Failed to save ' . ucfirst($platform) . ' settings'));
         }
         $this->db->CommitTrans();
     }
 }
Example #12
0
 /**
  * Return new instance of AmazonEC2 object
  *
  * @return AmazonEC2
  */
 private function GetAmazonEC2ClientObject(Scalr_Environment $environment, $region)
 {
     // Return new instance of AmazonEC2 object
     $AmazonEC2Client = Scalr_Service_Cloud_Aws::newEc2($region, $environment->getPlatformConfigValue(Modules_Platforms_Ec2::PRIVATE_KEY), $environment->getPlatformConfigValue(Modules_Platforms_Ec2::CERTIFICATE));
     return $AmazonEC2Client;
 }
Example #13
0
 /**
  * Gets platform property
  *
  * @deprecated by cloud credentials
  * @param    string             $name           The name of the platform property
  * @param    \Scalr_Environment $env            The environment
  * @param    string             $encrypted      optional This is ignored
  * @param    string             $cloudLocation  optional The cloud location
  * @return   string             Returns the value of the specified platform property
  */
 public function getConfigVariable($name, \Scalr_Environment $env, $encrypted = true, $cloudLocation = '')
 {
     $name = $this->platform ? "{$this->platform}.{$name}" : $name;
     return $env->getPlatformConfigValue($name, $encrypted, $cloudLocation);
 }
Example #14
0
 /**
  * {@inheritdoc}
  * @see \Scalr\Modules\PlatformModuleInterface::hasCloudPrices()
  */
 public function hasCloudPrices(\Scalr_Environment $env)
 {
     if (!$this->container->analytics->enabled) {
         return false;
     }
     if ($env->getPlatformConfigValue(self::ACCOUNT_TYPE) == self::ACCOUNT_TYPE_GOV_CLOUD) {
         $locations = $this->getLocations($env);
         $cloudLocation = key($locations);
     }
     return $this->container->analytics->prices->hasPriceForUrl(\SERVER_PLATFORMS::EC2, '', isset($cloudLocation) ? $cloudLocation : null);
 }
Example #15
0
 /**
  * @return Scalr_Service_Cloud_Openstack_v1_1_Client
  */
 private function getOsClient(Scalr_Environment $environment, $cloudLocation)
 {
     return Scalr_Service_Cloud_Openstack::newNovaCC($environment->getPlatformConfigValue(self::API_URL, true, $cloudLocation), $environment->getPlatformConfigValue(self::USERNAME, true, $cloudLocation), $environment->getPlatformConfigValue(self::API_KEY, true, $cloudLocation), $environment->getPlatformConfigValue(self::PROJECT_NAME, true, $cloudLocation));
 }
Example #16
0
 public function getRdsClient(Scalr_Environment $environment, $region)
 {
     return Scalr_Service_Cloud_Aws::newRds($environment->getPlatformConfigValue(self::ACCESS_KEY), $environment->getPlatformConfigValue(self::SECRET_KEY), $region);
 }
 /**
  *
  * @param \Scalr_Environment $environment
  * @param string $operationId
  * @param string $cloudLocation
  * @param string $scope
  * @return Google_Service_Compute_Operation $operation
  */
 public function GetAsyncOperationStatus(\Scalr_Environment $environment, $operationId, $cloudLocation, $scope = 'zones')
 {
     $projectName = $environment->getPlatformConfigValue(self::PROJECT_ID);
     $gce = $this->getClient($environment);
     if ($scope == 'zones') {
         $operation = $gce->zoneOperations->get($projectName, $cloudLocation, $operationId);
     } elseif ($scope == 'regions') {
         $operation = $gce->regionOperations->get($projectName, $cloudLocation, $operationId);
     }
     return $operation;
 }
Example #18
0
 private function saveEc2()
 {
     $pars = [];
     $enabled = false;
     $envAutoEnabled = false;
     $bNew = !$this->env->isPlatformEnabled(SERVER_PLATFORMS::EC2);
     $currentCloudCredentials = $this->env->keychain(SERVER_PLATFORMS::EC2);
     $ccProps = $currentCloudCredentials->properties;
     if ($this->getParam('ec2_is_enabled')) {
         $enabled = true;
         $pars[Entity\CloudCredentialsProperty::AWS_ACCOUNT_TYPE] = trim($this->checkVar(Entity\CloudCredentialsProperty::AWS_ACCOUNT_TYPE, 'string', "AWS Account Type required", SERVER_PLATFORMS::EC2));
         $pars[Entity\CloudCredentialsProperty::AWS_ACCESS_KEY] = trim($this->checkVar(Entity\CloudCredentialsProperty::AWS_ACCESS_KEY, 'string', "AWS Access Key required", SERVER_PLATFORMS::EC2));
         $pars[Entity\CloudCredentialsProperty::AWS_SECRET_KEY] = trim($this->checkVar(Entity\CloudCredentialsProperty::AWS_SECRET_KEY, 'password', "AWS Access Key required", SERVER_PLATFORMS::EC2));
         $pars[Entity\CloudCredentialsProperty::AWS_PRIVATE_KEY] = $this->checkVar(Entity\CloudCredentialsProperty::AWS_PRIVATE_KEY, 'file', '', SERVER_PLATFORMS::EC2);
         $pars[Entity\CloudCredentialsProperty::AWS_CERTIFICATE] = $this->checkVar(Entity\CloudCredentialsProperty::AWS_CERTIFICATE, 'file', '', SERVER_PLATFORMS::EC2);
         if ($this->getContainer()->analytics->enabled) {
             $pars[Entity\CloudCredentialsProperty::AWS_DETAILED_BILLING_ENABLED] = $this->checkVar2(Entity\CloudCredentialsProperty::AWS_DETAILED_BILLING_ENABLED, 'bool', '', SERVER_PLATFORMS::EC2);
             if (!empty($pars[Entity\CloudCredentialsProperty::AWS_DETAILED_BILLING_ENABLED])) {
                 $pars[Entity\CloudCredentialsProperty::AWS_DETAILED_BILLING_BUCKET] = $this->checkVar(Entity\CloudCredentialsProperty::AWS_DETAILED_BILLING_BUCKET, 'string', "Detailed billing bucket name is required", SERVER_PLATFORMS::EC2);
                 $pars[Entity\CloudCredentialsProperty::AWS_DETAILED_BILLING_PAYER_ACCOUNT] = $this->checkVar2(Entity\CloudCredentialsProperty::AWS_DETAILED_BILLING_PAYER_ACCOUNT, 'string', '', SERVER_PLATFORMS::EC2);
                 $pars[Entity\CloudCredentialsProperty::AWS_DETAILED_BILLING_REGION] = $this->checkVar(Entity\CloudCredentialsProperty::AWS_DETAILED_BILLING_REGION, 'string', "Aws region is required", SERVER_PLATFORMS::EC2);
             } else {
                 $pars[Entity\CloudCredentialsProperty::AWS_DETAILED_BILLING_BUCKET] = false;
                 $pars[Entity\CloudCredentialsProperty::AWS_DETAILED_BILLING_PAYER_ACCOUNT] = false;
                 $pars[Entity\CloudCredentialsProperty::AWS_DETAILED_BILLING_REGION] = false;
             }
         }
         // user can mull certificate and private key, check it
         if (strpos($pars[Entity\CloudCredentialsProperty::AWS_PRIVATE_KEY], 'BEGIN CERTIFICATE') !== FALSE && strpos($pars[Entity\CloudCredentialsProperty::AWS_CERTIFICATE], 'BEGIN PRIVATE KEY') !== FALSE) {
             // swap it
             $key = $pars[Entity\CloudCredentialsProperty::AWS_PRIVATE_KEY];
             $pars[Entity\CloudCredentialsProperty::AWS_PRIVATE_KEY] = $pars[Entity\CloudCredentialsProperty::AWS_CERTIFICATE];
             $pars[Entity\CloudCredentialsProperty::AWS_CERTIFICATE] = $key;
         }
         if ($pars[Entity\CloudCredentialsProperty::AWS_ACCOUNT_TYPE] == Entity\CloudCredentialsProperty::AWS_ACCOUNT_TYPE_GOV_CLOUD) {
             $region = \Scalr\Service\Aws::REGION_US_GOV_WEST_1;
         } else {
             if ($pars[Entity\CloudCredentialsProperty::AWS_ACCOUNT_TYPE] == Entity\CloudCredentialsProperty::AWS_ACCOUNT_TYPE_CN_CLOUD) {
                 $region = \Scalr\Service\Aws::REGION_CN_NORTH_1;
             } else {
                 $region = \Scalr\Service\Aws::REGION_US_EAST_1;
             }
         }
         if (!count($this->checkVarError)) {
             if ($pars[Entity\CloudCredentialsProperty::AWS_ACCESS_KEY] != $ccProps[Entity\CloudCredentialsProperty::AWS_ACCESS_KEY] or $pars[Entity\CloudCredentialsProperty::AWS_SECRET_KEY] != $ccProps[Entity\CloudCredentialsProperty::AWS_SECRET_KEY] or $pars[Entity\CloudCredentialsProperty::AWS_PRIVATE_KEY] != $ccProps[Entity\CloudCredentialsProperty::AWS_PRIVATE_KEY] or $pars[Entity\CloudCredentialsProperty::AWS_CERTIFICATE] != $ccProps[Entity\CloudCredentialsProperty::AWS_CERTIFICATE]) {
                 $aws = $this->env->aws($region, $pars[Entity\CloudCredentialsProperty::AWS_ACCESS_KEY], $pars[Entity\CloudCredentialsProperty::AWS_SECRET_KEY], !empty($pars[Entity\CloudCredentialsProperty::AWS_CERTIFICATE]) ? $pars[Entity\CloudCredentialsProperty::AWS_CERTIFICATE] : null, !empty($pars[Entity\CloudCredentialsProperty::AWS_PRIVATE_KEY]) ? $pars[Entity\CloudCredentialsProperty::AWS_PRIVATE_KEY] : null);
                 //Validates private key and certificate if they are provided
                 if (!empty($pars[Entity\CloudCredentialsProperty::AWS_CERTIFICATE]) || !empty($pars[Entity\CloudCredentialsProperty::AWS_PRIVATE_KEY])) {
                     try {
                         //SOAP is not supported anymore
                         //$aws->validateCertificateAndPrivateKey();
                     } catch (Exception $e) {
                         throw new Exception(_("Incorrect format of X.509 certificate or private key. Make sure that you are using files downloaded from AWS profile. ({$e->getMessage()})"));
                     }
                 }
                 //Validates both access and secret keys
                 try {
                     $buckets = $aws->s3->bucket->getList();
                 } catch (Exception $e) {
                     throw new Exception(sprintf(_("Failed to verify your EC2 access key and secret key: %s"), $e->getMessage()));
                 }
                 //Extract AWS Account ID
                 $pars[Entity\CloudCredentialsProperty::AWS_ACCOUNT_ID] = $aws->getAccountNumber();
                 try {
                     if ($ccProps[Entity\CloudCredentialsProperty::AWS_ACCOUNT_ID] != $pars[Entity\CloudCredentialsProperty::AWS_ACCOUNT_ID]) {
                         $this->db->Execute("DELETE FROM client_environment_properties WHERE name LIKE 'ec2.vpc.default%' AND env_id = ?", [$this->env->id]);
                     }
                 } catch (Exception $e) {
                 }
             } else {
                 $pars[Entity\CloudCredentialsProperty::AWS_ACCOUNT_ID] = $ccProps[Entity\CloudCredentialsProperty::AWS_ACCOUNT_ID];
             }
         } else {
             $this->response->failure();
             $this->response->data(['errors' => $this->checkVarError]);
             return;
         }
     }
     if ($enabled && $this->getContainer()->analytics->enabled && !empty($pars[Entity\CloudCredentialsProperty::AWS_DETAILED_BILLING_BUCKET])) {
         try {
             $region = $pars[Entity\CloudCredentialsProperty::AWS_DETAILED_BILLING_REGION];
             $aws = $this->env->aws($region, $pars[Entity\CloudCredentialsProperty::AWS_ACCESS_KEY], $pars[Entity\CloudCredentialsProperty::AWS_SECRET_KEY]);
             if (!empty($pars[Entity\CloudCredentialsProperty::AWS_DETAILED_BILLING_PAYER_ACCOUNT]) && $aws->getAccountNumber() != $pars[Entity\CloudCredentialsProperty::AWS_DETAILED_BILLING_PAYER_ACCOUNT]) {
                 $payerCredentials = $this->getUser()->getAccount()->cloudCredentialsList([SERVER_PLATFORMS::EC2], [], [Entity\CloudCredentialsProperty::AWS_ACCOUNT_ID => [['value' => $pars[Entity\CloudCredentialsProperty::AWS_DETAILED_BILLING_PAYER_ACCOUNT]]]]);
                 if (count($payerCredentials) == 0) {
                     throw new Exception("Payer account not found!");
                 }
                 $payerCredentials = $payerCredentials->current();
                 $aws = $this->env->aws($region, $payerCredentials->properties[Entity\CloudCredentialsProperty::AWS_ACCESS_KEY], $payerCredentials->properties[Entity\CloudCredentialsProperty::AWS_SECRET_KEY], !empty($payerCredentials->properties[Entity\CloudCredentialsProperty::AWS_CERTIFICATE]) ? $payerCredentials->properties[Entity\CloudCredentialsProperty::AWS_CERTIFICATE] : null, !empty($payerCredentials->properties[Entity\CloudCredentialsProperty::AWS_PRIVATE_KEY]) ? $payerCredentials->properties[Entity\CloudCredentialsProperty::AWS_PRIVATE_KEY] : null);
             }
             try {
                 $bucketObjects = $aws->s3->bucket->listObjects($pars[Entity\CloudCredentialsProperty::AWS_DETAILED_BILLING_BUCKET]);
             } catch (ClientException $e) {
                 if ($e->getErrorData() && $e->getErrorData()->getCode() == ErrorData::ERR_AUTHORIZATION_HEADER_MALFORMED && preg_match("/expecting\\s+'(.+?)'/", $e->getMessage(), $matches) && in_array($matches[1], Aws::getCloudLocations())) {
                     $expectingRegion = $matches[1];
                     if (isset($payerCredentials)) {
                         $aws = $this->env->aws($expectingRegion, $payerCredentials->properties[Entity\CloudCredentialsProperty::AWS_ACCESS_KEY], $payerCredentials->properties[Entity\CloudCredentialsProperty::AWS_SECRET_KEY], !empty($payerCredentials->properties[Entity\CloudCredentialsProperty::AWS_CERTIFICATE]) ? $payerCredentials->properties[Entity\CloudCredentialsProperty::AWS_CERTIFICATE] : null, !empty($payerCredentials->properties[Entity\CloudCredentialsProperty::AWS_PRIVATE_KEY]) ? $payerCredentials->properties[Entity\CloudCredentialsProperty::AWS_PRIVATE_KEY] : null);
                     } else {
                         $aws = $this->env->aws($expectingRegion, $pars[Entity\CloudCredentialsProperty::AWS_ACCESS_KEY], $pars[Entity\CloudCredentialsProperty::AWS_SECRET_KEY]);
                     }
                     $bucketObjects = $aws->s3->bucket->listObjects($pars[Entity\CloudCredentialsProperty::AWS_DETAILED_BILLING_BUCKET]);
                     $pars[Entity\CloudCredentialsProperty::AWS_DETAILED_BILLING_REGION] = $expectingRegion;
                 } else {
                     throw $e;
                 }
             }
             $objectName = (empty($pars[Entity\CloudCredentialsProperty::AWS_DETAILED_BILLING_PAYER_ACCOUNT]) ? '' : "{$pars[Entity\CloudCredentialsProperty::AWS_DETAILED_BILLING_PAYER_ACCOUNT]}-") . 'aws-billing-detailed-line-items-with-resources-and-tags';
             $objectExists = false;
             $bucketObjectName = null;
             foreach ($bucketObjects as $bucketObject) {
                 /* @var $bucketObject Scalr\Service\Aws\S3\DataType\ObjectData */
                 if (strpos($bucketObject->objectName, $objectName) !== false) {
                     $bucketObjectName = $bucketObject->objectName;
                     $pars[Entity\CloudCredentialsProperty::AWS_DETAILED_BILLING_ENABLED] = 1;
                     $objectExists = true;
                     break;
                 }
             }
             if (!$objectExists) {
                 $this->response->failure();
                 $this->response->data(['errors' => [Entity\CloudCredentialsProperty::AWS_DETAILED_BILLING_PAYER_ACCOUNT => "Object with name '{$objectName}' does not exist."]]);
                 return;
             }
             $aws->s3->object->getMetadata($pars[Entity\CloudCredentialsProperty::AWS_DETAILED_BILLING_BUCKET], $bucketObjectName);
         } catch (Exception $e) {
             $this->response->failure();
             $this->response->data(['errors' => [Entity\CloudCredentialsProperty::AWS_DETAILED_BILLING_BUCKET => sprintf("Cannot access billing bucket with name %s. Error: %s", $pars[Entity\CloudCredentialsProperty::AWS_DETAILED_BILLING_BUCKET], $e->getMessage())]]);
             return;
         }
     }
     $this->db->BeginTrans();
     try {
         $this->env->enablePlatform(SERVER_PLATFORMS::EC2, $enabled);
         if ($enabled) {
             $this->makeCloudCredentials(SERVER_PLATFORMS::EC2, $pars);
             if ($this->getContainer()->analytics->enabled && $bNew) {
                 $this->getContainer()->analytics->notifications->onCloudAdd('ec2', $this->env, $this->user);
             }
         }
         if (!$this->user->getAccount()->getSetting(Scalr_Account::SETTING_DATE_ENV_CONFIGURED)) {
             $this->user->getAccount()->setSetting(Scalr_Account::SETTING_DATE_ENV_CONFIGURED, time());
         }
         //TODO: cloud suspension info must work with cloud credentials
         if ($enabled && $this->env->status == Scalr_Environment::STATUS_INACTIVE && $this->env->getPlatformConfigValue('system.auto-disable-reason')) {
             // env was inactive due invalid keys for amazon, activate it
             $this->env->status = Scalr_Environment::STATUS_ACTIVE;
             $this->env->save();
             $this->env->setPlatformConfig(['system.auto-disable-reason' => NULL]);
             $envAutoEnabled = true;
         }
         $this->db->CommitTrans();
     } catch (Exception $e) {
         $this->db->RollbackTrans();
         throw new Exception(_("Failed to save AWS settings: {$e->getMessage()}"));
     }
     $this->response->success('Cloud credentials have been ' . ($enabled ? 'saved' : 'removed from Scalr'));
     $this->response->data(['enabled' => $enabled, 'demoFarm' => $demoFarm, 'envAutoEnabled' => $envAutoEnabled]);
 }
Example #19
0
 /**
  * @return Scalr_Service_Cloud_Eucalyptus_Client
  * Enter description here ...
  */
 private function getEucaClient(Scalr_Environment $environment, $cloudLocation)
 {
     return Scalr_Service_Cloud_Eucalyptus::newCloud($environment->getPlatformConfigValue(self::SECRET_KEY, true, $cloudLocation), $environment->getPlatformConfigValue(self::ACCESS_KEY, true, $cloudLocation), $environment->getPlatformConfigValue(self::EC2_URL, true, $cloudLocation));
 }
Example #20
0
 /**
  * Gets a normalized url for an each platform
  *
  * @param    string $platform Cloud platform
  * @return   string Returns url
  */
 public function getUrl($platform)
 {
     if (!isset($this->aUrl[$platform])) {
         if ($platform == \SERVER_PLATFORMS::EC2) {
             $value = '';
         } else {
             if (PlatformFactory::isOpenstack($platform)) {
                 $value = CloudLocation::normalizeUrl($this->env->getPlatformConfigValue($platform . '.' . OpenstackPlatformModule::KEYSTONE_URL));
             } else {
                 if (PlatformFactory::isCloudstack($platform)) {
                     $value = CloudLocation::normalizeUrl($this->env->getPlatformConfigValue($platform . '.' . CloudstackPlatformModule::API_URL));
                 } else {
                     if ($platform == \SERVER_PLATFORMS::GCE) {
                         $value = '';
                     }
                 }
             }
         }
         $this->aUrl[$platform] = $value;
     }
     return $this->aUrl[$platform];
 }
Example #21
0
 public function getDefaultVpc(\Scalr_Environment $environment, $cloudLocation)
 {
     $vpcId = $environment->getPlatformConfigValue(self::DEFAULT_VPC_ID . ".{$cloudLocation}");
     if ($vpcId === null || $vpcId === false) {
         $vpcId = "";
         $aws = $environment->aws($cloudLocation);
         $list = $aws->ec2->describeAccountAttributes(array('default-vpc'));
         foreach ($list as $item) {
             if ($item->attributeName == 'default-vpc') {
                 $vpcId = $item->attributeValueSet[0]->attributeValue;
             }
         }
         if ($vpcId == 'none') {
             $vpcId = '';
         }
         $environment->setPlatformConfig(array(self::DEFAULT_VPC_ID . ".{$cloudLocation}" => $vpcId));
     }
     return $vpcId;
 }