示例#1
1
 public function xSaveAction()
 {
     $this->request->defineParams(array('category' => array('type' => 'string'), 'name' => array('type' => 'string'), 'value' => array('type' => 'json')));
     $governance = new Scalr_Governance($this->getEnvironmentId());
     $category = $this->getParam('category');
     $name = $this->getParam('name');
     $value = $this->getParam('value');
     if ($category == Scalr_Governance::CATEGORY_GENERAL && $name == Scalr_Governance::GENERAL_LEASE) {
         $enabled = (bool) $value['limits']['enableDefaultLeaseDuration'];
         unset($value['limits']['enableDefaultLeaseDuration']);
         if (!$governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE) && $value['enabled'] == 1 && $enabled) {
             $dt = new DateTime();
             $dt->add(new DateInterval('P' . $value['limits']['defaultLifePeriod'] . 'D'));
             $farms = $this->db->GetCol('SELECT id FROM farms WHERE env_id = ? AND status = ?', array($this->getEnvironmentId(), FARM_STATUS::RUNNING));
             foreach ($farms as $farmId) {
                 $farm = DBFarm::LoadByID($farmId);
                 $farm->SetSetting(DBFarm::SETTING_LEASE_STATUS, 'Active');
                 $farm->SetSetting(DBFarm::SETTING_LEASE_TERMINATE_DATE, $dt->format('Y-m-d H:i:s'));
                 $farm->SetSetting(DBFarm::SETTING_LEASE_NOTIFICATION_SEND, '');
                 $farm->SetSetting(DBFarm::SETTING_LEASE_EXTEND_CNT, 0);
             }
         }
     }
     $governance->setValue($category, $name, $value);
     $this->response->success('Successfully saved');
 }
示例#2
0
 public function xSaveAction()
 {
     $this->request->defineParams(array('name' => array('type' => 'string'), 'value' => array('type' => 'json')));
     $governance = new Scalr_Governance($this->getEnvironmentId());
     $governance->setValue($this->request->getParam('name'), $this->request->getParam('value'));
     $this->response->success('Successfully saved');
 }
示例#3
0
文件: Sshkeys.php 项目: mheydt/scalr
 /**
  * Download private key
  *
  * @param int $sshKeyId
  * @param int $farmId
  * @param string $platform
  * @param string $cloudLocation
  * @param bool $formatPpk
  * @throws Scalr_Exception_InsufficientPermissions
  * @throws Scalr_UI_Exception_NotFound
  * @throws Exception
  */
 public function downloadPrivateAction($sshKeyId = null, $farmId = null, $platform = null, $cloudLocation = null, $formatPpk = false)
 {
     /* @var $sshKey SshKey */
     if ($sshKeyId) {
         $sshKey = SshKey::findPk($sshKeyId);
     } else {
         $sshKey = (new SshKey())->loadGlobalByFarmId($this->getEnvironmentId(), $platform, $cloudLocation, $farmId);
         if (!$sshKey && $platform == SERVER_PLATFORMS::EC2) {
             $governance = new \Scalr_Governance($this->getEnvironmentId());
             $keyName = $governance->getValue(SERVER_PLATFORMS::EC2, \Scalr_Governance::AWS_KEYPAIR);
             if ($keyName) {
                 throw new Exception("The SSH Key was not found. Note that SSH Key Governance is active, so Scalr does not automatically create SSH Keys for your Amazon EC2 Servers.");
             }
         }
     }
     if (!$sshKey) {
         throw new Exception('SSH key not found in database');
     }
     $this->checkPermissions($sshKey);
     $extension = $formatPpk ? 'ppk' : 'pem';
     $fileName = $sshKey->cloudLocation ? "{$sshKey->cloudKeyName}.{$sshKey->cloudLocation}.{$extension}" : "{$sshKey->cloudKeyName}.{$extension}";
     $key = $formatPpk ? $sshKey->getPuttyPrivateKey() : $sshKey->privateKey;
     $this->response->setHeader('Pragma', 'private');
     $this->response->setHeader('Cache-control', 'private, must-revalidate');
     $this->response->setHeader('Content-type', 'plain/text');
     $this->response->setHeader('Content-Disposition', 'attachment; filename="' . $fileName . '"');
     $this->response->setHeader('Content-Length', strlen($key));
     $this->response->setResponse($key);
 }
示例#4
0
 function handleWork($farmId)
 {
     try {
         $dbFarm = DBFarm::LoadByID($farmId);
         $governance = new Scalr_Governance($dbFarm->EnvID);
         $settings = $governance->getValue(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE, 'notifications');
         $curDate = new DateTime();
         $td = new DateTime($dbFarm->GetSetting(DBFarm::SETTING_LEASE_TERMINATE_DATE));
         if ($td > $curDate) {
             // only inform user
             $days = $td->diff($curDate)->days;
             $notifications = json_decode($dbFarm->GetSetting(DBFarm::SETTING_LEASE_NOTIFICATION_SEND), true);
             if (is_array($settings)) {
                 foreach ($settings as $n) {
                     if (!$notifications[$n['key']] && $n['period'] >= $days) {
                         $mailer = Scalr::getContainer()->mailer;
                         $tdHuman = Scalr_Util_DateTime::convertDateTime($td, $dbFarm->GetSetting(DBFarm::SETTING_TIMEZONE), 'M j, Y');
                         if ($n['to'] == 'owner') {
                             $user = new Scalr_Account_User();
                             $user->loadById($dbFarm->createdByUserId);
                             if (Scalr::config('scalr.auth_mode') == 'ldap') {
                                 $email = $user->getSetting(Scalr_Account_User::SETTING_LDAP_EMAIL);
                                 if (!$email) {
                                     $email = $user->getEmail();
                                 }
                             } else {
                                 $email = $user->getEmail();
                             }
                             $mailer->addTo($email);
                         } else {
                             foreach (explode(',', $n['emails']) as $email) {
                                 $mailer->addTo(trim($email));
                             }
                         }
                         $mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/farm_lease_terminate.eml', array('{{terminate_date}}' => $tdHuman, '{{farm}}' => $dbFarm->Name, '{{envName}}' => $dbFarm->GetEnvironmentObject()->name, '{{envId}}' => $dbFarm->GetEnvironmentObject()->id));
                         $notifications[$n['key']] = 1;
                         $dbFarm->SetSetting(DBFarm::SETTING_LEASE_NOTIFICATION_SEND, json_encode($notifications));
                         $this->logger->info("Notification was sent by key: " . $n['key'] . " about farm: " . $dbFarm->Name . " by lease manager");
                     }
                 }
             }
         } else {
             // terminate farm
             $event = new FarmTerminatedEvent(0, 1, false, 1);
             Scalr::FireEvent($farmId, $event);
             $this->logger->info("Farm: " . $dbFarm->Name . " was terminated by lease manager");
         }
     } catch (Exception $e) {
         var_dump($e->getMessage());
     }
 }
示例#5
0
 public function xListServersAction()
 {
     if (!$this->user->isAdmin()) {
         $governance = new Scalr_Governance($this->getEnvironmentId());
         $limits = $governance->getValue(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_CHEF, null);
     }
     $list = [];
     foreach ($this->getList() as $server) {
         if (!$limits || isset($limits['servers'][(string) $server['id']])) {
             $list[] = ['id' => (string) $server['id'], 'url' => $server['url'], 'username' => $server['username'], 'scope' => $server['scope']];
         }
     }
     $this->response->data(['data' => $list]);
 }
示例#6
0
 public function xCloneAction()
 {
     if (!$this->user->isAccountSuperAdmin() && !$this->request->isAllowed(Acl::RESOURCE_ENVADMINISTRATION_ENV_CLOUDS)) {
         throw new Scalr_Exception_InsufficientPermissions();
     }
     $params = array('envId' => array('type' => 'int'), 'name' => array('type' => 'string', 'validator' => array(Scalr_Validator::REQUIRED => true, Scalr_Validator::NOHTML => true)));
     $this->request->defineParams($params);
     $this->request->validate();
     $oldEnv = Scalr_Environment::init()->loadById($this->getParam('envId'));
     $this->user->getPermissions()->validate($oldEnv);
     if ($this->request->isValid()) {
         if (!$this->user->isAccountOwner() && !$this->user->isAccountSuperAdmin()) {
             throw new Scalr_Exception_InsufficientPermissions();
         }
         $this->user->getAccount()->validateLimit(Scalr_Limits::ACCOUNT_ENVIRONMENTS, 1);
         $env = $this->user->getAccount()->createEnvironment($this->getParam('name'));
         $env->status = Scalr_Environment::STATUS_ACTIVE;
         //Copy cloud credentials
         $cloudConfig = $oldEnv->getFullConfiguration();
         foreach ($cloudConfig as $group => $props) {
             $env->setPlatformConfig($props, null, $group);
         }
         //Copy teams & ACLs
         $teams = $oldEnv->getTeams();
         foreach ($teams as $teamId) {
             $env->addTeam($teamId);
         }
         //Copy Env level global variables
         $oldGv = new Scalr_Scripting_GlobalVariables($oldEnv->clientId, $oldEnv->id, Scalr_Scripting_GlobalVariables::SCOPE_ENVIRONMENT);
         $variables = $oldGv->getValues();
         $newGv = new Scalr_Scripting_GlobalVariables($env->clientId, $env->id, Scalr_Scripting_GlobalVariables::SCOPE_ENVIRONMENT);
         $newGv->setValues($variables);
         //Copy governance rules
         $oldGov = new Scalr_Governance($oldEnv->id);
         $govRules = $oldGov->getValues();
         $newGov = new Scalr_Governance($env->id);
         foreach ($govRules as $category => $rules) {
             foreach ($rules as $name => $data) {
                 $newGov->setValue($category, $name, $data);
             }
         }
         $this->response->success("Environment successfully cloned");
         $this->response->data(array('env' => array('id' => $env->id, 'name' => $env->name, 'status' => $env->status, 'platforms' => $env->getEnabledPlatforms(), 'teams' => $teams, 'ccId' => $env->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID))));
     } else {
         $this->response->failure($this->request->getValidationErrorsMessage());
     }
 }
