作者:rickb83
项目:scal
public function deleteAction()
{
$this->request->defineParams(array('sshKeyId' => array('type' => 'int')));
$sshKey = Scalr_SshKey::init()->loadById($this->getParam('sshKeyId'));
$this->user->getPermissions()->validate($sshKey);
if ($sshKey->type == Scalr_SshKey::TYPE_GLOBAL) {
if ($sshKey->platform == SERVER_PLATFORMS::EC2) {
$aws = $this->getEnvironment()->aws($sshKey->cloudLocation);
$aws->ec2->keyPair->delete($sshKey->cloudKeyName);
$sshKey->delete();
$this->response->success();
} elseif (PlatformFactory::isOpenstack($sshKey->platform)) {
$os = $this->getEnvironment()->openstack($sshKey->platform, $sshKey->cloudLocation);
try {
$os->servers->keypairs->delete($sshKey->cloudKeyName);
} catch (Exception $e) {
}
$sshKey->delete();
$this->response->success();
} else {
$sshKey->delete();
}
} else {
//TODO:
}
$this->response->success("SSH key successfully removed");
}
作者:mheyd
项目:scal
protected function run1($stage)
{
$this->console->out("Initializing instance_type_name field in servers_history table");
$result = $this->db->Execute("\n SELECT sh.* FROM servers_history sh\n JOIN servers s USING(server_id)\n WHERE sh.instance_type_name IS NULL\n AND sh.type IS NOT NULL\n AND sh.cloud_location IS NOT NULL\n ORDER BY sh.env_id, sh.platform DESC\n ");
$env = null;
$platform = null;
$this->db->BeginTrans();
try {
$sql = "UPDATE servers_history sh SET sh.instance_type_name = ? WHERE sh.server_id = ?";
while ($record = $result->FetchRow()) {
if (!isset($env) || $env->id != $record['env_id']) {
$env = Scalr_Environment::init()->loadById($record['env_id']);
$platform = null;
}
if (in_array($record['platform'], [\SERVER_PLATFORMS::EC2, \SERVER_PLATFORMS::GCE])) {
$this->db->Execute($sql, [$record['type'], $record['server_id']]);
continue;
}
if (!isset($platform) || $platform != $record['platform']) {
$platform = $record['platform'];
$platformModule = PlatformFactory::NewPlatform($record['platform']);
$url = $platformModule->getEndpointUrl($env);
}
$cloudLocationId = CloudLocation::calculateCloudLocationId($record['platform'], $record['cloud_location'], $url);
$instanceTypeEntity = CloudInstanceType::findPk($cloudLocationId, $record['type']);
/* @var $instanceTypeEntity CloudInstanceType */
if ($instanceTypeEntity) {
$this->db->Execute($sql, [$instanceTypeEntity->name, $record['server_id']]);
}
}
$this->db->CommitTrans();
} catch (Exception $e) {
$this->db->RollbackTrans();
}
}
作者:mheyd
项目:scal
/**
* Gets a new Instance of the adapter
*
* @param string|CloudCredentials|object $name The name of the adapter, or CloudCredentials entity, or cloud credentials data
*
* @return ApiEntityAdapter Returns the instance of cloud credentials adapter
*
* @throws ApiErrorException
*/
public function adapter($name, array $transform = null)
{
if (is_object($name)) {
//
$property = $name instanceof $this->entityClass ? static::$entityDescriminator : static::$objectDiscriminator;
$value = empty($transform) ? $name->{$property} : $transform[$name->{$property}];
switch (true) {
case PlatformFactory::isOpenstack($value, true):
$value = SERVER_PLATFORMS::OPENSTACK;
break;
case PlatformFactory::isCloudstack($value):
$value = SERVER_PLATFORMS::CLOUDSTACK;
break;
case PlatformFactory::isRackspace($value):
$value = SERVER_PLATFORMS::RACKSPACE;
break;
}
if (!isset(static::$inheritanceMap[$value])) {
throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, "Unknown cloud '{$value}'");
}
$class = empty(static::$inheritanceMap) ? $value : static::$inheritanceMap[$value];
$name = empty(static::$inheritedNamespace) ? $class : static::$inheritedNamespace . "\\{$class}";
}
return parent::adapter($name);
}
作者:mheyd
项目:scal
public function xGrowStorageAction()
{
$dbFarmRole = DBFarmRole::LoadByID($this->getParam('farmRoleId'));
$this->user->getPermissions()->validate($dbFarmRole->GetFarmObject());
$behavior = Scalr_Role_Behavior::loadByName($dbFarmRole->GetRoleObject()->getDbMsrBehavior());
$master = $behavior->getMasterServer($dbFarmRole);
if ($master) {
try {
$volume = Scalr_Storage_Volume::init()->loadById($dbFarmRole->GetSetting(Scalr_Db_Msr::VOLUME_ID));
if ($volume->type != MYSQL_STORAGE_ENGINE::EBS && $volume->type != MYSQL_STORAGE_ENGINE::RAID_EBS && $volume->type != 'raid') {
throw new Exception("Grow feature available only for EBS and RAID storage types");
}
if ($volume->size >= (int) $this->getParam('newSize')) {
throw new Exception("New size should be greather than current one ({$volume->size} GB)");
}
$volumeConfig = $volume->getConfig();
$platformAccessData = PlatformFactory::NewPlatform($dbFarmRole->Platform)->GetPlatformAccessData($this->environment, $master);
$newConfig = new stdClass();
$newConfig->size = $this->getParam('newSize');
$result = $master->scalarizr->mysql->growStorage($volumeConfig, $newConfig, $platformAccessData);
// Do not remove. We need to wait a bit before operation will be registered in scalr.
sleep(2);
$this->response->data(array('operationId' => $result));
} catch (Exception $e) {
throw new Exception("Cannot grow storage: {$e->getMessage()}");
}
} else {
throw new Exception("Impossible to increase storage size. No running master server.");
}
}
作者:solderzz
项目:scal
protected function run2($stage)
{
$this->console->out("Populating new properties");
$platforms = $envs = [];
foreach (array_keys(\SERVER_PLATFORMS::GetList()) as $platform) {
$platforms[$platform] = PlatformFactory::NewPlatform($platform);
}
$result = $this->db->Execute("\n SELECT s.server_id, s.`platform`, s.`cloud_location`, s.env_id, s.`type`\n FROM servers AS s\n WHERE s.`status` NOT IN (?, ?) AND s.`type` IS NOT NULL\n ", [Server::STATUS_PENDING_TERMINATE, Server::STATUS_TERMINATED]);
while ($row = $result->FetchRow()) {
if (!empty($row["type"])) {
if (!array_key_exists($row["env_id"], $envs)) {
$envs[$row["env_id"]] = \Scalr_Environment::init()->loadById($row["env_id"]);
}
if ($this->isPlatformEnabled($envs[$row["env_id"]], $row["platform"])) {
try {
$instanceTypeEntity = $platforms[$row["platform"]]->getInstanceType($row["type"], $envs[$row["env_id"]], $row["cloud_location"]);
/* @var $instanceTypeEntity CloudInstanceType */
if ($instanceTypeEntity && (int) $instanceTypeEntity->vcpus > 0) {
$this->db->Execute("\n INSERT IGNORE INTO server_properties (`server_id`, `name`, `value`) VALUES (?, ?, ?)\n ", [$row["server_id"], Server::INFO_INSTANCE_VCPUS, $instanceTypeEntity->vcpus]);
}
} catch (\Exception $e) {
$this->console->warning("Can't get access to %s, error: %s", $row["platform"], $e->getMessage());
}
}
}
}
}
作者:scal
项目:scal
/**
* Constructor
*
* @param string $platform Platform
* @param DBFarmRole $DBFarmRole optional Farm Role object
* @param int $index optional Server index within the Farm Role scope
* @param string $role_id optional Identifier of the Role
*/
public function __construct($platform, DBFarmRole $DBFarmRole = null, $index = null, $role_id = null)
{
$this->platform = $platform;
$this->dbFarmRole = $DBFarmRole;
$this->index = $index;
$this->roleId = $role_id === null ? $this->dbFarmRole->RoleID : $role_id;
if ($DBFarmRole) {
$this->envId = $DBFarmRole->GetFarmObject()->EnvID;
}
//Refletcion
$Reflect = new ReflectionClass(DBServer::$platformPropsClasses[$this->platform]);
foreach ($Reflect->getConstants() as $k => $v) {
$this->platformProps[] = $v;
}
if ($DBFarmRole) {
if (PlatformFactory::isOpenstack($this->platform)) {
$this->SetProperties(array(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION => $DBFarmRole->CloudLocation));
} elseif (PlatformFactory::isCloudstack($this->platform)) {
$this->SetProperties(array(CLOUDSTACK_SERVER_PROPERTIES::CLOUD_LOCATION => $DBFarmRole->CloudLocation));
} else {
switch ($this->platform) {
case SERVER_PLATFORMS::GCE:
$this->SetProperties(array(GCE_SERVER_PROPERTIES::CLOUD_LOCATION => $DBFarmRole->CloudLocation));
break;
case SERVER_PLATFORMS::EC2:
$this->SetProperties(array(EC2_SERVER_PROPERTIES::REGION => $DBFarmRole->CloudLocation));
break;
}
}
}
$this->SetProperties(array(SERVER_PROPERTIES::SZR_VESION => '0.20.0'));
}
作者:mheyd
项目:scal
protected function run2($stage)
{
$farms = $this->db->Execute("SELECT farmid, value FROM farm_settings WHERE name='ec2.vpc.id' AND value != '' AND value IS NOT NULL");
while ($farm = $farms->FetchRow()) {
$dbFarm = \DBFarm::LoadByID($farm['farmid']);
$roles = $dbFarm->GetFarmRoles();
foreach ($roles as $dbFarmRole) {
$vpcSubnetId = $dbFarmRole->GetSetting(Entity\FarmRoleSetting::AWS_VPC_SUBNET_ID);
if ($vpcSubnetId && substr($vpcSubnetId, 0, 6) != 'subnet') {
$subnets = json_decode($vpcSubnetId);
$vpcSubnetId = $subnets[0];
}
if ($vpcSubnetId) {
try {
$platform = PlatformFactory::NewPlatform(\SERVER_PLATFORMS::EC2);
$info = $platform->listSubnets(\Scalr_Environment::init()->loadById($dbFarm->EnvID), $dbFarmRole->CloudLocation, $farm['value'], true, $vpcSubnetId);
if ($info && $info['type'] != 'public') {
$routerRole = $dbFarm->GetFarmRoleByBehavior(\ROLE_BEHAVIORS::VPC_ROUTER);
$dbFarmRole->SetSetting(\Scalr_Role_Behavior_Router::ROLE_VPC_SCALR_ROUTER_ID, $routerRole->ID);
$this->console->out("Updating router.scalr.farm_role_id property for Farm Role: %s", $dbFarmRole->ID);
}
} catch (\Exception $e) {
continue;
}
}
}
}
}
作者:scal
项目:scal
protected function run1($stage)
{
$envs = [];
$platform = SERVER_PLATFORMS::GCE;
$platformModule = PlatformFactory::NewPlatform($platform);
/* @var $platformModule GoogleCEPlatformModule*/
$result = $this->db->Execute("\n SELECT s.`server_id`, s.`cloud_location`, s.`type`, s.`env_id`, sp.`value` AS vcpus\n FROM servers AS s\n LEFT JOIN server_properties sp ON sp.`server_id`= s.`server_id` AND sp.`name` = ?\n WHERE s.`status` NOT IN (?, ?)\n AND s.`type` IS NOT NULL\n AND s.`platform` = ?\n ", [Server::INFO_INSTANCE_VCPUS, Server::STATUS_PENDING_TERMINATE, Server::STATUS_TERMINATED, $platform]);
while ($row = $result->FetchRow()) {
if (!empty($row["type"]) && empty($row['vcpus'])) {
if (!array_key_exists($row["env_id"], $envs)) {
$envs[$row["env_id"]] = \Scalr_Environment::init()->loadById($row["env_id"]);
}
try {
$instanceTypeInfo = $platformModule->getInstanceType($row["type"], $envs[$row["env_id"]], $row["cloud_location"]);
if ($instanceTypeInfo instanceof CloudInstanceType) {
$vcpus = $instanceTypeInfo->vcpus;
} else {
trigger_error("Value of vcpus for instance type " . $row["type"] . " is missing for platform " . $platform, E_USER_WARNING);
$vcpus = 0;
}
if ((int) $vcpus > 0) {
$this->db->Execute("\n INSERT INTO server_properties (`server_id`, `name`, `value`) VALUES (?, ?, ?)\n ON DUPLICATE KEY UPDATE `value` = ?\n ", [$row["server_id"], Server::INFO_INSTANCE_VCPUS, $vcpus, $vcpus]);
}
} catch (\Exception $e) {
$this->console->warning("Can't get access to %s, error: %s", $platform, $e->getMessage());
}
}
}
}
作者:mheyd
项目:scal
/**
* Performs upgrade literally for the stage ONE.
*
* Implementation of this method performs update steps needs to be taken
* to accomplish upgrade successfully.
*
* If there are any error during an execution of this scenario it must
* throw an exception.
*
* @param int $stage optional The stage number
* @throws \Exception
*/
protected function run1($stage)
{
$environments = $this->db->Execute("SELECT id FROM client_environments WHERE status='Active'");
while ($env = $environments->FetchRow()) {
$environment = \Scalr_Environment::init()->loadById($env['id']);
foreach (PlatformFactory::getOpenstackBasedPlatforms() as $platform) {
if ($platform == \SERVER_PLATFORMS::RACKSPACENG_UK || $platform == \SERVER_PLATFORMS::RACKSPACENG_US) {
continue;
}
try {
if ($environment->isPlatformEnabled($platform)) {
$os = $environment->openstack($platform);
//It throws an exception on failure
$zones = $os->listZones();
$zone = array_shift($zones);
$os = $environment->openstack($platform, $zone->name);
// Check SG Extension
$pars[$this->getOpenStackOption($platform, 'EXT_SECURITYGROUPS_ENABLED')] = (int) $os->servers->isExtensionSupported(ServersExtension::securityGroups());
// Check Floating Ips Extension
$pars[$this->getOpenStackOption($platform, 'EXT_FLOATING_IPS_ENABLED')] = (int) $os->servers->isExtensionSupported(ServersExtension::floatingIps());
// Check Cinder Extension
$pars[$this->getOpenStackOption($platform, 'EXT_CINDER_ENABLED')] = (int) $os->hasService('volume');
// Check Swift Extension
$pars[$this->getOpenStackOption($platform, 'EXT_SWIFT_ENABLED')] = (int) $os->hasService('object-store');
// Check LBaas Extension
$pars[$this->getOpenStackOption($platform, 'EXT_LBAAS_ENABLED')] = $os->hasService('network') ? (int) $os->network->isExtensionSupported('lbaas') : 0;
$environment->setPlatformConfig($pars);
}
} catch (\Exception $e) {
$this->console->out("Update settings for env: {$env['id']} failed: " . $e->getMessage());
}
}
}
}
作者:sacredwebsit
项目:scal
public static function getAwsLocations()
{
$locations = array();
foreach (PlatformFactory::NewPlatform(SERVER_PLATFORMS::EC2)->getLocations($this->environment) as $key => $loc) {
$locations[] = array($key, $loc);
}
return $locations;
}
作者:sacredwebsit
项目:scal
public function viewAction()
{
if ($this->getParam('platform')) {
$locations = self::loadController('Platforms')->getCloudLocations(array($this->getParam('platform')), false);
} else {
$locations = self::loadController('Platforms')->getCloudLocations(PlatformFactory::getOpenstackBasedPlatforms(), false);
}
$this->response->page('ui/tools/openstack/volumes/view.js', array('locations' => $locations));
}
作者:scal
项目:scal
/**
* Gets AWS instance
*
* If cloud location is not specified it will use default cloud location for
* current User's session
*
* @param string $cloudLocation optional A Cloud Location
* @return Aws Returns AWS initialized for the specified cloud location
*/
protected function getAws($cloudLocation = null)
{
if (empty($cloudLocation)) {
$p = PlatformFactory::NewPlatform(SERVER_PLATFORMS::EC2);
$cloudLocations = $p->getLocations($this->environment);
list($cloudLocation) = each($cloudLocations);
}
return $this->environment->aws($cloudLocation);
}
作者:rickb83
项目:scal
/**
* @param jsonData $platforms
* @throws Exception
*/
public function xGetLocationsAction(JsonData $platforms)
{
$allPlatforms = $this->user->isScalrAdmin() ? array_keys(SERVER_PLATFORMS::GetList()) : $this->getEnvironment()->getEnabledPlatforms();
$result = array();
foreach ($platforms as $platform) {
if (in_array($platform, $allPlatforms)) {
$result[$platform] = !in_array($platform, array(SERVER_PLATFORMS::GCE, SERVER_PLATFORMS::ECS)) ? PlatformFactory::NewPlatform($platform)->getLocations($this->environment) : array();
}
}
$this->response->data(array('locations' => $result));
}
作者:scal
项目:scal
public function xGetResourceGroupsAction()
{
$data = array();
$azure = $this->environment->azure();
//Get Resource groups;
$rGroups = $azure->resourceManager->resourceGroup->getList($this->environment->keychain(SERVER_PLATFORMS::AZURE)->properties[Entity\CloudCredentialsProperty::AZURE_SUBSCRIPTION_ID]);
foreach ($rGroups as $rGroup) {
$data[] = ['id' => $rGroup->name, 'name' => "{$rGroup->name} ({$rGroup->location})"];
}
$p = PlatformFactory::NewPlatform(\SERVER_PLATFORMS::AZURE);
$this->response->data(array('data' => ['resourceGroups' => $data, 'cloudLocations' => $p->getLocations($this->environment)]));
}
作者:mheyd
项目:scal
public function xListIpsAction()
{
$this->request->defineParams(array('sort' => array('type' => 'json', 'default' => array('property' => 'ipId', 'direction' => 'ASC')), 'ipId'));
$platformName = $this->getParam('platform');
if (!$platformName) {
throw new Exception("Cloud should be specified");
}
$platform = PlatformFactory::NewPlatform($platformName);
$cs = $this->environment->cloudstack($platformName);
$ccProps = $this->environment->cloudCredentials($platformName)->properties;
$accountName = $ccProps[\Scalr\Model\Entity\CloudCredentialsProperty::CLOUDSTACK_ACCOUNT_NAME];
$domainId = $ccProps[\Scalr\Model\Entity\CloudCredentialsProperty::CLOUDSTACK_DOMAIN_ID];
$requestData = new ListIpAddressesData();
$requestData->account = $accountName;
$requestData->domainid = $domainId;
$requestData->zoneid = $this->getParam('cloudLocation');
$ipAddresses = $cs->listPublicIpAddresses($requestData);
$systemIp = $ccProps[\Scalr\Model\Entity\CloudCredentialsProperty::CLOUDSTACK_SHARED_IP . ".{$this->getParam('cloudLocation')}"];
$ips = array();
if (!empty($ipAddresses)) {
foreach ($ipAddresses as $pk => $pv) {
if ($this->getParam('ipId') && $this->getParam('ipId') != $pv->id) {
continue;
}
if ($pv->ipaddress == $systemIp) {
$pv->purpose = 'ScalrShared';
}
if ($pv->isstaticnat && !$pv->issystem) {
$pv->purpose = 'ElasticIP';
}
if ($pv->isstaticnat && $pv->issystem) {
$pv->purpose = 'PublicIP';
}
$item = array('ipId' => $pv->id, 'dtAllocated' => $pv->allocated, 'networkName' => $pv->associatednetworkname, 'purpose' => $pv->purpose ? $pv->purpose : "Not used", 'ip' => $pv->ipaddress, 'state' => $pv->state, 'instanceId' => $pv->virtualmachineid, 'fullinfo' => $pv, 'farmId' => false);
if ($item['instanceId']) {
try {
$dbServer = DBServer::LoadByPropertyValue(CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID, $item['instanceId']);
$item['farmId'] = $dbServer->farmId;
$item['farmRoleId'] = $dbServer->farmRoleId;
$item['serverIndex'] = $dbServer->index;
$item['serverId'] = $dbServer->serverId;
$item['farmName'] = $dbServer->GetFarmObject()->Name;
$item['roleName'] = $dbServer->GetFarmRoleObject()->GetRoleObject()->name;
} catch (Exception $e) {
}
}
$ips[] = $item;
}
}
$response = $this->buildResponseFromData($ips, array('serverId', 'ipId', 'ip', 'farmId', 'farmRoleId'));
$this->response->data($response);
}
作者:sacredwebsit
项目:scal
public function xSaveAction()
{
$this->request->defineParams(array('members' => array('type' => 'array')));
$platformObject = PlatformFactory::NewPlatform($this->platform);
$request = array('pool_id' => $this->getParam('pool_id'), 'weight' => $this->getParam('weight'), 'protocol_port' => $this->getParam('protocol_port'), 'admin_state_up' => $this->getParam('admin_state_up'));
foreach ($this->getParam('members') as $memberId) {
$details = $this->getClient()->servers->getServerDetails($memberId);
$ips = $platformObject->determineServerIps($this->getClient(), $details);
$request['address'] = $ips['localIp'];
$this->getClient()->network->lbMembers->create($request);
}
$this->response->success('Member(s) successfully created');
}
作者:mheyd
项目:scal
protected function run2($stage)
{
$envIds = $this->db->GetCol('SELECT DISTINCT env_id FROM `comments` WHERE env_id > 0');
$this->console->out("Environments to process: " . count($envIds));
foreach ($envIds as $index => $envId) {
if ($this->db->GetOne('SELECT 1 FROM `security_group_rules_comments` WHERE env_id = ? LIMIT 1', array($envId))) {
$this->console->out("Skip environment #{$index}(" . $envId . ")");
continue;
}
try {
$env = \Scalr_Environment::init()->loadById($envId);
} catch (\Exception $e) {
continue;
}
$locations = PlatformFactory::NewPlatform(\SERVER_PLATFORMS::EC2)->getLocations($env);
$container = \Scalr::getContainer();
$container->environment = $env;
foreach ($locations as $location => $locatonName) {
try {
$sgList = $env->aws($location)->ec2->securityGroup->describe();
} catch (\Exception $e) {
continue 2;
}
/* @var $sg SecurityGroupData */
foreach ($sgList as $sg) {
$rules = array();
foreach ($sg->ipPermissions as $rule) {
/* @var $ipRange IpRangeData */
foreach ($rule->ipRanges as $ipRange) {
$rules[] = "{$rule->ipProtocol}:{$rule->fromPort}:{$rule->toPort}:{$ipRange->cidrIp}";
}
/* @var $group UserIdGroupPairData */
foreach ($rule->groups as $group) {
$ruleSg = $group->userId . '/' . ($group->groupName ? $group->groupName : $group->groupId);
$rules[] = "{$rule->ipProtocol}:{$rule->fromPort}:{$rule->toPort}:{$ruleSg}";
}
}
foreach ($rules as $rule) {
$comment = $this->db->GetOne('SELECT comment FROM `comments` WHERE env_id = ? AND sg_name = ? AND rule = ? LIMIT 1', array($envId, $sg->groupName, $rule));
if ($comment) {
try {
$this->db->Execute("\n INSERT IGNORE `security_group_rules_comments` (`env_id`, `platform`, `cloud_location`, `vpc_id`, `group_name`, `rule`, `comment`)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n ", array($env->id, \SERVER_PLATFORMS::EC2, $location, $sg->vpcId, $sg->groupName, $rule, $comment));
} catch (\Exception $e) {
}
}
}
}
}
$this->console->out("Environment processed: #{$index}(" . $envId . ")");
}
}
作者:rickb83
项目:scal
public function xGetMigrateDetailsAction()
{
if (!$this->request->getEnvironment()->isPlatformEnabled(SERVER_PLATFORMS::EC2)) {
throw new Exception('You can migrate image between regions only on EC2 cloud');
}
$platform = PlatformFactory::NewPlatform(SERVER_PLATFORMS::EC2);
$locationsList = $platform->getLocations($this->environment);
foreach ($locationsList as $location => $name) {
if ($location != $this->getParam('cloudLocation')) {
$availableDestinations[] = array('cloudLocation' => $location, 'name' => $name);
}
}
$this->response->data(array('sourceRegion' => $this->getParam('cloudLocation'), 'availableDestinations' => $availableDestinations, 'snapshotId' => $this->getParam('snapshotId')));
}
作者:mheyd
项目:scal
/**
* @test
* @dataProvider providerBlockDeviceByType
*
* @param string $instanceType
* @param array $expectedBlockDeviceConfiguration
*/
public function blockDevicesTest($instanceType, array $expectedBlockDeviceConfiguration)
{
/* @var $pm Ec2PlatformModule */
$pm = PlatformFactory::NewPlatform('ec2');
$reflection = new ReflectionClass(get_class($pm));
$method = $reflection->getMethod('GetBlockDeviceMapping');
$method->setAccessible(true);
/* @var $mapping BlockDeviceMappingData[] */
$mapping = $method->invoke($pm, $instanceType, '');
$this->assertEquals(count($expectedBlockDeviceConfiguration), count($mapping), "Wrong count");
foreach ($mapping as $num => $blockDevice) {
$this->assertTrue(isset($expectedBlockDeviceConfiguration[$num]), "Invalid device position");
$this->assertEquals($expectedBlockDeviceConfiguration[$num], $blockDevice->deviceName, "Device name mismatch");
}
}
作者:scal
项目:scal
protected function run1($stage)
{
$platform = SERVER_PLATFORMS::EC2;
$platformModule = PlatformFactory::NewPlatform($platform);
/* @var $platformModule Ec2PlatformModule*/
$instanceTypes = $platformModule->getInstanceTypes(null, null, true);
$result = $this->db->Execute("\n SELECT s.server_id, s.`type`, sp.`value` AS vcpus\n FROM servers AS s\n LEFT JOIN server_properties sp ON sp.`server_id`= s.`server_id` AND sp.`name` = ?\n WHERE s.`status` NOT IN (?, ?)\n AND s.`type` IS NOT NULL\n AND s.`platform` = ?\n ", [Server::INFO_INSTANCE_VCPUS, Server::STATUS_PENDING_TERMINATE, Server::STATUS_TERMINATED, $platform]);
while ($row = $result->FetchRow()) {
if (!empty($row["type"]) && empty($row['vcpus'])) {
if (isset($instanceTypes[$row['type']]['vcpus']) && $instanceTypes[$row['type']]['vcpus'] > 0) {
$this->db->Execute("\n INSERT INTO server_properties (`server_id`, `name`, `value`) VALUES (?, ?, ?)\n ON DUPLICATE KEY UPDATE `value` = ?\n ", [$row["server_id"], Server::INFO_INSTANCE_VCPUS, $instanceTypes[$row['type']]['vcpus'], $instanceTypes[$row['type']]['vcpus']]);
}
}
}
}