public static function farmSave(DBFarm $DBFarm, array $roles) { foreach ($roles as $DBFarmRole) { if ($DBFarmRole->Platform != SERVER_PLATFORMS::CLOUDSTACK) { continue; } $location = $DBFarmRole->CloudLocation; $cs = Scalr_Service_Cloud_Cloudstack::newCloudstack($DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Cloudstack::API_URL), $DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Cloudstack::API_KEY), $DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Cloudstack::SECRET_KEY)); $sshKey = Scalr_SshKey::init(); if (!$sshKey->loadGlobalByFarmId($DBFarm->ID, $location)) { $key_name = "FARM-{$DBFarm->ID}"; $result = $cs->createSSHKeyPair($key_name); if ($result->keypair->privatekey) { $sshKey->farmId = $DBFarm->ID; $sshKey->clientId = $DBFarm->ClientID; $sshKey->envId = $DBFarm->EnvID; $sshKey->type = Scalr_SshKey::TYPE_GLOBAL; $sshKey->cloudLocation = $location; $sshKey->cloudKeyName = $key_name; $sshKey->platform = SERVER_PLATFORMS::CLOUDSTACK; $sshKey->setPrivate($result->keypair->privatekey); $sshKey->setPublic($sshKey->generatePublicKey()); $sshKey->save(); } } $networkId = $DBFarmRole->GetSetting(DBFarmRole::SETTING_CLOUDSTACK_NETWORK_ID); $set = fasle; foreach ($cs->listNetworks("", "", "", $networkId) as $network) { if ($network->id == $networkId) { $DBFarmRole->SetSetting(DBFarmRole::SETTING_CLOUDSTACK_NETWORK_TYPE, $network->type); $set = true; } } if (!$set) { throw new Exception("Unable to get GuestIPType for Network #{$networkId}. Please try again later or choose another network offering."); } } }
/** * @return Scalr_Net_Ssh2_Client * Enter description here ... */ public function GetSsh2Client() { $ssh2Client = new Scalr_Net_Ssh2_Client(); switch ($this->platform) { case SERVER_PLATFORMS::RACKSPACENG_UK: case SERVER_PLATFORMS::RACKSPACENG_US: $ssh2Client->addPassword('root', $this->GetProperty(OPENSTACK_SERVER_PROPERTIES::ADMIN_PASS)); break; case SERVER_PLATFORMS::RACKSPACE: $ssh2Client->addPassword('root', $this->GetProperty(RACKSPACE_SERVER_PROPERTIES::ADMIN_PASS)); break; case SERVER_PLATFORMS::GCE: $userName = '******'; if ($this->status == SERVER_STATUS::TEMPORARY) { $keyName = 'SCALR-ROLESBUILDER-' . SCALR_ID; } else { $keyName = "FARM-{$this->farmId}-" . SCALR_ID; } try { $key = Scalr_Model::init(Scalr_Model::SSH_KEY)->loadGlobalByName($keyName, "", $this->envId, SERVER_PLATFORMS::GCE); if (!$key) { throw new Exception(_("There is no SSH key for server: {$this->serverId}")); } } catch (Exception $e) { throw new Exception("Cannot init SshKey object: {$e->getMessage()}"); } $priv_key_file = tempnam("/tmp", "GCEPK"); @file_put_contents($priv_key_file, $key->getPrivate()); $this->tmpFiles[] = $priv_key_file; $pub_key_file = tempnam("/tmp", "GCEK"); @file_put_contents($pub_key_file, $key->getPublic()); $this->tmpFiles[] = $pub_key_file; $ssh2Client->addPubkey($userName, $pub_key_file, $priv_key_file); break; case SERVER_PLATFORMS::IDCF: case SERVER_PLATFORMS::ECS: case SERVER_PLATFORMS::EC2: $userName = '******'; $skipKeyValidation = false; // Temporary server for role builder $sshKey = \Scalr_SshKey::init(); if ($this->status == SERVER_STATUS::TEMPORARY) { $keyName = "SCALR-ROLESBUILDER-" . SCALR_ID . "-{$this->envId}"; if (!$sshKey->loadGlobalByName($keyName, $this->GetCloudLocation(), $this->envId, $this->platform)) { $keyName = "SCALR-ROLESBUILDER-" . SCALR_ID; } try { $bundleTaskId = $this->GetProperty(\SERVER_PROPERTIES::SZR_IMPORTING_BUNDLE_TASK_ID); $bundleTask = BundleTask::LoadById($bundleTaskId); if ($bundleTask->osFamily == 'amazon') { $userName = '******'; } } catch (Exception $e) { } } else { $keyName = "FARM-{$this->farmId}-" . SCALR_ID; $oldKeyName = "FARM-{$this->farmId}"; $key = $sshKey->loadGlobalByName($oldKeyName, $this->GetCloudLocation(), $this->envId, $this->platform); if ($key) { $keyName = $oldKeyName; $skipKeyValidation = true; } } if (!$skipKeyValidation) { try { $key = $sshKey->loadGlobalByName($keyName, $this->GetCloudLocation(), $this->envId, $this->platform); if (!$key) { throw new Exception(sprintf('Could not find SSH Key for server "%s" with name:"%s", cloud-location:"%s", platform:"%s", environment:"%d".', $this->serverId, $keyName, $this->GetCloudLocation(), $this->platform, $this->envId)); } } catch (Exception $e) { throw new Exception("Cannot init SshKey object: {$e->getMessage()}"); } } $priv_key_file = tempnam("/tmp", "AWSK"); @file_put_contents($priv_key_file, $key->getPrivate()); $this->tmpFiles[] = $priv_key_file; $pub_key_file = tempnam("/tmp", "AWSK"); $this->tmpFiles[] = $pub_key_file; $pubKey = $key->getPublic(); if (!stristr($pubKey, $keyName)) { $pubKey .= " {$keyName}"; } @file_put_contents($pub_key_file, $pubKey); $ssh2Client->addPubkey($userName, $pub_key_file, $priv_key_file); break; } return $ssh2Client; }
/** * {@inheritdoc} * @see \Scalr\Modules\PlatformModuleInterface::LaunchServer() */ public function LaunchServer(DBServer $DBServer, \Scalr_Server_LaunchOptions $launchOptions = null) { $config = \Scalr::getContainer()->config; $environment = $DBServer->GetEnvironmentObject(); $governance = new \Scalr_Governance($environment->id); if (!$launchOptions) { $launchOptions = new \Scalr_Server_LaunchOptions(); $DBRole = DBRole::loadById($DBServer->roleId); $launchOptions->imageId = $DBRole->getImageId($this->platform, $DBServer->GetCloudLocation()); $launchOptions->serverType = $DBServer->GetFarmRoleObject()->GetSetting(\DBFarmRole::SETTING_OPENSTACK_FLAVOR_ID); $launchOptions->cloudLocation = $DBServer->GetFarmRoleObject()->CloudLocation; $launchOptions->userData = $DBServer->GetCloudUserData(); $launchOptions->userData['platform'] = 'openstack'; $launchOptions->userData['region'] = $launchOptions->cloudLocation; $launchOptions->networks = @json_decode($DBServer->GetFarmRoleObject()->GetSetting(\DBFarmRole::SETTING_OPENSTACK_NETWORKS)); $gevernanceNetworks = $governance->getValue($this->platform, 'openstack.networks'); if (count($launchOptions->networks) == 0 && $gevernanceNetworks) { $launchOptions->networks = $gevernanceNetworks[$launchOptions->cloudLocation]; } foreach ($launchOptions->userData as $k => $v) { if (!$v) { unset($launchOptions->userData[$k]); } } $launchOptions->architecture = 'x86_64'; $isWindows = $DBServer->osType == 'windows' || $DBRole->osFamily == 'windows'; if ($DBServer->GetFarmRoleObject()->GetSetting('openstack.boot_from_volume') == 1) { $deviceMapping = new \stdClass(); $deviceMapping->device_name = 'vda'; $deviceMapping->source_type = 'image'; $deviceMapping->destination_type = 'volume'; $deviceMapping->delete_on_termination = true; $deviceMapping->guest_format = null; $deviceMapping->volume_size = 10; $deviceMapping->uuid = $launchOptions->imageId; $deviceMapping->boot_index = 0; } } else { $launchOptions->userData = array(); if (!$launchOptions->networks) { $launchOptions->networks = array(); } $isWindows = $DBServer->osType == 'windows'; } $client = $this->getOsClient($environment, $launchOptions->cloudLocation); // Prepare user data $u_data = ""; foreach ($launchOptions->userData as $k => $v) { $u_data .= "{$k}={$v};"; } $u_data = trim($u_data, ";"); $personality = new PersonalityList(); if ($isWindows) { $personality->append(new Personality('C:\\Program Files\\Scalarizr\\etc\\private.d\\.user-data', base64_encode($u_data))); } else { if ($DBServer->platform == \SERVER_PLATFORMS::ECS) { $personality->append(new Personality('/etc/.scalr-user-data', base64_encode($u_data))); } else { $personality->append(new Personality('/etc/scalr/private.d/.user-data', base64_encode($u_data))); } } //Check SecurityGroups $securityGroupsEnabled = $this->getConfigVariable(self::EXT_SECURITYGROUPS_ENABLED, $environment, false); $extProperties['security_groups'] = array(); if ($securityGroupsEnabled) { $securityGroups = $this->GetServerSecurityGroupsList($DBServer, $client, $governance); foreach ($securityGroups as $sg) { $itm = new \stdClass(); $itm->name = $sg; $extProperties['security_groups'][] = $itm; } } if ($deviceMapping) { $extProperties['block_device_mapping_v2'][] = $deviceMapping; } //Check key-pairs $keyPairsEnabled = $this->getConfigVariable(self::EXT_KEYPAIRS_ENABLED, $environment, false); if ($keyPairsEnabled === null || $keyPairsEnabled === false) { if ($client->servers->isExtensionSupported(ServersExtension::keypairs())) { $keyPairsEnabled = 1; } else { $keyPairsEnabled = 0; } $this->setConfigVariable(array(self::EXT_KEYPAIRS_ENABLED => $keyPairsEnabled), $environment, false); } if ($keyPairsEnabled) { $sshKey = \Scalr_SshKey::init(); if ($DBServer->status == \SERVER_STATUS::TEMPORARY) { $keyName = "SCALR-ROLESBUILDER-" . SCALR_ID; $farmId = NULL; } else { $keyName = "FARM-{$DBServer->farmId}-" . SCALR_ID; $farmId = $DBServer->farmId; } if ($sshKey->loadGlobalByName($keyName, $launchOptions->cloudLocation, $DBServer->envId, \SERVER_PLATFORMS::OPENSTACK)) { $keyLoaded = true; } if (!$keyLoaded && !$sshKey->loadGlobalByName($keyName, $launchOptions->cloudLocation, $DBServer->envId, $DBServer->platform)) { $result = $client->servers->createKeypair($keyName); if ($result->private_key) { $sshKey->farmId = $farmId; $sshKey->envId = $DBServer->envId; $sshKey->type = \Scalr_SshKey::TYPE_GLOBAL; $sshKey->cloudLocation = $launchOptions->cloudLocation; $sshKey->cloudKeyName = $keyName; $sshKey->platform = $DBServer->platform; $sshKey->setPrivate($result->private_key); $sshKey->setPublic($result->public_key); $sshKey->save(); } } $extProperties['key_name'] = $keyName; } //TODO: newtorks $networks = new NetworkList(); foreach ((array) $launchOptions->networks as $network) { if ($network) { $networks->append(new Network($network)); } } $osUserData = null; $osPersonality = null; $userDataMethod = $config->defined("scalr.{$this->platform}.user_data_method") ? $config("scalr.{$this->platform}.user_data_method") : null; if (!$userDataMethod || $userDataMethod == 'both' || $userDataMethod == 'personality') { $osPersonality = $personality; } if (!$userDataMethod || $userDataMethod == 'both' || $userDataMethod == 'meta-data' || $isWindows) { $osUserData = $launchOptions->userData; } try { $result = $client->servers->createServer($DBServer->serverId, $launchOptions->serverType, $launchOptions->imageId, null, $osUserData, $osPersonality, $networks, $extProperties); $DBServer->SetProperties([\OPENSTACK_SERVER_PROPERTIES::SERVER_ID => $result->id, \OPENSTACK_SERVER_PROPERTIES::IMAGE_ID => $launchOptions->imageId, \OPENSTACK_SERVER_PROPERTIES::FLAVOR_ID => $launchOptions->serverType, \OPENSTACK_SERVER_PROPERTIES::ADMIN_PASS => $result->adminPass, \OPENSTACK_SERVER_PROPERTIES::NAME => $DBServer->serverId, \SERVER_PROPERTIES::ARCHITECTURE => $launchOptions->architecture, \OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION => $launchOptions->cloudLocation, \SERVER_PROPERTIES::SYSTEM_USER_DATA_METHOD => $userDataMethod]); if ($DBServer->farmRoleId) { $ipPool = $DBServer->GetFarmRoleObject()->GetSetting(\DBFarmRole::SETTING_OPENSTACK_IP_POOL); if ($ipPool) { $DBServer->SetProperty(\SERVER_PROPERTIES::SYSTEM_IGNORE_INBOUND_MESSAGES, 1); } } $DBServer->osType = $isWindows ? 'windows' : 'linux'; $DBServer->cloudLocation = $launchOptions->cloudLocation; $DBServer->cloudLocationZone = ""; // Not supported by openstack return $DBServer; } catch (\Exception $e) { if (stripos($e->getMessage(), 'Invalid key_name provided')) { $sshKey->delete(); throw new \Exception(sprintf(_("Cannot launch new instance: KeyPair was removed from cloud. Re-generating it."), $e->getMessage())); } throw new \Exception(sprintf(_("Cannot launch new instance. %s"), $e->getMessage())); } }
public function LaunchServer(DBServer $DBServer, Scalr_Server_LaunchOptions $launchOptions = null) { $runInstanceRequest = new RunInstancesRequestData(isset($launchOptions->imageId) ? $launchOptions->imageId : null, 1, 1); $environment = $DBServer->GetEnvironmentObject(); $placementData = null; $noSecurityGroups = false; if (!$launchOptions) { $launchOptions = new Scalr_Server_LaunchOptions(); $DBRole = DBRole::loadById($DBServer->roleId); $dbFarmRole = $DBServer->GetFarmRoleObject(); /* $runInstanceRequest->setMonitoring( $dbFarmRole->GetSetting(DBFarmRole::SETTING_AWS_ENABLE_CW_MONITORING) ); */ $launchOptions->imageId = $DBRole->getImageId(SERVER_PLATFORMS::EUCALYPTUS, $dbFarmRole->CloudLocation); // Need OS Family to get block device mapping for OEL roles $imageInfo = $DBRole->getImageDetails(SERVER_PLATFORMS::EUCALYPTUS, $dbFarmRole->CloudLocation); $launchOptions->osFamily = $imageInfo['os_family']; $launchOptions->cloudLocation = $dbFarmRole->CloudLocation; $akiId = $DBServer->GetProperty(EUCA_SERVER_PROPERTIES::EKIID); if (!$akiId) { $akiId = $dbFarmRole->GetSetting(DBFarmRole::SETTING_EUCA_EKI_ID); } if ($akiId) { $runInstanceRequest->kernelId = $akiId; } $ariId = $DBServer->GetProperty(EUCA_SERVER_PROPERTIES::ERIID); if (!$ariId) { $ariId = $dbFarmRole->GetSetting(DBFarmRole::SETTING_EUCA_ERI_ID); } if ($ariId) { $runInstanceRequest->ramdiskId = $ariId; } $launchOptions->serverType = $dbFarmRole->GetSetting(DBFarmRole::SETTING_EUCA_INSTANCE_TYPE); /* if ($dbFarmRole->GetSetting(DBFarmRole::SETTING_AWS_EBS_OPTIMIZED) == 1) { $runInstanceRequest->ebsOptimized = true; } else { $runInstanceRequest->ebsOptimized = false; } */ foreach ($DBServer->GetCloudUserData() as $k => $v) { $u_data .= "{$k}={$v};"; } $runInstanceRequest->userData = base64_encode(trim($u_data, ";")); /* $vpcId = $dbFarmRole->GetFarmObject()->GetSetting(DBFarm::SETTING_EC2_VPC_ID); if ($vpcId) { if ($DBRole->hasBehavior(ROLE_BEHAVIORS::VPC_ROUTER)) { $networkInterface = new InstanceNetworkInterfaceSetRequestData(); $networkInterface->networkInterfaceId = $dbFarmRole->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_NID); $networkInterface->deviceIndex = 0; $networkInterface->deleteOnTermination = false; $runInstanceRequest->setNetworkInterface($networkInterface); $noSecurityGroups = true; } else { $vpcSubnetId = $dbFarmRole->GetSetting(DBFarmRole::SETTING_AWS_VPC_SUBNET_ID); $vpcInternetAccess = $dbFarmRole->GetSetting(DBFarmRole::SETTING_AWS_VPC_INTERNET_ACCESS); if (!$vpcSubnetId) { $aws = $environment->aws($launchOptions->cloudLocation); $subnet = $this->AllocateNewSubnet( $aws->ec2, $vpcId, $dbFarmRole->GetSetting(DBFarmRole::SETTING_AWS_VPC_AVAIL_ZONE), 24 ); try { $subnet->createTags(array( array('key' => "scalr-id", 'value' => SCALR_ID), array('key' => "scalr-sn-type", 'value' => $vpcInternetAccess), array('key' => "Name", 'value' => 'Scalr System Subnet') )); } catch (Exception $e) {} try { $routeTableId = $dbFarmRole->GetSetting(DBFarmRole::SETTING_AWS_VPC_ROUTING_TABLE_ID); Logger::getLogger('VPC')->warn(new FarmLogMessage($DBServer->farmId, "Internet access: {$vpcInternetAccess}")); if (!$routeTableId) { if ($vpcInternetAccess == Scalr_Role_Behavior_Router::INTERNET_ACCESS_OUTBOUND) { $routerRole = $DBServer->GetFarmObject()->GetFarmRoleByBehavior(ROLE_BEHAVIORS::VPC_ROUTER); if (!$routerRole) { if (\Scalr::config('scalr.instances_connection_policy') != 'local') throw new Exception("Outbound access require VPC router role in farm"); } $networkInterfaceId = $routerRole->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_NID); Logger::getLogger('EC2')->warn(new FarmLogMessage($DBServer->farmId, "Requesting outbound routing table. NID: {$networkInterfaceId}")); $routeTableId = $this->getRoutingTable($vpcInternetAccess, $aws, $networkInterfaceId, $vpcId); Logger::getLogger('EC2')->warn(new FarmLogMessage($DBServer->farmId, "Routing table ID: {$routeTableId}")); } elseif ($vpcInternetAccess == Scalr_Role_Behavior_Router::INTERNET_ACCESS_FULL) { $routeTableId = $this->getRoutingTable($vpcInternetAccess, $aws, null, $vpcId); } } $aws->ec2->routeTable->associate($routeTableId, $subnet->subnetId); } catch (Exception $e) { Logger::getLogger('EC2')->warn(new FarmLogMessage($DBServer->farmId, "Removing allocated subnet, due to routing table issues")); $aws->ec2->subnet->delete($subnet->subnetId); throw $e; } $vpcSubnetId = $subnet->subnetId; $dbFarmRole->SetSetting(DBFarmRole::SETTING_AWS_VPC_SUBNET_ID, $vpcSubnetId, DBFarmRole::TYPE_LCL); } if ($vpcSubnetId) { $runInstanceRequest->subnetId = $vpcSubnetId; } else throw new Exception("Unable to define subnetId for role in VPC"); } } */ $vpcId = false; } else { $runInstanceRequest->userData = base64_encode(trim($launchOptions->userData)); } $governance = new Scalr_Governance($DBServer->envId); $euca = $environment->eucalyptus($launchOptions->cloudLocation); // Set AMI, AKI and ARI ids $runInstanceRequest->imageId = $launchOptions->imageId; $runInstanceRequest->instanceInitiatedShutdownBehavior = 'terminate'; if (!$noSecurityGroups) { foreach ($this->GetServerSecurityGroupsList($DBServer, $euca->ec2, $vpcId, $governance) as $sgroup) { $runInstanceRequest->appendSecurityGroupId($sgroup); } if (!$runInstanceRequest->subnetId) { // Set availability zone if (!$launchOptions->availZone) { $avail_zone = $this->GetServerAvailZone($DBServer, $euca->ec2, $launchOptions); if ($avail_zone) { $placementData = new PlacementResponseData($avail_zone); } } else { $placementData = new PlacementResponseData($launchOptions->availZone); } } } $runInstanceRequest->minCount = 1; $runInstanceRequest->maxCount = 1; // Set instance type $runInstanceRequest->instanceType = $launchOptions->serverType; if ($placementData !== null) { $runInstanceRequest->setPlacement($placementData); } $sshKey = Scalr_SshKey::init(); if ($DBServer->status == SERVER_STATUS::TEMPORARY) { $keyName = "SCALR-ROLESBUILDER-" . SCALR_ID; $farmId = 0; } else { $keyName = $governance->getValue(Scalr_Governance::AWS_KEYPAIR); if ($keyName) { $skipKeyValidation = true; } else { $keyName = "FARM-{$DBServer->farmId}-" . SCALR_ID; $farmId = $DBServer->farmId; $oldKeyName = "FARM-{$DBServer->farmId}"; if ($sshKey->loadGlobalByName($oldKeyName, $launchOptions->cloudLocation, $DBServer->envId, SERVER_PLATFORMS::EUCALYPTUS)) { $keyName = $oldKeyName; $skipKeyValidation = true; } } } if (!$skipKeyValidation && !$sshKey->loadGlobalByName($keyName, $launchOptions->cloudLocation, $DBServer->envId, SERVER_PLATFORMS::EUCALYPTUS)) { $result = $euca->ec2->keyPair->create($keyName); if ($result->keyMaterial) { $sshKey->farmId = $farmId; $sshKey->clientId = $DBServer->clientId; $sshKey->envId = $DBServer->envId; $sshKey->type = Scalr_SshKey::TYPE_GLOBAL; $sshKey->cloudLocation = $launchOptions->cloudLocation; $sshKey->cloudKeyName = $keyName; $sshKey->platform = SERVER_PLATFORMS::EUCALYPTUS; $sshKey->setPrivate($result->keyMaterial); $sshKey->setPublic($sshKey->generatePublicKey()); $sshKey->save(); } } $runInstanceRequest->keyName = $keyName; try { $result = $euca->ec2->instance->run($runInstanceRequest); } catch (Exception $e) { if (stristr($e->getMessage(), "The key pair") && stristr($e->getMessage(), "does not exist")) { $sshKey->delete(); throw $e; } if (stristr($e->getMessage(), "The requested Availability Zone is no longer supported") || stristr($e->getMessage(), "is not supported in your requested Availability Zone") || stristr($e->getMessage(), "is currently constrained and we are no longer accepting new customer requests")) { $availZone = $runInstanceRequest->getPlacement() ? $runInstanceRequest->getPlacement()->availabilityZone : null; if ($availZone) { $DBServer->GetEnvironmentObject()->setPlatformConfig(array("eucalyptus.{$launchOptions->cloudLocation}.{$availZone}.unavailable" => time())); } throw $e; } else { throw $e; } } if ($result->instancesSet->get(0)->instanceId) { $DBServer->SetProperty(EUCA_SERVER_PROPERTIES::AVAIL_ZONE, $result->instancesSet->get(0)->placement->availabilityZone); $DBServer->SetProperty(EUCA_SERVER_PROPERTIES::INSTANCE_ID, $result->instancesSet->get(0)->instanceId); $DBServer->SetProperty(EUCA_SERVER_PROPERTIES::INSTANCE_TYPE, $runInstanceRequest->instanceType); $DBServer->SetProperty(EUCA_SERVER_PROPERTIES::EMIID, $runInstanceRequest->imageId); $DBServer->SetProperty(EUCA_SERVER_PROPERTIES::REGION, $launchOptions->cloudLocation); $DBServer->SetProperty(EUCA_SERVER_PROPERTIES::ARCHITECTURE, $result->instancesSet->get(0)->architecture); $DBServer->osType = $result->instancesSet->get(0)->platform ? $result->instancesSet->get(0)->platform : 'linux'; return $DBServer; } else { throw new Exception(sprintf(_("Cannot launch new instance. %s"), serialize($result))); } }
/** * {@inheritdoc} * @see \Scalr\Modules\PlatformModuleInterface::LaunchServer() */ public function LaunchServer(DBServer $DBServer, \Scalr_Server_LaunchOptions $launchOptions = null) { $runInstanceRequest = new RunInstancesRequestData(isset($launchOptions->imageId) ? $launchOptions->imageId : null, 1, 1); $environment = $DBServer->GetEnvironmentObject(); $governance = new \Scalr_Governance($DBServer->envId); $placementData = null; $noSecurityGroups = false; if (!$launchOptions) { $launchOptions = new \Scalr_Server_LaunchOptions(); $dbFarmRole = $DBServer->GetFarmRoleObject(); $DBRole = $dbFarmRole->GetRoleObject(); $runInstanceRequest->setMonitoring($dbFarmRole->GetSetting(\DBFarmRole::SETTING_AWS_ENABLE_CW_MONITORING)); $image = $DBRole->__getNewRoleObject()->getImage(SERVER_PLATFORMS::EC2, $dbFarmRole->CloudLocation); $launchOptions->imageId = $image->imageId; // Need OS Family to get block device mapping for OEL roles $launchOptions->osFamily = $image->getImage()->getOs()->family; $launchOptions->cloudLocation = $dbFarmRole->CloudLocation; $akiId = $DBServer->GetProperty(EC2_SERVER_PROPERTIES::AKIID); if (!$akiId) { $akiId = $dbFarmRole->GetSetting(\DBFarmRole::SETTING_AWS_AKI_ID); } if ($akiId) { $runInstanceRequest->kernelId = $akiId; } $ariId = $DBServer->GetProperty(EC2_SERVER_PROPERTIES::ARIID); if (!$ariId) { $ariId = $dbFarmRole->GetSetting(\DBFarmRole::SETTING_AWS_ARI_ID); } if ($ariId) { $runInstanceRequest->ramdiskId = $ariId; } $iType = $dbFarmRole->GetSetting(\DBFarmRole::SETTING_AWS_INSTANCE_TYPE); $launchOptions->serverType = $iType; // Check governance of instance types $types = $governance->getValue('ec2', 'aws.instance_type'); if (count($types) > 0) { if (!in_array($iType, $types)) { throw new Exception(sprintf("Instance type '%s' was prohibited to use by scalr account owner", $iType)); } } $iamProfileArn = $dbFarmRole->GetSetting(\DBFarmRole::SETTING_AWS_IAM_INSTANCE_PROFILE_ARN); if ($iamProfileArn) { $iamInstanceProfile = new IamInstanceProfileRequestData($iamProfileArn); $runInstanceRequest->setIamInstanceProfile($iamInstanceProfile); } if ($dbFarmRole->GetSetting(\DBFarmRole::SETTING_AWS_EBS_OPTIMIZED) == 1) { $runInstanceRequest->ebsOptimized = true; } else { $runInstanceRequest->ebsOptimized = false; } // Custom user-data (base.custom_user_data) $u_data = ''; foreach ($DBServer->GetCloudUserData() as $k => $v) { $u_data .= "{$k}={$v};"; } $u_data = trim($u_data, ";"); $customUserData = $dbFarmRole->GetSetting('base.custom_user_data'); if ($customUserData) { $repos = $DBServer->getScalarizrRepository(); $userData = str_replace(array('{SCALR_USER_DATA}', '{RPM_REPO_URL}', '{DEB_REPO_URL}'), array($u_data, $repos['rpm_repo_url'], $repos['deb_repo_url']), $customUserData); } else { $userData = $u_data; } $runInstanceRequest->userData = base64_encode($userData); $vpcId = $dbFarmRole->GetFarmObject()->GetSetting(DBFarm::SETTING_EC2_VPC_ID); if ($vpcId) { if ($DBRole->hasBehavior(ROLE_BEHAVIORS::VPC_ROUTER)) { $networkInterface = new InstanceNetworkInterfaceSetRequestData(); $networkInterface->networkInterfaceId = $dbFarmRole->GetSetting(\Scalr_Role_Behavior_Router::ROLE_VPC_NID); $networkInterface->deviceIndex = 0; $networkInterface->deleteOnTermination = false; $runInstanceRequest->setNetworkInterface($networkInterface); $noSecurityGroups = true; } else { $vpcSubnetId = $dbFarmRole->GetSetting(\DBFarmRole::SETTING_AWS_VPC_SUBNET_ID); // VPC Support v2 if ($vpcSubnetId && substr($vpcSubnetId, 0, 6) != 'subnet') { $subnets = json_decode($vpcSubnetId); $servers = $DBServer->GetFarmRoleObject()->GetServersByFilter(array("status" => array(SERVER_STATUS::RUNNING, SERVER_STATUS::INIT, SERVER_STATUS::PENDING))); $subnetsDistribution = array(); foreach ($servers as $cDbServer) { if ($cDbServer->serverId != $DBServer->serverId) { $subnetsDistribution[$cDbServer->GetProperty(EC2_SERVER_PROPERTIES::SUBNET_ID)]++; } } $sCount = 1000000; foreach ($subnets as $subnet) { if ((int) $subnetsDistribution[$subnet] <= $sCount) { $sCount = (int) $subnetsDistribution[$subnet]; $selectedSubnetId = $subnet; } } } else { $vpcInternetAccess = $dbFarmRole->GetSetting(\DBFarmRole::SETTING_AWS_VPC_INTERNET_ACCESS); if (!$vpcSubnetId) { $aws = $environment->aws($launchOptions->cloudLocation); $subnet = $this->AllocateNewSubnet($aws->ec2, $vpcId, $dbFarmRole->GetSetting(\DBFarmRole::SETTING_AWS_VPC_AVAIL_ZONE), 24); try { $subnet->createTags(array(array('key' => "scalr-id", 'value' => SCALR_ID), array('key' => "scalr-sn-type", 'value' => $vpcInternetAccess), array('key' => "Name", 'value' => 'Scalr System Subnet'))); } catch (Exception $e) { } try { $routeTableId = $dbFarmRole->GetSetting(\DBFarmRole::SETTING_AWS_VPC_ROUTING_TABLE_ID); \Logger::getLogger('VPC')->warn(new \FarmLogMessage($DBServer->farmId, "Internet access: {$vpcInternetAccess}")); if (!$routeTableId) { if ($vpcInternetAccess == \Scalr_Role_Behavior_Router::INTERNET_ACCESS_OUTBOUND) { $routerRole = $DBServer->GetFarmObject()->GetFarmRoleByBehavior(ROLE_BEHAVIORS::VPC_ROUTER); if (!$routerRole) { if (\Scalr::config('scalr.instances_connection_policy') != 'local') { throw new Exception("Outbound access require VPC router role in farm"); } } $networkInterfaceId = $routerRole->GetSetting(\Scalr_Role_Behavior_Router::ROLE_VPC_NID); \Logger::getLogger('EC2')->warn(new \FarmLogMessage($DBServer->farmId, "Requesting outbound routing table. NID: {$networkInterfaceId}")); $routeTableId = $this->getRoutingTable($vpcInternetAccess, $aws, $networkInterfaceId, $vpcId); \Logger::getLogger('EC2')->warn(new \FarmLogMessage($DBServer->farmId, "Routing table ID: {$routeTableId}")); } elseif ($vpcInternetAccess == \Scalr_Role_Behavior_Router::INTERNET_ACCESS_FULL) { $routeTableId = $this->getRoutingTable($vpcInternetAccess, $aws, null, $vpcId); } } $aws->ec2->routeTable->associate($routeTableId, $subnet->subnetId); } catch (Exception $e) { \Logger::getLogger('EC2')->warn(new \FarmLogMessage($DBServer->farmId, "Removing allocated subnet, due to routing table issues")); $aws->ec2->subnet->delete($subnet->subnetId); throw $e; } $selectedSubnetId = $subnet->subnetId; $dbFarmRole->SetSetting(\DBFarmRole::SETTING_AWS_VPC_SUBNET_ID, $selectedSubnetId, \DBFarmRole::TYPE_LCL); } else { $selectedSubnetId = $vpcSubnetId; } } if ($selectedSubnetId) { $networkInterface = new InstanceNetworkInterfaceSetRequestData(); $networkInterface->deviceIndex = 0; $networkInterface->deleteOnTermination = true; // //Check network private or public // // We don't need public IP for private subnets $info = $this->listSubnets($environment, $launchOptions->cloudLocation, $vpcId, true, $selectedSubnetId); if ($info && $info['type'] == 'public') { $networkInterface->associatePublicIpAddress = true; } $networkInterface->subnetId = $selectedSubnetId; $aws = $environment->aws($launchOptions->cloudLocation); $sgroups = $this->GetServerSecurityGroupsList($DBServer, $aws->ec2, $vpcId, $governance); $networkInterface->setSecurityGroupId($sgroups); $runInstanceRequest->setNetworkInterface($networkInterface); $noSecurityGroups = true; //$runInstanceRequest->subnetId = $selectedSubnetId; } else { throw new Exception("Unable to define subnetId for role in VPC"); } } } $rootDevice = json_decode($DBServer->GetFarmRoleObject()->GetSetting(\Scalr_Role_Behavior::ROLE_BASE_ROOT_DEVICE_CONFIG), true); if ($rootDevice && $rootDevice['settings']) { $rootDeviceSettings = $rootDevice['settings']; } $instanceInitiatedShutdownBehavior = $dbFarmRole->GetSetting(\DBFarmRole::SETTING_AWS_SHUTDOWN_BEHAVIOR); } else { $instanceInitiatedShutdownBehavior = null; $runInstanceRequest->userData = base64_encode(trim($launchOptions->userData)); } $aws = $environment->aws($launchOptions->cloudLocation); if (!$vpcId) { $vpcId = $this->getDefaultVpc($environment, $launchOptions->cloudLocation); } // Set AMI, AKI and ARI ids $runInstanceRequest->imageId = $launchOptions->imageId; $runInstanceRequest->instanceInitiatedShutdownBehavior = $instanceInitiatedShutdownBehavior ?: 'terminate'; if (!$noSecurityGroups) { foreach ($this->GetServerSecurityGroupsList($DBServer, $aws->ec2, $vpcId, $governance) as $sgroup) { $runInstanceRequest->appendSecurityGroupId($sgroup); } if (!$runInstanceRequest->subnetId) { // Set availability zone if (!$launchOptions->availZone) { $avail_zone = $this->GetServerAvailZone($DBServer, $aws->ec2, $launchOptions); if ($avail_zone) { $placementData = new PlacementResponseData($avail_zone); } } else { $placementData = new PlacementResponseData($launchOptions->availZone); } } } $runInstanceRequest->minCount = 1; $runInstanceRequest->maxCount = 1; // Set instance type $runInstanceRequest->instanceType = $launchOptions->serverType; if ($rootDeviceSettings) { $ebs = new EbsBlockDeviceData($rootDeviceSettings[FarmRoleStorageConfig::SETTING_EBS_SIZE], null, $rootDeviceSettings[FarmRoleStorageConfig::SETTING_EBS_TYPE], $rootDeviceSettings[FarmRoleStorageConfig::SETTING_EBS_IOPS], true, null); $rootBlockDevice = new BlockDeviceMappingData('/dev/sda1', null, null, $ebs); $runInstanceRequest->appendBlockDeviceMapping($rootBlockDevice); } if (substr($launchOptions->serverType, 0, 2) == 'm3' || substr($launchOptions->serverType, 0, 2) == 'm4' || substr($launchOptions->serverType, 0, 2) == 'i2' || substr($launchOptions->serverType, 0, 2) == 'r3' || substr($launchOptions->serverType, 0, 2) == 'd2' || $launchOptions->serverType == 'hi1.4xlarge' || $launchOptions->serverType == 'cc2.8xlarge' || $launchOptions->serverType == 'hs1.8xlarge' || $launchOptions->osFamily == 'oel') { foreach ($this->GetBlockDeviceMapping($launchOptions->serverType) as $bdm) { $runInstanceRequest->appendBlockDeviceMapping($bdm); } } if (in_array($runInstanceRequest->instanceType, array('c3.large', 'c3.xlarge', 'c3.2xlarge', 'c3.4xlarge', 'c3.8xlarge', 'cc2.8xlarge', 'cg1.4xlarge', 'g2.2xlarge', 'g2.8xlarge', 'cr1.8xlarge', 'r3.large', 'r3.xlarge', 'r3.2xlarge', 'r3.4xlarge', 'r3.8xlarge', 'hi1.4xlarge', 'hs1.8xlarge', 'i2.xlarge', 'i2.2xlarge', 'i2.4xlarge', 'i2.8xlarge', 'd2.xlarge', 'd2.2xlarge', 'd2.4xlarge', 'd2.8xlarge'))) { $placementGroup = $DBServer->GetFarmRoleObject()->GetSetting(\DBFarmRole::SETTING_AWS_CLUSTER_PG); if ($placementGroup) { if ($placementData === null) { $placementData = new PlacementResponseData(null, $placementGroup); } else { $placementData->groupName = $placementGroup; } } } if ($placementData !== null) { $runInstanceRequest->setPlacement($placementData); } $sshKey = \Scalr_SshKey::init(); if ($DBServer->status == SERVER_STATUS::TEMPORARY) { $keyName = "SCALR-ROLESBUILDER-" . SCALR_ID; if (!$sshKey->loadGlobalByName($keyName, $launchOptions->cloudLocation, $DBServer->envId, SERVER_PLATFORMS::EC2)) { $keyName = "SCALR-ROLESBUILDER-" . SCALR_ID . "-{$DBServer->envId}"; } $farmId = NULL; } else { $keyName = $governance->getValue(SERVER_PLATFORMS::EC2, \Scalr_Governance::AWS_KEYPAIR); if ($keyName) { $skipKeyValidation = true; } else { $keyName = "FARM-{$DBServer->farmId}-" . SCALR_ID; $farmId = $DBServer->farmId; $oldKeyName = "FARM-{$DBServer->farmId}"; if ($sshKey->loadGlobalByName($oldKeyName, $launchOptions->cloudLocation, $DBServer->envId, SERVER_PLATFORMS::EC2)) { $keyName = $oldKeyName; $skipKeyValidation = true; } } } if (!$skipKeyValidation && !$sshKey->loadGlobalByName($keyName, $launchOptions->cloudLocation, $DBServer->envId, SERVER_PLATFORMS::EC2)) { $result = $aws->ec2->keyPair->create($keyName); if ($result->keyMaterial) { $sshKey->farmId = $farmId; $sshKey->envId = $DBServer->envId; $sshKey->type = \Scalr_SshKey::TYPE_GLOBAL; $sshKey->cloudLocation = $launchOptions->cloudLocation; $sshKey->cloudKeyName = $keyName; $sshKey->platform = SERVER_PLATFORMS::EC2; $sshKey->setPrivate($result->keyMaterial); $sshKey->setPublic($sshKey->generatePublicKey()); $sshKey->save(); } } $runInstanceRequest->keyName = $keyName; try { $result = $aws->ec2->instance->run($runInstanceRequest); } catch (Exception $e) { if (stristr($e->getMessage(), "The key pair") && stristr($e->getMessage(), "does not exist")) { $sshKey->delete(); throw $e; } if (stristr($e->getMessage(), "The requested Availability Zone is no longer supported") || stristr($e->getMessage(), "is not supported in your requested Availability Zone") || stristr($e->getMessage(), "capacity in the Availability Zone you requested") || stristr($e->getMessage(), "Our system will be working on provisioning additional capacity") || stristr($e->getMessage(), "is currently constrained and we are no longer accepting new customer requests")) { $availZone = $runInstanceRequest->getPlacement() ? $runInstanceRequest->getPlacement()->availabilityZone : null; if ($availZone) { $DBServer->GetEnvironmentObject()->setPlatformConfig(array("aws.{$launchOptions->cloudLocation}.{$availZone}.unavailable" => time())); } throw $e; } else { throw $e; } } if ($result->instancesSet->get(0)->instanceId) { $DBServer->SetProperties([EC2_SERVER_PROPERTIES::REGION => $launchOptions->cloudLocation, EC2_SERVER_PROPERTIES::AVAIL_ZONE => $result->instancesSet->get(0)->placement->availabilityZone, EC2_SERVER_PROPERTIES::INSTANCE_ID => $result->instancesSet->get(0)->instanceId, EC2_SERVER_PROPERTIES::INSTANCE_TYPE => $runInstanceRequest->instanceType, EC2_SERVER_PROPERTIES::AMIID => $runInstanceRequest->imageId, EC2_SERVER_PROPERTIES::VPC_ID => $result->instancesSet->get(0)->vpcId, EC2_SERVER_PROPERTIES::SUBNET_ID => $result->instancesSet->get(0)->subnetId, EC2_SERVER_PROPERTIES::ARCHITECTURE => $result->instancesSet->get(0)->architecture]); $DBServer->setOsType($result->instancesSet->get(0)->platform ? $result->instancesSet->get(0)->platform : 'linux'); $DBServer->cloudLocation = $launchOptions->cloudLocation; $DBServer->cloudLocationZone = $result->instancesSet->get(0)->placement->availabilityZone; $DBServer->imageId = $launchOptions->imageId; // we set server history here $DBServer->getServerHistory(); return $DBServer; } else { throw new Exception(sprintf(_("Cannot launch new instance. %s"), serialize($result))); } }
public function xGetRoleSshPrivateKeyAction() { $dbFarmRole = DBFarmRole::LoadByID($this->getParam('farmRoleId')); $dbFarm = $dbFarmRole->GetFarmObject(); $this->user->getPermissions()->validate($dbFarmRole); $sshKey = Scalr_SshKey::init()->loadGlobalByFarmId($dbFarm->ID, $dbFarmRole->CloudLocation); if (!$sshKey) { throw new Exception("Key not found"); } $retval = $sshKey->getPrivate(); $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="' . $dbFarm->Name . '-' . $dbFarmRole->GetRoleObject()->name . '.pem"'); $this->response->setHeader('Content-Length', strlen($retval)); $this->response->setResponse($retval); }
private function getSshConsoleSettings($dbServer) { $userSshSettings = $this->user->getSshConsoleSettings(false, true, $dbServer->serverId); $ipType = $userSshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_IP] ? $userSshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_IP] : 'auto'; switch ($ipType) { case 'auto': $ipAddress = $dbServer->getSzrHost(); break; case 'public': $ipAddress = $dbServer->remoteIp; break; case 'private': $ipAddress = $dbServer->localIp; break; } if ($ipAddress) { $dBFarm = $dbServer->GetFarmObject(); $dbFarmRole = $dbServer->GetFarmRoleObject(); $dbRole = $dbFarmRole->GetRoleObject(); $sshPort = $dbRole->getProperty(DBRole::PROPERTY_SSH_PORT); if (!$sshPort) { $sshPort = 22; } $cSshPort = $dbServer->GetProperty(SERVER_PROPERTIES::CUSTOM_SSH_PORT); if ($cSshPort) { $sshPort = $cSshPort; } $sshSettings = array('serverId' => $dbServer->serverId, 'serverIndex' => $dbServer->index, 'ip' => $ipAddress, 'farmName' => $dBFarm->Name, 'farmId' => $dbServer->farmId, 'roleName' => $dbRole->name, 'farmRoleAlias' => $dbFarmRole->Alias, 'farmRoleId' => $dbFarmRole->ID, Scalr_Account_User::VAR_SSH_CONSOLE_IP => $ipAddress == $dbServer->remoteIp ? 'public' : 'private', Scalr_Account_User::VAR_SSH_CONSOLE_PORT => $userSshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_PORT] ? $userSshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_PORT] : $sshPort, Scalr_Account_User::VAR_SSH_CONSOLE_USERNAME => $userSshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_USERNAME] ? $userSshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_USERNAME] : ($dbServer->platform == SERVER_PLATFORMS::GCE ? 'scalr' : 'root'), Scalr_Account_User::VAR_SSH_CONSOLE_LOG_LEVEL => $userSshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_LOG_LEVEL] ? $userSshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_LOG_LEVEL] : 'CONFIG', Scalr_Account_User::VAR_SSH_CONSOLE_PREFERRED_PROVIDER => $userSshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_PREFERRED_PROVIDER] ? $userSshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_PREFERRED_PROVIDER] : '', Scalr_Account_User::VAR_SSH_CONSOLE_ENABLE_AGENT_FORWARDING => $userSshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_ENABLE_AGENT_FORWARDING] ? $userSshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_ENABLE_AGENT_FORWARDING] : '0'); if ($this->request->isAllowed(Acl::RESOURCE_SECURITY_SSH_KEYS)) { $sshKey = Scalr_SshKey::init()->loadGlobalByFarmId($dbServer->envId, $dbServer->farmId, $dbServer->GetFarmRoleObject()->CloudLocation, $dbServer->platform); if (!$sshKey) { throw new NotFoundException(sprintf("Cannot find ssh key corresponding to environment:'%d', farm:'%d', platform:'%s', cloud location:'%s'.", $dbServer->envId, $dbServer->farmId, strip_tags($dbServer->platform), strip_tags($dbServer->GetFarmRoleObject()->CloudLocation))); } $cloudKeyName = $sshKey->cloudKeyName; if (substr_count($cloudKeyName, '-') == 2) { $cloudKeyName = str_replace('-' . SCALR_ID, '-' . $sshKey->cloudLocation . '-' . SCALR_ID, $cloudKeyName); } $sshSettings['ssh.console.key'] = base64_encode($sshKey->getPrivate()); $sshSettings['ssh.console.putty_key'] = base64_encode($sshKey->getPuttyPrivateKey()); $sshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_KEY_NAME] = $userSshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_KEY_NAME] ? $userSshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_KEY_NAME] : $cloudKeyName; $sshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_DISABLE_KEY_AUTH] = $userSshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_DISABLE_KEY_AUTH] ? $userSshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_DISABLE_KEY_AUTH] : '0'; } else { $sshSettings['ssh.console.key'] = ''; $sshSettings['ssh.console.putty_key'] = ''; $sshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_KEY_NAME] = ''; $sshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_DISABLE_KEY_AUTH] = '1'; } return $sshSettings; } else { throw new Exception(_("SSH console not available for this server or server is not yet initialized")); } }
/** * @deprecated * Get list of roles for listView */ public function xListSshKeysAction() { $this->request->defineParams(array('sshKeyId' => array('type' => 'int'), 'farmId' => array('type' => 'int'), 'sort' => array('type' => 'json'))); $sql = "\n SELECT k.id, count(fr.id) AS status, f.name AS farmName\n FROM ssh_keys k\n LEFT JOIN farms f ON k.farm_id = f.id\n LEFT JOIN farm_roles fr ON k.farm_id = fr.farmid AND k.platform = fr.platform AND (k.cloud_location = fr.cloud_location OR k.cloud_location = '')\n WHERE k.env_id = ?\n AND :FILTER:\n "; $params = array($this->getEnvironmentId()); if ($this->getParam('sshKeyId')) { $sql .= " AND k.id = ?"; $params[] = $this->getParam('sshKeyId'); } if ($this->getParam('farmId')) { $sql .= " AND k.farm_id = ?"; $params[] = $this->getParam('farmId'); } $sql .= ' GROUP BY k.id'; $response = $this->buildResponseFromSql($sql, array('k.id', 'k.type', 'k.cloud_location', 'status'), array('k.cloud_key_name', 'k.cloud_location', 'k.farm_id', 'k.id'), $params); foreach ($response["data"] as &$row) { $sshKey = Scalr_SshKey::init()->loadById($row['id']); $row = array('id' => $sshKey->id, 'type' => $sshKey->type == Scalr_SshKey::TYPE_GLOBAL ? "{$sshKey->type} ({$sshKey->platform})" : $sshKey->type, 'cloud_key_name' => $sshKey->cloudKeyName, 'farm_id' => $sshKey->farmId, 'cloud_location' => $sshKey->cloudLocation, 'status' => $row['status'] ? 'In use' : 'Not used', 'farmName' => $row['farmName'], 'platform' => $sshKey->platform); } $this->response->data($response); }
public function LaunchServer(DBServer $DBServer, Scalr_Server_LaunchOptions $launchOptions = null) { $environment = $DBServer->GetEnvironmentObject(); $farmRole = $DBServer->GetFarmRoleObject(); if (!$launchOptions) { $launchOptions = new Scalr_Server_LaunchOptions(); $dbRole = DBRole::loadById($DBServer->roleId); $launchOptions->imageId = $dbRole->getImageId(SERVER_PLATFORMS::CLOUDSTACK, $DBServer->GetFarmRoleObject()->CloudLocation); $launchOptions->serverType = $DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_CLOUDSTACK_SERVICE_OFFERING_ID); $launchOptions->cloudLocation = $DBServer->GetFarmRoleObject()->CloudLocation; /* * User Data */ foreach ($DBServer->GetCloudUserData() as $k => $v) { $u_data .= "{$k}={$v};"; } $launchOptions->userData = trim($u_data, ";"); $launchOptions->architecture = 'x86_64'; } $cs = $this->getCloudStackClient($environment, $launchOptions->cloudLocation); $networkType = $farmRole->GetSetting(DBFarmRole::SETTING_CLOUDSTACK_NETWORK_TYPE); if ($networkType == 'Virtual') { $sharedIpId = $environment->getPlatformConfigValue(self::SHARED_IP_ID . ".{$launchOptions->cloudLocation}", false); if (!$sharedIpId) { $ipResult = $cs->associateIpAddress($launchOptions->cloudLocation); $ipId = $ipResult->id; if ($ipId) { while (true) { $ipInfo = $cs->listPublicIpAddresses($ipId); $ipInfo = $ipInfo->publicipaddress[0]; if (!$ipInfo) { throw new Exception("Cannot allocate IP address: listPublicIpAddresses -> failed"); } if ($ipInfo->state == 'Allocated') { $environment->setPlatformConfig(array(self::SHARED_IP_ID . ".{$launchOptions->cloudLocation}" => $ipId), false); $environment->setPlatformConfig(array(self::SHARED_IP . ".{$launchOptions->cloudLocation}" => $ipInfo->ipaddress), false); $environment->setPlatformConfig(array(self::SHARED_IP_INFO . ".{$launchOptions->cloudLocation}" => serialize($ipInfo)), false); $sharedIpId = $ipId; break; } else { if ($ipInfo->state == 'Allocating') { sleep(1); } else { throw new Exception("Cannot allocate IP address: ipAddress->state = {$ipInfo->state}"); } } } } else { throw new Exception("Cannot allocate IP address: associateIpAddress -> failed"); } } } $sshKey = Scalr_SshKey::init(); try { if (!$sshKey->loadGlobalByFarmId($DBFarm->ID, $launchOptions->cloudLocation)) { $key_name = "FARM-{$DBServer->farmId}"; $result = $cs->createSSHKeyPair($key_name); if ($result->keypair->privatekey) { $sshKey->farmId = $DBServer->farmId; $sshKey->clientId = $DBServer->clientId; $sshKey->envId = $DBServer->envId; $sshKey->type = Scalr_SshKey::TYPE_GLOBAL; $sshKey->cloudLocation = $launchOptions->cloudLocation; $sshKey->cloudKeyName = $key_name; $sshKey->platform = SERVER_PLATFORMS::CLOUDSTACK; $sshKey->setPrivate($result->keypair->privatekey); $sshKey->setPublic($sshKey->generatePublicKey()); $sshKey->save(); } } } catch (Exception $e) { } $keyName = $sshKey->cloudKeyName; $vResult = $cs->deployVirtualMachine($launchOptions->serverType, $launchOptions->imageId, $launchOptions->cloudLocation, null, null, "", null, $farmRole->GetRoleObject()->name, null, null, $keyName, "", $farmRole->GetSetting(DBFarmRole::SETTING_CLOUDSTACK_NETWORK_ID), null, null, null, base64_encode($launchOptions->userData)); if ($vResult->id) { $DBServer->SetProperty(CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID, $vResult->id); $DBServer->SetProperty(CLOUDSTACK_SERVER_PROPERTIES::CLOUD_LOCATION, $launchOptions->cloudLocation); $DBServer->SetProperty(CLOUDSTACK_SERVER_PROPERTIES::LAUNCH_JOB_ID, $vResult->jobid); return $DBServer; } else { throw new Exception(sprintf("Cannot launch new instance: %s", $vResult->errortext)); } }
/** * Get list of roles for listView */ public function xListSshKeysAction() { $this->request->defineParams(array('sshKeyId' => array('type' => 'int'), 'farmId' => array('type' => 'int'), 'sort' => array('type' => 'json'))); $sql = 'SELECT id FROM ssh_keys WHERE env_id = ? AND :FILTER:'; $params = array($this->getEnvironmentId()); if ($this->getParam('sshKeyId')) { $sql .= " AND id = ?"; $params[] = $this->getParam('sshKeyId'); } if ($this->getParam('farmId')) { $sql .= " AND farm_id = ?"; $params[] = $this->getParam('farmId'); } $response = $this->buildResponseFromSql($sql, array('id', 'type', 'cloud_location'), array('cloud_key_name', 'cloud_location', 'farm_id', 'id'), $params); foreach ($response["data"] as &$row) { $sshKey = Scalr_SshKey::init()->loadById($row['id']); $row = array('id' => $sshKey->id, 'type' => $sshKey->type == Scalr_SshKey::TYPE_GLOBAL ? "{$sshKey->type} ({$sshKey->platform})" : $sshKey->type, 'cloud_key_name' => $sshKey->cloudKeyName, 'farm_id' => $sshKey->farmId, 'cloud_location' => $sshKey->cloudLocation); } $this->response->data($response); }
public function sshConsoleAction() { $dbServer = DBServer::LoadByID($this->getParam('serverId')); $this->user->getPermissions()->validate($dbServer); if ($dbServer->remoteIp) { $dBFarm = $dbServer->GetFarmObject(); $dbRole = DBRole::loadById($dbServer->roleId); $sshPort = $dbRole->getProperty(DBRole::PROPERTY_SSH_PORT); if (!$sshPort) { $sshPort = 22; } $sshKey = Scalr_SshKey::init()->loadGlobalByFarmId($dbServer->farmId, $dbServer->GetFarmRoleObject()->CloudLocation); $this->response->page('ui/servers/sshconsole.js', array('serverId' => $dbServer->serverId, 'remoteIp' => $dbServer->remoteIp, 'localIp' => $dbServer->localIp, 'farmName' => $dBFarm->Name, 'farmId' => $dbServer->farmId, 'roleName' => $dbRole->name, "port" => $sshPort, "key" => base64_encode($sshKey->getPrivate()))); } else { throw new Exception(_("Server not initialized yet")); } }
public function sshConsoleAction() { $this->request->restrictAccess(Acl::RESOURCE_FARMS_SERVERS); $dbServer = DBServer::LoadByID($this->getParam('serverId')); $this->user->getPermissions()->validate($dbServer); if (\Scalr::config('scalr.instances_connection_policy') == 'local') { $ipAddress = $dbServer->localIp; } elseif (\Scalr::config('scalr.instances_connection_policy') == 'public') { $ipAddress = $dbServer->remoteIp; } elseif (\Scalr::config('scalr.instances_connection_policy') == 'auto') { if ($this->remoteIp) { $ipAddress = $dbServer->remoteIp; } else { $ipAddress = $dbServer->localIp; } } if ($ipAddress) { $dBFarm = $dbServer->GetFarmObject(); $dbRole = DBRole::loadById($dbServer->roleId); $sshPort = $dbRole->getProperty(DBRole::PROPERTY_SSH_PORT); if (!$sshPort) { $sshPort = 22; } $cSshPort = $dbServer->GetProperty(SERVER_PROPERTIES::CUSTOM_SSH_PORT); if ($cSshPort) { $sshPort = $cSshPort; } $sshKey = Scalr_SshKey::init()->loadGlobalByFarmId($dbServer->farmId, $dbServer->GetFarmRoleObject()->CloudLocation, $dbServer->platform); $this->response->page('ui/servers/sshconsole.js', array('serverId' => $dbServer->serverId, 'serverIndex' => $dbServer->index, 'remoteIp' => $ipAddress, 'localIp' => $dbServer->localIp, 'farmName' => $dBFarm->Name, 'farmId' => $dbServer->farmId, 'roleName' => $dbRole->name, 'port' => $sshPort, 'username' => $dbServer->platform == SERVER_PLATFORMS::GCE ? 'scalr' : 'root', "key" => base64_encode($sshKey->getPrivate()))); } else { throw new Exception(_("Server not initialized yet")); } }
public function sshConsoleAction() { $this->request->restrictAccess(Acl::RESOURCE_FARMS_SERVERS, Acl::PERM_FARMS_SERVERS_SSH_CONSOLE); $dbServer = DBServer::LoadByID($this->getParam('serverId')); $this->user->getPermissions()->validate($dbServer); $ipAddress = $dbServer->getSzrHost(); if ($ipAddress) { $dBFarm = $dbServer->GetFarmObject(); $dbRole = DBRole::loadById($dbServer->roleId); $sshPort = $dbRole->getProperty(DBRole::PROPERTY_SSH_PORT); if (!$sshPort) { $sshPort = 22; } $cSshPort = $dbServer->GetProperty(SERVER_PROPERTIES::CUSTOM_SSH_PORT); if ($cSshPort) { $sshPort = $cSshPort; } $userSshSettings = $this->user->getSshConsoleSettings(false, true, $dbServer->serverId); $sshSettings = array('serverId' => $dbServer->serverId, 'serverIndex' => $dbServer->index, 'remoteIp' => $ipAddress, 'localIp' => $dbServer->localIp, 'farmName' => $dBFarm->Name, 'farmId' => $dbServer->farmId, 'roleName' => $dbRole->name, Scalr_Account_User::VAR_SSH_CONSOLE_PORT => $userSshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_PORT] ? $userSshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_PORT] : $sshPort, Scalr_Account_User::VAR_SSH_CONSOLE_USERNAME => $userSshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_USERNAME] ? $userSshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_USERNAME] : ($dbServer->platform == SERVER_PLATFORMS::GCE ? 'scalr' : 'root'), Scalr_Account_User::VAR_SSH_CONSOLE_LOG_LEVEL => $userSshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_LOG_LEVEL] ? $userSshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_LOG_LEVEL] : 'CONFIG', Scalr_Account_User::VAR_SSH_CONSOLE_PREFERRED_PROVIDER => $userSshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_PREFERRED_PROVIDER] ? $userSshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_PREFERRED_PROVIDER] : ''); if ($this->request->isAllowed(Acl::RESOURCE_SECURITY_SSH_KEYS)) { $sshKey = Scalr_SshKey::init()->loadGlobalByFarmId($dbServer->envId, $dbServer->farmId, $dbServer->GetFarmRoleObject()->CloudLocation, $dbServer->platform); $cloudKeyName = $sshKey->cloudKeyName; if (substr_count($cloudKeyName, '-') == 2) { $cloudKeyName = str_replace('-' . SCALR_ID, '-' . $sshKey->cloudLocation . '-' . SCALR_ID, $cloudKeyName); } $sshSettings['ssh.console.key'] = base64_encode($sshKey->getPrivate()); $sshSettings['ssh.console.putty_key'] = base64_encode($sshKey->getPuttyPrivateKey()); $sshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_KEY_NAME] = $userSshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_KEY_NAME] ? $userSshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_KEY_NAME] : $cloudKeyName; $sshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_DISABLE_KEY_AUTH] = $userSshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_DISABLE_KEY_AUTH] ? $userSshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_DISABLE_KEY_AUTH] : '0'; } else { $sshSettings['ssh.console.key'] = ''; $sshSettings['ssh.console.putty_key'] = ''; $sshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_KEY_NAME] = ''; $sshSettings[Scalr_Account_User::VAR_SSH_CONSOLE_DISABLE_KEY_AUTH] = '1'; } $this->response->page('ui/servers/sshconsole.js', $sshSettings); } else { throw new Exception(_("SSH console not available for this server or server is not yet initialized")); } }
public function LaunchServer(DBServer $DBServer, Scalr_Server_LaunchOptions $launchOptions = null) { $environment = $DBServer->GetEnvironmentObject(); $diskOffering = null; $size = null; if (!$launchOptions) { $farmRole = $DBServer->GetFarmRoleObject(); $launchOptions = new Scalr_Server_LaunchOptions(); $dbRole = DBRole::loadById($DBServer->roleId); $launchOptions->imageId = $dbRole->getImageId($this->platform, $DBServer->GetFarmRoleObject()->CloudLocation); $launchOptions->serverType = $DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_CLOUDSTACK_SERVICE_OFFERING_ID); $launchOptions->cloudLocation = $DBServer->GetFarmRoleObject()->CloudLocation; /* * User Data */ foreach ($DBServer->GetCloudUserData() as $k => $v) { $u_data .= "{$k}={$v};"; } $launchOptions->userData = trim($u_data, ";"); $diskOffering = $farmRole->GetSetting(DBFarmRole::SETTING_CLOUDSTACK_DISK_OFFERING_ID); if ($diskOffering === false || $diskOffering === null) { $diskOffering = null; } $sharedIp = $farmRole->GetSetting(DBFarmRole::SETTING_CLOUDSTACK_SHARED_IP_ID); $networkType = $farmRole->GetSetting(DBFarmRole::SETTING_CLOUDSTACK_NETWORK_TYPE); $networkId = $farmRole->GetSetting(DBFarmRole::SETTING_CLOUDSTACK_NETWORK_ID); $roleName = $farmRole->GetRoleObject()->name; } else { $launchOptions->userData = array(); $roleName = 'TemporaryScalrServer' . rand(100, 999); } $launchOptions->architecture = 'x86_64'; $cs = $this->getCloudStackClient($environment, $launchOptions->cloudLocation); if (!$sharedIp) { if ($networkId && ($networkType == 'Virtual' || $networkType == 'Isolated' || !$networkType)) { $sharedIpId = $this->getConfigVariable(self::SHARED_IP_ID . ".{$launchOptions->cloudLocation}", $environment, false); if (!$sharedIpId) { $ipResult = $cs->associateIpAddress($launchOptions->cloudLocation); $ipId = $ipResult->id; if ($ipId) { while (true) { $ipInfo = $cs->listPublicIpAddresses($ipId); $ipInfo = $ipInfo->publicipaddress[0]; if (!$ipInfo) { throw new Exception("Cannot allocate IP address: listPublicIpAddresses -> failed"); } if ($ipInfo->state == 'Allocated') { $this->setConfigVariable(array(self::SHARED_IP_ID . ".{$launchOptions->cloudLocation}" => $ipId), $environment, false); $this->setConfigVariable(array(self::SHARED_IP . ".{$launchOptions->cloudLocation}" => $ipInfo->ipaddress), $environment, false); $this->setConfigVariable(array(self::SHARED_IP_INFO . ".{$launchOptions->cloudLocation}" => serialize($ipInfo)), $environment, false); $sharedIpId = $ipId; break; } else { if ($ipInfo->state == 'Allocating') { sleep(1); } else { throw new Exception("Cannot allocate IP address: ipAddress->state = {$ipInfo->state}"); } } } } else { throw new Exception("Cannot allocate IP address: associateIpAddress -> failed"); } } } } if ($DBServer->status == SERVER_STATUS::TEMPORARY) { $keyName = "SCALR-ROLESBUILDER-" . SCALR_ID; $farmId = 0; } else { $keyName = "FARM-{$DBServer->farmId}-" . SCALR_ID; $farmId = $DBServer->farmId; } $sshKey = Scalr_SshKey::init(); try { if (!$sshKey->loadGlobalByName($keyName, "", $DBServer->envId, $this->platform)) { $result = $cs->createSSHKeyPair($keyName); if ($result->keypair->privatekey) { $sshKey->farmId = $farmId; $sshKey->clientId = $DBServer->clientId; $sshKey->envId = $DBServer->envId; $sshKey->type = Scalr_SshKey::TYPE_GLOBAL; $sshKey->cloudLocation = ""; //$launchOptions->cloudLocation; $sshKey->cloudKeyName = $keyName; $sshKey->platform = $this->platform; $sshKey->setPrivate($result->keypair->privatekey); $sshKey->setPublic($sshKey->generatePublicKey()); $sshKey->save(); } } } catch (Exception $e) { Logger::getLogger("CloudStack")->error(new FarmLogMessage($DBServer->farmId, "Unable to generate keypair: {$e->getMessage()}")); } $vResult = $cs->deployVirtualMachine($launchOptions->serverType, $launchOptions->imageId, $launchOptions->cloudLocation, null, $diskOffering, $DBServer->serverId, null, $roleName, null, null, $keyName, "", $networkId, null, null, $size, base64_encode($launchOptions->userData)); if ($vResult->id) { $DBServer->SetProperty(CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID, $vResult->id); $DBServer->SetProperty(CLOUDSTACK_SERVER_PROPERTIES::CLOUD_LOCATION, $launchOptions->cloudLocation); $DBServer->SetProperty(CLOUDSTACK_SERVER_PROPERTIES::LAUNCH_JOB_ID, $vResult->jobid); $DBServer->SetProperty(SERVER_PROPERTIES::ARCHITECTURE, $launchOptions->architecture); return $DBServer; } else { throw new Exception(sprintf("Cannot launch new instance: %s", $vResult->errortext)); } }
public function LaunchServer(DBServer $DBServer, Scalr_Server_LaunchOptions $launchOptions = null) { $environment = $DBServer->GetEnvironmentObject(); if (!$launchOptions) { $launchOptions = new Scalr_Server_LaunchOptions(); $DBRole = DBRole::loadById($DBServer->roleId); $launchOptions->imageId = $DBRole->getImageId(SERVER_PLATFORMS::GCE, $DBServer->GetProperty(GCE_SERVER_PROPERTIES::CLOUD_LOCATION)); $launchOptions->serverType = $DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_GCE_MACHINE_TYPE); $launchOptions->cloudLocation = $DBServer->GetFarmRoleObject()->CloudLocation; $userData = $DBServer->GetCloudUserData(); $launchOptions->architecture = 'x86_64'; $networkName = $DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_GCE_NETWORK); } else { $userData = array(); $networkName = 'default'; } if ($DBServer->status == SERVER_STATUS::TEMPORARY) { $keyName = "SCALR-ROLESBUILDER-" . SCALR_ID; } else { $keyName = "FARM-{$DBServer->farmId}-" . SCALR_ID; } $sshKey = Scalr_SshKey::init(); if (!$sshKey->loadGlobalByName($keyName, "", $DBServer->envId, SERVER_PLATFORMS::GCE)) { $keys = $sshKey->generateKeypair(); if ($keys['public']) { $sshKey->farmId = $DBServer->farmId; $sshKey->clientId = $DBServer->clientId; $sshKey->envId = $DBServer->envId; $sshKey->type = Scalr_SshKey::TYPE_GLOBAL; $sshKey->cloudLocation = ""; $sshKey->cloudKeyName = $keyName; $sshKey->platform = SERVER_PLATFORMS::GCE; $sshKey->save(); $publicKey = $keys['public']; } else { throw new Exception("Scalr unable to generate ssh keypair"); } } else { $publicKey = $sshKey->getPublic(); } $gce = $this->getClient($environment, $launchOptions->cloudLocation); // // // Check firewall $firewalls = $gce->firewalls->listFirewalls($environment->getPlatformConfigValue(self::PROJECT_ID)); $firewallFound = false; foreach ($firewalls->getItems() as $f) { if ($f->getName() == 'scalr-system') { $firewallFound = true; break; } } // Create scalr firewall if (!$firewallFound) { $firewall = new Google_Firewall(); $firewall->setName('scalr-system'); $firewall->setNetwork($this->getObjectUrl($networkName, 'networks', $environment->getPlatformConfigValue(self::PROJECT_ID))); //Get scalr IP-pool IP list and set source ranges $firewall->setSourceRanges(\Scalr::config('scalr.aws.ip_pool')); // Set ports $tcp = new Google_FirewallAllowed(); $tcp->setIPProtocol('tcp'); $tcp->setPorts(array('1-65535')); $udp = new Google_FirewallAllowed(); $udp->setIPProtocol('udp'); $udp->setPorts(array('1-65535')); $firewall->setAllowed(array($tcp, $udp)); // Set target tags $firewall->setTargetTags(array('scalr')); $gce->firewalls->insert($environment->getPlatformConfigValue(self::PROJECT_ID), $firewall); } /// //// ////// $instance = new Google_Instance(); $instance->setKind("compute#instance"); $accessConfig = new Google_AccessConfig(); $accessConfig->setName("External NAT"); $accessConfig->setType("ONE_TO_ONE_NAT"); $network = new Google_NetworkInterface(); $network->setNetwork($this->getObjectUrl($networkName, 'networks', $environment->getPlatformConfigValue(self::PROJECT_ID))); $network->setAccessConfigs(array($accessConfig)); $instance->setNetworkInterfaces(array($network)); $serviceAccount = new Google_ServiceAccount(); $serviceAccount->setEmail("default"); $serviceAccount->setScopes(array("https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/devstorage.full_control")); $instance->setServiceAccounts(array($serviceAccount)); if ($launchOptions->cloudLocation != 'x-scalr-custom') { $availZone = $launchOptions->cloudLocation; } else { $location = $DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_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})"; } $DBServer->SetProperty("tmp.gce.avail_zone.algo2", "[A:{$aZones}][D:{$dZones}][S:{$availZone}]"); } $instance->setZone($this->getObjectUrl($availZone, 'zones', $environment->getPlatformConfigValue(self::PROJECT_ID))); $instance->setMachineType($this->getObjectUrl($launchOptions->serverType, 'machineTypes', $environment->getPlatformConfigValue(self::PROJECT_ID), $availZone)); $instance->setImage($this->getObjectUrl($launchOptions->imageId, 'images', $environment->getPlatformConfigValue(self::PROJECT_ID))); $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_Tags(); $gTags->setItems($tags); $instance->setTags($gTags); $metadata = new Google_Metadata(); $items = array(); // Set user data foreach ($userData as $k => $v) { $uData .= "{$k}={$v};"; } $uData = trim($uData, ";"); if ($uData) { $item = new Google_MetadataItems(); $item->setKey('scalr'); $item->setValue($uData); $items[] = $item; } // Add SSH Key $item = new Google_MetadataItems(); $item->setKey("sshKeys"); $item->setValue("scalr:{$publicKey}"); $items[] = $item; $metadata->setItems($items); $instance->setMetadata($metadata); try { $result = $gce->instances->insert($environment->getPlatformConfigValue(self::PROJECT_ID), $availZone, $instance); } catch (Exception $e) { throw new Exception(sprintf(_("Cannot launch new instance. %s (%s, %s)"), $e->getMessage(), $launchOptions->imageId, $launchOptions->serverType)); } if ($result->id) { $DBServer->SetProperty(GCE_SERVER_PROPERTIES::PROVISIONING_OP_ID, $result->name); $DBServer->SetProperty(GCE_SERVER_PROPERTIES::SERVER_NAME, $DBServer->serverId); $DBServer->SetProperty(GCE_SERVER_PROPERTIES::SERVER_ID, $DBServer->serverId); $DBServer->SetProperty(GCE_SERVER_PROPERTIES::CLOUD_LOCATION, $availZone); $DBServer->SetProperty(GCE_SERVER_PROPERTIES::MACHINE_TYPE, $launchOptions->serverType); $DBServer->SetProperty(SERVER_PROPERTIES::ARCHITECTURE, $launchOptions->architecture); return $DBServer; } else { throw new Exception(sprintf(_("Cannot launch new instance. %s (%s, %s)"), serialize($result), $launchOptions->imageId, $launchOptions->serverType)); } }
/** * {@inheritdoc} * @see \Scalr\Modules\PlatformModuleInterface::LaunchServer() */ public function LaunchServer(DBServer $DBServer, \Scalr_Server_LaunchOptions $launchOptions = null) { $runInstanceRequest = new RunInstancesRequestData(isset($launchOptions->imageId) ? $launchOptions->imageId : null, 1, 1); $environment = $DBServer->GetEnvironmentObject(); $placementData = null; $noSecurityGroups = false; if (!$launchOptions) { $launchOptions = new \Scalr_Server_LaunchOptions(); $DBRole = DBRole::loadById($DBServer->roleId); $dbFarmRole = $DBServer->GetFarmRoleObject(); /* $runInstanceRequest->setMonitoring( $dbFarmRole->GetSetting(DBFarmRole::SETTING_AWS_ENABLE_CW_MONITORING) ); */ $launchOptions->imageId = $DBRole->getImageId(\SERVER_PLATFORMS::EUCALYPTUS, $dbFarmRole->CloudLocation); // Need OS Family to get block device mapping for OEL roles $imageInfo = $DBRole->getImageDetails(\SERVER_PLATFORMS::EUCALYPTUS, $dbFarmRole->CloudLocation); $launchOptions->osFamily = $imageInfo['os_family']; $launchOptions->cloudLocation = $dbFarmRole->CloudLocation; $akiId = $DBServer->GetProperty(\EUCA_SERVER_PROPERTIES::EKIID); if (!$akiId) { $akiId = $dbFarmRole->GetSetting(DBFarmRole::SETTING_EUCA_EKI_ID); } if ($akiId) { $runInstanceRequest->kernelId = $akiId; } $ariId = $DBServer->GetProperty(\EUCA_SERVER_PROPERTIES::ERIID); if (!$ariId) { $ariId = $dbFarmRole->GetSetting(DBFarmRole::SETTING_EUCA_ERI_ID); } if ($ariId) { $runInstanceRequest->ramdiskId = $ariId; } $launchOptions->serverType = $dbFarmRole->GetSetting(DBFarmRole::SETTING_EUCA_INSTANCE_TYPE); foreach ($DBServer->GetCloudUserData() as $k => $v) { $u_data .= "{$k}={$v};"; } $runInstanceRequest->userData = base64_encode(trim($u_data, ";")); $vpcId = false; } else { $runInstanceRequest->userData = base64_encode(trim($launchOptions->userData)); } $governance = new \Scalr_Governance($DBServer->envId); $euca = $environment->eucalyptus($launchOptions->cloudLocation); // Set AMI, AKI and ARI ids $runInstanceRequest->imageId = $launchOptions->imageId; $runInstanceRequest->instanceInitiatedShutdownBehavior = 'terminate'; if (!$noSecurityGroups) { foreach ($this->GetServerSecurityGroupsList($DBServer, $euca->ec2, $vpcId, $governance) as $sgroup) { $runInstanceRequest->appendSecurityGroupId($sgroup); } if (!$runInstanceRequest->subnetId) { // Set availability zone if (!$launchOptions->availZone) { $avail_zone = $this->GetServerAvailZone($DBServer, $euca->ec2, $launchOptions); if ($avail_zone) { $placementData = new PlacementResponseData($avail_zone); } } else { $placementData = new PlacementResponseData($launchOptions->availZone); } } } $runInstanceRequest->minCount = 1; $runInstanceRequest->maxCount = 1; // Set instance type $runInstanceRequest->instanceType = $launchOptions->serverType; if ($placementData !== null) { $runInstanceRequest->setPlacement($placementData); } $sshKey = \Scalr_SshKey::init(); if ($DBServer->status == \SERVER_STATUS::TEMPORARY) { $keyName = "SCALR-ROLESBUILDER-" . SCALR_ID; $farmId = NULL; } else { $keyName = $governance->getValue(\SERVER_PLATFORMS::EUCALYPTUS, \Scalr_Governance::EUCALYPTUS_KEYPAIR); if ($keyName) { $skipKeyValidation = true; } else { $keyName = "FARM-{$DBServer->farmId}-" . SCALR_ID; $farmId = $DBServer->farmId; $oldKeyName = "FARM-{$DBServer->farmId}"; if ($sshKey->loadGlobalByName($oldKeyName, $launchOptions->cloudLocation, $DBServer->envId, \SERVER_PLATFORMS::EUCALYPTUS)) { $keyName = $oldKeyName; $skipKeyValidation = true; } } } if (!$skipKeyValidation && !$sshKey->loadGlobalByName($keyName, $launchOptions->cloudLocation, $DBServer->envId, \SERVER_PLATFORMS::EUCALYPTUS)) { $result = $euca->ec2->keyPair->create($keyName); if ($result->keyMaterial) { $sshKey->farmId = $farmId; $sshKey->envId = $DBServer->envId; $sshKey->type = \Scalr_SshKey::TYPE_GLOBAL; $sshKey->cloudLocation = $launchOptions->cloudLocation; $sshKey->cloudKeyName = $keyName; $sshKey->platform = \SERVER_PLATFORMS::EUCALYPTUS; $sshKey->setPrivate($result->keyMaterial); $sshKey->setPublic($sshKey->generatePublicKey()); $sshKey->save(); } } $runInstanceRequest->keyName = $keyName; try { $result = $euca->ec2->instance->run($runInstanceRequest); } catch (\Exception $e) { if (stristr($e->getMessage(), "The key pair") && stristr($e->getMessage(), "does not exist")) { $sshKey->delete(); throw $e; } if (stristr($e->getMessage(), "The requested Availability Zone is no longer supported") || stristr($e->getMessage(), "is not supported in your requested Availability Zone") || stristr($e->getMessage(), "is currently constrained and we are no longer accepting new customer requests")) { $availZone = $runInstanceRequest->getPlacement() ? $runInstanceRequest->getPlacement()->availabilityZone : null; if ($availZone) { $DBServer->GetEnvironmentObject()->setPlatformConfig(array("eucalyptus.{$launchOptions->cloudLocation}.{$availZone}.unavailable" => time())); } throw $e; } else { throw $e; } } if ($result->instancesSet->get(0)->instanceId) { $DBServer->SetProperties([\EUCA_SERVER_PROPERTIES::AVAIL_ZONE => $result->instancesSet->get(0)->placement->availabilityZone, \EUCA_SERVER_PROPERTIES::INSTANCE_ID => $result->instancesSet->get(0)->instanceId, \EUCA_SERVER_PROPERTIES::INSTANCE_TYPE => $runInstanceRequest->instanceType, \EUCA_SERVER_PROPERTIES::EMIID => $runInstanceRequest->imageId, \EUCA_SERVER_PROPERTIES::REGION => $launchOptions->cloudLocation, \EUCA_SERVER_PROPERTIES::ARCHITECTURE => $result->instancesSet->get(0)->architecture]); $DBServer->osType = $result->instancesSet->get(0)->platform ? $result->instancesSet->get(0)->platform : 'linux'; $DBServer->cloudLocation = $launchOptions->cloudLocation; $DBServer->cloudLocationZone = $result->instancesSet->get(0)->placement->availabilityZone; return $DBServer; } else { throw new \Exception(sprintf(_("Cannot launch new instance. %s"), serialize($result))); } }
public function LaunchServer(DBServer $DBServer, \Scalr_Server_LaunchOptions $launchOptions = null) { $environment = $DBServer->GetEnvironmentObject(); $rootDeviceSettings = null; 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(DBFarmRole::SETTING_GCE_MACHINE_TYPE); $launchOptions->cloudLocation = $DBServer->GetFarmRoleObject()->CloudLocation; $userData = $DBServer->GetCloudUserData(); $launchOptions->architecture = 'x86_64'; $networkName = $DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_GCE_NETWORK); $onHostMaintenance = $DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_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']; } } else { $userData = array(); $networkName = 'default'; $osType = 'linux'; } if (!$onHostMaintenance) { $onHostMaintenance = 'MIGRATE'; } if ($DBServer->status == \SERVER_STATUS::TEMPORARY) { $keyName = "SCALR-ROLESBUILDER-" . SCALR_ID; } else { $keyName = "FARM-{$DBServer->farmId}-" . SCALR_ID; } $sshKey = \Scalr_SshKey::init(); if (!$sshKey->loadGlobalByName($keyName, "", $DBServer->envId, \SERVER_PLATFORMS::GCE)) { $keys = $sshKey->generateKeypair(); if ($keys['public']) { $sshKey->farmId = $DBServer->farmId; $sshKey->envId = $DBServer->envId; $sshKey->type = \Scalr_SshKey::TYPE_GLOBAL; $sshKey->cloudLocation = ""; $sshKey->cloudKeyName = $keyName; $sshKey->platform = \SERVER_PLATFORMS::GCE; $sshKey->save(); $publicKey = $keys['public']; } else { throw new \Exception("Scalr unable to generate ssh keypair"); } } else { $publicKey = $sshKey->getPublic(); } $gce = $this->getClient($environment); // Check firewall $firewalls = $gce->firewalls->listFirewalls($environment->getPlatformConfigValue(self::PROJECT_ID)); $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', $environment->getPlatformConfigValue(self::PROJECT_ID))); //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($environment->getPlatformConfigValue(self::PROJECT_ID), $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', $environment->getPlatformConfigValue(self::PROJECT_ID))); $network->setAccessConfigs(array($accessConfig)); $instance->setNetworkInterfaces(array($network)); $serviceAccount = new \Google_Service_Compute_ServiceAccount(); $serviceAccount->setEmail("default"); $serviceAccount->setScopes(array("https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/devstorage.full_control")); $instance->setServiceAccounts(array($serviceAccount)); if ($launchOptions->cloudLocation != 'x-scalr-custom') { $availZone = $launchOptions->cloudLocation; } else { $location = $DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_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})"; } $DBServer->SetProperty("tmp.gce.avail_zone.algo2", "[A:{$aZones}][D:{$dZones}][S:{$availZone}]"); } $instance->setZone($this->getObjectUrl($availZone, 'zones', $environment->getPlatformConfigValue(self::PROJECT_ID))); $instance->setMachineType($this->getObjectUrl($launchOptions->serverType, 'machineTypes', $environment->getPlatformConfigValue(self::PROJECT_ID), $availZone)); //Create root disk $image = $this->getObjectUrl($launchOptions->imageId, 'images', $environment->getPlatformConfigValue(self::PROJECT_ID)); $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', $environment->getPlatformConfigValue(self::PROJECT_ID), $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); $instance->setDisks(array($attachedDisk)); $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; } $metadata->setItems($items); $instance->setMetadata($metadata); try { $result = $gce->instances->insert($environment->getPlatformConfigValue(self::PROJECT_ID), $availZone, $instance); } catch (\Exception $e) { throw new \Exception(sprintf(_("Cannot launch new instance. %s (%s, %s)"), $e->getMessage(), $image, $launchOptions->serverType)); } if ($result->id) { $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, \GCE_SERVER_PROPERTIES::MACHINE_TYPE => $launchOptions->serverType, \SERVER_PROPERTIES::ARCHITECTURE => $launchOptions->architecture, 'debug.region' => $result->region, 'debug.zone' => $result->zone]); $DBServer->setOsType($osType); $DBServer->cloudLocation = $availZone; $DBServer->cloudLocationZone = $availZone; $DBServer->imageId = $launchOptions->imageId; // we set server history here $DBServer->getServerHistory(); return $DBServer; } else { throw new \Exception(sprintf(_("Cannot launch new instance. %s (%s, %s)"), serialize($result), $launchOptions->imageId, $launchOptions->serverType)); } }
public function OnHostInit(HostInitEvent $event) { $msg = new Scalr_Messaging_Msg_HostInitResponse($event->DBServer->GetFarmObject()->GetSetting(DBFarm::SETTING_CRYPTO_KEY), $event->DBServer->index); $msg->cloudLocation = $event->DBServer->GetCloudLocation(); $dbServer = $event->DBServer; $dbFarmRole = $dbServer->GetFarmRoleObject(); if ($dbFarmRole) { foreach (Scalr_Role_Behavior::getListForFarmRole($dbFarmRole) as $behavior) { $msg = $behavior->extendMessage($msg, $dbServer); } } $msg->setGlobalVariables($dbServer, true, $event); /** * TODO: Move everything to Scalr_Db_Msr_* */ if ($dbFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::MYSQL)) { $isMaster = (int) $dbServer->GetProperty(SERVER_PROPERTIES::DB_MYSQL_MASTER); $msg->mysql = (object) array("replicationMaster" => $isMaster, "rootPassword" => $dbFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_ROOT_PASSWORD), "replPassword" => $dbFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_REPL_PASSWORD), "statPassword" => $dbFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_STAT_PASSWORD), "logFile" => $dbFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_LOG_FILE), "logPos" => $dbFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_LOG_POS)); if ($event->DBServer->IsSupported("0.7")) { if ($dbFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_SCALR_VOLUME_ID) && $isMaster) { try { $volume = Scalr_Storage_Volume::init()->loadById($dbFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_SCALR_VOLUME_ID)); $msg->mysql->volumeConfig = $volume->getConfig(); } catch (Exception $e) { } } /*** * For Rackspace we ALWAYS need snapsjot_config for mysql * ***/ if ($dbFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_SCALR_SNAPSHOT_ID)) { try { $snapshotConfig = Scalr_Storage_Snapshot::init()->loadById($dbFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_SCALR_SNAPSHOT_ID)); $msg->mysql->snapshotConfig = $snapshotConfig->getConfig(); } catch (Exception $e) { $this->Logger->error(new FarmLogMessage($event->DBServer->farmId, "Cannot get snaphotConfig for hostInit message: {$e->getMessage()}")); } } if (!$msg->mysql->snapshotConfig && $dbFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_SNAPSHOT_ID)) { $msg->mysql->snapshotConfig = new stdClass(); $msg->mysql->snapshotConfig->type = $dbFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_DATA_STORAGE_ENGINE); $msg->mysql->snapshotConfig->id = $dbFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_SNAPSHOT_ID); } if ($isMaster && !$msg->mysql->volumeConfig) { $msg->mysql->volumeConfig = new stdClass(); $msg->mysql->volumeConfig->type = $dbFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_DATA_STORAGE_ENGINE); if (!$dbFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_MASTER_EBS_VOLUME_ID)) { if (in_array($dbFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_DATA_STORAGE_ENGINE), array(MYSQL_STORAGE_ENGINE::EBS, MYSQL_STORAGE_ENGINE::CSVOL))) { $msg->mysql->volumeConfig->size = $dbFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_EBS_VOLUME_SIZE); if ($dbFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_DATA_STORAGE_ENGINE) == MYSQL_STORAGE_ENGINE::EBS) { $msg->mysql->volumeConfig->volumeType = $dbFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_EBS_TYPE); if ($msg->mysql->volumeConfig->volumeType == 'io1') { $msg->mysql->volumeConfig->iops = $dbFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_EBS_IOPS); } } } elseif ($dbFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_DATA_STORAGE_ENGINE) == MYSQL_STORAGE_ENGINE::EPH) { //$msg->mysql->volumeConfig->snap_backend = "cf://mysql-data-bundle/scalr-{$dbFarmRole->GetFarmObject()->Hash}"; $msg->mysql->volumeConfig->snap_backend = sprintf("cf://scalr-%s-%s/data-bundles/%s/mysql/", $event->DBServer->envId, $event->DBServer->GetCloudLocation(), $event->DBServer->farmId); $msg->mysql->volumeConfig->vg = 'mysql'; $msg->mysql->volumeConfig->disk = new stdClass(); $msg->mysql->volumeConfig->disk->type = 'loop'; $msg->mysql->volumeConfig->disk->size = '75%root'; } } else { $msg->mysql->volumeConfig->id = $dbFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_MASTER_EBS_VOLUME_ID); } } } else { if ($isMaster) { $msg->mysql->volumeId = $dbFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_MASTER_EBS_VOLUME_ID); } $msg->mysql->snapshotId = $dbFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_SNAPSHOT_ID); } } // Create ssh keypair for rackspace if ($event->DBServer->IsSupported("0.7")) { $authSshKey = $event->DBServer->platform == SERVER_PLATFORMS::RACKSPACE || $event->DBServer->platform == SERVER_PLATFORMS::NIMBULA || $event->DBServer->isCloudstack(); if ($event->DBServer->isOpenstack()) { $platform = PlatformFactory::NewPlatform($event->DBServer->platform); $isKeyPairsSupported = $platform->getConfigVariable(OpenstackPlatformModule::EXT_KEYPAIRS_ENABLED, $event->DBServer->GetEnvironmentObject(), false); if ($isKeyPairsSupported != 1) { $authSshKey = true; } } if ($authSshKey) { $sshKey = Scalr_SshKey::init(); if (!$sshKey->loadGlobalByFarmId($event->DBServer->envId, $event->DBServer->farmId, $event->DBServer->GetFarmRoleObject()->CloudLocation, $event->DBServer->platform)) { $key_name = "FARM-{$event->DBServer->farmId}-" . SCALR_ID; $sshKey->generateKeypair(); $sshKey->farmId = $event->DBServer->farmId; $sshKey->envId = $event->DBServer->envId; $sshKey->type = Scalr_SshKey::TYPE_GLOBAL; $sshKey->platform = $event->DBServer->platform; $sshKey->cloudLocation = $event->DBServer->GetFarmRoleObject()->CloudLocation; $sshKey->cloudKeyName = $key_name; $sshKey->platform = $event->DBServer->platform; $sshKey->save(); } $sshKeysMsg = new Scalr_Messaging_Msg_UpdateSshAuthorizedKeys(array($sshKey->getPublic()), array()); $event->DBServer->SendMessage($sshKeysMsg, false, true); } } // Send HostInitResponse to target server $event->DBServer->SendMessage($msg); // Send broadcast HostInit $servers = DBFarm::LoadByID($this->FarmID)->GetServersByFilter(array('status' => array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING))); $event->msgExpected = count($servers); foreach ((array) $servers as $DBServer) { if (!$DBServer->IsSupported('0.5')) { $event->msgExpected--; continue; } if ($DBServer->status == SERVER_STATUS::INIT && $DBServer->serverId != $event->DBServer->serverId) { $event->msgExpected--; continue; } $hiMsg = new Scalr_Messaging_Msg_HostInit(); $hiMsg->setServerMetaData($event->DBServer); $hiMsg = Scalr_Scripting_Manager::extendMessage($hiMsg, $event, $event->DBServer, $DBServer); if ($event->DBServer->farmRoleId != 0) { foreach (Scalr_Role_Behavior::getListForFarmRole($event->DBServer->GetFarmRoleObject()) as $behavior) { $hiMsg = $behavior->extendMessage($hiMsg, $event->DBServer); } } $hiMsg = $DBServer->SendMessage($hiMsg, false, true); if ($hiMsg->dbMessageId) { $event->msgCreated++; } } }
/** * Get list of roles for listView */ public function xListSshKeysAction() { $this->request->defineParams(array('sshKeyId' => array('type' => 'int'), 'sort' => array('type' => 'string', 'default' => 'id'), 'dir' => array('type' => 'string', 'default' => 'ASC'))); $sql = "SELECT id from ssh_keys WHERE env_id='" . $this->getEnvironmentId() . "'"; if ($this->getParam('sshKeyId')) { $sql .= " AND id='{$this->getParam('sshKeyId')}'"; } $response = $this->buildResponseFromSql($sql, array("cloud_key_name", "farm_id", "id")); foreach ($response["data"] as &$row) { $sshKey = Scalr_SshKey::init()->loadById($row['id']); $row = array('id' => $sshKey->id, 'type' => $sshKey->type == Scalr_SshKey::TYPE_GLOBAL ? "{$sshKey->type} ({$sshKey->platform})" : $sshKey->type, 'cloud_key_name' => $sshKey->cloudKeyName, 'farm_id' => $sshKey->farmId, 'cloud_location' => $sshKey->cloudLocation); } $this->response->data($response); }