示例#7
0
 public function xCreateAction()
 {
     $this->request->defineParams(array('listeners' => array('type' => 'json'), 'healthcheck' => array('type' => 'json'), 'zones' => array('type' => 'array'), 'subnets' => array('type' => 'array'), 'scheme' => array('type' => 'string')));
     $healthCheck = $this->getParam('healthcheck');
     $elb = $this->environment->aws($this->getParam('cloudLocation'))->elb;
     //prepare listeners
     $listenersList = new ListenerList();
     $li = 0;
     foreach ($this->getParam('listeners') as $listener) {
         $listener_chunks = explode("#", $listener);
         $listenersList->append(new ListenerData(trim($listener_chunks[1]), trim($listener_chunks[2]), trim($listener_chunks[0]), null, trim($listener_chunks[3])));
     }
     $availZones = $this->getParam('zones');
     $subnets = $this->getParam('subnets');
     $scheme = $this->getParam('scheme');
     $elb_name = sprintf("scalr-%s-%s", CryptoTool::sault(10), rand(100, 999));
     $healthCheckType = new HealthCheckData();
     $healthCheckType->target = $healthCheck['target'];
     $healthCheckType->healthyThreshold = $healthCheck['healthyThreshold'];
     $healthCheckType->interval = $healthCheck['interval'];
     $healthCheckType->timeout = $healthCheck['timeout'];
     $healthCheckType->unhealthyThreshold = $healthCheck['unhealthyThreshold'];
     //Creates a new ELB
     $dnsName = $elb->loadBalancer->create($elb_name, $listenersList, !empty($availZones) ? $availZones : null, !empty($subnets) ? $subnets : null, null, !empty($scheme) ? $scheme : null);
     $tags = [['key' => \Scalr_Governance::SCALR_META_TAG_NAME, 'value' => $this->environment->applyGlobalVarsToValue(\Scalr_Governance::SCALR_META_TAG_VALUE)]];
     //Tags governance
     $governance = new \Scalr_Governance($this->environment->id);
     $gTags = (array) $governance->getValue('ec2', \Scalr_Governance::AWS_TAGS);
     if (count($gTags) > 0) {
         foreach ($gTags as $tKey => $tValue) {
             $tags[] = array('key' => $tKey, 'value' => $this->environment->applyGlobalVarsToValue($tValue));
         }
     }
     $elb->loadBalancer->addTags($elb_name, $tags);
     try {
         $elb->loadBalancer->configureHealthCheck($elb_name, $healthCheckType);
     } catch (Exception $e) {
         $elb->loadBalancer->delete($elb_name);
         throw $e;
     }
     // return all as in xListElb
     $this->response->data(array('elb' => array('name' => $elb_name, 'dnsName' => $dnsName)));
 }
 /**
  * Gets the list of the security groups for the specified db server.
  *
  * If server does not have required security groups this method will create them.
  *
  * @param   DBServer               $DBServer The DB Server instance
  * @param   \Scalr\Service\Aws\Ec2 $ec2      Ec2 Client instance
  * @param   string                 $vpcId    optional The ID of VPC
  * @return  array  Returns array looks like array(groupid-1, groupid-2, ..., groupid-N)
  */
 private function GetServerSecurityGroupsList(DBServer $DBServer, \Scalr\Service\Aws\Ec2 $ec2, $vpcId = "", \Scalr_Governance $governance = null)
 {
     $retval = array();
     $checkGroups = array();
     $sgGovernance = true;
     $allowAdditionalSgs = true;
     $vpcId = null;
     if ($governance) {
         $sgs = $governance->getValue(\SERVER_PLATFORMS::EUCALYPTUS, \Scalr_Governance::EUCALYPTUS_SECURITY_GROUPS);
         if ($sgs !== null) {
             $governanceSecurityGroups = @explode(",", $sgs);
             if (!empty($governanceSecurityGroups)) {
                 foreach ($governanceSecurityGroups as $sg) {
                     if ($sg != '') {
                         array_push($checkGroups, trim($sg));
                     }
                 }
             }
             $sgGovernance = false;
             $allowAdditionalSgs = $governance->getValue(\SERVER_PLATFORMS::EUCALYPTUS, \Scalr_Governance::EUCALYPTUS_SECURITY_GROUPS, 'allow_additional_sec_groups');
         }
     }
     if (!$sgGovernance || $allowAdditionalSgs) {
         if ($DBServer->farmRoleId != 0) {
             $dbFarmRole = $DBServer->GetFarmRoleObject();
             if ($dbFarmRole->GetSetting(DBFarmRole::SETTING_EUCA_SECURITY_GROUPS_LIST) !== null) {
                 // New SG management
                 $sgs = @json_decode($dbFarmRole->GetSetting(DBFarmRole::SETTING_EUCA_SECURITY_GROUPS_LIST));
                 if (!empty($sgs)) {
                     foreach ($sgs as $sg) {
                         if (stripos($sg, 'sg-') === 0) {
                             array_push($retval, $sg);
                         } else {
                             array_push($checkGroups, $sg);
                         }
                     }
                 }
             }
         } else {
             array_push($checkGroups, 'scalr-rb-system');
         }
     }
     // No name based security groups, return only SG ids.
     if (empty($checkGroups)) {
         return $retval;
     }
     // Filter groups
     $filter = array(array('name' => SecurityGroupFilterNameType::groupName(), 'value' => $checkGroups));
     // Get filtered list of SG required by scalr;
     try {
         $list = $ec2->securityGroup->describe(null, null, $filter);
         $sgList = array();
         foreach ($list as $sg) {
             /* @var $sg \Scalr\Service\Aws\Ec2\DataType\SecurityGroupData */
             if ($vpcId == '' && !$sg->vpcId || $vpcId && $sg->vpcId == $vpcId) {
                 $sgList[$sg->groupName] = $sg->groupId;
             }
         }
         unset($list);
     } catch (\Exception $e) {
         throw new \Exception("Cannot get list of security groups (1): {$e->getMessage()}");
     }
     foreach ($checkGroups as $groupName) {
         // Check default SG
         if ($groupName == 'default') {
             array_push($retval, $sgList[$groupName]);
             // Check Roles builder SG
         } elseif ($groupName == 'scalr-rb-system') {
             if (!isset($sgList[$groupName])) {
                 try {
                     $securityGroupId = $ec2->securityGroup->create('scalr-rb-system', "Security group for Roles Builder", $vpcId);
                     $ipRangeList = new IpRangeList();
                     foreach (\Scalr::config('scalr.aws.ip_pool') as $ip) {
                         $ipRangeList->append(new IpRangeData($ip));
                     }
                     sleep(2);
                     $ec2->securityGroup->authorizeIngress(array(new IpPermissionData('tcp', 22, 22, $ipRangeList), new IpPermissionData('tcp', 8008, 8013, $ipRangeList)), $securityGroupId);
                     $sgList['scalr-rb-system'] = $securityGroupId;
                 } catch (\Exception $e) {
                     throw new \Exception(sprintf(_("Cannot create security group '%s': %s"), 'scalr-rb-system', $e->getMessage()));
                 }
             }
             array_push($retval, $sgList[$groupName]);
             //Check scalr-farm.* security group
         } elseif (stripos($groupName, 'scalr-farm.') === 0) {
             if (!isset($sgList[$groupName])) {
                 try {
                     $securityGroupId = $ec2->securityGroup->create($groupName, sprintf("Security group for FarmID N%s", $DBServer->farmId), $vpcId);
                     sleep(2);
                     $userIdGroupPairList = new UserIdGroupPairList(new UserIdGroupPairData($DBServer->GetEnvironmentObject()->getPlatformConfigValue(self::ACCOUNT_ID), null, $groupName));
                     $ec2->securityGroup->authorizeIngress(array(new IpPermissionData('tcp', 0, 65535, null, $userIdGroupPairList), new IpPermissionData('udp', 0, 65535, null, $userIdGroupPairList)), $securityGroupId);
                     $sgList[$groupName] = $securityGroupId;
                 } catch (\Exception $e) {
                     throw new \Exception(sprintf(_("Cannot create security group '%s': %s"), $groupName, $e->getMessage()));
                 }
             }
             array_push($retval, $sgList[$groupName]);
             //Check scalr-role.* security group
         } elseif (stripos($groupName, 'scalr-role.') === 0) {
             if (!isset($sgList[$groupName])) {
                 try {
                     $securityGroupId = $ec2->securityGroup->create($groupName, sprintf("Security group for FarmRoleID N%s on FarmID N%s", $DBServer->GetFarmRoleObject()->ID, $DBServer->farmId), $vpcId);
                     sleep(2);
                     // DB rules
                     $dbRules = $DBServer->GetFarmRoleObject()->GetRoleObject()->getSecurityRules();
                     $groupRules = array();
                     foreach ($dbRules as $rule) {
                         $groupRules[\Scalr_Util_CryptoTool::hash($rule['rule'])] = $rule;
                     }
                     // Behavior rules
                     foreach (\Scalr_Role_Behavior::getListForFarmRole($DBServer->GetFarmRoleObject()) as $bObj) {
                         $bRules = $bObj->getSecurityRules();
                         foreach ($bRules as $r) {
                             if ($r) {
                                 $groupRules[\Scalr_Util_CryptoTool::hash($r)] = array('rule' => $r);
                             }
                         }
                     }
                     // Default rules
                     $userIdGroupPairList = new UserIdGroupPairList(new UserIdGroupPairData($DBServer->GetEnvironmentObject()->getPlatformConfigValue(self::ACCOUNT_ID), null, $groupName));
                     $rules = array(new IpPermissionData('tcp', 0, 65535, null, $userIdGroupPairList), new IpPermissionData('udp', 0, 65535, null, $userIdGroupPairList));
                     foreach ($groupRules as $rule) {
                         $group_rule = explode(":", $rule["rule"]);
                         $rules[] = new IpPermissionData($group_rule[0], $group_rule[1], $group_rule[2], new IpRangeData($group_rule[3]));
                     }
                     $ec2->securityGroup->authorizeIngress($rules, $securityGroupId);
                     $sgList[$groupName] = $securityGroupId;
                 } catch (\Exception $e) {
                     throw new \Exception(sprintf(_("Cannot create security group '%s': %s"), $groupName, $e->getMessage()));
                 }
             }
             array_push($retval, $sgList[$groupName]);
         } elseif ($groupName == \Scalr::config('scalr.aws.security_group_name')) {
             if (!isset($sgList[$groupName])) {
                 try {
                     $securityGroupId = $ec2->securityGroup->create($groupName, "Security rules needed by Scalr", $vpcId);
                     $ipRangeList = new IpRangeList();
                     foreach (\Scalr::config('scalr.aws.ip_pool') as $ip) {
                         $ipRangeList->append(new IpRangeData($ip));
                     }
                     // TODO: Open only FOR VPC ranges
                     $ipRangeList->append(new IpRangeData('10.0.0.0/8'));
                     sleep(2);
                     $ec2->securityGroup->authorizeIngress(array(new IpPermissionData('tcp', 3306, 3306, $ipRangeList), new IpPermissionData('tcp', 8008, 8013, $ipRangeList), new IpPermissionData('udp', 8014, 8014, $ipRangeList)), $securityGroupId);
                     $sgList[$groupName] = $securityGroupId;
                 } catch (\Exception $e) {
                     throw new \Exception(sprintf(_("Cannot create security group '%s': %s"), $groupName, $e->getMessage()));
                 }
             }
             array_push($retval, $sgList[$groupName]);
         } else {
             if (!isset($sgList[$groupName])) {
                 throw new \Exception(sprintf(_("Security group '%s' is not found"), $groupName));
             } else {
                 array_push($retval, $sgList[$groupName]);
             }
         }
     }
     return $retval;
 }
示例#9
0
文件: Farms.php 项目: rickb838/scalr
 public function buildAction()
 {
     $this->request->restrictAccess(Acl::RESOURCE_FARMS, Acl::PERM_FARMS_MANAGE);
     $this->request->defineParams(array('farmId' => array('type' => 'int'), 'roleId' => array('type' => 'int')));
     $farmId = $this->getParam('farmId');
     $roleId = $this->getParam('roleId');
     $moduleParams = array('farmId' => $farmId, 'roleId' => $roleId, 'behaviors' => ROLE_BEHAVIORS::GetName(null, true));
     unset($moduleParams['behaviors'][ROLE_BEHAVIORS::CASSANDRA]);
     unset($moduleParams['behaviors'][ROLE_BEHAVIORS::CUSTOM]);
     unset($moduleParams['behaviors'][ROLE_BEHAVIORS::HAPROXY]);
     //platforms list
     $platforms = self::loadController('Platforms')->getEnabledPlatforms();
     if (empty($platforms)) {
         throw new Exception('Before building new farm you need to configure environment and setup cloud credentials');
     }
     //categories list
     $categories = $this->db->GetAll("SELECT c.id, c.name, COUNT(DISTINCT r.id) AS total\n             FROM role_categories c\n             LEFT JOIN roles r ON c.id = r.cat_id AND r.env_id IN(0, ?) AND r.id IN (\n                SELECT role_id\n                FROM role_images\n                WHERE role_id = r.id\n                AND platform IN ('" . implode("','", array_keys($platforms)) . "')\n             )\n             LEFT JOIN roles_queue q ON r.id = q.role_id\n             WHERE c.env_id IN (0, ?)\n             AND q.id IS NULL\n             GROUP BY c.id\n            ", array($this->environment->id, $this->environment->id));
     $moduleParams['categories'] = array();
     foreach ($categories as $g) {
         $moduleParams['categories'][$g['id']] = $g;
     }
     $moduleParams['farmVpcEc2Enabled'] = $this->getEnvironment()->isPlatformEnabled(SERVER_PLATFORMS::EC2);
     if ($moduleParams['farmVpcEc2Enabled']) {
         $moduleParams['farmVpcEc2Locations'] = self::loadController('Platforms')->getCloudLocations(SERVER_PLATFORMS::EC2, false);
     }
     if ($farmId) {
         $c = self::loadController('Builder', 'Scalr_UI_Controller_Farms');
         $moduleParams['farm'] = $c->getFarm2($farmId);
     } else {
         // TODO: remove hack, do better
         $vars = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARM);
         $moduleParams['farmVariables'] = $vars->getValues();
     }
     $moduleParams['tabs'] = array('vpcrouter', 'dbmsr', 'mongodb', 'mysql', 'scaling', 'network', 'gce', 'cloudfoundry', 'rabbitmq', 'haproxy', 'proxy', 'rds', 'scripting', 'nimbula', 'ec2', 'security', 'devel', 'storage', 'variables', 'advanced');
     if ($this->user->getAccount()->isFeatureEnabled(Scalr_Limits::FEATURE_CHEF)) {
         $moduleParams['tabs'][] = 'chef';
     }
     //deprecated tabs
     $moduleParams['tabs'][] = 'deployments';
     $moduleParams['tabs'][] = 'ebs';
     $moduleParams['tabs'][] = 'params';
     $moduleParams['tabs'][] = 'servicesconfig';
     $conf = $this->getContainer()->config->get('scalr.load_statistics.connections.plotter');
     $moduleParams['tabParams'] = array('farmId' => $farmId, 'farmHash' => $moduleParams['farm'] ? $moduleParams['farm']['farm']['hash'] : '', 'accountId' => $this->environment->getPlatformConfigValue(Ec2PlatformModule::ACCOUNT_ID), 'remoteAddress' => $this->request->getRemoteAddr(), 'monitoringHostUrl' => "{$conf['scheme']}://{$conf['host']}:{$conf['port']}", 'nginx' => array('server_section' => @file_get_contents("../templates/services/nginx/server_section.tpl"), 'server_section_ssl' => @file_get_contents("../templates/services/nginx/server_section_ssl.tpl")));
     // TODO: Features
     $moduleParams['tabParams']['featureRAID'] = $this->user->getAccount()->isFeatureEnabled(Scalr_Limits::FEATURE_RAID);
     $moduleParams['tabParams']['featureMFS'] = $this->user->getAccount()->isFeatureEnabled(Scalr_Limits::FEATURE_MFS);
     $moduleParams['tabParams']['scalr.dns.global.enabled'] = \Scalr::config('scalr.dns.global.enabled');
     $moduleParams['tabParams']['scalr.instances_connection_policy'] = \Scalr::config('scalr.instances_connection_policy');
     $moduleParams['tabParams']['scalr.scalarizr_update.repos'] = array_keys(\Scalr::config('scalr.scalarizr_update.repos'));
     $moduleParams['tabParams']['scalr.scalarizr_update.default_repo'] = \Scalr::config('scalr.scalarizr_update.default_repo');
     $moduleParams['metrics'] = self::loadController('Metrics', 'Scalr_UI_Controller_Scaling')->getList();
     $moduleParams['timezones_list'] = Scalr_Util_DateTime::getTimezones();
     $moduleParams['timezone_default'] = $this->user->getSetting(Scalr_Account_User::SETTING_UI_TIMEZONE);
     if ($moduleParams['farm']['farm']['ownerEditable']) {
         $moduleParams['usersList'] = Scalr_Account_User::getList($this->user->getAccountId());
     }
     $governance = new Scalr_Governance($this->getEnvironmentId());
     $moduleParams['governance'] = $governance->getValues(true);
     $defaultFarmRoleSecurityGroups = array('default');
     if (\Scalr::config('scalr.aws.security_group_name')) {
         $defaultFarmRoleSecurityGroups[] = \Scalr::config('scalr.aws.security_group_name');
     }
     $moduleParams['roleDefaultSettings'] = array('base.keep_scripting_logs_time' => \Scalr::config('scalr.system.scripting.default_instance_log_rotation_period'), 'security_groups.list' => json_encode($defaultFarmRoleSecurityGroups));
     //cost analytics
     if ($this->getContainer()->analytics->enabled && $this->getEnvironment()->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID)) {
         $costCenter = $this->getContainer()->analytics->ccs->get($this->getEnvironment()->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID));
         $projects = [];
         if ($costCenter instanceof CostCentreEntity) {
             $projectsIterator = new SharedProjectsFilterIterator($costCenter->getProjects(), $costCenter->ccId, $this->user, $this->getEnvironment());
             foreach ($projectsIterator as $item) {
                 /* @var $item ProjectEntity */
                 $projects[] = array('projectId' => $item->projectId, 'name' => $item->name);
             }
             $costCentreName = $costCenter->name;
         } else {
             $costCentreName = '';
         }
         $moduleParams['analytics'] = array('costCenterName' => $costCentreName, 'projects' => $projects);
         if ($farmId) {
             $dbFarm = DBFarm::LoadByID($farmId);
             $moduleParams['farm']['farm']['projectId'] = $dbFarm->GetSetting(DBFarm::SETTING_PROJECT_ID);
         }
     }
     $this->response->page('ui/farms/builder.js', $moduleParams, array('ui/farms/builder/selroles.js', 'ui/farms/builder/roleedit.js', 'ui/farms/builder/roleslibrary.js', 'ui/farms/builder/tabs/dbmsr.js', 'ui/farms/builder/tabs/cloudfoundry.js', 'ui/farms/builder/tabs/rabbitmq.js', 'ui/farms/builder/tabs/mongodb.js', 'ui/farms/builder/tabs/haproxy.js', 'ui/farms/builder/tabs/proxy.js', 'ui/farms/builder/tabs/mysql.js', 'ui/farms/builder/tabs/nimbula.js', 'ui/farms/builder/tabs/rds.js', 'ui/farms/builder/tabs/gce.js', 'ui/farms/builder/tabs/scaling.js', 'ui/farms/builder/tabs/scripting.js', 'ui/farms/builder/tabs/advanced.js', 'ui/farms/builder/tabs/ec2.js', 'ui/farms/builder/tabs/security.js', 'ui/farms/builder/tabs/storage.js', 'ui/farms/builder/tabs/variables.js', 'ui/farms/builder/tabs/devel.js', 'ui/farms/builder/tabs/chef.js', 'ui/farms/builder/tabs/vpcrouter.js', 'ui/farms/builder/tabs/network.js', 'ui/farms/builder/tabs/deployments.js', 'ui/farms/builder/tabs/ebs.js', 'ui/farms/builder/tabs/params.js', 'ui/farms/builder/tabs/servicesconfig.js', 'ui/farms/builder/roleslibrary/ec2.js', 'ui/farms/builder/roleslibrary/vpc.js', 'ui/farms/builder/roleslibrary/euca.js', 'ui/farms/builder/roleslibrary/rackspace.js', 'ui/farms/builder/roleslibrary/openstack.js', 'ui/farms/builder/roleslibrary/cloudstack.js', 'ui/farms/builder/roleslibrary/gce.js', 'ui/farms/builder/roleslibrary/mongodb.js', 'ui/farms/builder/roleslibrary/dbmsr.js', 'ui/farms/builder/roleslibrary/proxy.js', 'ui/farms/builder/roleslibrary/haproxy.js', 'ui/farms/builder/roleslibrary/chef.js', 'codemirror/codemirror.js', 'ui/core/variablefield.js', 'ui/scripts/scriptfield.js', 'ux-boxselect.js', 'ui/monitoring/window.js', 'ui/services/chef/chefsettings.js', 'ui/security/groups/sgeditor.js'), array('ui/farms/builder/selroles.css', 'ui/farms/builder/roleedit.css', 'ui/farms/builder/roleslibrary.css', 'codemirror/codemirror.css', 'ui/core/variablefield.css', 'ui/scripts/scriptfield.css', 'ui/farms/builder/tabs/scaling.css'));
 }
