public static function removeIpFromServer(\DBServer $dbServer) { try { if ($dbServer->GetProperty(\OPENSTACK_SERVER_PROPERTIES::FLOATING_IP)) { if ($dbServer->farmRoleId) { if ($dbServer->GetFarmRoleObject()->GetSetting(\DBFarmRole::SETTING_OPENSTACK_KEEP_FIP_ON_SUSPEND)) { if (in_array($dbServer->status, array(\SERVER_STATUS::PENDING_SUSPEND, \SERVER_STATUS::SUSPENDED)) || $dbServer->GetRealStatus()->isSuspended()) { return false; } } } $environment = $dbServer->GetEnvironmentObject(); $osClient = $environment->openstack($dbServer->platform, $dbServer->GetCloudLocation()); $ipId = $dbServer->GetProperty(\OPENSTACK_SERVER_PROPERTIES::FLOATING_IP_ID); if ($osClient->hasService('network')) { $osClient->network->floatingIps->delete($ipId); } else { $osClient->servers->deleteFloatingIp($ipId); } $dbServer->SetProperties(array(\OPENSTACK_SERVER_PROPERTIES::FLOATING_IP => null, \OPENSTACK_SERVER_PROPERTIES::FLOATING_IP_ID => null)); } } catch (\Exception $e) { \Logger::getLogger("OpenStackObserver")->fatal("OpenStackObserver observer failed: " . $e->getMessage()); } }
public function GetServerIPAddresses(DBServer $DBServer) { $client = $this->getOsClient($DBServer->GetEnvironmentObject(), $DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION)); $result = $client->servers->getServerDetails($DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::SERVER_ID)); if ($result->accessIPv4) { $remoteIp = $result->accessIPv4; } if (!$remoteIp) { if (is_array($result->addresses->public)) { foreach ($result->addresses->public as $addr) { if ($addr->version == 4) { $remoteIp = $addr->addr; break; } } } } if (is_array($result->addresses->private)) { foreach ($result->addresses->private as $addr) { if ($addr->version == 4) { $localIp = $addr->addr; break; } } } if (!$localIp) { $localIp = $remoteIp; } return array('localIp' => $localIp, 'remoteIp' => $remoteIp); }
/** * {@inheritdoc} * @see \Scalr\Modules\Platforms\Openstack\OpenstackPlatformModule::GetServerIPAddresses() */ public function GetServerIPAddresses(\DBServer $DBServer) { $config = \Scalr::getContainer()->config; $client = $this->getOsClient($DBServer->GetEnvironmentObject(), $DBServer->GetProperty(\OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION)); $result = $client->servers->getServerDetails($DBServer->GetProperty(\OPENSTACK_SERVER_PROPERTIES::SERVER_ID)); $publicNetworkName = 'public'; $privateNetworkName = 'private'; if (is_array($result->addresses->{$publicNetworkName})) { foreach ($result->addresses->{$publicNetworkName} as $addr) { if ($addr->version == 4) { $remoteIp = $addr->addr; break; } } } if (!$remoteIp && $result->accessIPv4) { $remoteIp = $result->accessIPv4; } if (is_array($result->addresses->{$privateNetworkName})) { foreach ($result->addresses->{$privateNetworkName} as $addr) { if ($addr->version == 4) { $localIp = $addr->addr; break; } } } if (!$localIp) { $localIp = $remoteIp; } return array('localIp' => $localIp, 'remoteIp' => $remoteIp); }
public static function setupScalrAgent(\DBServer $dbServer) { $baseurl = \Scalr::config('scalr.endpoint.scheme') . "://" . \Scalr::config('scalr.endpoint.host'); $env = $dbServer->GetEnvironmentObject(); $azure = $env->azure(); $branch = $dbServer->getScalarizrRepository()['repository']; $develRepos = \Scalr::getContainer()->config->get('scalr.scalarizr_update.devel_repos'); $scmBranch = $dbServer->GetFarmRoleObject()->GetSetting('user-data.scm_branch'); if ($scmBranch != '' && $develRepos) { $branch = $dbServer->GetFarmRoleObject()->GetSetting('base.devel_repository'); $scmBranch = "{$scmBranch}/"; } else { $scmBranch = ''; } if ($dbServer->osType == 'linux') { $extensionProperties = new ResourceExtensionProperties('Microsoft.OSTCExtensions', 'CustomScriptForLinux', '1.2'); $extensionProperties->setSettings(['commandToExecute' => "bash -c 'curl -k -L \"{$baseurl}/public/linux/{$branch}/azure/{$scmBranch}install_scalarizr.sh\" | bash && service scalr-upd-client start'"]); } else { $extensionProperties = new ResourceExtensionProperties('Microsoft.Compute', 'CustomScriptExtension', '1.4'); $extensionProperties->setSettings(["commandToExecute" => "powershell -NoProfile -ExecutionPolicy Bypass -Command \"iex ((new-object net.webclient).DownloadString('{$baseurl}/public/windows/{$branch}/{$scmBranch}install_scalarizr.ps1')); start-service ScalrUpdClient\""]); } $createExtension = new CreateResourceExtension('scalarizr', $dbServer->cloudLocation, $extensionProperties); try { $response = $azure->compute->resourceExtension->create($env->keychain(SERVER_PLATFORMS::AZURE)->properties[Entity\CloudCredentialsProperty::AZURE_SUBSCRIPTION_ID], $dbServer->GetProperty(\AZURE_SERVER_PROPERTIES::RESOURCE_GROUP), $dbServer->GetProperty(\AZURE_SERVER_PROPERTIES::SERVER_NAME), $createExtension); \Scalr::getContainer()->logger(\LOG_CATEGORY::FARM)->info(new \FarmLogMessage($dbServer, sprintf(_("Created azure resource extension to install and launch scalr agent")))); $dbServer->SetProperty(\AZURE_SERVER_PROPERTIES::SZR_EXTENSION_DEPLOYED, 1); } catch (\Exception $e) { \Scalr::getContainer()->logger(\LOG_CATEGORY::FARM)->fatal(new \FarmLogMessage($dbServer, sprintf(_("Unable to create azure resource extension to install and launch scalr agent: %s"), $e->getMessage()))); } }
/** * {@inheritdoc} * @see \Scalr\Modules\Platforms\Cloudstack\CloudstackPlatformModule::TerminateServer() */ public function TerminateServer(\DBServer $DBServer) { $cs = $DBServer->GetEnvironmentObject()->cloudstack($this->platform); if (!$DBServer->GetProperty(\CLOUDSTACK_SERVER_PROPERTIES::IS_STOPPED_BEFORE_TERMINATE)) { $cs->instance->stop($DBServer->GetProperty(\CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID), true); $DBServer->SetProperty(\CLOUDSTACK_SERVER_PROPERTIES::IS_STOPPED_BEFORE_TERMINATE, 1); } return parent::TerminateServer($DBServer); }
private function DeregisterInstanceFromLB(DBServer $DBServer) { try { $DBFarmRole = $DBServer->GetFarmRoleObject(); if ($DBFarmRole->GetSetting(DBFarmRole::SETTING_BALANCING_USE_ELB) == 1) { $Client = $DBServer->GetClient(); $AmazonELBClient = Scalr_Service_Cloud_Aws::newElb($DBServer->GetProperty(EC2_SERVER_PROPERTIES::REGION), $DBServer->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Ec2::ACCESS_KEY), $DBServer->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Ec2::SECRET_KEY)); $AmazonELBClient->DeregisterInstancesFromLoadBalancer($DBFarmRole->GetSetting(DBFarmRole::SETTING_BALANCING_NAME), array($DBServer->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID))); Logger::getLogger(LOG_CATEGORY::FARM)->info(new FarmLogMessage($this->FarmID, sprintf(_("Instance '%s' deregistered from '%s' load balancer"), $DBServer->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID), $DBFarmRole->GetSetting(DBFarmRole::SETTING_BALANCING_NAME)))); } } catch (Exception $e) { Logger::getLogger(LOG_CATEGORY::FARM)->info(new FarmLogMessage($this->FarmID, sprintf(_("Cannot deregister instance from the load balancer: %s"), $e->getMessage()))); } }
public function __construct(DBFarmRole $dbFarmRole, DBServer $dbServer, $type) { $this->dbFarmRole = $dbFarmRole; $this->dbServer = $dbServer; $this->logger = Logger::getLogger(__CLASS__); $this->replicationMaster = (int) $dbServer->GetProperty(Scalr_Db_Msr::REPLICATION_MASTER); $this->buildStorageSettings(); }
public function onHostDown(DBServer $dbServer) { $nodeName = $dbServer->GetProperty(self::SERVER_CHEF_NODENAME); $config = $this->getConfiguration($dbServer); if (!empty($nodeName) && isset($config->serverUrl)) { $this->removeNodeFromChefServer($dbServer, $config, $nodeName); $dbServer->SetProperty(self::SERVER_CHEF_NODENAME, ""); } }
private function cleanupFloatingIps(DBServer $dbServer) { try { if ($dbServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::FLOATING_IP)) { $environment = $dbServer->GetEnvironmentObject(); $osClient = $environment->openstack($dbServer->platform, $dbServer->GetCloudLocation()); $ipId = $dbServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::FLOATING_IP_ID); if ($osClient->hasService('network')) { $osClient->network->floatingIps->delete($ipId); } else { $osClient->servers->deleteFloatingIp($ipId); } $dbServer->SetProperties(array(OPENSTACK_SERVER_PROPERTIES::FLOATING_IP => null, OPENSTACK_SERVER_PROPERTIES::FLOATING_IP_ID => null)); } } catch (Exception $e) { Logger::getLogger("OpenStackObserver")->fatal("OpenStackObserver observer failed: " . $e->getMessage()); } }
public function listDnsRecords(DBServer $dbServer) { $records = array(); array_push($records, array("name" => "int-rabbitmq", "value" => $dbServer->localIp, "type" => "A", "ttl" => 90, "server_id" => $dbServer->serverId, "issystem" => '1')); array_push($records, array("name" => "ext-rabbitmq", "value" => $dbServer->remoteIp, "type" => "A", "ttl" => 90, "server_id" => $dbServer->serverId, "issystem" => '1')); $nodeType = $dbServer->GetProperty(self::SERVER_NODE_TYPE); array_push($records, array("name" => "int-rabbitmq-{$nodeType}", "value" => $dbServer->localIp, "type" => "A", "ttl" => 90, "server_id" => $dbServer->serverId, "issystem" => '1')); array_push($records, array("name" => "ext-rabbitmq-{$nodeType}", "value" => $dbServer->remoteIp, "type" => "A", "ttl" => 90, "server_id" => $dbServer->serverId, "issystem" => '1')); }
private function setConfig(DBServer $dbServer, $behavior, $config) { $port = $dbServer->GetProperty(SERVER_PROPERTIES::SZR_API_PORT); if (!$port) { $port = 8010; } $client = Scalr_Net_Scalarizr_Client::getClient($dbServer, Scalr_Net_Scalarizr_Client::NAMESPACE_SERVICE, $port); $result = $client->setPreset($behavior, $config); return $result->result; }
private function getDbStorageStatus(DBServer $masterServer, $behavior) { // Get Stoarge usage $size = array('total' => -1, 'used' => -1, 'free' => -1); try { $port = $masterServer->GetProperty(SERVER_PROPERTIES::SZR_API_PORT); if (!$port) { $port = 8010; } $client = Scalr_Net_Scalarizr_Client::getClient($masterServer, Scalr_Net_Scalarizr_Client::NAMESPACE_SYSTEM, $port); if ($behavior == ROLE_BEHAVIORS::REDIS) { $mpoint = '/mnt/redisstorage'; } elseif ($behavior == ROLE_BEHAVIORS::POSTGRESQL) { $mpoint = '/mnt/pgstorage'; } else { $mpoint = '/mnt/dbstorage'; } $usage = (array) $client->statvfs(array($mpoint)); $size = (array) $usage[$mpoint]; if ($size['total']) { $size['used'] = $size['total'] - $size['free']; // Convert KB to GB foreach ($size as $k => $v) { $size[$k] = round($v / 1024 / 1024, 2); } } } catch (Exception $e) { $this->response->varDump($e->getMessage()); } $retval = array('engine' => $masterServer->GetFarmRoleObject()->GetSetting(Scalr_Db_Msr::DATA_STORAGE_ENGINE), 'id' => $masterServer->GetFarmRoleObject()->GetSetting(Scalr_Db_Msr::VOLUME_ID) ? $masterServer->GetFarmRoleObject()->GetSetting(Scalr_Db_Msr::VOLUME_ID) : '', 'fs' => $masterServer->GetFarmRoleObject()->GetSetting(Scalr_Db_Msr::DATA_STORAGE_FSTYPE), 'size' => $size); $retval['growSupported'] = in_array($retval['engine'], array(MYSQL_STORAGE_ENGINE::EBS, MYSQL_STORAGE_ENGINE::RAID_EBS)) && in_array($behavior, array(ROLE_BEHAVIORS::MYSQL2, ROLE_BEHAVIORS::PERCONA, ROLE_BEHAVIORS::MARIADB)); switch ($retval['engine']) { case MYSQL_STORAGE_ENGINE::EBS: $retval['engineName'] = 'Single EBS volume'; break; case MYSQL_STORAGE_ENGINE::RAID_EBS: $retval['engineName'] = sprintf('RAID %s on %s EBS volumes', $masterServer->GetFarmRoleObject()->GetSetting(Scalr_Db_Msr::DATA_STORAGE_RAID_LEVEL), $masterServer->GetFarmRoleObject()->GetSetting(Scalr_Db_Msr::DATA_STORAGE_RAID_DISKS_COUNT)); break; case MYSQL_STORAGE_ENGINE::LVM: $retval['engineName'] = 'LVM on ephemeral device(s)'; break; case MYSQL_STORAGE_ENGINE::EPH: $retval['engineName'] = 'Ephemeral device'; break; case MYSQL_STORAGE_ENGINE::CSVOL: $retval['engineName'] = 'Single Cloudstack volume'; break; default: $retval['engineName'] = $retval['engine']; break; } return $retval; }
private function openstackSetFloatingIp(DBServer $DBServer) { $ipPool = $DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_OPENSTACK_IP_POOL); if (!$DBServer->remoteIp && in_array($DBServer->status, array(SERVER_STATUS::PENDING, SERVER_STATUS::INIT, SERVER_STATUS::SUSPENDED)) && $ipPool) { //$ipAddress = \Scalr\Modules\Platforms\Openstack\Helpers\OpenstackHelper::setFloatingIpForServer($DBServer); $osClient = $DBServer->GetEnvironmentObject()->openstack($DBServer->platform, $DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION)); if ($osClient->hasService('network')) { $platform = PlatformFactory::NewPlatform($DBServer->platform); $serverIps = $platform->GetServerIPAddresses($DBServer); /********* USE Quantum (Neuron) NETWORK *******/ $ips = $osClient->network->floatingIps->list(); //Check free existing IP $ipAssigned = false; $ipAddress = false; $ipInfo = false; foreach ($ips as $ip) { if ($ip->fixed_ip_address == $serverIps['localIp'] && $ip->port_id) { $ipAssigned = true; $ipInfo = $ip; break; } if (!$ip->fixed_ip_address && $ip->floating_ip_address && !$ip->port_id) { $ipInfo = $ip; } } if ($ipInfo) { Logger::getLogger("Openstack")->warn(new FarmLogMessage($DBServer->farmId, "Found free floating IP: {$ipInfo->floating_ip_address} for use (" . json_encode($ipInfo) . ")")); } if (!$ipInfo || !$ipAssigned) { // Get instance port $ports = $osClient->network->ports->list(); foreach ($ports as $port) { /* */ if ($port->device_id == $DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::SERVER_ID)) { $serverNetworkPort[] = $port; } } if (count($serverNetworkPort) == 0) { Logger::getLogger("Openstack")->error(new FarmLogMessage($DBServer->farmId, "Unable to identify network port of instance")); } else { $publicNetworkId = $ipPool; while (count($serverNetworkPort) > 0) { try { $port = array_shift($serverNetworkPort); if (!$ipInfo) { $ipInfo = $osClient->network->floatingIps->create($publicNetworkId, $port->id); Logger::getLogger("Openstack")->warn(new FarmLogMessage($DBServer->farmId, "Allocated new IP {$ipInfo->floating_ip_address} for port: {$port->id}")); } else { $osClient->network->floatingIps->update($ipInfo->id, $port->id); Logger::getLogger("Openstack")->warn(new FarmLogMessage($DBServer->farmId, "Existing floating IP {$ipInfo->floating_ip_address} was used for port: {$port->id}")); } $DBServer->SetProperties(array(OPENSTACK_SERVER_PROPERTIES::FLOATING_IP => $ipInfo->floating_ip_address, OPENSTACK_SERVER_PROPERTIES::FLOATING_IP_ID => $ipInfo->id)); $ipAddress = $ipInfo->floating_ip_address; break; } catch (Exception $e) { $this->logger->error("Scalr unable to allocate new floating IP from pool: " . $e->getMessage()); } } } } else { Logger::getLogger("Openstack")->warn(new FarmLogMessage($DBServer->farmId, "IP: {$ipInfo->floating_ip_address} already assigned")); $ipAddress = $ipInfo->floating_ip_address; } } else { /********* USE NOVA NETWORK *******/ //Check free existing IP $ipAssigned = false; $ipAddress = false; $ips = $osClient->servers->floatingIps->list($ipPool); foreach ($ips as $ip) { //if (!$ip->instance_id) { // $ipAddress = $ip->ip; //} if ($ip->instance_id == $DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::SERVER_ID)) { $ipAddress = $ip->ip; $ipAssigned = true; } } //If no free IP allocate new from pool if (!$ipAddress) { $ip = $osClient->servers->floatingIps->create($ipPool); $ipAddress = $ip->ip; $DBServer->SetProperties(array(OPENSTACK_SERVER_PROPERTIES::FLOATING_IP => $ip->ip, OPENSTACK_SERVER_PROPERTIES::FLOATING_IP_ID => $ip->id)); } if (!$ipAssigned) { //Associate floating IP with Instance $osClient->servers->addFloatingIp($DBServer->GetCloudServerID(), $ipAddress); } } if ($ipAddress) { $DBServer->remoteIp = $ipAddress; $DBServer->Save(); $DBServer->SetProperty(SERVER_PROPERTIES::SYSTEM_IGNORE_INBOUND_MESSAGES, null); } } }
public function PutAccessData(DBServer $DBServer, Scalr_Messaging_Msg $message) { $put = false; $put |= $message instanceof Scalr_Messaging_Msg_Rebundle; $put |= $message instanceof Scalr_Messaging_Msg_HostInitResponse; $put |= $message instanceof Scalr_Messaging_Msg_Mysql_PromoteToMaster; $put |= $message instanceof Scalr_Messaging_Msg_Mysql_NewMasterUp; $put |= $message instanceof Scalr_Messaging_Msg_Mysql_CreateDataBundle; $put |= $message instanceof Scalr_Messaging_Msg_Mysql_CreateBackup; $put |= $message instanceof Scalr_Messaging_Msg_DbMsr_PromoteToMaster; $put |= $message instanceof Scalr_Messaging_Msg_DbMsr_CreateDataBundle; $put |= $message instanceof Scalr_Messaging_Msg_DbMsr_CreateBackup; if ($put) { $environment = $DBServer->GetEnvironmentObject(); $accessData = new stdClass(); $accessData->username = $environment->getPlatformConfigValue(self::USERNAME, true, $DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION)); $accessData->password = $environment->getPlatformConfigValue(self::API_KEY, true, $DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION)); $accessData->authUrl = $environment->getPlatformConfigValue(self::API_URL, true, $DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION)); $accessData->projectId = $environment->getPlatformConfigValue(self::PROJECT_NAME, true, $DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION)); $accessData->cloudLocation = $DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION); $message->platformAccessData = $accessData; } }
public function PutAccessData(DBServer $DBServer, Scalr_Messaging_Msg $message) { $put = false; $put |= $message instanceof Scalr_Messaging_Msg_Rebundle; $put |= $message instanceof Scalr_Messaging_Msg_HostInitResponse; $put |= $message instanceof Scalr_Messaging_Msg_Mysql_PromoteToMaster; $put |= $message instanceof Scalr_Messaging_Msg_Mysql_NewMasterUp; $put |= $message instanceof Scalr_Messaging_Msg_Mysql_CreateDataBundle; $put |= $message instanceof Scalr_Messaging_Msg_Mysql_CreateBackup; $put |= $message instanceof Scalr_Messaging_Msg_DbMsr_PromoteToMaster; $put |= $message instanceof Scalr_Messaging_Msg_DbMsr_CreateDataBundle; $put |= $message instanceof Scalr_Messaging_Msg_DbMsr_CreateBackup; if ($put) { $environment = $DBServer->GetEnvironmentObject(); $accessData = new stdClass(); $accessData->username = $environment->getPlatformConfigValue(self::USERNAME, true, $DBServer->GetProperty(RACKSPACE_SERVER_PROPERTIES::DATACENTER)); $accessData->apiKey = $environment->getPlatformConfigValue(self::API_KEY, true, $DBServer->GetProperty(RACKSPACE_SERVER_PROPERTIES::DATACENTER)); switch ($DBServer->GetProperty(RACKSPACE_SERVER_PROPERTIES::DATACENTER)) { case 'rs-ORD1': $accessData->authHost = 'auth.api.rackspacecloud.com'; break; case 'rs-LONx': $accessData->authHost = 'lon.auth.api.rackspacecloud.com'; break; } $message->platformAccessData = $accessData; } }
public function getConfiguration(DBServer $dbServer) { $configuration = new stdClass(); $dbFarmRole = $dbServer->GetFarmRoleObject(); if (!$dbFarmRole->GetSetting(self::ROLE_CHEF_BOOTSTRAP)) { return $configuration; } $jsonAttributes = $dbFarmRole->GetSetting(self::ROLE_CHEF_ATTRIBUTES); $chefCookbookUrl = $dbFarmRole->GetSetting(self::ROLE_CHEF_COOKBOOK_URL); if ($chefCookbookUrl) { $configuration->cookbookUrl = $chefCookbookUrl; $configuration->runList = $dbFarmRole->GetSetting(self::ROLE_CHEF_RUNLIST); $configuration->cookbookUrlType = $dbFarmRole->GetSetting(self::ROLE_CHEF_COOKBOOK_URL_TYPE); $configuration->sshPrivateKey = $dbFarmRole->GetSetting(self::ROLE_CHEF_SSH_PRIVATE_KEY); $configuration->relativePath = $dbFarmRole->GetSetting(self::ROLE_CHEF_RELATIVE_PATH); } else { // Get chef server info $chefServerId = $dbFarmRole->GetSetting(self::ROLE_CHEF_SERVER_ID); $chefServerInfo = $this->db->GetRow("SELECT * FROM services_chef_servers WHERE id=?", array($chefServerId)); $chefServerInfo['v_auth_key'] = trim($this->getCrypto()->decrypt($chefServerInfo['v_auth_key'], $this->cryptoKey)); // Prepare node name $configuration->nodeName = $dbServer->GetProperty(self::SERVER_CHEF_NODENAME); if (!$configuration->nodeName) { $nodeNameTpl = $dbFarmRole->GetSetting(self::ROLE_CHEF_NODENAME_TPL); if ($nodeNameTpl) { $params = $dbServer->GetScriptingVars(); $keys = array_keys($params); $f = create_function('$item', 'return "%".$item."%";'); $keys = array_map($f, $keys); $values = array_values($params); $configuration->nodeName = str_replace($keys, $values, $nodeNameTpl); //TODO: Add support for Global variables } } $configuration->serverUrl = $chefServerInfo['url']; $configuration->validatorName = $chefServerInfo['v_username']; $configuration->validatorKey = $chefServerInfo['v_auth_key']; if ($dbFarmRole->GetSetting(self::ROLE_CHEF_ROLE_NAME)) { $configuration->role = $dbFarmRole->GetSetting(self::ROLE_CHEF_ROLE_NAME); } else { $configuration->runList = $dbFarmRole->GetSetting(self::ROLE_CHEF_RUNLIST); } $configuration->environment = $dbFarmRole->GetSetting(self::ROLE_CHEF_ENVIRONMENT); $configuration->daemonize = $dbFarmRole->GetSetting(self::ROLE_CHEF_DAEMONIZE); } if ($jsonAttributes) { $params = $dbServer->GetScriptingVars(); // Prepare keys array and array with values for replacement in script $keys = array_keys($params); $f = create_function('$item', 'return "%".$item."%";'); $keys = array_map($f, $keys); $values = array_values($params); $contents = str_replace($keys, $values, $jsonAttributes); $configuration->jsonAttributes = str_replace('\\%', "%", $contents); //TODO: Add support for Global variables } return $configuration; }
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))); } }
private function GetServerAvailZone(DBServer $DBServer, $EC2Client, Scalr_Server_LaunchOptions $launchOptions) { if ($DBServer->status == SERVER_STATUS::TEMPORARY) { return false; } $server_avail_zone = $DBServer->GetProperty(EC2_SERVER_PROPERTIES::AVAIL_ZONE); if ($DBServer->replaceServerID && !$server_avail_zone) { try { $rDbServer = DBServer::LoadByID($DBServer->replaceServerID); $server_avail_zone = $rDbServer->GetProperty(EC2_SERVER_PROPERTIES::AVAIL_ZONE); } catch (Exception $e) { } } $role_avail_zone = $this->db->GetOne("SELECT ec2_avail_zone FROM ec2_ebs WHERE server_index=? AND farm_roleid=?", array($DBServer->index, $DBServer->farmRoleId)); if (!$role_avail_zone) { if ($server_avail_zone && $server_avail_zone != 'x-scalr-diff' && !stristr($server_avail_zone, "x-scalr-custom")) { return $server_avail_zone; } $role_avail_zone = $DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_AWS_AVAIL_ZONE); } if (!$role_avail_zone) { return false; } if ($role_avail_zone == "x-scalr-diff" || stristr($role_avail_zone, "x-scalr-custom")) { //TODO: Elastic Load Balancer $avail_zones = array(); if (stristr($role_avail_zone, "x-scalr-custom")) { $zones = explode("=", $role_avail_zone); foreach (explode(":", $zones[1]) as $zone) { if ($zone != "") { array_push($avail_zones, $zone); } } } else { // Get list of all available zones $avail_zones_resp = $EC2Client->DescribeAvailabilityZones(); foreach ($avail_zones_resp->availabilityZoneInfo->item as $zone) { $zoneName = (string) $zone->zoneName; if (strstr($zone->zoneState, 'available')) { $isUnavailable = $DBServer->GetEnvironmentObject()->getPlatformConfigValue("aws.{$launchOptions->cloudLocation}.{$zoneName}.unavailable", false); if ($isUnavailable && $isUnavailable + 3600 < time()) { $DBServer->GetEnvironmentObject()->setPlatformConfig(array("aws.{$launchOptions->cloudLocation}.{$zoneName}.unavailable" => false), false); $isUnavailable = false; } if (!$isUnavailable) { array_push($avail_zones, $zoneName); } } } } sort($avail_zones); $avail_zones = array_reverse($avail_zones); $servers = $DBServer->GetFarmRoleObject()->GetServersByFilter(array("status" => array(SERVER_STATUS::RUNNING, SERVER_STATUS::INIT, SERVER_STATUS::PENDING))); $availZoneDistribution = array(); foreach ($servers as $cDbServer) { $availZoneDistribution[$cDbServer->GetProperty(EC2_SERVER_PROPERTIES::AVAIL_ZONE)]++; } $sCount = 1000000; foreach ($avail_zones as $zone) { if ((int) $availZoneDistribution[$zone] <= $sCount) { $sCount = (int) $availZoneDistribution[$zone]; $availZone = $zone; } } /*** OLD Algorithm ***/ /* // Get count of curently running instances $instance_count = $this->db->GetOne("SELECT COUNT(*) FROM servers WHERE farm_roleid=? AND status NOT IN (?,?)", array($DBServer->farmRoleId, SERVER_STATUS::PENDING_TERMINATE, SERVER_STATUS::TERMINATED) ); // Get zone index. $zone_index = ($instance_count) % count($avail_zones); $availZone = $avail_zones[$zone_index]; */ /***** OLD Algorithm END *****/ return $availZone; } else { return $role_avail_zone; } }
private function getServerDNSRecords(DBServer $DBServer) { $records = array(); if ($DBServer->status != SERVER_STATUS::RUNNING) { return $records; } if ($DBServer->GetProperty(SERVER_PROPERTIES::EXCLUDE_FROM_DNS)) { return $records; } $DBFarmRole = $DBServer->GetFarmRoleObject(); if ($DBFarmRole->GetSetting(DBFarmRole::SETTING_EXCLUDE_FROM_DNS)) { return $records; } if ($DBFarmRole->ID == $this->farmRoleId) { $ip = $this->privateRootRecords == 1 ? $DBServer->localIp : $DBServer->remoteIp; if ($ip) { array_push($records, array("name" => "@", "value" => $ip, "type" => "A", "ttl" => 90, "server_id" => $DBServer->serverId, "issystem" => '1')); } } if (!$DBFarmRole->GetSetting(DBFarmRole::SETTING_DNS_CREATE_RECORDS)) { return $records; } $int_record_alias = $DBFarmRole->GetSetting(DBFarmRole::SETTING_DNS_INT_RECORD_ALIAS); $int_record = "int-{$DBFarmRole->GetRoleObject()->name}"; $ext_record_alias = $DBFarmRole->GetSetting(DBFarmRole::SETTING_DNS_EXT_RECORD_ALIAS); $ext_record = "ext-{$DBFarmRole->GetRoleObject()->name}"; if ($int_record_alias) { $int_record = $DBServer->applyGlobalVarsToValue($int_record_alias); } if ($ext_record_alias) { $ext_record = $DBServer->applyGlobalVarsToValue($ext_record_alias); } array_push($records, array("name" => $int_record, "value" => $DBServer->localIp, "type" => "A", "ttl" => 90, "server_id" => $DBServer->serverId, "issystem" => '1')); array_push($records, array("name" => $ext_record, "value" => $DBServer->remoteIp, "type" => "A", "ttl" => 90, "server_id" => $DBServer->serverId, "issystem" => '1')); $records = array_merge($records, (array) $this->getDbRecords($DBServer)); $records = array_merge($records, (array) $this->getBehaviorsRecords($DBServer)); if ($DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::MYSQL)) { array_push($records, array("name" => "int-mysql", "value" => $DBServer->localIp, "type" => "A", "ttl" => 90, "server_id" => $DBServer->serverId, "issystem" => '1')); array_push($records, array("name" => "ext-mysql", "value" => $DBServer->remoteIp, "type" => "A", "ttl" => 90, "server_id" => $DBServer->serverId, "issystem" => '1')); if ($DBServer->GetProperty(SERVER_PROPERTIES::DB_MYSQL_MASTER)) { array_push($records, array("name" => "int-mysql-master", "value" => $DBServer->localIp, "type" => "A", "ttl" => 90, "server_id" => $DBServer->serverId, "issystem" => '1')); array_push($records, array("name" => "ext-mysql-master", "value" => $DBServer->remoteIp, "type" => "A", "ttl" => 90, "server_id" => $DBServer->serverId, "issystem" => '1')); array_push($records, array("name" => "{$int_record}-master", "value" => $DBServer->localIp, "type" => "A", "ttl" => 90, "server_id" => $DBServer->serverId, "issystem" => '1')); array_push($records, array("name" => "{$ext_record}-master", "value" => $DBServer->remoteIp, "type" => "A", "ttl" => 90, "server_id" => $DBServer->serverId, "issystem" => '1')); } if ($DBFarmRole->GetRunningInstancesCount() == 1 || !$DBServer->GetProperty(SERVER_PROPERTIES::DB_MYSQL_MASTER)) { array_push($records, array("name" => "int-mysql-slave", "value" => $DBServer->localIp, "type" => "A", "ttl" => 90, "server_id" => $DBServer->serverId, "issystem" => '1')); array_push($records, array("name" => "ext-mysql-slave", "value" => $DBServer->remoteIp, "type" => "A", "ttl" => 90, "server_id" => $DBServer->serverId, "issystem" => '1')); array_push($records, array("name" => "{$int_record}-slave", "value" => $DBServer->localIp, "type" => "A", "ttl" => 90, "server_id" => $DBServer->serverId, "issystem" => '1')); array_push($records, array("name" => "{$ext_record}-slave", "value" => $DBServer->remoteIp, "type" => "A", "ttl" => 90, "server_id" => $DBServer->serverId, "issystem" => '1')); } } return $records; }
private function getServerDNSRecords(DBServer $DBServer) { $records = array(); if ($DBServer->status != SERVER_STATUS::RUNNING) { return $records; } if ($DBServer->GetProperty(SERVER_PROPERTIES::EXCLUDE_FROM_DNS)) { return $records; } $DBFarmRole = $DBServer->GetFarmRoleObject(); if ($DBFarmRole->GetSetting(DBFarmRole::SETTING_EXCLUDE_FROM_DNS)) { return $records; } if ($DBFarmRole->ID == $this->farmRoleId) { array_push($records, array("name" => "@", "value" => $DBServer->remoteIp, "type" => "A", "ttl" => 90, "server_id" => $DBServer->serverId, "issystem" => '1')); } if (!$DBFarmRole->GetSetting(DBFarmRole::SETTING_DNS_CREATE_RECORDS)) { return $records; } $int_record_alias = $DBFarmRole->GetSetting(DBFarmRole::SETTING_DNS_INT_RECORD_ALIAS); $int_record = "int-{$DBFarmRole->GetRoleObject()->name}"; $ext_record_alias = $DBFarmRole->GetSetting(DBFarmRole::SETTING_DNS_EXT_RECORD_ALIAS); $ext_record = "ext-{$DBFarmRole->GetRoleObject()->name}"; if ($int_record_alias || $ext_record_alias) { $params = $DBServer->GetScriptingVars(); $keys = array_keys($params); $f = create_function('$item', 'return "%".$item."%";'); $keys = array_map($f, $keys); $values = array_values($params); } if ($int_record_alias) { $int_record = str_replace($keys, $values, $int_record_alias); } if ($ext_record_alias) { $ext_record = str_replace($keys, $values, $ext_record_alias); } array_push($records, array("name" => $int_record, "value" => $DBServer->localIp, "type" => "A", "ttl" => 90, "server_id" => $DBServer->serverId, "issystem" => '1')); array_push($records, array("name" => $ext_record, "value" => $DBServer->remoteIp, "type" => "A", "ttl" => 90, "server_id" => $DBServer->serverId, "issystem" => '1')); $records = array_merge($records, (array) $this->getDbRecords($DBServer)); $records = array_merge($records, (array) $this->getBehaviorsRecords($DBServer)); if ($DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::MYSQL)) { array_push($records, array("name" => "int-mysql", "value" => $DBServer->localIp, "type" => "A", "ttl" => 90, "server_id" => $DBServer->serverId, "issystem" => '1')); array_push($records, array("name" => "ext-mysql", "value" => $DBServer->remoteIp, "type" => "A", "ttl" => 90, "server_id" => $DBServer->serverId, "issystem" => '1')); if ($DBServer->GetProperty(SERVER_PROPERTIES::DB_MYSQL_MASTER)) { array_push($records, array("name" => "int-mysql-master", "value" => $DBServer->localIp, "type" => "A", "ttl" => 90, "server_id" => $DBServer->serverId, "issystem" => '1')); array_push($records, array("name" => "ext-mysql-master", "value" => $DBServer->remoteIp, "type" => "A", "ttl" => 90, "server_id" => $DBServer->serverId, "issystem" => '1')); array_push($records, array("name" => "{$int_record}-master", "value" => $DBServer->localIp, "type" => "A", "ttl" => 90, "server_id" => $DBServer->serverId, "issystem" => '1')); array_push($records, array("name" => "{$ext_record}-master", "value" => $DBServer->remoteIp, "type" => "A", "ttl" => 90, "server_id" => $DBServer->serverId, "issystem" => '1')); } if ($DBFarmRole->GetRunningInstancesCount() == 1 || !$DBServer->GetProperty(SERVER_PROPERTIES::DB_MYSQL_MASTER)) { array_push($records, array("name" => "int-mysql-slave", "value" => $DBServer->localIp, "type" => "A", "ttl" => 90, "server_id" => $DBServer->serverId, "issystem" => '1')); array_push($records, array("name" => "ext-mysql-slave", "value" => $DBServer->remoteIp, "type" => "A", "ttl" => 90, "server_id" => $DBServer->serverId, "issystem" => '1')); array_push($records, array("name" => "{$int_record}-slave", "value" => $DBServer->localIp, "type" => "A", "ttl" => 90, "server_id" => $DBServer->serverId, "issystem" => '1')); array_push($records, array("name" => "{$ext_record}-slave", "value" => $DBServer->remoteIp, "type" => "A", "ttl" => 90, "server_id" => $DBServer->serverId, "issystem" => '1')); } } return $records; }
private function getSzrCmd(DBServer $dbServer) { $baseurl = \Scalr::config('scalr.endpoint.scheme') . "://" . \Scalr::config('scalr.endpoint.host'); $platform = $dbServer->isOpenstack() ? SERVER_PLATFORMS::OPENSTACK : $dbServer->platform; $options = array('server-id' => $dbServer->serverId, 'role-name' => $dbServer->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_ROLE_NAME), 'crypto-key' => $dbServer->GetProperty(SERVER_PROPERTIES::SZR_KEY), 'platform' => $platform, 'queryenv-url' => $baseurl . "/query-env", 'messaging-p2p.producer-url' => $baseurl . "/messaging", 'env-id' => $dbServer->envId, 'region' => $dbServer->GetCloudLocation(), 'scalr-id' => SCALR_ID); $command = 'scalarizr --import -y'; foreach ($options as $k => $v) { $command .= sprintf(' -o %s=%s', $k, $v); } return $command; }
/** * @param DBServer $dbServer * @param bool $cached check only cached information * @param int $timeout * @return array|NULL */ public function getServerStatus(DBServer $dbServer, $cached = true, $timeout = 0) { if ($dbServer->status == SERVER_STATUS::RUNNING && ($dbServer->IsSupported('0.8') && $dbServer->osType == 'linux' || $dbServer->IsSupported('0.19') && $dbServer->osType == 'windows')) { if ($cached && !$dbServer->IsSupported('2.7.7')) { return ['status' => 'statusNoCache', 'error' => "<span style='color:gray;'>Scalarizr is checking actual status</span>"]; } try { $port = $dbServer->GetProperty(SERVER_PROPERTIES::SZR_UPDC_PORT); if (!$port) { $port = 8008; } if (!$timeout) { $timeout = \Scalr::config('scalr.system.instances_connection_timeout'); } $updateClient = new Scalr_Net_Scalarizr_UpdateClient($dbServer, $port, $timeout); $scalarizr = $updateClient->getStatus($cached); try { if ($dbServer->farmRoleId != 0) { $scheduledOn = $dbServer->GetFarmRoleObject()->GetSetting('scheduled_on'); } } catch (Exception $e) { } $nextUpdate = null; if ($scalarizr->candidate && $scalarizr->installed != $scalarizr->candidate) { $nextUpdate = ['candidate' => htmlspecialchars($scalarizr->candidate), 'scheduledOn' => $scheduledOn ? Scalr_Util_DateTime::convertTzFromUTC($scheduledOn) : null]; } return ['status' => htmlspecialchars($scalarizr->service_status), 'version' => htmlspecialchars($scalarizr->installed), 'candidate' => htmlspecialchars($scalarizr->candidate), 'repository' => ucfirst(htmlspecialchars($scalarizr->repository)), 'lastUpdate' => ['date' => $scalarizr->executed_at ? Scalr_Util_DateTime::convertTzFromUTC($scalarizr->executed_at) : "", 'error' => nl2br(htmlspecialchars($scalarizr->error))], 'nextUpdate' => $nextUpdate, 'fullInfo' => $scalarizr]; } catch (Exception $e) { if (stristr($e->getMessage(), "Method not found")) { return ['status' => 'statusNotAvailable', 'error' => "<span style='color:red;'>Scalarizr status is not available, because scalr-upd-client installed on this server is too old.</span>"]; } else { return ['status' => 'statusNotAvailable', 'error' => "<span style='color:red;'>Scalarizr status is not available: {$e->getMessage()}</span>"]; } } } }
public function LaunchServer(DBServer $DBServer, Scalr_Server_LaunchOptions $launchOptions = null) { $RDSClient = $this->getRdsClient($DBServer->GetEnvironmentObject(), $DBServer->GetProperty(RDS_SERVER_PROPERTIES::REGION)); $DBRole = DBRole::loadById($DBServer->roleId); $server_id = "scalr-{$DBServer->serverId}"; $avail_zone = $DBServer->GetProperty(RDS_SERVER_PROPERTIES::AVAIL_ZONE) ? $DBServer->GetProperty(RDS_SERVER_PROPERTIES::AVAIL_ZONE) : $DBServer->GetProperty(RDS_SERVER_PROPERTIES::REGION) . "a"; try { if ($DBRole->getImageId(SERVER_PLATFORMS::RDS, $DBServer->GetProperty(RDS_SERVER_PROPERTIES::REGION)) == 'ScalrEmpty') { $RDSClient->CreateDBInstance($server_id, $DBServer->GetProperty(RDS_SERVER_PROPERTIES::STORAGE), $DBServer->GetProperty(RDS_SERVER_PROPERTIES::INSTANCE_CLASS), $DBServer->GetProperty(RDS_SERVER_PROPERTIES::INSTANCE_ENGINE), $DBServer->GetProperty(RDS_SERVER_PROPERTIES::MASTER_USER), $DBServer->GetProperty(RDS_SERVER_PROPERTIES::MASTER_PASS), $DBServer->GetProperty(RDS_SERVER_PROPERTIES::PORT), null, null, null, $avail_zone, null, null, null); } else { $RDSClient->RestoreDBInstanceFromDBSnapshot($DBRole->getImageId(SERVER_PLATFORMS::RDS, $DBServer->GetProperty(RDS_SERVER_PROPERTIES::REGION)), $server_id, $DBServer->GetProperty(RDS_SERVER_PROPERTIES::INSTANCE_CLASS), $DBServer->GetProperty(RDS_SERVER_PROPERTIES::PORT), $DBServer->GetProperty(RDS_SERVER_PROPERTIES::AVAIL_ZONE)); } $DBServer->SetProperty(RDS_SERVER_PROPERTIES::INSTANCE_ID, $server_id); $DBServer->SetProperty(RDS_SERVER_PROPERTIES::SNAPSHOT_ID, $DBRole->getImageId(SERVER_PLATFORMS::RDS, $DBServer->GetProperty(RDS_SERVER_PROPERTIES::REGION))); return $DBServer; } catch (Exception $e) { throw new Exception(sprintf(_("Cannot launch new instance. %s"), $e->getMessage())); } }
public function GetServerExtendedInformation(DBServer $DBServer) { try { try { $client = $this->getOsClient($DBServer->GetEnvironmentObject(), $DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION)); $iinfo = $client->servers->getServerDetails($DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::SERVER_ID)); $ips = $this->GetServerIPAddresses($DBServer); } catch (Exception $e) { } if ($iinfo) { $retval = array('Cloud Server ID' => $DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::SERVER_ID), 'Image ID' => $iinfo->image->id, 'Flavor ID' => $iinfo->flavor->id, 'Public IP' => $ips['remoteIp'] ? $ips['remoteIp'] : $DBServer->remoteIp, 'Private IP' => $ips['localIp'] ? $ips['localIp'] : $DBServer->localIp, 'Status' => $iinfo->status, 'Name' => $iinfo->name, 'Host ID' => $iinfo->hostId, 'Progress' => $iinfo->progress); if ($iinfo->status == 'ERROR') { $retval['Status'] = "{$retval['Status']} (Fault message: {$iinfo->fault->message})"; } if ($iinfo->key_name) { $retval['Key name'] = $iinfo->key_name; } if ($iinfo->security_groups) { $list = array(); foreach ($iinfo->security_groups as $sg) { $list[] = $sg->name; } $retval['Security Groups'] = implode(", ", $list); } return $retval; } } catch (Exception $e) { } return false; }
private function onHostInit($message, DBServer $dbserver) { if ($dbserver->status == SERVER_STATUS::PENDING) { // Update server crypto key $srv_props = array(); if ($message->cryptoKey) { $srv_props[SERVER_PROPERTIES::SZR_KEY] = trim($message->cryptoKey); $srv_props[SERVER_PROPERTIES::SZR_KEY_TYPE] = SZR_KEY_TYPE::PERMANENT; } if ($dbserver->platform != SERVER_PLATFORMS::CLOUDSTACK) { $srv_props[SERVER_PROPERTIES::SZR_SNMP_PORT] = $message->snmpPort; $remoteIp = $message->remoteIp; } else { if ($dbserver->farmRoleId) { $dbFarmRole = $dbserver->GetFarmRoleObject(); $networkType = $dbFarmRole->GetSetting(DBFarmRole::SETTING_CLOUDSTACK_NETWORK_TYPE); if ($networkType == 'Direct') { $remoteIp = $message->localIp; $srv_props[SERVER_PROPERTIES::SZR_SNMP_PORT] = $message->snmpPort; } else { $env = $dbserver->GetEnvironmentObject(); $remoteIp = $env->getPlatformConfigValue(Modules_Platforms_Cloudstack::SHARED_IP . "." . $dbserver->GetProperty(CLOUDSTACK_SERVER_PROPERTIES::CLOUD_LOCATION), false); } } else { $remoteIp = $message->localIp; $srv_props[SERVER_PROPERTIES::SZR_SNMP_PORT] = $message->snmpPort; } } //Update auto-update settings //TODO: Check auto-update client version if ($dbserver->IsSupported('0.7.225')) { $dbserver->SetProperties($srv_props); try { $repo = $dbserver->GetFarmObject()->GetSetting(DBFarm::SETTING_SZR_UPD_REPOSITORY); $schedule = $dbserver->GetFarmObject()->GetSetting(DBFarm::SETTING_SZR_UPD_SCHEDULE); if ($repo && $schedule) { $updateClient = new Scalr_Net_Scalarizr_UpdateClient($dbserver); $updateClient->configure($repo, $schedule); } } catch (Exception $e) { } } // MySQL specific $dbFarmRole = $dbserver->GetFarmRoleObject(); if ($dbFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::MYSQL)) { $master = $dbFarmRole->GetFarmObject()->GetMySQLInstances(true); // If no masters in role this server becomes it if (!$master[0] && !(int) $dbFarmRole->GetSetting(DbFarmRole::SETTING_MYSQL_SLAVE_TO_MASTER)) { $srv_props[SERVER_PROPERTIES::DB_MYSQL_MASTER] = 1; } } //MSR Replication Master //TODO: MySQL if ($dbFarmRole->GetRoleObject()->getDbMsrBehavior()) { $servers = $dbFarmRole->GetServersByFilter(array('status' => array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING))); if (!$dbFarmRole->GetSetting(Scalr_Db_Msr::SLAVE_TO_MASTER)) { $masterFound = false; foreach ($servers as $server) { if ($server->GetProperty(Scalr_Db_Msr::REPLICATION_MASTER)) { $masterFound = true; } } if (!$masterFound) { $srv_props[Scalr_Db_Msr::REPLICATION_MASTER] = 1; } } elseif ($dbFarmRole->GetSetting(Scalr_Db_Msr::SLAVE_TO_MASTER) && count($servers) == 0) { $dbFarmRole->SetSetting(Scalr_Db_Msr::SLAVE_TO_MASTER, 0); $srv_props[Scalr_Db_Msr::REPLICATION_MASTER] = 1; } } $dbserver->SetProperties($srv_props); return new HostInitEvent($dbserver, $message->localIp, $remoteIp, $message->sshPubKey); } else { $this->logger->error("Strange situation. Received HostInit message" . " from server '{$dbserver->serverId}' ({$message->remoteIp})" . " with state {$dbserver->status}!"); } }
private function onHello($message, DBServer $dbserver) { if ($dbserver->status == SERVER_STATUS::TEMPORARY) { $bundleTask = BundleTask::LoadById($dbserver->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_BUNDLE_TASK_ID)); $bundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::PENDING; $bundleTask->Log("Received Hello message from scalarizr on server. Creating image"); $bundleTask->osFamily = $message->dist->distributor; $bundleTask->osName = $message->dist->codename; $bundleTask->osVersion = $message->dist->release; if (in_array($message->dist->distributor, array('redhat', 'oel', 'scientific')) && $dbserver->platform == SERVER_PLATFORMS::EC2) { $bundleTask->bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM; } $bundleTask->save(); } if ($dbserver->status == SERVER_STATUS::IMPORTING) { if (!$dbserver->remoteIp || !$dbserver->localIp) { if (!$dbserver->remoteIp && $message->remoteIp && $dbserver->platform != SERVER_PLATFORMS::IDCF) { $dbserver->remoteIp = $message->remoteIp; } if (!$dbserver->localIp && $message->localIp) { $dbserver->localIp = $message->localIp; } if (!$message->behaviour) { $message->behaviour = array('base'); } if ((!$dbserver->remoteIp || $dbserver->localIp == $dbserver->remoteIp) && $message->messageIpAddress != $dbserver->remoteIp) { $dbserver->remoteIp = $message->messageIpAddress; } } if (count($message->behaviour) == 1 && $message->behaviour[0] == ROLE_BEHAVIORS::CHEF) { $message->behaviour[] = ROLE_BEHAVIORS::BASE; } $dbserver->SetProperty(SERVER_PROPERTIES::SZR_IMPORTING_BEHAVIOR, @implode(",", $message->behaviour)); $dbserver->save(); $importVersion = $dbserver->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_VERSION); if ($importVersion == 2) { $dbserver->SetProperties(array(SERVER_PROPERTIES::ARCHITECTURE => $message->architecture)); } else { if ($dbserver->isOpenstack()) { $env = $dbserver->GetEnvironmentObject(); $os = $env->openstack($dbserver->platform, $dbserver->GetProperty(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION)); $csServer = null; $list = $os->servers->list(true); do { foreach ($list as $_tmp) { $ipaddresses = array(); if (!is_array($_tmp->addresses)) { $_tmp->addresses = (array) $_tmp->addresses; } foreach ($_tmp->addresses as $net => $addresses) { foreach ($addresses as $addr) { if ($addr->version == 4) { array_push($ipaddresses, $addr->addr); } } } if ($_tmp->accessIPv4) { array_push($ipaddresses, $_tmp->accessIPv4); } if (in_array($dbserver->localIp, $ipaddresses) || in_array($dbserver->remoteIp, $ipaddresses)) { $osServer = $_tmp; } } } while (false !== ($list = $list->getNextPage())); if (!$osServer) { $this->logger->error(sprintf("Server not found on Openstack (server_id: %s, remote_ip: %s, local_ip: %s)", $dbserver->serverId, $dbserver->remoteIp, $dbserver->localIp)); return; } $dbserver->SetProperties(array(OPENSTACK_SERVER_PROPERTIES::SERVER_ID => $osServer->id, OPENSTACK_SERVER_PROPERTIES::NAME => $osServer->name, OPENSTACK_SERVER_PROPERTIES::IMAGE_ID => $osServer->image->id, OPENSTACK_SERVER_PROPERTIES::FLAVOR_ID => $osServer->flavor->id, OPENSTACK_SERVER_PROPERTIES::HOST_ID => $osServer->hostId, SERVER_PROPERTIES::ARCHITECTURE => $message->architecture)); } elseif ($dbserver->isCloudstack()) { $dbserver->SetProperties(array(CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID => $message->cloudstack->instanceId, CLOUDSTACK_SERVER_PROPERTIES::CLOUD_LOCATION => $message->cloudstack->availZone, SERVER_PROPERTIES::ARCHITECTURE => $message->architecture)); } else { switch ($dbserver->platform) { case SERVER_PLATFORMS::EC2: $dbserver->SetProperties(array(EC2_SERVER_PROPERTIES::AMIID => $message->awsAmiId, EC2_SERVER_PROPERTIES::INSTANCE_ID => $message->awsInstanceId, EC2_SERVER_PROPERTIES::INSTANCE_TYPE => $message->awsInstanceType, EC2_SERVER_PROPERTIES::AVAIL_ZONE => $message->awsAvailZone, EC2_SERVER_PROPERTIES::REGION => substr($message->awsAvailZone, 0, -1), SERVER_PROPERTIES::ARCHITECTURE => $message->architecture)); break; case SERVER_PLATFORMS::EUCALYPTUS: $dbserver->SetProperties(array(EUCA_SERVER_PROPERTIES::EMIID => $message->awsAmiId, EUCA_SERVER_PROPERTIES::INSTANCE_ID => $message->awsInstanceId, EUCA_SERVER_PROPERTIES::INSTANCE_TYPE => $message->awsInstanceType, EUCA_SERVER_PROPERTIES::AVAIL_ZONE => $message->awsAvailZone, SERVER_PROPERTIES::ARCHITECTURE => $message->architecture)); break; case SERVER_PLATFORMS::GCE: $dbserver->SetProperties(array(GCE_SERVER_PROPERTIES::CLOUD_LOCATION => $message->{$dbserver->platform}->cloudLocation, GCE_SERVER_PROPERTIES::SERVER_ID => $message->{$dbserver->platform}->serverId, GCE_SERVER_PROPERTIES::SERVER_NAME => $message->{$dbserver->platform}->serverName, GCE_SERVER_PROPERTIES::MACHINE_TYPE => $message->{$dbserver->platform}->machineType, SERVER_PROPERTIES::ARCHITECTURE => $message->architecture)); break; case SERVER_PLATFORMS::NIMBULA: $dbserver->SetProperties(array(NIMBULA_SERVER_PROPERTIES::NAME => $message->serverName, SERVER_PROPERTIES::ARCHITECTURE => $message->architecture)); break; case SERVER_PLATFORMS::RACKSPACE: $env = $dbserver->GetEnvironmentObject(); $cs = Scalr_Service_Cloud_Rackspace::newRackspaceCS($env->getPlatformConfigValue(RackspacePlatformModule::USERNAME, true, $dbserver->GetProperty(RACKSPACE_SERVER_PROPERTIES::DATACENTER)), $env->getPlatformConfigValue(RackspacePlatformModule::API_KEY, true, $dbserver->GetProperty(RACKSPACE_SERVER_PROPERTIES::DATACENTER)), $dbserver->GetProperty(RACKSPACE_SERVER_PROPERTIES::DATACENTER)); $csServer = null; $list = $cs->listServers(true); if ($list) { foreach ($list->servers as $_tmp) { if ($_tmp->addresses->public && in_array($message->remoteIp, $_tmp->addresses->public)) { $csServer = $_tmp; } } } if (!$csServer) { $this->logger->error(sprintf("Server not found on CloudServers (server_id: %s, remote_ip: %s, local_ip: %s)", $dbserver->serverId, $message->remoteIp, $message->localIp)); return; } $dbserver->SetProperties(array(RACKSPACE_SERVER_PROPERTIES::SERVER_ID => $csServer->id, RACKSPACE_SERVER_PROPERTIES::NAME => $csServer->name, RACKSPACE_SERVER_PROPERTIES::IMAGE_ID => $csServer->imageId, RACKSPACE_SERVER_PROPERTIES::FLAVOR_ID => $csServer->flavorId, RACKSPACE_SERVER_PROPERTIES::HOST_ID => $csServer->hostId, SERVER_PROPERTIES::ARCHITECTURE => $message->architecture)); break; } } } //TODO: search for existing bundle task // Bundle image $creInfo = new ServerSnapshotCreateInfo($dbserver, $dbserver->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_ROLE_NAME), SERVER_REPLACEMENT_TYPE::NO_REPLACE); $bundleTask = BundleTask::Create($creInfo); $bundleTask->osFamily = $message->dist->distributor; $bundleTask->osName = $message->dist->codename; $bundleTask->osVersion = $message->dist->release; if (in_array($message->dist->distributor, array('oel', 'redhat', 'scientific')) && $dbserver->platform == SERVER_PLATFORMS::EC2) { $bundleTask->bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM; } $bundleTask->setDate("started"); $bundleTask->createdByEmail = $dbserver->GetProperty(SERVER_PROPERTIES::LAUNCHED_BY_EMAIL); $bundleTask->createdById = $dbserver->GetProperty(SERVER_PROPERTIES::LAUNCHED_BY_ID); if ($importVersion == 2) { $bundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::ESTABLISHING_COMMUNICATION; } $bundleTask->Save(); $dbserver->SetProperty(SERVER_PROPERTIES::SZR_IMPORTING_BUNDLE_TASK_ID, $bundleTask->id); } }
public function IsServerExists(DBServer $DBServer) { return in_array($DBServer->GetProperty(CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID), array_keys($this->GetServersList($DBServer->GetEnvironmentObject(), $this->GetServerCloudLocation($DBServer)))); }
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)); } }
private function getVolumeIdByServer(DBServer $dbServer) { return $this->db->GetOne("SELECT volume_id FROM services_mongodb_volumes_map WHERE farm_roleid = ? AND shard_index = ? AND replica_set_index = ? LIMIT 1", array($dbServer->farmRoleId, $dbServer->GetProperty(self::SERVER_SHARD_INDEX), $dbServer->GetProperty(self::SERVER_REPLICA_SET_INDEX))); }
public function LaunchServer(DBServer $DBServer, Scalr_Server_LaunchOptions $launchOptions = null) { $DBRole = DBRole::loadById($DBServer->roleId); $eucaClient = $this->getEucaClient($DBServer->GetEnvironmentObject(), $DBServer->GetCloudLocation()); $i_type = $DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_EUCA_INSTANCE_TYPE); foreach ($DBServer->GetCloudUserData() as $k => $v) { $u_data .= "{$k}={$v};"; } /* $imageId, $instanceType, $keyName = null, $availZone = null, $securityGroup = array(), $userData = "", $minCount = 1, $maxCount = 1, $kernelId = null, $ramdiskId = null, $monitoring = false */ $DBServer->SetProperty(SERVER_PROPERTIES::ARCHITECTURE, $DBRole->architecture); $key_pair_name = Scalr_Model::init(Scalr_Model::SSH_KEY)->loadGlobalByFarmId($DBServer->farmId, $DBServer->GetProperty(EUCA_SERVER_PROPERTIES::REGION))->cloudKeyName; $result = $eucaClient->runInstances($DBRole->getImageId(SERVER_PLATFORMS::EUCALYPTUS, $DBServer->GetProperty(EUCA_SERVER_PROPERTIES::REGION)), $i_type, $key_pair_name, $this->GetServerAvailZone($DBServer), $this->GetServerSecurityGroupsList($DBServer, $eucaClient), trim($u_data, ";")); if ($result->instancesSet) { $DBServer->SetProperty(EUCA_SERVER_PROPERTIES::AVAIL_ZONE, (string) $result->instancesSet->item[0]->placement->availabilityZone); $DBServer->SetProperty(EUCA_SERVER_PROPERTIES::INSTANCE_ID, (string) $result->instancesSet->item[0]->instanceId); $DBServer->SetProperty(EUCA_SERVER_PROPERTIES::INSTANCE_TYPE, $i_type); $DBServer->SetProperty(EUCA_SERVER_PROPERTIES::EMIID, $DBRole->getImageId(SERVER_PLATFORMS::EUCALYPTUS, $DBServer->GetProperty(EUCA_SERVER_PROPERTIES::REGION))); return $DBServer; } }