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()))); } }
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()); } }
private function sendNewDbMsrMasterUpMessage(DBServer $newMasterServer) { $dbFarmRole = $newMasterServer->GetFarmRoleObject(); $servers = $dbFarmRole->GetServersByFilter(array('status' => array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING))); $dbType = $newMasterServer->GetFarmRoleObject()->GetRoleObject()->getDbMsrBehavior(); $props = Scalr_Db_Msr_Info::init($dbFarmRole, $newMasterServer, $dbType)->getMessageProperties(); foreach ($servers as $dbServer) { $msg = new Scalr_Messaging_Msg_DbMsr_NewMasterUp($dbFarmRole->GetRoleObject()->getBehaviors(), $dbFarmRole->GetRoleObject()->name, $newMasterServer->localIp, $newMasterServer->remoteIp, $dbType); $msg->{$dbType} = new stdClass(); $msg->{$dbType}->snapshotConfig = $props->snapshotConfig; foreach (Scalr_Role_Behavior::getListForFarmRole($dbFarmRole) as $behavior) { $msg = $behavior->extendMessage($msg, $dbServer); } $dbServer->SendMessage($msg); } }
private function sendNewDbMsrMasterUpMessage(\DBServer $newMasterServer, $event) { $dbFarmRole = $newMasterServer->GetFarmRoleObject(); $servers = $dbFarmRole->GetServersByFilter(array('status' => array(\SERVER_STATUS::INIT, \SERVER_STATUS::RUNNING))); $dbType = $newMasterServer->GetFarmRoleObject()->GetRoleObject()->getDbMsrBehavior(); $props = \Scalr_Db_Msr_Info::init($dbFarmRole, $newMasterServer, $dbType)->getMessageProperties(); foreach ($servers as $dbServer) { $msg = new \Scalr_Messaging_Msg_DbMsr_NewMasterUp($dbType); $msg->setServerMetaData($newMasterServer); $msg->{$dbType} = new \stdClass(); $msg->{$dbType}->snapshotConfig = $props->snapshotConfig; foreach (\Scalr_Role_Behavior::getListForFarmRole($dbFarmRole) as $behavior) { $msg = $behavior->extendMessage($msg, $dbServer); } $dbServer->SendMessage($msg, false, true); } }
public function setServerMetaData(DBServer $dbServer) { try { $this->behaviour = $dbServer->GetFarmRoleObject()->GetRoleObject()->getBehaviors(); $this->roleName = $dbServer->GetFarmRoleObject()->GetRoleObject()->name; $this->farmRoleAlias = $dbServer->GetFarmRoleObject()->Alias; if (empty($this->farmRoleAlias)) { $this->farmRoleAlias = $this->roleName; } } catch (Exception $e) { } $this->localIp = $dbServer->localIp; $this->remoteIp = $dbServer->remoteIp; $this->serverIndex = $dbServer->index; $this->serverId = $dbServer->serverId; $this->cloudLocation = $dbServer->GetCloudLocation(); $this->farmRoleId = $dbServer->farmRoleId; }
public function getConfiguration(DBServer $dbServer) { $config = new stdClass(); $config->cookie = $dbServer->GetFarmRoleObject()->GetSetting(self::ROLE_COOKIE_NAME); $config->volumeConfig = $this->getVolumeConfig($dbServer->GetFarmRoleObject(), $dbServer); $config->nodeType = $this->getNodeType($dbServer->GetFarmRoleObject(), $dbServer); $config->password = $dbServer->GetFarmRoleObject()->GetSetting(self::ROLE_PASSWORD); $dbServer->SetProperty(self::SERVER_NODE_TYPE, $config->nodeType); return $config; }
public function getConfiguration(DBServer $dbServer) { $configuration = new stdClass(); $configuration->proxies = json_decode($dbServer->GetFarmRoleObject()->GetSetting(self::ROLE_PROXIES), true); if ($dbServer->GetFarmRoleObject()->GetSetting(self::ROLE_TEMPLATE)) { $configuration->template = $dbServer->GetFarmRoleObject()->GetSetting(self::ROLE_TEMPLATE); } if (count($configuration->proxies) > 0) { $dbFarm = $dbServer->GetFarmObject(); foreach ($configuration->proxies as &$proxy) { if (count($proxy['backends']) > 0) { foreach ($proxy['backends'] as &$backend) { if (isset($backend['farm_role_alias']) && !empty($backend['farm_role_alias'])) { $backend['farm_role_id'] = $dbFarm->GetFarmRoleIdByAlias($backend['farm_role_alias']); } } } } } return $configuration; }
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 extendMessage(Scalr_Messaging_Msg $message, DBServer $dbServer) { $message = parent::extendMessage($message); switch (get_class($message)) { case "Scalr_Messaging_Msg_HostInitResponse": $message->rabbitmq = new stdClass(); $message->rabbitmq->cookie = $dbServer->GetFarmRoleObject()->GetSetting(self::ROLE_COOKIE_NAME); $message->rabbitmq->volumeConfig = $this->getVolumeConfig($dbServer->GetFarmRoleObject(), $dbServer); $message->rabbitmq->nodeType = $this->getNodeType($dbServer->GetFarmRoleObject(), $dbServer); $message->rabbitmq->password = $dbServer->GetFarmRoleObject()->GetSetting(self::ROLE_PASSWORD); $dbServer->SetProperty(self::SERVER_NODE_TYPE, $message->rabbitmq->nodeType); break; } return $message; }
private function DeregisterInstanceFromLB(DBServer $DBServer) { try { $DBFarmRole = $DBServer->GetFarmRoleObject(); if ($DBFarmRole->GetSetting(DBFarmRole::SETTING_BALANCING_USE_ELB)) { $useElb = true; $elbId = $DBFarmRole->GetSetting(DBFarmRole::SETTING_BALANCING_NAME); } if ($DBFarmRole->GetSetting(DBFarmRole::SETTING_AWS_ELB_ENABLED)) { $useElb = true; $elbId = $DBFarmRole->GetSetting(DBFarmRole::SETTING_AWS_ELB_ID); } if ($useElb) { $Client = $DBServer->GetClient(); $elb = $DBServer->GetEnvironmentObject()->aws($DBServer)->elb; $elb->loadBalancer->deregisterInstances($elbId, $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), $elbId))); } } 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 handleMessage(Scalr_Messaging_Msg $message, DBServer $dbServer) { try { $dbFarmRole = $dbServer->GetFarmRoleObject(); } catch (Exception $e) { } switch (get_class($message)) { case "Scalr_Messaging_Msg_HostUp": if ($message->dbType && in_array($message->dbType, array(ROLE_BEHAVIORS::REDIS, ROLE_BEHAVIORS::POSTGRESQL, ROLE_BEHAVIORS::MYSQL2))) { $dbMsrInfo = Scalr_Db_Msr_Info::init($dbFarmRole, $dbServer, $message->dbType); $dbMsrInfo->setMsrSettings($message->{$message->dbType}); } break; case "Scalr_Messaging_Msg_DbMsr_PromoteToMasterResult": if (Scalr_Db_Msr::onPromoteToMasterResult($message, $dbServer)) { Scalr::FireEvent($dbServer->farmId, new NewDbMsrMasterUpEvent($dbServer)); } break; case "Scalr_Messaging_Msg_DbMsr_CreateDataBundleResult": if ($message->status == "ok") { Scalr_Db_Msr::onCreateDataBundleResult($message, $dbServer); } else { $dbFarmRole->SetSetting(Scalr_Db_Msr::DATA_BUNDLE_IS_RUNNING, 0); //TODO: store last error } break; case "Scalr_Messaging_Msg_DbMsr_CreateBackupResult": if ($message->status == "ok") { Scalr_Db_Msr::onCreateBackupResult($message, $dbServer); } else { $dbFarmRole->SetSetting(Scalr_Db_Msr::DATA_BACKUP_IS_RUNNING, 0); //TODO: store last error } break; } }
public static function getEventScriptList(AbstractServerEvent $event, DBServer $eventServer, DBServer $targetServer) { $db = \Scalr::getDb(); $accountScripts = $db->GetAll("\n SELECT * FROM account_scripts\n WHERE account_id = ?\n AND (event_name = ? OR event_name = '*')\n ", [$eventServer->clientId, $event->GetName()]); $roleScripts = $db->GetAll("\n SELECT * FROM role_scripts\n WHERE (event_name = ? OR event_name = '*') AND role_id = ?\n ", [$event->GetName(), $eventServer->GetFarmRoleObject()->RoleID]); $scripts = $db->GetAll("\n SELECT *, `script_type` as `type`\n FROM farm_role_scripts\n WHERE (event_name = ? OR event_name = '*') AND farmid = ?\n ", [$event->GetName(), $eventServer->farmId]); foreach ($accountScripts as $script) { $scripts[] = array("id" => "a{$script['id']}", "type" => $script['script_type'], "scriptid" => $script['script_id'], "params" => $script['params'], "event_name" => $event->GetName(), "target" => $script['target'], "version" => $script['version'], "timeout" => $script['timeout'], "issync" => $script['issync'], "order_index" => $script['order_index'], "scope" => "account", 'script_path' => $script['script_path'], 'run_as' => $script['run_as'], 'script_type' => $script['script_type']); } foreach ($roleScripts as $script) { $params = $db->GetOne("\n SELECT params\n FROM farm_role_scripting_params\n WHERE farm_role_id = ?\n AND `hash` = ?\n AND farm_role_script_id = '0'\n LIMIT 1\n ", array($eventServer->farmRoleId, $script['hash'])); if ($params) { $script['params'] = $params; } $scripts[] = array("id" => "r{$script['id']}", "scriptid" => $script['script_id'], "type" => $script['script_type'], "params" => $script['params'], "event_name" => $event->GetName(), "target" => $script['target'], "version" => $script['version'], "timeout" => $script['timeout'], "issync" => $script['issync'], "order_index" => $script['order_index'], "scope" => "role", 'script_path' => $script['script_path'], 'run_as' => $script['run_as'], 'script_type' => $script['script_type']); } $retval = []; foreach ($scripts as $scriptSettings) { $scriptSettings['order_index'] = (double) $scriptSettings['order_index']; // If target set to that instance only if ($scriptSettings['target'] == Script::TARGET_INSTANCE && $eventServer->serverId != $targetServer->serverId) { continue; } // If target set to all instances in specific role if ($scriptSettings['target'] == Script::TARGET_ROLE && $eventServer->farmRoleId != $targetServer->farmRoleId) { continue; } if (!$scriptSettings['scope']) { // Validate that event was triggered on the same farmRoleId as script if ($eventServer->farmRoleId != $scriptSettings['farm_roleid']) { continue; } // Validate that target server has the same farmRoleId as event server with target ROLE if ($scriptSettings['target'] == Script::TARGET_ROLE && $targetServer->farmRoleId != $scriptSettings['farm_roleid']) { continue; } } if ($scriptSettings['target'] == Script::TARGET_ROLES || $scriptSettings['target'] == Script::TARGET_BEHAVIORS || $scriptSettings['target'] == Script::TARGET_FARMROLES) { if ($scriptSettings['scope'] != 'role') { $targets = $db->GetAll("SELECT * FROM farm_role_scripting_targets WHERE farm_role_script_id = ?", array($scriptSettings['id'])); } else { $targets = []; } $execute = false; foreach ($targets as $target) { switch ($target['target_type']) { case "farmrole": if ($scriptSettings['target'] == Script::TARGET_ROLES && $targetServer->farmRoleId == $target['target'] || $scriptSettings['target'] == Script::TARGET_FARMROLES && $targetServer->GetFarmRoleObject()->Alias == $target['target']) { $execute = true; } break; case "behavior": if ($targetServer->GetFarmRoleObject()->GetRoleObject()->hasBehavior($target['target'])) { $execute = true; } break; } } if (!$execute) { continue; } } if ($scriptSettings['target'] == "" || $scriptSettings['id'] == "") { continue; } $script = self::prepareScript($scriptSettings, $targetServer, $event); if ($script) { while (true) { $index = (string) $scriptSettings['order_index']; if (empty($retval[$index])) { $retval[$index] = $script; break; } else { $scriptSettings['order_index'] += 0.01; } } } } if (!empty($retval) && is_array($retval)) { ksort($retval); } return $retval; }
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 static function onPromoteToMasterResult(Scalr_Messaging_Msg_DbMsr_PromoteToMasterResult $message, DBServer $dbServer) { $dbFarm = $dbServer->GetFarmObject(); $dbFarmRole = $dbServer->GetFarmRoleObject(); $dbFarmRole->SetSetting(Scalr_Db_Msr::SLAVE_TO_MASTER, 0); if ($message->status == Scalr_Messaging_Msg_Mysql_PromoteToMasterResult::STATUS_FAILED) { $dbServer->SetProperty(Scalr_Db_Msr::REPLICATION_MASTER, 0); return false; } $dbSettings = $message->{$message->dbType}; //Update volumeCondig if ($dbSettings->volumeConfig) { try { $storageVolume = Scalr_Storage_Volume::init(); try { $storageVolume->loadById($dbSettings->volumeConfig->id); $storageVolume->setConfig($dbSettings->volumeConfig); $storageVolume->save(); } catch (Exception $e) { if (strpos($e->getMessage(), 'not found')) { $storageVolume->loadBy(array('id' => $dbSettings->volumeConfig->id, 'client_id' => $dbServer->clientId, 'env_id' => $dbServer->envId, 'name' => "'{$message->dbType}' data volume", 'type' => $dbFarmRole->GetSetting(Scalr_Db_Msr::DATA_STORAGE_ENGINE), 'platform' => $dbServer->platform, 'size' => $dbSettings->volumeConfig->size, 'fstype' => $dbSettings->volumeConfig->fstype, 'purpose' => $message->dbType, 'farm_roleid' => $dbFarmRole->ID, 'server_index' => $dbServer->index)); $storageVolume->setConfig($dbSettings->volumeConfig); $storageVolume->save(true); } else { throw $e; } } } catch (Exception $e) { Logger::getLogger(__CLASS__)->error(new FarmLogMessage($dbServer->farmId, "Cannot save storage volume: {$e->getMessage()}")); } } self::onCreateDataBundleResult($message, $dbServer); return true; }
/** launchOptions: imageId */ public function LaunchServer(DBServer $DBServer, Scalr_Server_LaunchOptions $launchOptions = null) { if (!$launchOptions) { $launchOptions = new Scalr_Server_LaunchOptions(); $DBRole = DBRole::loadById($DBServer->roleId); $launchOptions->imageId = $DBRole->getImageId(SERVER_PLATFORMS::OPENSTACK, $DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION)); $launchOptions->serverType = $DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_OPENSTACK_FLAVOR_ID); $launchOptions->cloudLocation = $DBServer->GetFarmRoleObject()->CloudLocation; foreach ($DBServer->GetCloudUserData() as $k => $v) { $u_data .= "{$k}={$v};"; } $launchOptions->userData = trim($u_data, ";"); $launchOptions->architecture = 'x86_64'; } $osClient = $this->getOsClient($DBServer->GetEnvironmentObject(), $launchOptions->cloudLocation); $result = $osClient->serverCreate($DBServer->serverId, $launchOptions->imageId, $launchOptions->serverType, base64_encode($launchOptions->userData), array('path' => '/etc/scalr/private.d/.user-data', 'contents' => base64_encode($launchOptions->userData))); if ($result->server) { //TODO: $DBServer->SetProperty(OPENSTACK_SERVER_PROPERTIES::SERVER_ID, $result->server->id); $DBServer->SetProperty(OPENSTACK_SERVER_PROPERTIES::IMAGE_ID, $result->server->image->id); $DBServer->SetProperty(OPENSTACK_SERVER_PROPERTIES::FLAVOR_ID, $result->server->flavor->id); $DBServer->SetProperty(OPENSTACK_SERVER_PROPERTIES::ADMIN_PASS, $result->server->adminPass); $DBServer->SetProperty(OPENSTACK_SERVER_PROPERTIES::NAME, $DBServer->serverId); $DBServer->SetProperty(OPENSTACK_SERVER_PROPERTIES::HOST_ID, $result->server->hostId); $DBServer->SetProperty(SERVER_PROPERTIES::ARCHITECTURE, $launchOptions->architecture); $DBServer->SetProperty(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION, $launchOptions->cloudLocation); return $DBServer; } else { throw new Exception(sprintf(_("Cannot launch new instance. %s"), $result->faultstring)); } }
/** launchOptions: imageId */ public function LaunchServer(DBServer $DBServer, Scalr_Server_LaunchOptions $launchOptions = null) { if (!$launchOptions) { $launchOptions = new Scalr_Server_LaunchOptions(); $DBRole = DBRole::loadById($DBServer->roleId); $launchOptions->imageId = $DBRole->getImageId(SERVER_PLATFORMS::RACKSPACE, $DBServer->GetProperty(RACKSPACE_SERVER_PROPERTIES::DATACENTER)); $launchOptions->serverType = $DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_RS_FLAVOR_ID); $launchOptions->cloudLocation = $DBServer->GetFarmRoleObject()->CloudLocation; foreach ($DBServer->GetCloudUserData() as $k => $v) { $u_data .= "{$k}={$v};"; } $launchOptions->userData = trim($u_data, ";"); $launchOptions->architecture = 'x86_64'; } $rsClient = $this->getRsClient($DBServer->GetEnvironmentObject(), $launchOptions->cloudLocation); //Cannot launch new instance. Request to Rackspace failed (Code: 413): {"overLimit":{"message":"Too many requests...","code":413,"retryAfter":"2012-03-12T09:44:56.343-05:00"}} (19641119, 4) try { $result = $rsClient->createServer($DBServer->serverId, $launchOptions->imageId, $launchOptions->serverType, array(), array('path' => '/etc/scalr/private.d/.user-data', 'contents' => base64_encode($launchOptions->userData))); } catch (Exception $e) { throw new Exception(sprintf(_("Cannot launch new instance. %s (%s, %s)"), $e->getMessage(), $launchOptions->imageId, $launchOptions->serverType)); } if ($result->server) { $DBServer->SetProperty(RACKSPACE_SERVER_PROPERTIES::SERVER_ID, $result->server->id); $DBServer->SetProperty(RACKSPACE_SERVER_PROPERTIES::IMAGE_ID, $result->server->imageId); $DBServer->SetProperty(RACKSPACE_SERVER_PROPERTIES::FLAVOR_ID, $result->server->flavorId); $DBServer->SetProperty(RACKSPACE_SERVER_PROPERTIES::ADMIN_PASS, $result->server->adminPass); $DBServer->SetProperty(RACKSPACE_SERVER_PROPERTIES::NAME, $DBServer->serverId); $DBServer->SetProperty(RACKSPACE_SERVER_PROPERTIES::HOST_ID, $result->server->hostId); $DBServer->SetProperty(SERVER_PROPERTIES::ARCHITECTURE, $launchOptions->architecture); $DBServer->SetProperty(RACKSPACE_SERVER_PROPERTIES::DATACENTER, $launchOptions->cloudLocation); return $DBServer; } else { throw new Exception(sprintf(_("Cannot launch new instance. %s (%s, %s)"), serialize($result), $launchOptions->imageId, $launchOptions->serverType)); } }
public function getBaseConfiguration(DBServer $dbServer, $isHostInit = false, $onlyBase = false) { $configuration = new stdClass(); $dbFarmRole = $dbServer->GetFarmRoleObject(); //Storage if (!$onlyBase) { try { if ($dbFarmRole) { $storage = new FarmRoleStorage($dbFarmRole); $volumes = $storage->getVolumesConfigs($dbServer, $isHostInit); if (!empty($volumes)) { $configuration->volumes = $volumes; } } } catch (Exception $e) { $this->logger->error(new FarmLogMessage($dbServer->farmId, "Cannot init storage: {$e->getMessage()}")); } } // Base try { if ($dbFarmRole) { $scriptingLogTimeout = $dbFarmRole->GetSetting(self::ROLE_BASE_KEEP_SCRIPTING_LOGS_TIME); if (!$scriptingLogTimeout) { $scriptingLogTimeout = 3600; } $configuration->base = new stdClass(); $configuration->base->keepScriptingLogsTime = $scriptingLogTimeout; $configuration->base->abortInitOnScriptFail = (int) $dbFarmRole->GetSetting(self::ROLE_BASE_ABORT_INIT_ON_SCRIPT_FAIL); $configuration->base->disableFirewallManagement = (int) $dbFarmRole->GetSetting(self::ROLE_BASE_DISABLE_FIREWALL_MANAGEMENT); $configuration->base->rebootAfterHostinitPhase = (int) $dbFarmRole->GetSetting(self::ROLE_BASE_REBOOT_AFTER_HOSTINIT_PHASE); $configuration->base->resumeStrategy = PlatformFactory::NewPlatform($dbFarmRole->Platform)->getResumeStrategy(); //Dev falgs for our if (Scalr::isHostedScalr() && $dbServer->envId == 3414) { $configuration->base->unionScriptExecutor = 1; } $governance = new Scalr_Governance($dbFarmRole->GetFarmObject()->EnvID); if ($governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_HOSTNAME_FORMAT)) { $hostNameFormat = $governance->getValue(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_HOSTNAME_FORMAT); } else { $hostNameFormat = $dbFarmRole->GetSetting(self::ROLE_BASE_HOSTNAME_FORMAT); } $configuration->base->hostname = !empty($hostNameFormat) ? $dbServer->applyGlobalVarsToValue($hostNameFormat) : ''; if ($configuration->base->hostname != '') { $dbServer->SetProperty(self::SERVER_BASE_HOSTNAME, $configuration->base->hostname); } $apiPort = null; $messagingPort = null; if (!PlatformFactory::isCloudstack($dbFarmRole->Platform)) { $apiPort = $dbFarmRole->GetSetting(self::ROLE_BASE_API_PORT); $messagingPort = $dbFarmRole->GetSetting(self::ROLE_BASE_MESSAGING_PORT); } $configuration->base->apiPort = $apiPort ? $apiPort : 8010; $configuration->base->messagingPort = $messagingPort ? $messagingPort : 8013; } //Update settings $updateSettings = $dbServer->getScalarizrRepository(); $configuration->base->update = new stdClass(); foreach ($updateSettings as $k => $v) { $configuration->base->update->{$k} = $v; } } catch (Exception $e) { } return $configuration; }
private function GetServerAvailZone(DBServer $DBServer) { return $DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_EUCA_AVAIL_ZONE); }
public static function listServerGlobalVariables(DBServer $dbServer, $includeSystem = false, AbstractServerEvent $event = null) { $retval = array(); if ($includeSystem) { $variables = $dbServer->GetScriptingVars(); if ($event) { if ($event->DBServer) { foreach ($event->DBServer->GetScriptingVars() as $k => $v) { $variables["event_{$k}"] = $v; } } foreach ($event->GetScriptingVars() as $k => $v) { $variables[$k] = $event->{$v}; } if (isset($event->params) && is_array($event->params)) { foreach ($event->params as $k => $v) { $variables[$k] = $v; } } $variables['event_name'] = $event->GetName(); } $formats = \Scalr::config("scalr.system.global_variables.format"); foreach ($variables as $name => $value) { $name = "SCALR_" . strtoupper($name); $value = trim($value); if (isset($formats[$name])) { $value = @sprintf($formats[$name], $value); } $private = strpos($name, 'SCALR_EVENT_') === 0 ? 1 : 0; $retval[] = (object) array('name' => $name, 'value' => $value, 'private' => $private, 'system' => 1); } } try { $globalVariables = new Scalr_Scripting_GlobalVariables($dbServer->GetEnvironmentObject()->clientId, $dbServer->envId, ScopeInterface::SCOPE_SERVER); $vars = $globalVariables->listVariables($dbServer->GetFarmRoleObject()->RoleID, $dbServer->farmId, $dbServer->farmRoleId, $dbServer->serverId); foreach ($vars as $v) { $retval[] = (object) $v; } } catch (Exception $e) { } return $retval; }
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; }
/** * @param Scalr_Messaging_Msg_Mysql_PromoteToMasterResult $message * @param DBServer $dbserver */ private function onMysql_PromoteToMasterResult($message, DBServer $dbserver) { $dbserver->GetFarmRoleObject()->SetSetting(DBFarmRole::SETTING_MYSQL_SLAVE_TO_MASTER, 0); if ($message->status == Scalr_Messaging_Msg_Mysql_PromoteToMasterResult::STATUS_OK) { $dbFarm = $dbserver->GetFarmObject(); $dbFarmRole = $dbserver->GetFarmRoleObject(); $oldMaster = $dbFarm->GetMySQLInstances(true); if ($dbserver->IsSupported("0.7")) { if ($message->volumeConfig) { try { $storageVolume = Scalr_Storage_Volume::init(); try { $storageVolume->loadById($message->volumeConfig->id); $storageVolume->setConfig($message->volumeConfig); $storageVolume->save(); } catch (Exception $e) { if (strpos($e->getMessage(), 'not found')) { $storageVolume->loadBy(array('id' => $message->volumeConfig->id, 'client_id' => $dbserver->clientId, 'env_id' => $dbserver->envId, 'name' => "MySQL data volume", 'type' => $dbFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_DATA_STORAGE_ENGINE), 'platform' => $dbserver->platform, 'size' => $message->volumeConfig->size, 'fstype' => $message->volumeConfig->fstype, 'purpose' => ROLE_BEHAVIORS::MYSQL, 'farm_roleid' => $dbserver->farmRoleId, 'server_index' => $dbserver->index)); $storageVolume->setConfig($message->volumeConfig); $storageVolume->save(true); } else { throw $e; } } } catch (Exception $e) { $this->logger->error(new FarmLogMessage($dbserver->farmId, "Cannot save storage volume: {$e->getMessage()}")); } } if ($message->snapshotConfig) { try { $snapshot = Scalr_Model::init(Scalr_Model::STORAGE_SNAPSHOT); $snapshot->loadBy(array('id' => $message->snapshotConfig->id, 'client_id' => $dbserver->clientId, 'env_id' => $dbserver->envId, 'name' => "Automatical MySQL data bundle", 'type' => $dbFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_DATA_STORAGE_ENGINE), 'platform' => $dbserver->platform, 'description' => "MySQL data bundle created automatically by Scalr", 'ismysql' => true)); $snapshot->setConfig($message->snapshotConfig); $snapshot->save(true); $dbFarmRole->SetSetting(DBFarmRole::SETTING_MYSQL_SCALR_SNAPSHOT_ID, $snapshot->id); $dbFarmRole->SetSetting(DBFarmRole::SETTING_MYSQL_LOG_FILE, $message->logFile); $dbFarmRole->SetSetting(DBFarmRole::SETTING_MYSQL_LOG_POS, $message->logPos); } catch (Exception $e) { $this->logger->error(new FarmLogMessage($dbserver->farmId, "Cannot save storage snapshot: {$e->getMessage()}")); } } } else { // TODO: delete old slave volume if new one was created $dbFarmRole->SetSetting(DBFarmRole::SETTING_MYSQL_MASTER_EBS_VOLUME_ID, $message->volumeId); } return new NewMysqlMasterUpEvent($dbserver, "", $oldMaster[0]); } elseif ($message->status == Scalr_Messaging_Msg_Mysql_PromoteToMasterResult::STATUS_FAILED) { $dbserver->SetProperty(SERVER_PROPERTIES::DB_MYSQL_MASTER, 0); $dbserver->SetProperty(Scalr_Db_Msr::REPLICATION_MASTER, 0); // XXX: Need to do smth $this->logger->error(sprintf("Promote to Master failed for server %s. Last error: %s", $dbserver->serverId, $message->lastError)); } }
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 getConfiguration(DBServer $dbServer) { $configuration = new stdClass(); $chefSettings = $dbServer->GetFarmRoleObject()->getChefSettings(); if (empty($chefSettings[self::ROLE_CHEF_BOOTSTRAP])) { return $configuration; } $jsonAttributes = $chefSettings[self::ROLE_CHEF_ATTRIBUTES]; if (!empty($chefSettings[self::ROLE_CHEF_COOKBOOK_URL])) { $configuration->cookbookUrl = $chefSettings[self::ROLE_CHEF_COOKBOOK_URL]; $configuration->runList = $chefSettings[self::ROLE_CHEF_RUNLIST]; $configuration->cookbookUrlType = $chefSettings[self::ROLE_CHEF_COOKBOOK_URL_TYPE]; $configuration->sshPrivateKey = isset($chefSettings[self::ROLE_CHEF_SSH_PRIVATE_KEY]) ? $chefSettings[self::ROLE_CHEF_SSH_PRIVATE_KEY] : false; $configuration->relativePath = isset($chefSettings[self::ROLE_CHEF_RELATIVE_PATH]) ? $chefSettings[self::ROLE_CHEF_RELATIVE_PATH] : false; } else { // Get chef server info $chefServerInfo = $this->db->GetRow("SELECT * FROM services_chef_servers WHERE id=?", array($chefSettings[self::ROLE_CHEF_SERVER_ID])); $chefServerInfo['v_auth_key'] = trim($this->getCrypto()->decrypt($chefServerInfo['v_auth_key'], $this->cryptoKey)); // Prepare node name $configuration->nodeName = $chefSettings[self::SERVER_CHEF_NODENAME]; if (!$configuration->nodeName) { $nodeNameTpl = $chefSettings[self::ROLE_CHEF_NODENAME_TPL]; if ($nodeNameTpl) { $configuration->nodeName = $dbServer->applyGlobalVarsToValue($nodeNameTpl); } } $configuration->serverUrl = $chefServerInfo['url']; $configuration->validatorName = $chefServerInfo['v_username']; $configuration->validatorKey = $chefServerInfo['v_auth_key']; if (!empty($chefSettings[self::ROLE_CHEF_ROLE_NAME])) { $configuration->role = $chefSettings[self::ROLE_CHEF_ROLE_NAME]; } else { $configuration->runList = $chefSettings[self::ROLE_CHEF_RUNLIST]; } $configuration->environment = $chefSettings[self::ROLE_CHEF_ENVIRONMENT]; $configuration->daemonize = $chefSettings[self::ROLE_CHEF_DAEMONIZE]; } $configuration->logLevel = !$chefSettings[self::ROLE_CHEF_LOG_LEVEL] ? 'auto' : $chefSettings[self::ROLE_CHEF_LOG_LEVEL]; if ($jsonAttributes) { $configuration->jsonAttributes = $dbServer->applyGlobalVarsToValue($jsonAttributes); } return $configuration; }
/** * @param DBServer $dbServer * @return boolean|string */ public static function setEipForServer(DBServer $dbServer) { $db = \Scalr::getDb(); try { $dbFarm = DBFarm::LoadByID($dbServer->farmId); $dbFarmRole = $dbServer->GetFarmRoleObject(); if (!$dbFarmRole->GetSetting(DBFarmRole::SETTING_AWS_USE_ELASIC_IPS)) { return false; } $aws = $dbFarm->GetEnvironmentObject()->aws($dbFarmRole->CloudLocation); $isVPC = $dbFarm->GetSetting(DBFarm::SETTING_EC2_VPC_ID); } catch (Exception $e) { Logger::getLogger(LOG_CATEGORY::FARM)->fatal(new FarmLogMessage($dbServer->farmId, sprintf(_("Cannot allocate elastic ip address for instance %s on farm %s (0)"), $dbServer->serverId, $dbFarm->Name))); } $ip = $db->GetRow("\n SELECT * FROM elastic_ips\n WHERE farmid=?\n AND ((farm_roleid=? AND instance_index=?) OR server_id = ?)\n LIMIT 1\n ", array($dbServer->farmId, $dbFarmRole->ID, $dbServer->index, $dbServer->serverId)); if ($ip['ipaddress']) { if (!self::checkElasticIp($ip['ipaddress'], $aws)) { Logger::getLogger(LOG_CATEGORY::FARM)->warn(new FarmLogMessage($dbServer->farmId, sprintf(_("Elastic IP '%s' does not belong to you. Allocating new one."), $ip['ipaddress']))); $db->Execute("DELETE FROM elastic_ips WHERE ipaddress=?", array($ip['ipaddress'])); $ip = false; } } if ($ip && $ip['ipaddress'] == $dbServer->remoteIp) { Logger::getLogger(LOG_CATEGORY::FARM)->fatal(new FarmLogMessage($dbServer->farmId, sprintf(_("Cannot allocate elastic ip address for instance %s on farm %s (1)"), $dbServer->serverId, $dbFarm->Name))); } // If free IP not found we must allocate new IP if (!$ip) { $alocatedIps = $db->GetOne("SELECT COUNT(*) FROM elastic_ips WHERE farm_roleid = ?", array($dbFarmRole->ID)); // Check elastic IPs limit. We cannot allocate more than 'Max instances' option for role if ($alocatedIps < $dbFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_MAX_INSTANCES)) { try { $domain = null; if ($isVPC) { $domain = 'vpc'; } $address = $aws->ec2->address->allocate($domain); } catch (Exception $e) { Logger::getLogger(LOG_CATEGORY::FARM)->error(new FarmLogMessage($dbServer->farmId, sprintf(_("Cannot allocate new elastic ip for instance '%s': %s"), $dbServer->serverId, $e->getMessage()))); return false; } // Add allocated IP address to database $db->Execute("\n INSERT INTO elastic_ips\n SET env_id=?,\n farmid=?,\n farm_roleid=?,\n ipaddress=?,\n clientid=?,\n instance_index=?,\n allocation_id=?,\n state='0', server_id=''\n ", array($dbServer->envId, $dbServer->farmId, $dbServer->farmRoleId, $address->publicIp, $dbServer->clientId, $dbServer->index, $address->allocationId)); $ip = array('ipaddress' => $address->publicIp, 'allocation_id' => $address->allocationId); Logger::getLogger(LOG_CATEGORY::FARM)->info(new FarmLogMessage($dbServer->farmId, sprintf(_("Allocated new IP: %s"), $ip['ipaddress']))); // Waiting... sleep(5); } else { Logger::getLogger(__CLASS__)->fatal(_("Limit for elastic IPs reached. Check zomby records in database.")); } } if ($ip['ipaddress']) { $allocationId = null; if ($isVPC) { $allocationId = $ip['allocation_id']; } self::associateIpAddress($dbServer, $ip['ipaddress'], $allocationId); // Update leastic IPs table $db->Execute("UPDATE elastic_ips SET state='1', server_id=? WHERE ipaddress=?", array($dbServer->serverId, $ip['ipaddress'])); Scalr::FireEvent($dbServer->farmId, new IPAddressChangedEvent($dbServer, $ip['ipaddress'], $dbServer->localIp)); } else { Logger::getLogger(LOG_CATEGORY::FARM)->fatal(new FarmLogMessage($dbServer->farmId, sprintf(_("Cannot allocate elastic ip address for instance %s on farm %s (2)"), $dbServer->serverId, $dbFarm->Name))); return false; } return $ip['ipaddress']; }
public static function setStaticNatForServer(\DBServer $dbServer) { $db = \Scalr::getDb(); try { $dbFarm = DBFarm::LoadByID($dbServer->farmId); $dbFarmRole = $dbServer->GetFarmRoleObject(); if (!$dbFarmRole->GetSetting(Entity\FarmRoleSetting::CLOUDSTACK_USE_STATIC_NAT)) { return false; } $cs = $dbFarm->GetEnvironmentObject()->cloudstack($dbFarmRole->Platform); } catch (Exception $e) { \Scalr::getContainer()->logger(\LOG_CATEGORY::FARM)->fatal(new \FarmLogMessage($dbServer, sprintf(_("Cannot allocate elastic ip address for instance %s on farm %s (0)"), !empty($dbServer->serverId) ? $dbServer->serverId : null, !empty($dbFarm->Name) ? $dbFarm->Name : null))); return false; } $ip = $db->GetRow("\n SELECT * FROM elastic_ips\n WHERE farmid=?\n AND ((farm_roleid=? AND instance_index=?) OR server_id = ?)\n LIMIT 1\n ", array($dbServer->farmId, $dbFarmRole->ID, $dbServer->index, $dbServer->serverId)); if ($ip['ipaddress']) { if (!self::checkStaticNatIp($ip['ipaddress'], $cs)) { \Scalr::getContainer()->logger(\LOG_CATEGORY::FARM)->warn(new \FarmLogMessage($dbServer, sprintf(_("Static NAT IP '%s' does not belong to you. Allocating new one."), !empty($ip['ipaddress']) ? $ip['ipaddress'] : null))); $db->Execute("DELETE FROM elastic_ips WHERE ipaddress=?", array($ip['ipaddress'])); $ip = false; } } if ($ip && $ip['ipaddress'] == $dbServer->remoteIp) { return $ip['ipaddress']; } // If free IP not found we must allocate new IP if (!$ip) { $alocatedIps = $db->GetOne("SELECT COUNT(*) FROM elastic_ips WHERE farm_roleid = ?", array($dbFarmRole->ID)); // Check elastic IPs limit. We cannot allocate more than 'Max instances' option for role if ($alocatedIps < $dbFarmRole->GetSetting(Entity\FarmRoleSetting::SCALING_MAX_INSTANCES)) { try { $requestObject = new AssociateIpAddressData(); $requestObject->zoneid = $dbFarmRole->CloudLocation; $ipResult = $cs->associateIpAddress($requestObject); $ipId = !empty($ipResult->id) ? $ipResult->id : null; if ($ipId) { while (true) { $requestObject = new ListIpAddressesData(); $requestObject->id = $ipId; $ipInfo = $cs->listPublicIpAddresses($requestObject); $ipInfo = count($ipInfo) > 0 ? $ipInfo[0] : null; if (!$ipInfo) { throw new Exception("Cannot allocate IP address: listPublicIpAddresses -> failed"); } if ($ipInfo->state == 'Allocated') { 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"); } } catch (Exception $e) { \Scalr::getContainer()->logger(\LOG_CATEGORY::FARM)->error(new \FarmLogMessage($dbServer, sprintf(_("Cannot allocate new elastic ip for instance '%s': %s"), !empty($dbServer->serverId) ? $dbServer->serverId : null, $e->getMessage()))); return false; } // Add allocated IP address to database $db->Execute("INSERT INTO elastic_ips SET\n env_id=?,\n farmid=?,\n farm_roleid=?,\n ipaddress=?,\n clientid=?,\n instance_index=?,\n allocation_id=?,\n state='0', server_id=''\n ", array($dbServer->envId, $dbServer->farmId, $dbServer->farmRoleId, $ipInfo->ipaddress, $dbServer->clientId, $dbServer->index, $ipId)); $ip = array('ipaddress' => $ipInfo->ipaddress, 'allocation_id' => $ipId); \Scalr::getContainer()->logger(\LOG_CATEGORY::FARM)->info(new \FarmLogMessage($dbServer, sprintf(_("Allocated new IP: %s"), $ip['ipaddress']))); // Waiting... sleep(5); } else { \Scalr::getContainer()->logger(__CLASS__)->fatal(_("Limit for elastic IPs reached. Check zomby records in database.")); } } if ($ip['ipaddress']) { self::associateIpAddress($dbServer, $ip['ipaddress'], $ip['allocation_id']); // Update leastic IPs table $db->Execute("UPDATE elastic_ips SET state='1', server_id=? WHERE ipaddress=?", array($dbServer->serverId, $ip['ipaddress'])); \Scalr::FireEvent($dbServer->farmId, new \IPAddressChangedEvent($dbServer, $ip['ipaddress'], $dbServer->localIp)); } else { \Scalr::getContainer()->logger(\LOG_CATEGORY::FARM)->fatal(new \FarmLogMessage($dbServer, sprintf(_("Cannot allocate elastic ip address for instance %s on farm %s (2)"), !empty($dbServer->serverId) ? $dbServer->serverId : null, !empty($dbFarm->Name) ? $dbFarm->Name : null))); return false; } return $ip['ipaddress']; }
/** * Gets the list of the security groups for the specified db server. * * If server does not have required security groups this method will create them. * * @param DBServer $DBServer The DB Server instance * @param \Scalr\Service\Aws\Ec2 $ec2 Ec2 Client instance * @param string $vpcId optional The ID of VPC * @return array Returns array looks like array(groupid-1, groupid-2, ..., groupid-N) */ private function GetServerSecurityGroupsList(DBServer $DBServer, \Scalr\Service\Aws\Ec2 $ec2, $vpcId = "", Scalr_Governance $governance = null) { $retval = array(); $checkGroups = array(); $sgGovernance = true; $allowAdditionalSgs = true; if ($governance) { $sgs = $governance->getValue(Scalr_Governance::EUCALYPTUS_SECURITY_GROUPS); if ($sgs !== null) { $governanceSecurityGroups = @explode(",", $sgs); if (!empty($governanceSecurityGroups)) { foreach ($governanceSecurityGroups as $sg) { if ($sg != '') { array_push($checkGroups, trim($sg)); } } } $sgGovernance = false; $allowAdditionalSgs = $governance->getValue(Scalr_Governance::EUCALYPTUS_SECURITY_GROUPS, 'allow_additional_sec_groups'); } } if (!$sgGovernance || $allowAdditionalSgs) { if ($DBServer->farmRoleId != 0) { $dbFarmRole = $DBServer->GetFarmRoleObject(); if ($dbFarmRole->GetSetting(DBFarmRole::SETTING_EUCA_SECURITY_GROUPS_LIST) !== null) { // New SG management $sgs = @json_decode($dbFarmRole->GetSetting(DBFarmRole::SETTING_EUCA_SECURITY_GROUPS_LIST)); if (!empty($sgs)) { foreach ($sgs as $sg) { if (stripos($sg, 'sg-') === 0) { array_push($retval, $sg); } else { array_push($checkGroups, $sg); } } } } } else { array_push($checkGroups, 'scalr-rb-system'); } } // No name based security groups, return only SG ids. if (empty($checkGroups)) { return $retval; } // Filter groups $filter = array(array('name' => SecurityGroupFilterNameType::groupName(), 'value' => $checkGroups)); // If instance run in VPC, add VPC filter if ($vpcId != '') { $filter[] = array('name' => SecurityGroupFilterNameType::vpcId(), 'value' => $vpcId); } // Get filtered list of SG required by scalr; try { $list = $ec2->securityGroup->describe(null, null, $filter); $sgList = array(); foreach ($list as $sg) { /* @var $sg \Scalr\Service\Aws\Ec2\DataType\SecurityGroupData */ if ($vpcId == '' && !$sg->vpcId || $vpcId && $sg->vpcId == $vpcId) { $sgList[$sg->groupName] = $sg->groupId; } } unset($list); } catch (Exception $e) { throw new Exception("Cannot get list of security groups (1): {$e->getMessage()}"); } foreach ($checkGroups as $groupName) { // Check default SG if ($groupName == 'default') { array_push($retval, $sgList[$groupName]); // Check Roles builder SG } elseif ($groupName == 'scalr-rb-system') { if (!isset($sgList[$groupName])) { try { $securityGroupId = $ec2->securityGroup->create('scalr-rb-system', "Security group for Roles Builder", $vpcId); $ipRangeList = new IpRangeList(); foreach (\Scalr::config('scalr.aws.ip_pool') as $ip) { $ipRangeList->append(new IpRangeData($ip)); } sleep(2); $ec2->securityGroup->authorizeIngress(array(new IpPermissionData('tcp', 22, 22, $ipRangeList), new IpPermissionData('tcp', 8008, 8013, $ipRangeList)), $securityGroupId); $sgList['scalr-rb-system'] = $securityGroupId; } catch (Exception $e) { throw new Exception(sprintf(_("Cannot create security group '%s': %s"), 'scalr-rb-system', $e->getMessage())); } } array_push($retval, $sgList[$groupName]); //Check scalr-farm.* security group } elseif (stripos($groupName, 'scalr-farm.') === 0) { if (!isset($sgList[$groupName])) { try { $securityGroupId = $ec2->securityGroup->create($groupName, sprintf("Security group for FarmID N%s", $DBServer->farmId), $vpcId); sleep(2); $userIdGroupPairList = new UserIdGroupPairList(new UserIdGroupPairData($DBServer->GetEnvironmentObject()->getPlatformConfigValue(self::ACCOUNT_ID), null, $groupName)); $ec2->securityGroup->authorizeIngress(array(new IpPermissionData('tcp', 0, 65535, null, $userIdGroupPairList), new IpPermissionData('udp', 0, 65535, null, $userIdGroupPairList)), $securityGroupId); $sgList[$groupName] = $securityGroupId; } catch (Exception $e) { throw new Exception(sprintf(_("Cannot create security group '%s': %s"), $groupName, $e->getMessage())); } } array_push($retval, $sgList[$groupName]); //Check scalr-role.* security group } elseif (stripos($groupName, 'scalr-role.') === 0) { if (!isset($sgList[$groupName])) { try { $securityGroupId = $ec2->securityGroup->create($groupName, sprintf("Security group for FarmRoleID N%s on FarmID N%s", $DBServer->GetFarmRoleObject()->ID, $DBServer->farmId), $vpcId); sleep(2); // DB rules $dbRules = $DBServer->GetFarmRoleObject()->GetRoleObject()->getSecurityRules(); $groupRules = array(); foreach ($dbRules as $rule) { $groupRules[Scalr_Util_CryptoTool::hash($rule['rule'])] = $rule; } // Behavior rules foreach (Scalr_Role_Behavior::getListForFarmRole($DBServer->GetFarmRoleObject()) as $bObj) { $bRules = $bObj->getSecurityRules(); foreach ($bRules as $r) { if ($r) { $groupRules[Scalr_Util_CryptoTool::hash($r)] = array('rule' => $r); } } } // Default rules $userIdGroupPairList = new UserIdGroupPairList(new UserIdGroupPairData($DBServer->GetEnvironmentObject()->getPlatformConfigValue(self::ACCOUNT_ID), null, $groupName)); $rules = array(new IpPermissionData('tcp', 0, 65535, null, $userIdGroupPairList), new IpPermissionData('udp', 0, 65535, null, $userIdGroupPairList)); foreach ($groupRules as $rule) { $group_rule = explode(":", $rule["rule"]); $rules[] = new IpPermissionData($group_rule[0], $group_rule[1], $group_rule[2], new IpRangeData($group_rule[3])); } $ec2->securityGroup->authorizeIngress($rules, $securityGroupId); $sgList[$groupName] = $securityGroupId; } catch (Exception $e) { throw new Exception(sprintf(_("Cannot create security group '%s': %s"), $groupName, $e->getMessage())); } } array_push($retval, $sgList[$groupName]); } elseif ($groupName == \Scalr::config('scalr.aws.security_group_name')) { if (!isset($sgList[$groupName])) { try { $securityGroupId = $ec2->securityGroup->create($groupName, "Security rules needed by Scalr", $vpcId); $ipRangeList = new IpRangeList(); foreach (\Scalr::config('scalr.aws.ip_pool') as $ip) { $ipRangeList->append(new IpRangeData($ip)); } // TODO: Open only FOR VPC ranges $ipRangeList->append(new IpRangeData('10.0.0.0/8')); sleep(2); $ec2->securityGroup->authorizeIngress(array(new IpPermissionData('tcp', 3306, 3306, $ipRangeList), new IpPermissionData('tcp', 8008, 8013, $ipRangeList), new IpPermissionData('udp', 8014, 8014, $ipRangeList)), $securityGroupId); $sgList[$groupName] = $securityGroupId; } catch (Exception $e) { throw new Exception(sprintf(_("Cannot create security group '%s': %s"), $groupName, $e->getMessage())); } } array_push($retval, $sgList[$groupName]); } else { if (!isset($sgList[$groupName])) { throw new Exception(sprintf(_("Security group '%s' is not found"), $groupName)); } else { array_push($retval, $sgList[$groupName]); } } } return $retval; }
public function extendMessage(Scalr_Messaging_Msg $message, DBServer $dbServer) { $message = parent::extendMessage($message); $dbFarmRole = $dbServer->GetFarmRoleObject(); $chefServerId = $dbFarmRole->GetSetting(self::ROLE_CHEF_SERVER_ID); $runListId = $dbFarmRole->GetSetting(self::ROLE_CHEF_RUNLIST_ID); if (!$chefServerId || !$runListId) { return $message; } $chefRunListInfo = $this->db->GetRow("SELECT * FROM services_chef_runlists WHERE id=?", array($runListId)); $chefServerInfo = $this->db->GetRow("SELECT * FROM services_chef_servers WHERE id=?", array($chefRunListInfo['chef_server_id'])); $chefServerInfo['v_auth_key'] = trim($this->getCrypto()->decrypt($chefServerInfo['v_auth_key'], $this->cryptoKey)); switch (get_class($message)) { case "Scalr_Messaging_Msg_HostInitResponse": $message->chef = new stdClass(); $message->chef->serverUrl = $chefServerInfo['url']; $message->chef->role = $dbFarmRole->GetSetting(self::ROLE_CHEF_ROLE_NAME); $message->chef->validatorName = $chefServerInfo['v_username']; $message->chef->validatorKey = $chefServerInfo['v_auth_key']; $message->chef->environment = $chefRunListInfo['chef_environment']; break; } return $message; }
private function getDbStorageStatus(DBServer $masterServer, $behavior) { // Get Stoarge usage $size = array('total' => -1, 'used' => -1, 'free' => -1); try { if ($behavior == ROLE_BEHAVIORS::REDIS) { $mpoint = '/mnt/redisstorage'; } elseif ($behavior == ROLE_BEHAVIORS::POSTGRESQL) { $mpoint = '/mnt/pgstorage'; } else { $mpoint = '/mnt/dbstorage'; } $usage = (array) $masterServer->scalarizr->system->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->debugException($e); } $retval = array('engine' => $masterServer->GetFarmRoleObject()->GetSetting(Scalr_Db_Msr::DATA_STORAGE_ENGINE), 'level' => $masterServer->GetFarmRoleObject()->GetSetting(Scalr_Db_Msr::DATA_STORAGE_RAID_LEVEL), '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); if ($this->request->getHeaderVar('Interface-Beta')) { $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, ROLE_BEHAVIORS::REDIS, ROLE_BEHAVIORS::POSTGRESQL)); } else { $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)); } if ($retval['growSupported'] && $retval['engine'] == MYSQL_STORAGE_ENGINE::RAID_EBS && in_array($retval['level'], array('0', '10'))) { $retval['growSupported'] = false; } if ($retval['growSupported']) { $retval['ebs_settings'] = array('volumeType' => $masterServer->GetFarmRoleObject()->GetSetting(Scalr_Db_Msr::DATA_STORAGE_EBS_TYPE), 'size' => $masterServer->GetFarmRoleObject()->GetSetting(Scalr_Db_Msr::DATA_STORAGE_EBS_SIZE)); if ($retval['ebs_settings']['volumeType'] == 'io1') { $retval['ebs_settings']['iops'] = $masterServer->GetFarmRoleObject()->GetSetting(Scalr_Db_Msr::DATA_STORAGE_EBS_IOPS); } } 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; }
public function getConfiguration(DBServer $dbServer) { $configuration = new stdClass(); $configuration->keyfile = $dbServer->GetFarmRoleObject()->GetSetting(self::ROLE_KEYFILE); $configuration->volumeConfig = $this->getVolumeConfig($dbServer->GetFarmRoleObject(), $dbServer); $configuration->snapshotConfig = $this->getSnapshotConfig($dbServer->GetFarmRoleObject(), $dbServer); $configuration->password = $dbServer->GetFarmRoleObject()->GetSetting(self::ROLE_PASSWORD); $configuration->replicaSetIndex = $dbServer->GetProperty(self::SERVER_REPLICA_SET_INDEX); $configuration->shardIndex = $dbServer->GetProperty(self::SERVER_SHARD_INDEX); $configuration->shardsTotal = $dbServer->GetFarmRoleObject()->GetSetting(self::ROLE_SHARDS_COUNT); $configuration->replicasPerShard = $dbServer->GetFarmRoleObject()->GetSetting(self::ROLE_REPLICAS_COUNT); $mmsApiKey = $dbServer->GetFarmRoleObject()->GetSetting(self::ROLE_MMS_API_KEY); if ($mmsApiKey) { $configuration->mms = new stdClass(); $configuration->mms->apiKey = $mmsApiKey; $configuration->mms->secretKey = $dbServer->GetFarmRoleObject()->GetSetting(self::ROLE_MMS_SECRET_KEY); } if ($dbServer->GetFarmRoleObject()->GetSetting(self::ROLE_SSL_ENABLED) == 1) { $cert = new Scalr_Service_Ssl_Certificate(); $cert->loadById($dbServer->GetFarmRoleObject()->GetSetting(self::ROLE_SSL_CERT_ID)); $configuration->ssl = new stdClass(); $configuration->ssl->privateKey = $cert->sslPkey; $configuration->ssl->certificate = $cert->sslCert; $configuration->ssl->privateKeyPassword = $cert->sslPkeyPassword; } $configServers = $this->db->GetAll("SELECT * FROM services_mongodb_config_servers WHERE\n `farm_role_id` = ?\n ", array($dbServer->farmRoleId)); if (count($configServers) > 0) { $configuration->config_servers = array(); foreach ($configServers as $cs) { $itm = new stdClass(); $itm->id = $cs['config_server_index']; $itm->replicaSetIndex = $cs['replica_set_index']; $itm->shardIndex = $cs['shard_index']; try { $volume = Scalr_Storage_Volume::init()->loadById($cs['volume_id']); $volumeConfig = $volume->getConfig(); } catch (Exception $e) { } $itm->volume = $volumeConfig; $configuration->config_servers[] = $itm; } } return $configuration; }
public function LaunchServer(DBServer $DBServer, Scalr_Server_LaunchOptions $launchOptions = null) { $environment = $DBServer->GetEnvironmentObject(); $farmRole = $DBServer->GetFarmRoleObject(); $location = $farmRole->CloudLocation; $nimbulaClient = $this->getNimbulaClient($environment, $location); $dbRole = $DBServer->GetFarmRoleObject()->GetRoleObject(); if (!$dbRole->getProperty(DBRole::PROPERTY_NIMBULA_ENTRY)) { $username = $environment->getPlatformConfigValue(self::USERNAME); $imageLists = $nimbulaClient->imageListList(); $listFound = false; foreach ($imageLists as $list) { if ($list->name == "{$username}/scalr") { $listFound = true; } } if (!$listFound) { $nimbulaClient->imageListCreate('scalr', 'Image list for scalr images'); } $entry = (int) $environment->getPlatformConfigValue(Modules_Platforms_Nimbula::IMAGE_LIST_ENTRY_VALUE); $entry++; $nimbulaClient->imageListAddEntry('scalr', $dbRole->getImageId($DBServer->platform, $location), $entry); $environment->setPlatformConfig(array(Modules_Platforms_Nimbula::IMAGE_LIST_ENTRY_VALUE => $entry)); $dbRole->setProperty(DBRole::PROPERTY_NIMBULA_ENTRY, $entry); } $instance = $nimbulaClient->instanceLaunch($DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_NIMBULA_SHAPE), $DBServer->GetEnvironmentObject()->getPlatformConfigValue(self::USERNAME) . "/scalr", $dbRole->getProperty(DBRole::PROPERTY_NIMBULA_ENTRY), "Scalr server: FarmID: {$DBServer->farmId} RoleName: {$DBServer->GetFarmRoleObject()->GetRoleObject()->name}"); $instanceInfo = $instance->instances[0]; if ($instanceInfo->name) { $serverName = str_replace($DBServer->GetEnvironmentObject()->getPlatformConfigValue(self::USERNAME) . "/", "", $instanceInfo->name); $DBServer->SetProperty(NIMBULA_SERVER_PROPERTIES::NAME, $serverName); $DBServer->SetProperty(NIMBULA_SERVER_PROPERTIES::CLOUD_LOCATION, $location); return $DBServer; } else { throw new Exception("Scalr unable to launch Nimbula server"); } }