示例#10
0
 public function getBaseConfiguration(DBServer $dbServer, $isHostInit = false, $onlyBase = false)
 {
     $configuration = new stdClass();
     $dbFarmRole = $dbServer->GetFarmRoleObject();
     //Storage
     if (!$onlyBase) {
         try {
             if ($dbFarmRole) {
                 $storage = new FarmRoleStorage($dbFarmRole);
                 $volumes = $storage->getVolumesConfigs($dbServer, $isHostInit);
                 if (!empty($volumes)) {
                     $configuration->volumes = $volumes;
                 }
             }
         } catch (Exception $e) {
             $this->logger->error(new FarmLogMessage($dbServer->farmId, "Cannot init storage: {$e->getMessage()}"));
         }
     }
     // Base
     try {
         if ($dbFarmRole) {
             $scriptingLogTimeout = $dbFarmRole->GetSetting(self::ROLE_BASE_KEEP_SCRIPTING_LOGS_TIME);
             if (!$scriptingLogTimeout) {
                 $scriptingLogTimeout = 3600;
             }
             $configuration->base = new stdClass();
             $configuration->base->keepScriptingLogsTime = $scriptingLogTimeout;
             $configuration->base->abortInitOnScriptFail = (int) $dbFarmRole->GetSetting(self::ROLE_BASE_ABORT_INIT_ON_SCRIPT_FAIL);
             $configuration->base->disableFirewallManagement = (int) $dbFarmRole->GetSetting(self::ROLE_BASE_DISABLE_FIREWALL_MANAGEMENT);
             $configuration->base->rebootAfterHostinitPhase = (int) $dbFarmRole->GetSetting(self::ROLE_BASE_REBOOT_AFTER_HOSTINIT_PHASE);
             $configuration->base->resumeStrategy = PlatformFactory::NewPlatform($dbFarmRole->Platform)->getResumeStrategy();
             //Dev falgs for our
             if (Scalr::isHostedScalr() && $dbServer->envId == 3414) {
                 $configuration->base->unionScriptExecutor = 1;
             }
             $governance = new Scalr_Governance($dbFarmRole->GetFarmObject()->EnvID);
             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 = $dbFarmRole->GetSetting(self::ROLE_BASE_HOSTNAME_FORMAT);
             }
             $configuration->base->hostname = !empty($hostNameFormat) ? $dbServer->applyGlobalVarsToValue($hostNameFormat) : '';
             if ($configuration->base->hostname != '') {
                 $dbServer->SetProperty(self::SERVER_BASE_HOSTNAME, $configuration->base->hostname);
             }
             $apiPort = null;
             $messagingPort = null;
             if (!PlatformFactory::isCloudstack($dbFarmRole->Platform)) {
                 $apiPort = $dbFarmRole->GetSetting(self::ROLE_BASE_API_PORT);
                 $messagingPort = $dbFarmRole->GetSetting(self::ROLE_BASE_MESSAGING_PORT);
             }
             $configuration->base->apiPort = $apiPort ? $apiPort : 8010;
             $configuration->base->messagingPort = $messagingPort ? $messagingPort : 8013;
         }
         //Update settings
         $updateSettings = $dbServer->getScalarizrRepository();
         $configuration->base->update = new stdClass();
         foreach ($updateSettings as $k => $v) {
             $configuration->base->update->{$k} = $v;
         }
     } catch (Exception $e) {
     }
     return $configuration;
 }
示例#11
0
 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));
     }
 }
示例#12
0
 private function GetServerSecurityGroupsList(DBServer $DBServer, \Scalr\Service\OpenStack\OpenStack $osClient, \Scalr_Governance $governance = null)
 {
     $retval = array();
     $checkGroups = array();
     $sgGovernance = true;
     $allowAdditionalSgs = true;
     if ($governance) {
         $sgs = $governance->getValue($DBServer->platform, \Scalr_Governance::OPENSTACK_SECURITY_GROUPS);
         if ($sgs !== null) {
             $governanceSecurityGroups = @explode(",", $sgs);
             if (!empty($governanceSecurityGroups)) {
                 foreach ($governanceSecurityGroups as $sg) {
                     if ($sg != '') {
                         array_push($checkGroups, trim($sg));
                     }
                 }
             }
             $sgGovernance = false;
             $allowAdditionalSgs = $governance->getValue($DBServer->platform, \Scalr_Governance::OPENSTACK_SECURITY_GROUPS, 'allow_additional_sec_groups');
         }
     }
     if (!$sgGovernance || $allowAdditionalSgs) {
         if ($DBServer->farmRoleId != 0) {
             $dbFarmRole = $DBServer->GetFarmRoleObject();
             if ($dbFarmRole->GetSetting(\DBFarmRole::SETTING_OPENSTACK_SECURITY_GROUPS_LIST) !== null) {
                 // New SG management
                 $sgs = @json_decode($dbFarmRole->GetSetting(\DBFarmRole::SETTING_OPENSTACK_SECURITY_GROUPS_LIST));
                 if (!empty($sgs)) {
                     foreach ($sgs as $sg) {
                         array_push($checkGroups, $sg);
                     }
                 }
             } else {
                 // Old SG management
                 array_push($checkGroups, 'default');
                 array_push($checkGroups, \Scalr::config('scalr.aws.security_group_name'));
             }
         } else {
             array_push($checkGroups, 'scalr-rb-system');
         }
     }
     try {
         if ($this->hasOpenStackNetworkSecurityGroupExtension($osClient)) {
             $list = $osClient->network->securityGroups->list();
         } else {
             $list = $osClient->servers->securityGroups->list();
         }
         do {
             foreach ($list as $sg) {
                 $sgroups[strtolower($sg->name)] = $sg;
                 $sgroupIds[strtolower($sg->id)] = $sg;
             }
             if ($list instanceof PaginationInterface) {
                 $list = $list->getNextPage();
             } else {
                 $list = false;
             }
         } while ($list !== false);
         unset($list);
     } catch (\Exception $e) {
         throw new \Exception("GetServerSecurityGroupsList failed: {$e->getMessage()}");
     }
     foreach ($checkGroups as $groupName) {
         if (preg_match('/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/si', $groupName) || !in_array($groupName, array('scalr-rb-system', 'default', \Scalr::config('scalr.aws.security_group_name')))) {
             if (isset($sgroupIds[$groupName])) {
                 $groupName = $sgroupIds[$groupName]->name;
             } else {
                 throw new \Exception(sprintf(_("Security group '%s' is not found"), $groupName));
             }
         }
         // Check default SG
         if ($groupName == 'default') {
             array_push($retval, $groupName);
             // Check Roles builder SG
         } elseif ($groupName == 'scalr-rb-system' || $groupName == \Scalr::config('scalr.aws.security_group_name')) {
             if (!isset($sgroups[$groupName])) {
                 if ($this->hasOpenStackNetworkSecurityGroupExtension($osClient)) {
                     try {
                         $group = $osClient->network->securityGroups->create($groupName, _("Scalr system security group"));
                         $groupId = $group->id;
                     } catch (\Exception $e) {
                         throw new \Exception("GetServerSecurityGroupsList failed on scalr.ip-pool: {$e->getMessage()}");
                     }
                     //Temporary solution because of API requests rate limit
                     $rule = new \stdClass();
                     $rule->protocol = "tcp";
                     $rule->port_range_min = 1;
                     $rule->port_range_max = 65535;
                     $rule->remote_ip_prefix = "0.0.0.0/0";
                     $rule->security_group_id = $groupId;
                     $res = $osClient->servers->securityGroups->addRule($rule);
                     $rule = new \stdClass();
                     $rule->protocol = "udp";
                     $rule->port_range_min = 1;
                     $rule->port_range_max = 65535;
                     $rule->remote_ip_prefix = "0.0.0.0/0";
                     $rule->security_group_id = $groupId;
                     $res = $osClient->servers->securityGroups->addRule($rule);
                 } else {
                     try {
                         $group = $osClient->servers->securityGroups->create($groupName, _("Scalr system security group"));
                         $groupId = $group->id;
                     } catch (\Exception $e) {
                         throw new \Exception("GetServerSecurityGroupsList failed on scalr.ip-pool: {$e->getMessage()}");
                     }
                     //Temporary solution because of API requests rate limit
                     $rule = new \stdClass();
                     $rule->ip_protocol = "tcp";
                     $rule->from_port = 1;
                     $rule->to_port = 65535;
                     $rule->cidr = "0.0.0.0/0";
                     $rule->parent_group_id = $groupId;
                     $res = $osClient->servers->securityGroups->addRule($rule);
                     $rule = new \stdClass();
                     $rule->ip_protocol = "udp";
                     $rule->from_port = 1;
                     $rule->to_port = 65535;
                     $rule->cidr = "0.0.0.0/0";
                     $rule->parent_group_id = $groupId;
                     $res = $osClient->servers->securityGroups->addRule($rule);
                 }
             }
             array_push($retval, $groupName);
         } else {
             if (!isset($sgroups[$groupName])) {
                 throw new \Exception(sprintf(_("Security group '%s' is not found"), $groupName));
             } else {
                 array_push($retval, $groupName);
             }
         }
     }
     return $retval;
 }
示例#13
0
文件: Elb.php 项目: rickb838/scalr
 public function createAction()
 {
     $governance = new Scalr_Governance($this->getEnvironmentId());
     $this->response->page('ui/tools/aws/ec2/elb/create.js', array('vpcLimits' => $governance->getValue(SERVER_PLATFORMS::EC2, Scalr_Governance::AWS_VPC, null), 'zones' => self::loadController('Ec2', 'Scalr_UI_Controller_Platforms')->getAvailZones($this->getParam('cloudLocation'))), array('ux-boxselect.js'));
 }
示例#14
0
 public function FarmCreate($Name, $Description = "", $ProjectID = "")
 {
     $this->restrictAccess(Acl::RESOURCE_FARMS, Acl::PERM_FARMS_MANAGE);
     $ProjectID = strtolower($ProjectID);
     $response = $this->CreateInitialResponse();
     $Name = $this->stripValue($Name);
     $Description = $this->stripValue($Description);
     if (!$Name || strlen($Name) < 5) {
         throw new Exception('Name should be at least 5 characters');
     }
     $dbFarm = new DBFarm();
     $dbFarm->ClientID = $this->user->getAccountId();
     $dbFarm->EnvID = $this->Environment->id;
     $dbFarm->Status = FARM_STATUS::TERMINATED;
     $dbFarm->createdByUserId = $this->user->getId();
     $dbFarm->createdByUserEmail = $this->user->getEmail();
     $dbFarm->changedByUserId = $this->user->getId();
     $dbFarm->changedTime = microtime();
     $dbFarm->Name = $Name;
     $dbFarm->RolesLaunchOrder = 0;
     $dbFarm->Comments = $Description;
     $dbFarm->save();
     //Associates cost analytics project with the farm.
     $dbFarm->setProject(!empty($ProjectID) ? $ProjectID : null);
     $governance = new Scalr_Governance($this->Environment->id);
     if ($governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE)) {
         $dbFarm->SetSetting(DBFarm::SETTING_LEASE_STATUS, 'Active');
         // for created farm
     }
     $response->FarmID = $dbFarm->ID;
     return $response;
 }
示例#15
0
 /**
  * Prepare governance security groups patterns
  * @param   string  $list List of security groups, separated by comma
  * @return  Array   Security groups patterns
  */
 public static function prepareSecurityGroupsPatterns($list)
 {
     $result = [];
     if (!empty($list)) {
         $sgs = explode(',', $list);
         foreach ($sgs as $sg) {
             $sg = trim($sg);
             if (!empty($sg)) {
                 $pattern = ['value' => $sg];
                 if (strpos($sg, '*') !== false) {
                     $pattern['regexp'] = \Scalr_Governance::convertAsteriskPatternToRegexp($sg);
                 }
                 $result[strtolower($sg)] = $pattern;
             }
         }
     }
     return $result;
 }
示例#16
0
 private function GetServerSecurityGroupsList(DBServer $DBServer, OpenStack $osClient, \Scalr_Governance $governance = null)
 {
     $retval = $sgroups = $sgroupIds = $checkGroups = [];
     $sgGovernance = false;
     $allowAdditionalSgs = true;
     if ($governance) {
         $sgs = $governance->getValue($DBServer->platform, \Scalr_Governance::OPENSTACK_SECURITY_GROUPS);
         if ($sgs !== null) {
             $governanceSecurityGroups = @explode(",", $sgs);
             if (!empty($governanceSecurityGroups)) {
                 foreach ($governanceSecurityGroups as $sg) {
                     if ($sg != '') {
                         array_push($checkGroups, trim($sg));
                     }
                 }
             }
             if (!empty($checkGroups)) {
                 $sgGovernance = true;
             }
             $allowAdditionalSgs = $governance->getValue($DBServer->platform, \Scalr_Governance::OPENSTACK_SECURITY_GROUPS, 'allow_additional_sec_groups');
         }
     }
     if (!$sgGovernance || $allowAdditionalSgs) {
         if ($DBServer->farmRoleId != 0) {
             $dbFarmRole = $DBServer->GetFarmRoleObject();
             if ($dbFarmRole->GetSetting(Entity\FarmRoleSetting::OPENSTACK_SECURITY_GROUPS_LIST) !== null) {
                 // New SG management
                 $sgs = @json_decode($dbFarmRole->GetSetting(Entity\FarmRoleSetting::OPENSTACK_SECURITY_GROUPS_LIST));
                 if (!empty($sgs)) {
                     foreach ($sgs as $sg) {
                         array_push($checkGroups, $sg);
                     }
                 }
             } else {
                 // Old SG management
                 array_push($checkGroups, 'default');
                 array_push($checkGroups, \Scalr::config('scalr.aws.security_group_name'));
             }
         } else {
             array_push($checkGroups, 'scalr-rb-system');
         }
     }
     try {
         $list = $osClient->listSecurityGroups();
         do {
             foreach ($list as $sg) {
                 $sgroups[strtolower($sg->name)] = $sg;
                 $sgroupIds[strtolower($sg->id)] = $sg;
             }
             if ($list instanceof PaginationInterface) {
                 $list = $list->getNextPage();
             } else {
                 $list = false;
             }
         } while ($list !== false);
         unset($list);
     } catch (\Exception $e) {
         throw new \Exception("GetServerSecurityGroupsList failed: {$e->getMessage()}");
     }
     foreach ($checkGroups as $groupName) {
         if (preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i', $groupName)) {
             if (isset($sgroupIds[strtolower($groupName)])) {
                 $groupName = $sgroupIds[$groupName]->name;
             } else {
                 throw new \Exception(sprintf(_("Security group '%s' is not found (1)"), $groupName));
             }
         } elseif (preg_match('/^\\d+$/', $groupName)) {
             // In openstack IceHouse, SG ID is integer and not UUID
             if (isset($sgroupIds[strtolower($groupName)])) {
                 $groupName = $sgroupIds[$groupName]->name;
             } else {
                 throw new \Exception(sprintf(_("Security group '%s' is not found (1)"), $groupName));
             }
         }
         if ($groupName == 'default') {
             // Check default SG
             array_push($retval, $groupName);
         } elseif ($groupName == 'scalr-rb-system' || $groupName == \Scalr::config('scalr.aws.security_group_name')) {
             // Check Roles builder SG
             if (!isset($sgroups[strtolower($groupName)])) {
                 try {
                     $group = $osClient->createSecurityGroup($groupName, _("Scalr system security group"));
                     $groupId = $group->id;
                 } catch (\Exception $e) {
                     throw new \Exception("GetServerSecurityGroupsList failed on scalr.ip-pool: {$e->getMessage()}");
                 }
                 $r = new CreateSecurityGroupRule($groupId);
                 $r->direction = 'ingress';
                 $r->protocol = 'tcp';
                 $r->port_range_min = 1;
                 $r->port_range_max = 65535;
                 $r->remote_ip_prefix = "0.0.0.0/0";
                 $res = $osClient->createSecurityGroupRule($r);
                 $r = new CreateSecurityGroupRule($groupId);
                 $r->direction = 'ingress';
                 $r->protocol = 'udp';
                 $r->port_range_min = 1;
                 $r->port_range_max = 65535;
                 $r->remote_ip_prefix = "0.0.0.0/0";
                 $res = $osClient->createSecurityGroupRule($r);
             }
             array_push($retval, $groupName);
         } else {
             if (!isset($sgroups[strtolower($groupName)])) {
                 throw new \Exception(sprintf(_("Security group '%s' is not found (2)"), $groupName));
             } else {
                 array_push($retval, $groupName);
             }
         }
     }
     return $retval;
 }
示例#17
0
 /**
  * Gets default vpc security group list
  *
  * @param SecurityGroupList   $vpcSglist
  * @param string    $vpcId
  * @return array
  */
 private function getDefaultSgRow($vpcSglist, $vpcId)
 {
     $governance = new Scalr_Governance($this->getEnvironmentId());
     $values = $governance->getValues(true);
     if (!empty($values['ec2']['aws.additional_security_groups']->value)) {
         $sgDefaultNames = explode(',', $values['ec2']['aws.additional_security_groups']->value);
     }
     $defaultSecurityGroups = [];
     $vpcSgNames = [];
     foreach ($vpcSglist as $vpcSg) {
         /* @var $vpcSg Scalr\Service\Aws\Ec2\DataType\SecurityGroupData */
         if (!empty($sgDefaultNames)) {
             if ($vpcSg->vpcId == $vpcId && in_array($vpcSg->groupName, $sgDefaultNames)) {
                 $defaultSecurityGroups[] = ['securityGroupId' => $vpcSg->groupId, 'securityGroupName' => $vpcSg->groupName];
             }
             $vpcSgNames[] = $vpcSg->groupName;
         } else {
             if ($vpcSg->vpcId == $vpcId && $vpcSg->groupName == 'default') {
                 $defaultSecurityGroups[] = ['securityGroupId' => $vpcSg->groupId, 'securityGroupName' => $vpcSg->groupName];
                 break;
             }
         }
     }
     if (!empty($sgDefaultNames)) {
         $missingSgs = array_diff($sgDefaultNames, $vpcSgNames);
         foreach ($missingSgs as $missingSg) {
             $defaultSecurityGroups[] = ['securityGroupId' => null, 'securityGroupName' => $missingSg];
         }
     }
     return $defaultSecurityGroups;
 }
示例#18
0
文件: Instances.php 项目: scalr/scalr
 /**
  * xLaunchInstanceAction
  *
  * @param string   $cloudLocation
  * @param string   $Engine
  * @param string   $DBInstanceIdentifier
  * @param string   $DBInstanceClass
  * @param string   $MasterUsername
  * @param RawData  $MasterUserPassword
  * @param string   $DBParameterGroup
  * @param string   $LicenseModel                optional
  * @param string   $OptionGroupName             optional
  * @param string   $AllocatedStorage            optional
  * @param string   $StorageType                 optional
  * @param int      $farmId                      optional
  * @param string   $DBName                      optional
  * @param int      $Port                        optional
  * @param string   $VpcId                       optional
  * @param JsonData $VpcSecurityGroups           optional
  * @param JsonData $DBSecurityGroups            optional
  * @param JsonData $SubnetIds                   optional
  * @param bool     $StorageEncrypted            optional
  * @param string   $KmsKeyId                    optional
  * @param string   $PreferredBackupWindow       optional
  * @param string   $CharacterSetName            optional
  * @param bool     $MultiAZ                     optional
  * @param bool     $AutoMinorVersionUpgrade     optional
  * @param string   $AvailabilityZone            optional
  * @param int      $Iops                        optional
  * @param string   $BackupRetentionPeriod       optional
  * @param string   $PreferredMaintenanceWindow  optional
  * @param string   $DBSubnetGroupName           optional
  * @param string   $EngineVersion               optional
  * @param bool     $PubliclyAccessible          optional
  * @throws Exception
  * @throws ScalrException
  */
 public function xLaunchInstanceAction($cloudLocation, $Engine, $DBInstanceIdentifier, $DBInstanceClass, $MasterUsername, RawData $MasterUserPassword, $DBParameterGroup, $LicenseModel = null, $OptionGroupName = null, $AllocatedStorage = null, $StorageType = null, $farmId = null, $DBName = null, $Port = null, $VpcId = null, JsonData $VpcSecurityGroups = null, JsonData $DBSecurityGroups = null, JsonData $SubnetIds = null, $StorageEncrypted = false, $KmsKeyId = null, $PreferredBackupWindow = null, $CharacterSetName = null, $MultiAZ = null, $AutoMinorVersionUpgrade = false, $AvailabilityZone = null, $Iops = null, $BackupRetentionPeriod = null, $PreferredMaintenanceWindow = null, $DBSubnetGroupName = null, $EngineVersion = null, $PubliclyAccessible = false)
 {
     $this->request->restrictAccess(Acl::RESOURCE_AWS_RDS, Acl::PERM_AWS_RDS_MANAGE);
     $aws = $this->getAwsClient($cloudLocation);
     if ($Engine == 'mysql') {
         $Engine = 'MySQL';
     }
     $request = new CreateDBInstanceRequestData($DBInstanceIdentifier, $DBInstanceClass, $Engine);
     if ($Engine == 'aurora') {
         $StorageType = 'aurora';
         $request->dBClusterIdentifier = strtolower($DBInstanceIdentifier);
     }
     if ($StorageEncrypted) {
         $request->storageEncrypted = $Engine != 'aurora' ? true : null;
         if ($KmsKeyId) {
             $kmsKey = $aws->kms->key->describe($KmsKeyId);
             if (!$kmsKey->enabled) {
                 throw new Exception("This KMS Key is disabled, please choose another one.");
             }
             $allowed = true;
             $governance = new Scalr_Governance($this->getEnvironmentId());
             $allowedKeys = $governance->getValue(SERVER_PLATFORMS::EC2, Scalr_Governance::AWS_KMS_KEYS, $cloudLocation);
             if (!empty($allowedKeys)) {
                 $allowed = false;
                 foreach ($allowedKeys['keys'] as $key) {
                     if ($key['id'] == $kmsKey->keyId) {
                         $allowed = true;
                         break;
                     }
                 }
             }
             if (!$allowed) {
                 throw new ScalrException("A KMS Policy is active in this Environment, access to '{$kmsKey->keyId}' has been restricted by account owner.");
             }
             $request->kmsKeyId = $Engine != 'aurora' ? $KmsKeyId : null;
         }
     }
     if (empty($request->dBClusterIdentifier)) {
         $request->allocatedStorage = $AllocatedStorage;
         $request->masterUsername = $MasterUsername;
         $request->masterUserPassword = (string) $MasterUserPassword;
         $request->dBName = $DBName ?: null;
         $request->port = $Port ?: null;
         $request->preferredBackupWindow = $PreferredBackupWindow ?: null;
         $vpcSgIds = [];
         foreach ($VpcSecurityGroups as $VpcSecurityGroup) {
             $vpcSgIds[] = $VpcSecurityGroup['id'];
         }
         $request->vpcSecurityGroupIds = empty($vpcSgIds) ? null : $vpcSgIds;
     }
     $request->characterSetName = $CharacterSetName ?: null;
     if (!empty($DBParameterGroup)) {
         $paramGroups = $aws->rds->dbParameterGroup->describe();
         foreach ($paramGroups as $param) {
             /* @var $param DBParameterGroupData */
             if ($param->dBParameterGroupName == $DBParameterGroup) {
                 $paramGroup = $param;
                 break;
             }
         }
     }
     if (!empty($paramGroup)) {
         $request->dBParameterGroupName = $paramGroup->dBParameterGroupName;
     }
     $isMirror = $MultiAZ && in_array($Engine, [DBInstanceData::ENGINE_SQL_SERVER_SE, DBInstanceData::ENGINE_SQL_SERVER_EE]);
     $optionList = $aws->rds->optionGroup->describe($Engine);
     foreach ($optionList as $option) {
         /* @var $option OptionGroupData */
         if ($option->optionGroupName == $OptionGroupName) {
             $optionGroup = $option;
             break;
         }
     }
     if (isset($optionGroup)) {
         $request->optionGroupName = $optionGroup->optionGroupName;
     } else {
         if ($isMirror) {
             $request->optionGroupName = $OptionGroupName;
         }
     }
     $dbSgIds = [];
     foreach ($DBSecurityGroups as $DBSecurityGroup) {
         $dbSgIds[] = $DBSecurityGroup;
     }
     $request->dBSecurityGroups = empty($dbSgIds) ? null : $dbSgIds;
     $request->autoMinorVersionUpgrade = $AutoMinorVersionUpgrade;
     $request->availabilityZone = $AvailabilityZone ?: null;
     $request->backupRetentionPeriod = $BackupRetentionPeriod ?: null;
     $request->preferredMaintenanceWindow = $PreferredMaintenanceWindow ?: null;
     $request->multiAZ = $isMirror ? false : $MultiAZ;
     $request->storageType = $StorageType;
     $request->dBSubnetGroupName = $DBSubnetGroupName ?: null;
     $request->licenseModel = $LicenseModel;
     $request->engineVersion = $EngineVersion ?: null;
     $request->iops = $Iops ?: null;
     if ($VpcId) {
         $request->publiclyAccessible = $PubliclyAccessible;
     }
     $tagsObject = $farmId ? DBFarm::LoadByID($farmId) : $this->environment;
     $request->tags = new TagsList($tagsObject->getAwsTags());
     $result = self::loadController('Aws', 'Scalr_UI_Controller_Tools')->checkSecurityGroupsPolicy($VpcSecurityGroups, Aws::SERVICE_INTERFACE_RDS);
     if ($result === true) {
         $result = self::loadController('Aws', 'Scalr_UI_Controller_Tools')->checkVpcPolicy($VpcId, $SubnetIds, $cloudLocation);
     }
     if ($result === true) {
         if (!empty($request->dBClusterIdentifier)) {
             try {
                 $checkInstance = $aws->rds->dbInstance->describe($request->dBInstanceIdentifier);
             } catch (Exception $e) {
                 $checkInstance = [];
             }
             if (count($checkInstance) > 0) {
                 throw new Exception(sprintf("AWS Error. DB Instance with identifier %s already exists.", $request->dBInstanceIdentifier));
             }
             self::loadController('Clusters', 'Scalr_UI_Controller_Tools_Aws_Rds')->xSaveAction($cloudLocation, $request->dBClusterIdentifier, $Engine, $MasterUsername, $MasterUserPassword, $VpcId, $Port, $DBName, $request->characterSetName, $request->dBParameterGroupName, $request->optionGroupName, new JsonData([$request->availabilityZone]), $request->backupRetentionPeriod, $PreferredBackupWindow, $request->preferredMaintenanceWindow, $request->dBSubnetGroupName, $request->engineVersion, $farmId, $VpcSecurityGroups, $SubnetIds, $StorageEncrypted, $KmsKeyId);
         }
         $instance = $aws->rds->dbInstance->create($request);
         CloudResource::deletePk($request->dBInstanceIdentifier, CloudResource::TYPE_AWS_RDS, $this->getEnvironmentId(), \SERVER_PLATFORMS::EC2, $cloudLocation);
         if ($farmId) {
             $cloudResource = new CloudResource();
             $cloudResource->id = $request->dBInstanceIdentifier;
             $cloudResource->type = CloudResource::TYPE_AWS_RDS;
             $cloudResource->platform = \SERVER_PLATFORMS::EC2;
             $cloudResource->cloudLocation = $cloudLocation;
             $cloudResource->envId = $this->getEnvironmentId();
             $cloudResource->farmId = $farmId;
             $cloudResource->save();
         }
         $vpcSglist = null;
         if (!empty($VpcId)) {
             $filter[] = ['name' => SecurityGroupFilterNameType::vpcId(), 'value' => $VpcId];
             $vpcSglist = $aws->ec2->securityGroup->describe(null, null, $filter);
         }
         $clusters = null;
         if (!empty($instance->dBClusterIdentifier)) {
             /* @var $cluster DBClusterData */
             $clusters = $aws->rds->dbCluster->describe($instance->dBClusterIdentifier);
         }
         $data = $this->getDbInstanceData($aws, $instance, $vpcSglist, $clusters);
         $data['isReplica'] = false;
         if ($isMirror) {
             $data['MultiAZ'] = true;
         }
         $this->response->success("DB Instance successfully created");
         $this->response->data(['instance' => $data, 'cloudLocation' => $cloudLocation]);
     } else {
         $this->response->failure($result);
     }
 }
示例#19
0
文件: Import.php 项目: scalr/scalr
 /**
  * @param   string  $platform       Name of platform
  * @param   string  $cloudLocation  Name of location
  * @param   array   $ids            The list of the identifiers of the cloud instances
  * @param   int     $roleId         optional    Identifier of Role
  * @return  array
  * @throws  Exception
  */
 public function checkStatus($platform, $cloudLocation, $ids, $roleId = null)
 {
     if (!in_array($platform, $this->allowedPlatforms)) {
         throw new Exception(sprintf("Platform '%s' is not supported", $platform));
     }
     if (!$this->environment->isPlatformEnabled($platform)) {
         throw new Exception(sprintf("Platform '%s' is not enabled", $platform));
     }
     if (empty($ids) || empty($ids[0])) {
         throw new Exception("You should provide at least one instanceId");
     }
     $instances = PlatformFactory::NewPlatform($platform)->getOrphanedServers($this->getEnvironmentEntity(), $cloudLocation, $ids);
     $status = ['instances' => $instances];
     $imageIds = array_unique(array_map(function ($item) {
         return $item->imageId;
     }, $instances));
     if (count($imageIds) != 1) {
         $status['compatibility'] = ['success' => false];
         return $status;
     }
     /* @var $instance OrphanedServer */
     $instance = $instances[0];
     $status['compatibility'] = ['success' => true];
     // Check vpc compatibility
     if ($instance->vpcId && $instance->subnetId) {
         $gov = new Scalr_Governance($this->getEnvironmentId());
         $vpcGovernanceRegions = $gov->getValue(SERVER_PLATFORMS::EC2, Scalr_Governance::AWS_VPC, 'regions');
         if (isset($vpcGovernanceRegions)) {
             if (!array_key_exists($cloudLocation, $vpcGovernanceRegions)) {
                 $status['compatibility']['success'] = false;
                 $status['compatibility']['message'] = sprintf('Region <b>%s</b> is not allowed by the Governance.', $cloudLocation);
             } else {
                 $vpcGovernanceIds = $vpcGovernanceRegions[$cloudLocation]['ids'];
                 if (!empty($vpcGovernanceIds) && !in_array($instance->vpcId, $vpcGovernanceIds)) {
                     $status['compatibility']['success'] = false;
                     $status['compatibility']['message'] = sprintf('VPC <b>%s</b> is not allowed by the Governance.', $instance->vpcId);
                 } else {
                     $vpcGovernanceIds = $gov->getValue(SERVER_PLATFORMS::EC2, Scalr_Governance::AWS_VPC, 'ids');
                     /* @var $platformObject Ec2PlatformModule */
                     $platformObject = PlatformFactory::NewPlatform(SERVER_PLATFORMS::EC2);
                     $subnet = $platformObject->listSubnets($this->getEnvironment(), $cloudLocation, $instance->vpcId, true, $instance->subnetId);
                     if (isset($vpcGovernanceIds[$instance->vpcId])) {
                         if (!empty($vpcGovernanceIds[$instance->vpcId]) && is_array($vpcGovernanceIds[$instance->vpcId]) && !in_array($instance->subnetId, $vpcGovernanceIds[$instance->vpcId])) {
                             $status['compatibility']['success'] = false;
                             $status['compatibility']['message'] = sprintf('Subnet <b>%s</b> is prohibited by the Governance.', $instance->subnetId);
                         } else {
                             if ($vpcGovernanceIds[$instance->vpcId] == "outbound-only" && $subnet['type'] != 'private') {
                                 $status['compatibility']['success'] = false;
                                 $status['compatibility']['message'] = 'Only private subnets are allowed by the Governance.';
                             } else {
                                 if ($vpcGovernanceIds[$instance->vpcId] == "full" && $subnet['type'] != 'public') {
                                     $status['compatibility']['success'] = false;
                                     $status['compatibility']['message'] = 'Only public subnets are allowed by the Governance.';
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     if (!$status['compatibility']['success']) {
         return $status;
     }
     $scopeCriteria = ['$or' => [['accountId' => null], ['$and' => [['accountId' => $this->getUser()->accountId], ['$or' => [['envId' => null], ['envId' => $this->getEnvironment()->id]]]]]]];
     /* @var $image Entity\Image */
     $image = Entity\Image::findOne([['platform' => $platform], ['cloudLocation' => $cloudLocation], ['id' => $instance->imageId], $scopeCriteria]);
     $status['image'] = ['success' => !!$image, 'data' => ['id' => $instance->imageId]];
     if ($image) {
         if ($image->isScalarized) {
             $status['image']['success'] = false;
             $status['image']['isScalarized'] = true;
             return $status;
         }
         $status['image']['data'] = ['hash' => $image->hash, 'name' => $image->name, 'id' => $image->id, 'scope' => $image->getScope()];
         $criteria = [['platform' => $platform], ['imageId' => $image->id]];
         if (!($platform == SERVER_PLATFORMS::GCE || $platform == SERVER_PLATFORMS::AZURE)) {
             $criteria[] = ['cloudLocation' => $cloudLocation];
         }
         $roleIds = [];
         foreach (Entity\RoleImage::find($criteria) as $ri) {
             $roleIds[] = $ri->roleId;
         }
         if (count($roleIds)) {
             $roles = Entity\Role::find([['id' => ['$in' => $roleIds]], ['isScalarized' => false], $scopeCriteria]);
             $status['role'] = ['availableRoles' => [], 'image' => Scalr_UI_Controller_Images::controller()->convertEntityToArray($image)];
             $selectedRole = null;
             if (count($roles) == 1) {
                 $selectedRole = $roles->current();
             } else {
                 if ($roleId && in_array($roleId, $roleIds)) {
                     foreach ($roles as $role) {
                         /* @var $role Entity\Role */
                         if ($role->id == $roleId) {
                             $selectedRole = $role;
                             break;
                         }
                     }
                 }
             }
             foreach ($roles as $role) {
                 /* @var $role Entity\Role */
                 $status['role']['availableRoles'][] = ['id' => $role->id, 'name' => $role->name, 'scope' => $role->getScope()];
             }
             if ($selectedRole) {
                 $status['role']['success'] = true;
                 $status['role']['data'] = ['id' => $selectedRole->id, 'name' => $selectedRole->name, 'scope' => $selectedRole->getScope()];
                 $farms = [];
                 $status['farmrole'] = ['instance' => ['instanceType' => $instance->instanceType, 'vpcId' => $instance->vpcId, 'subnetId' => $instance->subnetId, 'roleName' => $selectedRole->name]];
                 foreach (Entity\Farm::find([['envId' => $this->getEnvironment()->id], ['status' => FARM_STATUS::RUNNING]]) as $farm) {
                     /* @var $farm Entity\Farm */
                     if ($this->request->hasPermissions($farm, Acl::PERM_FARMS_UPDATE) && $this->request->hasPermissions($farm, Acl::PERM_FARMS_SERVERS)) {
                         // cloud specific (EC2)
                         if ($farm->settings[Entity\FarmSetting::EC2_VPC_ID] == $instance->vpcId) {
                             $farms[$farm->id] = ['id' => $farm->id, 'name' => $farm->name, 'farmroles' => []];
                         }
                     }
                 }
                 foreach (Entity\FarmRole::find([['farmId' => ['$in' => array_keys($farms)]], ['roleId' => $selectedRole->id]]) as $farmRole) {
                     /* @var $farmRole Entity\FarmRole */
                     if (isset($farms[$farmRole->farmId])) {
                         if (!$instance->subnetId || $instance->subnetId && in_array($instance->subnetId, json_decode($farmRole->settings[Entity\FarmRoleSetting::AWS_VPC_SUBNET_ID]))) {
                             $farms[$farmRole->farmId]['farmroles'][] = ['id' => $farmRole->id, 'name' => $farmRole->alias, 'tags' => $farmRole->getCloudTags(true)];
                         }
                     }
                 }
                 $status['farmrole']['data'] = array_values($farms);
                 $status['farmrole']['success'] = false;
             } else {
                 if (count($roles) > 1) {
                     $status['role']['success'] = false;
                 } else {
                     $status['role']['success'] = false;
                 }
             }
         } else {
             $status['role']['success'] = false;
             $status['role']['image'] = Scalr_UI_Controller_Images::controller()->convertEntityToArray($image);
         }
     }
     return $status;
 }
示例#20
0
文件: Elb.php 项目: mheydt/scalr
 public function createAction($cloudLocation)
 {
     $this->request->restrictAccess(Acl::RESOURCE_AWS_ELB, Acl::PERM_AWS_ELB_MANAGE);
     $governance = new Scalr_Governance($this->getEnvironmentId());
     $this->response->page('ui/tools/aws/ec2/elb/create.js', array('vpcLimits' => $governance->getValue(SERVER_PLATFORMS::EC2, Scalr_Governance::AWS_VPC, null), 'zones' => self::loadController('Ec2', 'Scalr_UI_Controller_Platforms')->getAvailZones($cloudLocation)));
 }
示例#21
0
 /**
  * Return list of tags that should be applied on EC2 resources
  * @param string $addNameTag
  * @return array
  */
 public function getAwsTags($addNameTag = false)
 {
     $tags = [];
     $governance = new \Scalr_Governance($this->envId);
     if ($addNameTag) {
         $nameFormat = $governance->getValue(SERVER_PLATFORMS::EC2, \Scalr_Governance::AWS_INSTANCE_NAME_FORMAT);
         if (!$nameFormat) {
             $nameFormat = $this->GetFarmRoleObject()->GetSetting(Entity\FarmRoleSetting::AWS_INSTANCE_NAME_FORMAT);
             if (!$nameFormat) {
                 $nameFormat = "{SCALR_FARM_NAME} -> {SCALR_FARM_ROLE_ALIAS} #{SCALR_INSTANCE_INDEX}";
             }
         }
         $instanceName = $this->applyGlobalVarsToValue($nameFormat);
         $tags['Name'] = $instanceName;
     }
     $tags[\Scalr_Governance::SCALR_META_TAG_NAME] = $this->applyGlobalVarsToValue(\Scalr_Governance::SCALR_META_TAG_VALUE);
     $gTags = (array) $governance->getValue(SERVER_PLATFORMS::EC2, \Scalr_Governance::AWS_TAGS);
     $gAllowAdditionalTags = $governance->getValue(SERVER_PLATFORMS::EC2, \Scalr_Governance::AWS_TAGS, 'allow_additional_tags');
     if (count($gTags) > 0) {
         foreach ($gTags as $tKey => $tValue) {
             if ($tKey && count($tags) < 10 && !isset($tags[$tKey])) {
                 $tags[$tKey] = $this->applyGlobalVarsToValue($tValue);
             }
         }
     }
     if (count($gTags) == 0 || $gAllowAdditionalTags) {
         //Custom tags
         $cTags = $this->GetFarmRoleObject()->GetSetting(Entity\FarmRoleSetting::AWS_TAGS_LIST);
         $tagsList = @explode("\n", $cTags);
         foreach ((array) $tagsList as $tag) {
             $tag = trim($tag);
             if ($tag && count($tags) < 10) {
                 $tagChunks = explode("=", $tag);
                 if (!isset($tags[trim($tagChunks[0])])) {
                     $tags[trim($tagChunks[0])] = $this->applyGlobalVarsToValue(trim($tagChunks[1]));
                 }
             }
         }
     }
     return $tags;
 }
示例#22
0
 /**
  * Gets the list of the security groups for the specified db server.
  *
  * If server does not have required security groups this method will create them.
  *
  * @param   DBServer               $DBServer    The DB Server instance
  * @param   \Scalr\Service\Aws\Ec2 $ec2         Ec2 Client instance
  * @param   string                 $vpcId       optional The ID of VPC
  * @param   \Scalr_Governance      $governance  Governance
  * @param   string                 $osFamily    optional OS family of the instance
  * @return  array  Returns array looks like array(groupid-1, groupid-2, ..., groupid-N)
  */
 private function GetServerSecurityGroupsList(DBServer $DBServer, \Scalr\Service\Aws\Ec2 $ec2, $vpcId = "", \Scalr_Governance $governance = null, $osFamily = null)
 {
     $retval = array();
     $checkGroups = array();
     $wildCardSgs = [];
     $sgGovernance = false;
     $allowAdditionalSgs = true;
     $roleBuilderSgName = \Scalr::config('scalr.aws.security_group_name') . "-rb";
     if ($governance && $DBServer->farmRoleId) {
         $sgs = $governance->getValue(SERVER_PLATFORMS::EC2, \Scalr_Governance::AWS_SECURITY_GROUPS);
         if ($osFamily == 'windows' && $governance->getValue(SERVER_PLATFORMS::EC2, \Scalr_Governance::AWS_SECURITY_GROUPS, 'windows')) {
             $sgs = $governance->getValue(SERVER_PLATFORMS::EC2, \Scalr_Governance::AWS_SECURITY_GROUPS, 'windows');
         }
         if ($sgs !== null) {
             $governanceSecurityGroups = @explode(",", $sgs);
             if (!empty($governanceSecurityGroups)) {
                 foreach ($governanceSecurityGroups as $sg) {
                     if ($sg != '') {
                         array_push($checkGroups, trim($sg));
                         if (strpos($sg, '*') !== false) {
                             array_push($wildCardSgs, trim($sg));
                         }
                     }
                 }
             }
             if (!empty($checkGroups)) {
                 $sgGovernance = true;
             }
             $allowAdditionalSgs = $governance->getValue(SERVER_PLATFORMS::EC2, \Scalr_Governance::AWS_SECURITY_GROUPS, 'allow_additional_sec_groups');
         }
     }
     if (!$sgGovernance || $allowAdditionalSgs) {
         if ($DBServer->farmRoleId != 0) {
             $dbFarmRole = $DBServer->GetFarmRoleObject();
             if ($dbFarmRole->GetSetting(Entity\FarmRoleSetting::AWS_SECURITY_GROUPS_LIST) !== null) {
                 // New SG management
                 $sgs = @json_decode($dbFarmRole->GetSetting(Entity\FarmRoleSetting::AWS_SECURITY_GROUPS_LIST));
                 if (!empty($sgs)) {
                     foreach ($sgs as $sg) {
                         if (stripos($sg, 'sg-') === 0) {
                             array_push($retval, $sg);
                         } else {
                             array_push($checkGroups, $sg);
                         }
                     }
                 }
             } else {
                 // Old SG management
                 array_push($checkGroups, 'default');
                 array_push($checkGroups, \Scalr::config('scalr.aws.security_group_name'));
                 if (!$vpcId) {
                     array_push($checkGroups, "scalr-farm.{$DBServer->farmId}");
                     array_push($checkGroups, "scalr-role.{$DBServer->farmRoleId}");
                 }
                 $additionalSgs = trim($dbFarmRole->GetSetting(Entity\FarmRoleSetting::AWS_SG_LIST));
                 if ($additionalSgs) {
                     $sgs = explode(",", $additionalSgs);
                     if (!empty($sgs)) {
                         foreach ($sgs as $sg) {
                             $sg = trim($sg);
                             if (stripos($sg, 'sg-') === 0) {
                                 array_push($retval, $sg);
                             } else {
                                 array_push($checkGroups, $sg);
                             }
                         }
                     }
                 }
             }
         } else {
             array_push($checkGroups, $roleBuilderSgName);
         }
     }
     // No name based security groups, return only SG ids.
     if (empty($checkGroups)) {
         return $retval;
     }
     // Filter groups
     $filter = array(array('name' => SecurityGroupFilterNameType::groupName(), 'value' => $checkGroups));
     // If instance run in VPC, add VPC filter
     if ($vpcId != '') {
         $filter[] = array('name' => SecurityGroupFilterNameType::vpcId(), 'value' => $vpcId);
     }
     // Get filtered list of SG required by scalr;
     try {
         $list = $ec2->securityGroup->describe(null, null, $filter);
         $sgList = array();
         foreach ($list as $sg) {
             /* @var $sg \Scalr\Service\Aws\Ec2\DataType\SecurityGroupData */
             if ($vpcId == '' && !$sg->vpcId || $vpcId && $sg->vpcId == $vpcId) {
                 $sgList[$sg->groupName] = $sg->groupId;
             }
         }
         unset($list);
     } catch (Exception $e) {
         throw new Exception("Cannot get list of security groups (1): {$e->getMessage()}");
     }
     foreach ($checkGroups as $groupName) {
         // Check default SG
         if ($groupName == 'default') {
             array_push($retval, $sgList[$groupName]);
             // Check Roles builder SG
         } elseif ($groupName == $roleBuilderSgName) {
             if (!isset($sgList[$groupName])) {
                 try {
                     $securityGroupId = $ec2->securityGroup->create($roleBuilderSgName, "Security group for Roles Builder", $vpcId);
                     $ipRangeList = new IpRangeList();
                     foreach (\Scalr::config('scalr.aws.ip_pool') as $ip) {
                         $ipRangeList->append(new IpRangeData($ip));
                     }
                     sleep(2);
                     $ec2->securityGroup->authorizeIngress(array(new IpPermissionData('tcp', 22, 22, $ipRangeList), new IpPermissionData('tcp', 8008, 8013, $ipRangeList)), $securityGroupId);
                     $sgList[$roleBuilderSgName] = $securityGroupId;
                 } catch (Exception $e) {
                     throw new Exception(sprintf(_("Cannot create security group '%s': %s"), $roleBuilderSgName, $e->getMessage()));
                 }
             }
             array_push($retval, $sgList[$groupName]);
             //Check scalr-farm.* security group
         } elseif (stripos($groupName, 'scalr-farm.') === 0) {
             if (!isset($sgList[$groupName])) {
                 try {
                     $securityGroupId = $ec2->securityGroup->create($groupName, sprintf("Security group for FarmID N%s", $DBServer->farmId), $vpcId);
                     sleep(2);
                     $userIdGroupPairList = new UserIdGroupPairList(new UserIdGroupPairData($DBServer->GetEnvironmentObject()->keychain(SERVER_PLATFORMS::EC2)->properties[Entity\CloudCredentialsProperty::AWS_ACCOUNT_ID], null, $groupName));
                     $ec2->securityGroup->authorizeIngress(array(new IpPermissionData('tcp', 0, 65535, null, $userIdGroupPairList), new IpPermissionData('udp', 0, 65535, null, $userIdGroupPairList)), $securityGroupId);
                     $sgList[$groupName] = $securityGroupId;
                 } catch (Exception $e) {
                     throw new Exception(sprintf(_("Cannot create security group '%s': %s"), $groupName, $e->getMessage()));
                 }
             }
             array_push($retval, $sgList[$groupName]);
             //Check scalr-role.* security group
         } elseif (stripos($groupName, 'scalr-role.') === 0) {
             if (!isset($sgList[$groupName])) {
                 try {
                     $securityGroupId = $ec2->securityGroup->create($groupName, sprintf("Security group for FarmRoleID N%s on FarmID N%s", $DBServer->GetFarmRoleObject()->ID, $DBServer->farmId), $vpcId);
                     sleep(2);
                     // DB rules
                     $dbRules = $DBServer->GetFarmRoleObject()->GetRoleObject()->getSecurityRules();
                     $groupRules = array();
                     foreach ($dbRules as $rule) {
                         $groupRules[CryptoTool::hash($rule['rule'])] = $rule;
                     }
                     // Behavior rules
                     foreach (\Scalr_Role_Behavior::getListForFarmRole($DBServer->GetFarmRoleObject()) as $bObj) {
                         $bRules = $bObj->getSecurityRules();
                         foreach ($bRules as $r) {
                             if ($r) {
                                 $groupRules[CryptoTool::hash($r)] = array('rule' => $r);
                             }
                         }
                     }
                     // Default rules
                     $userIdGroupPairList = new UserIdGroupPairList(new UserIdGroupPairData($DBServer->GetEnvironmentObject()->keychain(SERVER_PLATFORMS::EC2)->properties[Entity\CloudCredentialsProperty::AWS_ACCOUNT_ID], null, $groupName));
                     $rules = array(new IpPermissionData('tcp', 0, 65535, null, $userIdGroupPairList), new IpPermissionData('udp', 0, 65535, null, $userIdGroupPairList));
                     foreach ($groupRules as $rule) {
                         $group_rule = explode(":", $rule["rule"]);
                         $rules[] = new IpPermissionData($group_rule[0], $group_rule[1], $group_rule[2], new IpRangeData($group_rule[3]));
                     }
                     $ec2->securityGroup->authorizeIngress($rules, $securityGroupId);
                     $sgList[$groupName] = $securityGroupId;
                 } catch (Exception $e) {
                     throw new Exception(sprintf(_("Cannot create security group '%s': %s"), $groupName, $e->getMessage()));
                 }
             }
             array_push($retval, $sgList[$groupName]);
         } elseif ($groupName == \Scalr::config('scalr.aws.security_group_name')) {
             if (!isset($sgList[$groupName])) {
                 try {
                     $securityGroupId = $ec2->securityGroup->create($groupName, "Security rules needed by Scalr", $vpcId);
                     $ipRangeList = new IpRangeList();
                     foreach (\Scalr::config('scalr.aws.ip_pool') as $ip) {
                         $ipRangeList->append(new IpRangeData($ip));
                     }
                     // TODO: Open only FOR VPC ranges
                     $ipRangeList->append(new IpRangeData('10.0.0.0/8'));
                     sleep(2);
                     $ec2->securityGroup->authorizeIngress(array(new IpPermissionData('tcp', 3306, 3306, $ipRangeList), new IpPermissionData('tcp', 8008, 8013, $ipRangeList), new IpPermissionData('udp', 8014, 8014, $ipRangeList)), $securityGroupId);
                     $sgList[$groupName] = $securityGroupId;
                 } catch (Exception $e) {
                     throw new Exception(sprintf(_("Cannot create security group '%s': %s"), $groupName, $e->getMessage()));
                 }
             }
             array_push($retval, $sgList[$groupName]);
         } else {
             if (!isset($sgList[$groupName])) {
                 if (!in_array($groupName, $wildCardSgs)) {
                     throw new Exception(sprintf(_("Security group '%s' is not found"), $groupName));
                 } else {
                     $wildCardMatchedSgs = [];
                     $groupNamePattern = \Scalr_Governance::convertAsteriskPatternToRegexp($groupName);
                     foreach ($sgList as $sgGroupName => $sgGroupId) {
                         if (preg_match($groupNamePattern, $sgGroupName) === 1) {
                             array_push($wildCardMatchedSgs, $sgGroupId);
                         }
                     }
                     if (empty($wildCardMatchedSgs)) {
                         throw new Exception(sprintf(_("Security group matched to pattern '%s' is not found."), $groupName));
                     } else {
                         if (count($wildCardMatchedSgs) > 1) {
                             throw new Exception(sprintf(_("There are more than one Security group matched to pattern '%s' found."), $groupName));
                         } else {
                             array_push($retval, $wildCardMatchedSgs[0]);
                         }
                     }
                 }
             } else {
                 array_push($retval, $sgList[$groupName]);
             }
         }
     }
     return $retval;
 }
示例#23
0
文件: Groups.php 项目: rickb838/scalr
 public function createAction()
 {
     $governance = new Scalr_Governance($this->getEnvironmentId());
     $this->response->page('ui/security/groups/edit.js', array('platform' => $this->getParam('platform'), 'cloudLocation' => $this->getParam('cloudLocation'), 'cloudLocationName' => $this->getCloudLocationName($this->getParam('platform'), $this->getParam('cloudLocation')), 'accountId' => $this->environment->getPlatformConfigValue(Ec2PlatformModule::ACCOUNT_ID), 'vpcLimits' => $governance->getValue(SERVER_PLATFORMS::EC2, Scalr_Governance::AWS_VPC, null), 'remoteAddress' => $this->request->getRemoteAddr()), array('ui/security/groups/sgeditor.js'));
 }
示例#24
0
 /**
  * {@inheritdoc}
  * @see \Scalr\Modules\PlatformModuleInterface::LaunchServer()
  */
 public function LaunchServer(DBServer $DBServer, Scalr_Server_LaunchOptions $launchOptions = null)
 {
     $environment = $DBServer->GetEnvironmentObject();
     $governance = new \Scalr_Governance($DBServer->envId);
     $azure = $environment->azure();
     $subscriptionId = $environment->keychain(SERVER_PLATFORMS::AZURE)->properties[CloudCredentialsProperty::AZURE_SUBSCRIPTION_ID];
     if (!$launchOptions) {
         $dbFarmRole = $DBServer->GetFarmRoleObject();
         $DBRole = $dbFarmRole->GetRoleObject();
         $launchOptions = new \Scalr_Server_LaunchOptions();
         $launchOptions->cloudLocation = $dbFarmRole->CloudLocation;
         $launchOptions->serverType = $dbFarmRole->GetSetting(FarmRoleSetting::INSTANCE_TYPE);
         $launchOptions->availZone = $dbFarmRole->GetSetting(FarmRoleSetting::SETTING_AZURE_AVAIL_SET);
         $launchOptions->imageId = $DBRole->__getNewRoleObject()->getImage(\SERVER_PLATFORMS::AZURE, "")->imageId;
         $isWindows = $DBRole->getOs()->family == 'windows';
         // Set User Data
         $u_data = "";
         foreach ($DBServer->GetCloudUserData() as $k => $v) {
             $u_data .= "{$k}={$v};";
         }
         $launchOptions->userData = trim($u_data, ";");
         $launchOptions->azureResourceGroup = $dbFarmRole->GetSetting(FarmRoleSetting::SETTING_AZURE_RESOURCE_GROUP);
         $launchOptions->azureStorageAccount = $dbFarmRole->GetSetting(FarmRoleSetting::SETTING_AZURE_STORAGE_ACCOUNT);
         //Create NIC
         try {
             $ipConfigProperties = new IpConfigurationProperties(["id" => sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/virtualNetworks/%s/subnets/%s", $subscriptionId, $launchOptions->azureResourceGroup, $dbFarmRole->GetSetting(FarmRoleSetting::SETTING_AZURE_VIRTUAL_NETWORK), $dbFarmRole->GetSetting(FarmRoleSetting::SETTING_AZURE_SUBNET))], "Dynamic");
             $publicIpName = null;
             if ($governance->isEnabled(\SERVER_PLATFORMS::AZURE, \Scalr_Governance::AZURE_NETWORK)) {
                 $usePublicIp = $governance->getValue(\SERVER_PLATFORMS::AZURE, \Scalr_Governance::AZURE_NETWORK, 'use_public_ips');
             }
             if (!isset($usePublicIp)) {
                 $usePublicIp = $dbFarmRole->GetSetting(FarmRoleSetting::SETTING_AZURE_USE_PUBLIC_IPS);
             }
             if ($usePublicIp) {
                 //Create Public IP object
                 $publicIpName = "scalr-{$DBServer->serverId}";
                 $createPublicIpAddressRequest = new CreatePublicIpAddress($launchOptions->cloudLocation, new PublicIpAddressProperties('Dynamic'));
                 $ipCreateResult = $azure->network->publicIPAddress->create($subscriptionId, $launchOptions->azureResourceGroup, $publicIpName, $createPublicIpAddressRequest);
             }
             if ($publicIpName) {
                 $ipConfigProperties->publicIPAddress = ["id" => sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/publicIPAddresses/%s", $subscriptionId, $launchOptions->azureResourceGroup, $publicIpName)];
             }
             $nicProperties = new InterfaceProperties([new InterfaceIpConfigurationsData('public1', $ipConfigProperties)]);
             //Security group
             $sg = $dbFarmRole->GetSetting(FarmRoleSetting::SETTING_AZURE_SECURITY_GROUPS_LIST);
             if ($sg) {
                 $sgName = json_decode($sg);
                 if ($sgName) {
                     $sgroup = new SecurityGroupData();
                     $sgroup->id = sprintf('/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/networkSecurityGroups/%s', $subscriptionId, $launchOptions->azureResourceGroup, $sgName[0]);
                     $nicProperties->setNetworkSecurityGroup($sgroup);
                 }
             }
             $createNicData = new CreateInterface($launchOptions->cloudLocation, $nicProperties);
             $nicResponse = $azure->network->interface->create($subscriptionId, $launchOptions->azureResourceGroup, "scalr-{$DBServer->serverId}", $createNicData);
         } catch (\Exception $e) {
             throw new \Exception("Scalr is unable to create NetworkInterface: {$e->getMessage()}");
         }
         $launchOptions->azureNicName = "scalr-{$DBServer->serverId}";
         $launchOptions->azurePublicIpName = $publicIpName;
     }
     // Configure OS Profile
     // Make sure that password always have 1 special character.
     $adminPassword = \Scalr::GenerateSecurePassword(16, ['D' => '.']);
     $osProfile = new OsProfile('scalr', $adminPassword);
     $osProfile->computerName = \Scalr::GenerateUID(true);
     $osProfile->customData = base64_encode(trim($launchOptions->userData));
     // Configure Network Profile
     $networkProfile = ["networkInterfaces" => [["id" => sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/networkInterfaces/%s", $subscriptionId, $launchOptions->azureResourceGroup, $launchOptions->azureNicName)]]];
     // Configure Storage Profile
     $osDiskName = "scalr-{$DBServer->serverId}";
     $vhd = ['uri' => sprintf("https://%s.blob.core.windows.net/vhds/%s.vhd", $launchOptions->azureStorageAccount, $osDiskName)];
     $storageProfile = new StorageProfile(new OsDisk($osDiskName, $vhd, 'FromImage'));
     if (preg_match("/^([^\\/]+)\\/([^\\/]+)\\/([^\\/]+)\\/([^\\/]+)(\\/(1))?\$/", rtrim($launchOptions->imageId, '/'), $imageChunks)) {
         $publisher = $imageChunks[1];
         $offer = $imageChunks[2];
         $sku = $imageChunks[3];
         $version = $imageChunks[4];
         $isMarketPlaceImage = isset($imageChunks[5]) ? true : false;
         if ($isMarketPlaceImage) {
             $plan = new PlanProperties($sku, $publisher, $offer);
         }
         $storageProfile->setImageReference(['publisher' => $publisher, 'offer' => $offer, 'sku' => $sku, 'version' => $version]);
     } else {
         throw new \Exception("Image definition '{$launchOptions->imageId}' is not supported");
     }
     $vmProps = new VirtualMachineProperties(["vmSize" => $launchOptions->serverType], $networkProfile, $storageProfile, $osProfile);
     // Set availability set if configured.
     if ($launchOptions->availZone) {
         $vmProps->availabilitySet = ['id' => sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/availabilitySets/%s", $subscriptionId, $launchOptions->azureResourceGroup, $launchOptions->availZone)];
     }
     $vmData = new CreateVirtualMachine($DBServer->serverId, $launchOptions->cloudLocation, $vmProps);
     $vmData->tags = $DBServer->getAzureTags();
     if (isset($plan)) {
         $vmData->setPlan($plan);
     }
     $azure->compute->virtualMachine->create($subscriptionId, $launchOptions->azureResourceGroup, $vmData);
     $DBServer->setOsType($isWindows ? 'windows' : 'linux');
     $instanceTypeInfo = $this->getInstanceType($launchOptions->serverType, $environment, $launchOptions->cloudLocation);
     /* @var $instanceTypeInfo CloudInstanceType */
     $DBServer->SetProperties([\AZURE_SERVER_PROPERTIES::SERVER_NAME => $DBServer->serverId, \AZURE_SERVER_PROPERTIES::ADMIN_PASSWORD => $adminPassword, \AZURE_SERVER_PROPERTIES::RESOURCE_GROUP => $launchOptions->azureResourceGroup, \AZURE_SERVER_PROPERTIES::CLOUD_LOCATION => $launchOptions->cloudLocation, \AZURE_SERVER_PROPERTIES::AVAIL_SET => $launchOptions->availZone, \AZURE_SERVER_PROPERTIES::NETWORK_INTERFACE => $launchOptions->azureNicName, \AZURE_SERVER_PROPERTIES::PUBLIC_IP_NAME => $launchOptions->azurePublicIpName, \SERVER_PROPERTIES::INFO_INSTANCE_VCPUS => $instanceTypeInfo ? $instanceTypeInfo->vcpus : null]);
     $params = ['type' => $launchOptions->serverType];
     if ($instanceTypeInfo) {
         $params['instanceTypeName'] = $instanceTypeInfo->name;
     }
     $DBServer->imageId = $launchOptions->imageId;
     $DBServer->update($params);
     $DBServer->cloudLocation = $launchOptions->cloudLocation;
     $DBServer->cloudLocationZone = $launchOptions->availZone;
     // we set server history here
     $DBServer->getServerHistory()->update(['cloudServerId' => $DBServer->serverId]);
     return $DBServer;
 }
示例#25
0
 /**
  * Gets AWS tags that should be applied to the resource
  *
  * @return  array  Returns list of the AWS tags
  */
 public function getAwsTags()
 {
     $tags = [['key' => \Scalr_Governance::SCALR_META_TAG_NAME, 'value' => $this->applyGlobalVarsToValue(\Scalr_Governance::SCALR_META_TAG_VALUE)]];
     //Tags governance
     $governance = new \Scalr_Governance($this->EnvID);
     $gTags = (array) $governance->getValue('ec2', \Scalr_Governance::AWS_TAGS);
     if (count($gTags) > 0) {
         foreach ($gTags as $tKey => $tValue) {
             $tags[] = ['key' => $tKey, 'value' => $this->applyGlobalVarsToValue($tValue)];
         }
     }
     return $tags;
 }
 public function FarmCreate($Name, $Description = "", $ProjectID = "", array $Configuration = array())
 {
     $this->restrictFarmAccess(null, Acl::PERM_FARMS_MANAGE);
     $governance = new Scalr_Governance($this->Environment->id);
     $ProjectID = strtolower($ProjectID);
     $response = $this->CreateInitialResponse();
     $Name = $this->stripValue($Name);
     $Description = $this->stripValue($Description);
     if (!$Name || strlen($Name) < 5) {
         throw new Exception('Name should be at least 5 characters');
     }
     if ($Configuration['vpc_region'] && !$Configuration['vpc_id']) {
         throw new Exception("VPC ID is required if VPC region was specified");
     }
     if (!$Configuration['vpc_region'] && $Configuration['vpc_id']) {
         throw new Exception("VPC Region is required if VPC ID was specified");
     }
     // VPC Governance validation
     $vpcGovernance = $governance->getValue('ec2', 'aws.vpc');
     if ($vpcGovernance) {
         $vpcGovernanceRegions = $governance->getValue('ec2', 'aws.vpc', 'regions');
         if (!$Configuration['vpc_region']) {
             throw new Exception("VPC configuration is required according to governance settings");
         }
         if (!in_array($Configuration['vpc_region'], array_keys($vpcGovernanceRegions))) {
             throw new Exception(sprintf("Only %s region(s) allowed according to governance settings", implode(', ', array_keys($vpcGovernanceRegions))));
         }
         if (!in_array($Configuration['vpc_id'], $vpcGovernanceRegions[$Configuration['vpc_region']]['ids'])) {
             throw new Exception(sprintf("Only %s VPC(s) allowed according to governance settings", implode(', ', $vpcGovernanceRegions[$Configuration['vpc_region']]['ids'])));
         }
     }
     $dbFarm = new DBFarm();
     $dbFarm->ClientID = $this->user->getAccountId();
     $dbFarm->EnvID = $this->Environment->id;
     $dbFarm->Status = FARM_STATUS::TERMINATED;
     $dbFarm->createdByUserId = $this->user->getId();
     $dbFarm->createdByUserEmail = $this->user->getEmail();
     $dbFarm->changedByUserId = $this->user->getId();
     $dbFarm->changedTime = microtime();
     $dbFarm->Name = $Name;
     $dbFarm->RolesLaunchOrder = 0;
     $dbFarm->Comments = $Description;
     $dbFarm->save();
     //Associates cost analytics project with the farm.
     $dbFarm->setProject(!empty($ProjectID) ? $ProjectID : null);
     if ($governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE)) {
         $dbFarm->SetSetting(DBFarm::SETTING_LEASE_STATUS, 'Active');
         // for created farm
     }
     if (!$Configuration['timezone']) {
         $Configuration['timezone'] = date_default_timezone_get();
     }
     $dbFarm->SetSetting(DBFarm::SETTING_TIMEZONE, $Configuration['timezone']);
     if ($Configuration['vpc_region']) {
         $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_ID, $Configuration['vpc_id']);
         $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_REGION, $Configuration['vpc_region']);
     }
     $response->FarmID = $dbFarm->ID;
     return $response;
 }
示例#27
0
文件: Ec2.php 项目: mheydt/scalr
 /**
  * Gets default vpc security group list
  *
  * @param SecurityGroupList   $sgList
  * @param string              $vpcId
  * @param string              $serviceName Service name (rds, elb ...)
  * @return array
  */
 private function getDefaultSgRow($sgList, $vpcId, $serviceName = null)
 {
     $governance = new Scalr_Governance($this->getEnvironmentId());
     $governanceSecurityGroups = $governance->getValue(SERVER_PLATFORMS::EC2, Scalr_Governance::getEc2SecurityGroupPolicyNameForService($serviceName), null);
     $vpcSgList = [];
     $sgDefaultNames = [];
     $wildCardSgDefaultNames = [];
     $defaultSecurityGroups = [];
     foreach ($sgList as $sg) {
         if ($sg->vpcId == $vpcId) {
             $vpcSgList[$sg->groupName] = $sg->groupId;
         }
     }
     if (!empty($governanceSecurityGroups['value'])) {
         $sgs = explode(',', $governanceSecurityGroups['value']);
         foreach ($sgs as $sg) {
             if ($sg != '') {
                 array_push($sgDefaultNames, trim($sg));
                 if (strpos($sg, '*') !== false) {
                     array_push($wildCardSgDefaultNames, trim($sg));
                 }
             }
         }
         unset($sgs);
     }
     if (!empty($sgDefaultNames)) {
         $foundVpcSgNames = [];
         foreach ($sgDefaultNames as $groupName) {
             if (!isset($vpcSgList[$groupName])) {
                 if (in_array($groupName, $wildCardSgDefaultNames)) {
                     $wildCardMatchedSgs = [];
                     $groupNamePattern = \Scalr_Governance::convertAsteriskPatternToRegexp($groupName);
                     foreach ($vpcSgList as $sgGroupName => $sgGroupId) {
                         if (preg_match($groupNamePattern, $sgGroupName) === 1) {
                             array_push($wildCardMatchedSgs, $sgGroupName);
                         }
                     }
                     if (count($wildCardMatchedSgs) == 1) {
                         $defaultSecurityGroups[] = ['securityGroupId' => $vpcSgList[$wildCardMatchedSgs[0]], 'securityGroupName' => $wildCardMatchedSgs[0]];
                     } else {
                         $defaultSecurityGroups[] = ['securityGroupId' => null, 'securityGroupName' => $groupName];
                     }
                     $foundVpcSgNames[] = $groupName;
                 }
             } else {
                 $defaultSecurityGroups[] = ['securityGroupId' => $vpcSgList[$groupName], 'securityGroupName' => $groupName];
                 $foundVpcSgNames[] = $groupName;
             }
         }
         $missingSgs = array_diff($sgDefaultNames, $foundVpcSgNames);
         foreach ($missingSgs as $missingSg) {
             $defaultSecurityGroups[] = ['securityGroupId' => null, 'securityGroupName' => $missingSg];
         }
     } elseif (isset($vpcSgList['default']) && empty($governanceSecurityGroups)) {
         $defaultSecurityGroups[] = ['securityGroupId' => $vpcSgList['default'], 'securityGroupName' => 'default'];
     }
     return $defaultSecurityGroups;
 }
 private function GetServerSecurityGroupsList(DBServer $DBServer, \Scalr\Service\CloudStack\CloudStack $csClient, \Scalr_Governance $governance = null)
 {
     $retval = array();
     $checkGroups = array();
     $sgGovernance = true;
     $allowAdditionalSgs = true;
     if ($governance) {
         $sgs = $governance->getValue($DBServer->platform, \Scalr_Governance::CLOUDSTACK_SECURITY_GROUPS);
         if ($sgs !== null) {
             $governanceSecurityGroups = @explode(",", $sgs);
             if (!empty($governanceSecurityGroups)) {
                 foreach ($governanceSecurityGroups as $sg) {
                     if ($sg != '') {
                         array_push($checkGroups, trim($sg));
                     }
                 }
             }
             $sgGovernance = false;
             $allowAdditionalSgs = $governance->getValue($DBServer->platform, \Scalr_Governance::CLOUDSTACK_SECURITY_GROUPS, 'allow_additional_sec_groups');
         }
     }
     if (!$sgGovernance || $allowAdditionalSgs) {
         if ($DBServer->farmRoleId != 0) {
             $dbFarmRole = $DBServer->GetFarmRoleObject();
             if ($dbFarmRole->GetSetting(\DBFarmRole::SETTING_CLOUDSTACK_SECURITY_GROUPS_LIST) !== null) {
                 // New SG management
                 $sgs = @json_decode($dbFarmRole->GetSetting(\DBFarmRole::SETTING_CLOUDSTACK_SECURITY_GROUPS_LIST));
                 if (!empty($sgs)) {
                     foreach ($sgs as $sg) {
                         array_push($checkGroups, $sg);
                     }
                 }
             }
         } else {
             array_push($checkGroups, 'scalr-rb-system');
         }
     }
     try {
         $sgroups = array();
         $sgroupIds = array();
         $list = $csClient->securityGroup->describe();
         foreach ($list as $sg) {
             /* @var $sg SecurityGroupData */
             $sgroups[strtolower($sg->name)] = $sg;
             $sgroupIds[strtolower($sg->id)] = $sg;
         }
     } catch (\Exception $e) {
         throw new \Exception("GetServerSecurityGroupsList failed: {$e->getMessage()}");
     }
     foreach ($checkGroups as $groupName) {
         // || !in_array($groupName, array('scalr-rb-system', 'default', \Scalr::config('scalr.aws.security_group_name')))
         if (preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/si', $groupName)) {
             if (isset($sgroupIds[strtolower($groupName)])) {
                 $groupName = $sgroupIds[$groupName]->name;
             } else {
                 throw new \Exception(sprintf(_("Security group '%s' is not found (1)"), $groupName));
             }
         }
         // Check default SG
         if ($groupName == 'default') {
             array_push($retval, $sgroups[$groupName]->id);
             // Check Roles builder SG
         } elseif ($groupName == 'scalr-rb-system' || $groupName == \Scalr::config('scalr.aws.security_group_name')) {
             if (!isset($sgroups[strtolower($groupName)])) {
                 $request = new CreateSecurityGroupData($groupName);
                 $request->description = _("Scalr system security group");
                 $sg = $csClient->securityGroup->create($request);
                 $sgroups[strtolower($groupName)] = $sg;
                 $sgroupIds[strtolower($sg->id)] = $sg;
             }
             array_push($retval, $sgroups[$groupName]->id);
         } else {
             if (!isset($sgroups[strtolower($groupName)])) {
                 throw new \Exception(sprintf(_("Security group '%s' is not found (2)"), $groupName));
             } else {
                 array_push($retval, $sgroups[strtolower($groupName)]->id);
             }
         }
     }
     return $retval;
 }
示例#29
0
 /**
  * Checks request data
  *
  * @param JsonData   $vpcSecurityGroups
  * @param string     $vpcId
  * @param JsonData   $subnetIds
  * @param string     $cloudLocation
  * @return bool|string Returns error message if access to some data restricted. False otherwise.
  * @throws Scalr_Exception_Core
  */
 private function checkPolicy($vpcSecurityGroups = null, $vpcId = null, $subnetIds = null, $cloudLocation = null)
 {
     $governance = new Scalr_Governance($this->getEnvironmentId());
     $values = $governance->getValues(true);
     if (!empty($values[SERVER_PLATFORMS::EC2][Scalr_Governance::AWS_VPC]->value)) {
         if (!empty($cloudLocation) && !array_key_exists($cloudLocation, (array) $values[SERVER_PLATFORMS::EC2][Scalr_Governance::AWS_VPC]->regions)) {
             return sprintf("A Vpc Policy is active in this Environment, access to %s region has been restricted by account owner.", $cloudLocation);
         }
         if (!empty($vpcId)) {
             foreach ($values[SERVER_PLATFORMS::EC2][Scalr_Governance::AWS_VPC]->regions as $region => $policy) {
                 if (!empty($policy->ids) && !empty($cloudLocation) && $cloudLocation == $region && !in_array($vpcId, (array) $policy->ids)) {
                     return sprintf("A Vpc Policy is active in this Environment, access to vpc %s has been restricted by account owner.", $vpcId);
                 }
             }
             foreach ($values[SERVER_PLATFORMS::EC2][Scalr_Governance::AWS_VPC]->ids as $vpc => $restrictions) {
                 $subnetIds = (array) $subnetIds;
                 $missingSubnets = array_diff($subnetIds, $restrictions);
                 $s = count($missingSubnets) > 1 ? 's' : '';
                 if (!empty($restrictions) && is_array($restrictions) && $vpc == $vpcId && !empty($missingSubnets)) {
                     return sprintf("A Vpc Policy is active in this Environment, access to subnet%s %s has been restricted by account owner.", $s, implode(', ', $missingSubnets));
                 }
             }
         }
     }
     if (!empty($vpcSecurityGroups)) {
         foreach ($vpcSecurityGroups as $vpcSecurityGroup) {
             if (empty($vpcSecurityGroup['id'])) {
                 $notFoundGroups[] = $vpcSecurityGroup['name'];
             }
             $vpcSecurityGroupNames[] = $vpcSecurityGroup['name'];
         }
     }
     if (!empty($values[SERVER_PLATFORMS::EC2][Scalr_Governance::AWS_SECURITY_GROUPS]->value) && !empty($vpcSecurityGroupNames)) {
         if (!empty($notFoundGroups)) {
             $s = count($notFoundGroups) > 1 ? 's' : '';
             $es = $s ? '' : "e{$s}";
             $they = $s ? "they" : 'it';
             return sprintf("A Security Group Policy is active in this Environment, and requires that you attach the following Security Group%s to your DB instance: %s, but %s do%s not exist in current Vpc.", $s, implode(', ', $notFoundGroups), $they, $es);
         }
         $sgDefaultNames = explode(',', $values[SERVER_PLATFORMS::EC2][Scalr_Governance::AWS_SECURITY_GROUPS]->value);
         if ($missingGroups = array_diff($sgDefaultNames, $vpcSecurityGroupNames)) {
             return sprintf("A Security Group Policy is active in this Environment, and requires that you attach the following Security Groups to your DB instance: %s", implode(', ', $missingGroups));
         }
         sort($sgDefaultNames);
         sort($vpcSecurityGroupNames);
         if (empty($values[SERVER_PLATFORMS::EC2][Scalr_Governance::AWS_SECURITY_GROUPS]->allow_additional_sec_groups) && $sgDefaultNames != $vpcSecurityGroupNames) {
             return sprintf("A Security Group Policy is active in this Environment, and you can't apply additional security groups to your DB instance.");
         }
     }
     return false;
 }
示例#30
0
 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));
 }