Пример #1
0
 /**
  * @test
  */
 public function testAppend()
 {
     $p = new Personality('/path', 'contents');
     $list = new PersonalityList(array($p, $p));
     $list->append($p);
     foreach ($list as $v) {
         $this->assertSame($p, $v);
     }
     $this->assertEquals('[{"path":"\\/path","contents":"contents"},{"path":"\\/path","contents":"contents"},{"path":"\\/path","contents":"contents"}]', $list->toJson());
 }
Пример #2
0
 /**
  * {@inheritdoc}
  * @see \Scalr\Modules\PlatformModuleInterface::LaunchServer()
  */
 public function LaunchServer(DBServer $DBServer, \Scalr_Server_LaunchOptions $launchOptions = null)
 {
     $config = \Scalr::getContainer()->config;
     $environment = $DBServer->GetEnvironmentObject();
     $governance = new \Scalr_Governance($environment->id);
     if (!$launchOptions) {
         $launchOptions = new \Scalr_Server_LaunchOptions();
         $DBRole = DBRole::loadById($DBServer->roleId);
         $launchOptions->imageId = $DBRole->getImageId($this->platform, $DBServer->GetCloudLocation());
         $launchOptions->serverType = $DBServer->GetFarmRoleObject()->GetSetting(\DBFarmRole::SETTING_OPENSTACK_FLAVOR_ID);
         $launchOptions->cloudLocation = $DBServer->GetFarmRoleObject()->CloudLocation;
         $launchOptions->userData = $DBServer->GetCloudUserData();
         $launchOptions->userData['platform'] = 'openstack';
         $launchOptions->userData['region'] = $launchOptions->cloudLocation;
         $launchOptions->networks = @json_decode($DBServer->GetFarmRoleObject()->GetSetting(\DBFarmRole::SETTING_OPENSTACK_NETWORKS));
         $gevernanceNetworks = $governance->getValue($this->platform, 'openstack.networks');
         if (count($launchOptions->networks) == 0 && $gevernanceNetworks) {
             $launchOptions->networks = $gevernanceNetworks[$launchOptions->cloudLocation];
         }
         foreach ($launchOptions->userData as $k => $v) {
             if (!$v) {
                 unset($launchOptions->userData[$k]);
             }
         }
         $launchOptions->architecture = 'x86_64';
         $isWindows = $DBServer->osType == 'windows' || $DBRole->osFamily == 'windows';
         if ($DBServer->GetFarmRoleObject()->GetSetting('openstack.boot_from_volume') == 1) {
             $deviceMapping = new \stdClass();
             $deviceMapping->device_name = 'vda';
             $deviceMapping->source_type = 'image';
             $deviceMapping->destination_type = 'volume';
             $deviceMapping->delete_on_termination = true;
             $deviceMapping->guest_format = null;
             $deviceMapping->volume_size = 10;
             $deviceMapping->uuid = $launchOptions->imageId;
             $deviceMapping->boot_index = 0;
         }
     } else {
         $launchOptions->userData = array();
         if (!$launchOptions->networks) {
             $launchOptions->networks = array();
         }
         $isWindows = $DBServer->osType == 'windows';
     }
     $client = $this->getOsClient($environment, $launchOptions->cloudLocation);
     // Prepare user data
     $u_data = "";
     foreach ($launchOptions->userData as $k => $v) {
         $u_data .= "{$k}={$v};";
     }
     $u_data = trim($u_data, ";");
     $personality = new PersonalityList();
     if ($isWindows) {
         $personality->append(new Personality('C:\\Program Files\\Scalarizr\\etc\\private.d\\.user-data', base64_encode($u_data)));
     } else {
         if ($DBServer->platform == \SERVER_PLATFORMS::ECS) {
             $personality->append(new Personality('/etc/.scalr-user-data', base64_encode($u_data)));
         } else {
             $personality->append(new Personality('/etc/scalr/private.d/.user-data', base64_encode($u_data)));
         }
     }
     //Check SecurityGroups
     $securityGroupsEnabled = $this->getConfigVariable(self::EXT_SECURITYGROUPS_ENABLED, $environment, false);
     $extProperties['security_groups'] = array();
     if ($securityGroupsEnabled) {
         $securityGroups = $this->GetServerSecurityGroupsList($DBServer, $client, $governance);
         foreach ($securityGroups as $sg) {
             $itm = new \stdClass();
             $itm->name = $sg;
             $extProperties['security_groups'][] = $itm;
         }
     }
     if ($deviceMapping) {
         $extProperties['block_device_mapping_v2'][] = $deviceMapping;
     }
     //Check key-pairs
     $keyPairsEnabled = $this->getConfigVariable(self::EXT_KEYPAIRS_ENABLED, $environment, false);
     if ($keyPairsEnabled === null || $keyPairsEnabled === false) {
         if ($client->servers->isExtensionSupported(ServersExtension::keypairs())) {
             $keyPairsEnabled = 1;
         } else {
             $keyPairsEnabled = 0;
         }
         $this->setConfigVariable(array(self::EXT_KEYPAIRS_ENABLED => $keyPairsEnabled), $environment, false);
     }
     if ($keyPairsEnabled) {
         $sshKey = \Scalr_SshKey::init();
         if ($DBServer->status == \SERVER_STATUS::TEMPORARY) {
             $keyName = "SCALR-ROLESBUILDER-" . SCALR_ID;
             $farmId = NULL;
         } else {
             $keyName = "FARM-{$DBServer->farmId}-" . SCALR_ID;
             $farmId = $DBServer->farmId;
         }
         if ($sshKey->loadGlobalByName($keyName, $launchOptions->cloudLocation, $DBServer->envId, \SERVER_PLATFORMS::OPENSTACK)) {
             $keyLoaded = true;
         }
         if (!$keyLoaded && !$sshKey->loadGlobalByName($keyName, $launchOptions->cloudLocation, $DBServer->envId, $DBServer->platform)) {
             $result = $client->servers->createKeypair($keyName);
             if ($result->private_key) {
                 $sshKey->farmId = $farmId;
                 $sshKey->envId = $DBServer->envId;
                 $sshKey->type = \Scalr_SshKey::TYPE_GLOBAL;
                 $sshKey->cloudLocation = $launchOptions->cloudLocation;
                 $sshKey->cloudKeyName = $keyName;
                 $sshKey->platform = $DBServer->platform;
                 $sshKey->setPrivate($result->private_key);
                 $sshKey->setPublic($result->public_key);
                 $sshKey->save();
             }
         }
         $extProperties['key_name'] = $keyName;
     }
     //TODO: newtorks
     $networks = new NetworkList();
     foreach ((array) $launchOptions->networks as $network) {
         if ($network) {
             $networks->append(new Network($network));
         }
     }
     $osUserData = null;
     $osPersonality = null;
     $userDataMethod = $config->defined("scalr.{$this->platform}.user_data_method") ? $config("scalr.{$this->platform}.user_data_method") : null;
     if (!$userDataMethod || $userDataMethod == 'both' || $userDataMethod == 'personality') {
         $osPersonality = $personality;
     }
     if (!$userDataMethod || $userDataMethod == 'both' || $userDataMethod == 'meta-data' || $isWindows) {
         $osUserData = $launchOptions->userData;
     }
     try {
         $result = $client->servers->createServer($DBServer->serverId, $launchOptions->serverType, $launchOptions->imageId, null, $osUserData, $osPersonality, $networks, $extProperties);
         $DBServer->SetProperties([\OPENSTACK_SERVER_PROPERTIES::SERVER_ID => $result->id, \OPENSTACK_SERVER_PROPERTIES::IMAGE_ID => $launchOptions->imageId, \OPENSTACK_SERVER_PROPERTIES::FLAVOR_ID => $launchOptions->serverType, \OPENSTACK_SERVER_PROPERTIES::ADMIN_PASS => $result->adminPass, \OPENSTACK_SERVER_PROPERTIES::NAME => $DBServer->serverId, \SERVER_PROPERTIES::ARCHITECTURE => $launchOptions->architecture, \OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION => $launchOptions->cloudLocation, \SERVER_PROPERTIES::SYSTEM_USER_DATA_METHOD => $userDataMethod]);
         if ($DBServer->farmRoleId) {
             $ipPool = $DBServer->GetFarmRoleObject()->GetSetting(\DBFarmRole::SETTING_OPENSTACK_IP_POOL);
             if ($ipPool) {
                 $DBServer->SetProperty(\SERVER_PROPERTIES::SYSTEM_IGNORE_INBOUND_MESSAGES, 1);
             }
         }
         $DBServer->osType = $isWindows ? 'windows' : 'linux';
         $DBServer->cloudLocation = $launchOptions->cloudLocation;
         $DBServer->cloudLocationZone = "";
         // Not supported by openstack
         return $DBServer;
     } catch (\Exception $e) {
         if (stripos($e->getMessage(), 'Invalid key_name provided')) {
             $sshKey->delete();
             throw new \Exception(sprintf(_("Cannot launch new instance: KeyPair was removed from cloud. Re-generating it."), $e->getMessage()));
         }
         throw new \Exception(sprintf(_("Cannot launch new instance. %s"), $e->getMessage()));
     }
 }
Пример #3
0
 /**
  * @test
  * @dataProvider providerRs
  * @functional
  */
 public function testFunctionalOpenStack($platform, $region, $imageId)
 {
     if ($platform === self::EMPTY_CONFIG) {
         $this->markTestSkipped();
     }
     /* @var $rs OpenStack */
     if ($this->getContainer()->environment->isPlatformEnabled($platform)) {
         $rs = $this->getContainer()->openstack($platform, $region);
         //$rs->setDebug();
         $this->assertInstanceOf($this->getOpenStackClassName('OpenStack'), $rs);
     } else {
         //Environment has not been activated yet.
         $this->markTestSkipped(sprintf('Environment for the "%s" platform has not been activated.', $platform));
     }
     $os = $this->getContainer()->openstack($platform, 'INVALID-REGION-TEST');
     try {
         $ext = $os->servers->listExtensions();
         unset($os);
         $this->assertTrue(false, 'An exception must be thrown in this test');
     } catch (OpenStackException $e) {
         $this->assertTrue(true);
     }
     unset($os);
     // security groups test
     $sgTestName = self::getTestName(self::NAME_SECURITY_GROUP);
     $listSecurityGroups = $rs->listSecurityGroups();
     $this->assertTrue($listSecurityGroups instanceof \ArrayIterator);
     foreach ($listSecurityGroups as $v) {
         if ($v->name == self::getTestName('security-group')) {
             $rs->deleteSecurityGroup($v->id);
         }
     }
     unset($listSecurityGroups);
     //Create security group test
     $sg = $rs->createSecurityGroup($sgTestName, 'phpunit test security group');
     $this->assertNotEmpty($sg);
     $this->assertInternalType('object', $sg);
     $this->assertNotEmpty($sg->id);
     $this->assertEquals($sgTestName, $sg->name);
     $this->assertNotEmpty($sg->description);
     $ruleToAdd = ["security_group_id" => $sg->id, "protocol" => 'tcp', "remote_group_id" => $sg->id, "direction" => "ingress", "port_range_max" => null, "port_range_min" => null];
     //Add a new rule to security group
     $rule = $rs->createSecurityGroupRule($ruleToAdd);
     $this->assertNotEmpty($rule);
     $this->assertNotEmpty($rule->id);
     $this->assertInternalType('object', $rule);
     //Removes rule
     $ret = $rs->deleteSecurityGroupRule($rule->id);
     $this->assertTrue($ret);
     //Delete security group test
     $ret = $rs->deleteSecurityGroup($sg->id);
     $this->assertTrue($ret);
     unset($sg);
     //Pagination test
     $list = $rs->servers->listImages(true, array('limit' => 10));
     $this->assertInstanceOf(self::ABSTRACT_PAGINATION_CLASS, $list);
     do {
         foreach ($list as $image) {
             $this->assertNotEmpty($image->id);
         }
     } while (false !== ($list = $list->getNextPage()));
     $one = $rs->servers;
     $this->assertInstanceOf($this->getOpenStackClassName('Services\\ServersService'), $one);
     $two = $rs->servers;
     $this->assertInstanceOf($this->getOpenStackClassName('Services\\ServersService'), $two);
     $this->assertSame($one, $two, 'Service interface is expected to be cached within each separate OpenStack instance.');
     $aZones = $rs->listZones();
     $this->assertNotEmpty($aZones);
     unset($aZones);
     //List tenants test
     //IMPORTANT: It does not work with API v3
     //$tenants = $rs->listTenants();
     //$this->assertNotEmpty($tenants);
     //$this->assertTrue(is_array($tenants));
     //unset($tenants);
     //Get Limits test
     $limits = $rs->servers->getLimits();
     $this->assertTrue(is_object($limits));
     unset($limits);
     $aExtensions = $rs->servers->listExtensions();
     $this->assertTrue(is_array($aExtensions));
     unset($aExtensions);
     $aExtensions = $rs->volume->listExtensions();
     $this->assertTrue(is_array($aExtensions));
     unset($aExtensions);
     $hasNetwork = $rs->hasService(OpenStack::SERVICE_NETWORK);
     if ($hasNetwork) {
         $aExtensions = $rs->network->listExtensions();
         $this->assertTrue(is_array($aExtensions));
         unset($aExtensions);
         //Quantum API tests
         $testNetworkName = self::getTestName(self::NAME_NETWORK);
         $testSubnetName = self::getTestName(self::NAME_SUBNET);
         $testPortName = self::getTestName(self::NAME_PORT);
         $testRouterName = self::getTestName(self::NAME_ROUTER);
         $testLbPoolName = self::getTestName(self::NAME_LB_POOL);
         $testLbVipName = self::getTestName(self::NAME_LB_VIP);
         //ListNetworks test
         $networks = $rs->network->networks->list(null, array('status' => 'ACTIVE', 'shared' => false));
         $this->assertTrue($networks instanceof \ArrayIterator);
         if (isset($networks[0])) {
             $this->assertInternalType('object', $networks[0]);
             $this->assertNotEmpty($networks[0]->id);
             //Show Network test
             $network = $rs->network->networks->list($networks[0]->id);
             $this->assertEquals($networks[0], $network);
             unset($network);
         }
         $publicNetworkId = null;
         foreach ($networks as $network) {
             if ($network->{"router:external"} == true) {
                 $publicNetworkId = $network->id;
             }
         }
         unset($networks);
         if (empty($publicNetworkId)) {
             $networks = $rs->network->networks->list();
             foreach ($networks as $network) {
                 if ($network->shared == true && $network->status == 'ACTIVE') {
                     $publicNetworkId = $network->id;
                     break;
                 }
             }
             unset($networks);
         }
         $this->assertNotEmpty($publicNetworkId, 'Could not find public network to continue.');
         //ListSubnets test
         $subnets = $rs->network->subnets->list();
         $this->assertTrue($subnets instanceof \ArrayIterator);
         if (isset($subnets[0])) {
             $this->assertInternalType('object', $subnets[0]);
             $this->assertNotEmpty($subnets[0]->id);
             //Show Subnet test
             $subnet = $rs->network->subnets->list($subnets[0]->id);
             $this->assertEquals($subnets[0], $subnet);
             unset($subnet);
         }
         unset($subnets);
         //ListPorts test
         $ports = $rs->network->ports->list();
         $this->assertTrue($ports instanceof \ArrayIterator);
         if (isset($ports[0])) {
             $this->assertInternalType('object', $ports[0]);
             $this->assertNotEmpty($ports[0]->id);
             //Show Port test
             $port = $rs->network->ports->list($ports[0]->id);
             $this->assertEquals($ports[0], $port);
             unset($port);
         }
         unset($ports);
         if ($rs->network->isExtensionSupported(NetworkExtension::loadbalancingService())) {
             //Removes previously created LBaaS VIP if it exists
             $lbVips = $rs->network->lbVips->list(null, array('name' => $testLbVipName));
             foreach ($lbVips as $lbVip) {
                 $ret = $rs->network->lbVips->delete($lbVip->id);
                 $this->assertTrue($ret, 'Could not remove previously created Load balancer VIP (id:' . $lbVip->id . ').');
             }
             $this->assertTrue($lbVips instanceof \ArrayIterator);
             unset($lbVips);
             //Removes previously created pools if they exist.
             $lbPools = $rs->network->lbPools->list(null, array('name' => $testLbPoolName));
             $this->assertTrue($lbPools instanceof \ArrayIterator);
             foreach ($lbPools as $lbPool) {
                 if (!empty($lbPool->health_monitors)) {
                     foreach ($lbPool->health_monitors as $healthMonitorId) {
                         //Removes previously associated health monitors with test pools
                         $ret = $rs->network->lbPools->disassociateHealthMonitor($lbPool->id, $healthMonitorId);
                         $this->assertTrue($ret);
                         $ret = $rs->network->lbHealthMonitors->delete($healthMonitorId);
                         $this->assertTrue($ret);
                     }
                 }
                 if (!empty($lbPool->members)) {
                     foreach ($lbPool->members as $memberId) {
                         //Remove previously created members
                         $ret = $rs->network->lbMembers->delete($memberId);
                         $this->assertTrue($ret, 'Could not remove previously created LBaas member (id:' . $memberId . ').');
                     }
                 }
                 $ret = $rs->network->lbPools->delete($lbPool->id);
                 $this->assertTrue($ret, 'Could not remove previously created LBaaS pool.');
             }
             unset($lbPools);
         }
         //Tries to find the ports which have been created recently by this test
         $ports = $rs->network->ports->list(null, array('name' => array($testPortName, $testPortName . '1')));
         foreach ($ports as $port) {
             //Removes previously created ports
             $rs->network->ports->delete($port->id);
         }
         unset($ports);
         //Tries to find the networks that have been created recently by this test
         $networks = $rs->network->networks->list(null, array('name' => $testNetworkName));
         foreach ($networks as $network) {
             //Removes previously created networks
             $rs->network->networks->update($network->id, null, false);
             //Trying to remove allocated ports
             $portsToRemove = $rs->network->ports->list(null, array('networkId' => $network->id));
             foreach ($portsToRemove as $p) {
                 if (isset($p->device_owner) && isset($p->device_id) && $p->device_owner == 'network:router_interface') {
                     $rs->network->ports->update($p->id, array('admin_state_up' => false));
                     $rs->network->routers->removeInterface($p->device_id, null, $p->id);
                 }
             }
             $rs->network->networks->delete($network->id);
         }
         unset($networks);
         //Tries to find the subnets that where created by this test but hadn't been removed yet.
         $subnets = $rs->network->subnets->list(null, array('name' => array($testSubnetName, $testSubnetName . '1')));
         $this->assertTrue($subnets instanceof \ArrayIterator);
         foreach ($subnets as $subnet) {
             //Removes previously created subnets
             $rs->network->subnets->delete($subnet->id);
         }
         //Creates new network
         $network = $rs->network->networks->create($testNetworkName, false, false);
         $this->assertInternalType('object', $network);
         $this->assertNotEmpty($network->id);
         $this->assertEquals(false, $network->admin_state_up);
         $this->assertEquals(false, $network->shared);
         //Updates newtork state
         $network = $rs->network->networks->update($network->id, null, true);
         $this->assertInternalType('object', $network);
         $this->assertEquals(true, $network->admin_state_up);
         //Creates subnet
         $subnet = $rs->network->subnets->create(array('network_id' => $network->id, 'cidr' => self::SUBNET_CIDR, 'name' => $testSubnetName));
         $this->assertInternalType('object', $subnet);
         $this->assertEquals($testSubnetName, $subnet->name);
         $this->assertNotEmpty($subnet->id);
         //Updates the subnet
         $subnet = $rs->network->subnets->update($subnet->id, array('name' => $testSubnetName . '1'));
         $this->assertInternalType('object', $subnet);
         $this->assertNotEmpty($subnet->name);
         $this->assertEquals($testSubnetName . '1', $subnet->name);
         //Load Balancing Service (LBaaS) tests
         if ($rs->network->isExtensionSupported(NetworkExtension::loadbalancingService())) {
             $this->assertNotEmpty($subnet->id, 'Subnet is needed to proceed.');
             //The tenant creates a pool, which is initially empty
             $lbPool = $rs->network->lbPools->create(array('subnet_id' => $subnet->id, 'lb_method' => 'ROUND_ROBIN', 'protocol' => 'TCP', 'name' => $testLbPoolName));
             $this->assertNotEmpty($lbPool);
             $this->assertInstanceOf('stdClass', $lbPool);
             $this->assertEquals($testLbPoolName, $lbPool->name);
             $this->assertNotEmpty($lbPool->id);
             //Tests update pool method
             $lbPool = $rs->network->lbPools->update($lbPool->id, array('name' => $testLbPoolName));
             $this->assertNotEmpty($lbPool);
             $this->assertInstanceOf('stdClass', $lbPool);
             $this->assertEquals($testLbPoolName, $lbPool->name);
             //The tenant creates one or several members in the pool
             $lbMember = $rs->network->lbMembers->create(array('pool_id' => $lbPool->id, 'protocol_port' => 8080, 'address' => self::LB_MEMBER_ADDRESS, 'weight' => 2));
             $this->assertNotEmpty($lbMember);
             $this->assertInternalType('object', $lbMember);
             $this->assertEquals($lbPool->id, $lbMember->pool_id);
             $this->assertTrue($lbMember->admin_state_up);
             //Tests update member method
             $lbMember = $rs->network->lbMembers->update($lbMember->id, array('weight' => 3));
             $this->assertNotEmpty($lbMember);
             $this->assertInternalType('object', $lbMember);
             $this->assertEquals(3, $lbMember->weight);
             //The tenant create one or several health monitors
             $lbHealthMonitor = $rs->network->lbHealthMonitors->create(array('delay' => 4, 'max_retries' => 3, 'type' => 'TCP', 'timeout' => 1));
             $this->assertNotEmpty($lbHealthMonitor);
             $this->assertInternalType('object', $lbHealthMonitor);
             $this->assertNotEmpty($lbHealthMonitor->id);
             $this->assertTrue($lbHealthMonitor->admin_state_up);
             $this->assertEquals(4, $lbHealthMonitor->delay);
             $this->assertEquals(3, $lbHealthMonitor->max_retries);
             $this->assertEquals('TCP', $lbHealthMonitor->type);
             $this->assertEquals(1, $lbHealthMonitor->timeout);
             //Tests update health monitor
             $lbHealthMonitor = $rs->network->lbHealthMonitors->update($lbHealthMonitor->id, array('max_retries' => 4));
             $this->assertNotEmpty($lbHealthMonitor);
             $this->assertInternalType('object', $lbHealthMonitor);
             $this->assertNotEmpty($lbHealthMonitor->id);
             $this->assertEquals(4, $lbHealthMonitor->max_retries);
             //The tenant associates the Health Monitors with the Pool
             $ret = $rs->network->lbPools->associateHealthMonitor($lbPool->id, $lbHealthMonitor->id);
             $this->assertInternalType('object', $ret);
             //Checks if health monitor is successfully associated
             $tmpPool = $rs->network->lbPools->list($lbPool->id);
             $this->assertNotEmpty($tmpPool);
             $this->assertInternalType('object', $tmpPool);
             $this->assertEquals($lbPool->id, $tmpPool->id);
             $this->assertNotEmpty($tmpPool->health_monitors);
             $this->assertContains($lbHealthMonitor->id, $tmpPool->health_monitors);
             $lbPool = $tmpPool;
             unset($tmpPool);
             //The tenant finally creates a VIP associated with the Pool
             $lbVip = $rs->network->lbVips->create(array('protocol' => 'TCP', 'protocol_port' => 8080, 'name' => $testLbVipName, 'subnet_id' => $subnet->id, 'pool_id' => $lbPool->id));
             $this->assertNotEmpty($lbVip);
             $this->assertInternalType('object', $lbVip);
             $this->assertEquals('TCP', $lbVip->protocol);
             $this->assertEquals(8080, $lbVip->protocol_port);
             $this->assertEquals($testLbVipName, $lbVip->name);
             $this->assertEquals($subnet->id, $lbVip->subnet_id);
             $this->assertEquals($lbPool->id, $lbVip->pool_id);
             //Tests update method
             $lbVip = $rs->network->lbVips->update($lbVip->id, array('name' => $testLbVipName));
             $this->assertNotEmpty($lbVip);
             $this->assertInternalType('object', $lbVip);
             sleep(1);
             //Deletes VIP
             $ret = $rs->network->lbVips->delete($lbVip->id);
             $this->assertTrue($ret);
             //Disassotiates the Health Monitors with the pool
             $ret = $rs->network->lbPools->disassociateHealthMonitor($lbPool->id, $lbHealthMonitor->id);
             $this->assertTrue($ret);
             //Checks if health monitor is successfully disassociated
             $tmpPool = $rs->network->lbPools->list($lbPool->id);
             $this->assertNotEmpty($tmpPool);
             $this->assertInternalType('object', $tmpPool);
             $this->assertEquals($lbPool->id, $tmpPool->id);
             $this->assertNotContains($lbHealthMonitor->id, $tmpPool->health_monitors);
             $lbPool = $tmpPool;
             unset($tmpPool);
             //Deletes LBaaS health monitor
             $ret = $rs->network->lbHealthMonitors->delete($lbHealthMonitor->id);
             $this->assertTrue($ret);
             //Delete LBaaS member
             $ret = $rs->network->lbMembers->delete($lbMember->id);
             $this->assertTrue($ret);
             //Delete LBaaS pool
             $ret = $rs->network->lbPools->delete($lbPool->id);
             $this->assertTrue($ret);
         }
         //Removes subnet
         $ret = $rs->network->subnets->delete($subnet->id);
         $this->assertTrue($ret);
         //Removes created network
         $rs->network->networks->update($network->id, null, false);
         $ret = $rs->network->networks->delete($network->id);
         $this->assertTrue($ret);
         unset($network);
         //Security group extension test
         if ($rs->network->isExtensionSupported(NetworkExtension::securityGroup())) {
             $sgTestName = self::getTestName(self::NAME_SECURITY_GROUP);
             //Removes previously created test security group if it actually exists
             $sgList = $rs->network->securityGroups->list(null, ['name' => $sgTestName]);
             $this->assertInstanceOf(self::ABSTRACT_PAGINATION_CLASS, $sgList);
             foreach ($sgList as $sg) {
                 $this->assertNotEmpty($sg->name);
                 $this->assertNotEmpty($sg->id);
                 if ($sg->name === $sgTestName) {
                     //Removes previously created test security group
                     $res = $rs->network->securityGroups->delete($sg->id);
                     $this->assertTrue($res);
                 }
             }
             unset($sgList);
             //List Security groups test
             $sgList = $rs->network->securityGroups->list();
             $this->assertInstanceOf(self::ABSTRACT_PAGINATION_CLASS, $sgList);
             unset($sgList);
             //Create security group test
             $sg = $rs->network->securityGroups->create($sgTestName, 'phpunit test security group');
             $this->assertNotEmpty($sg);
             $this->assertInternalType('object', $sg);
             $this->assertNotEmpty($sg->id);
             $this->assertEquals($sgTestName, $sg->name);
             $this->assertNotEmpty($sg->description);
             //Update security group test
             //ListRules test
             //Gets the rules set for the created security group
             $rulesList = $rs->network->securityGroups->listRules(null, ['securityGroupId' => $sg->id]);
             $this->assertInstanceOf(self::ABSTRACT_PAGINATION_CLASS, $rulesList);
             if (count($rulesList)) {
                 //Some providers have default rules out from the box
                 foreach ($rulesList as $r) {
                     //Removing default rules
                     $rs->network->securityGroups->deleteRule($r->id);
                 }
             }
             $ruleToAdd = ["security_group_id" => $sg->id, "remote_group_id" => null, "direction" => "ingress", "remote_ip_prefix" => "0.0.0.0/0", "port_range_max" => null, "port_range_min" => null];
             //Add a new rule to security group
             $rule = $rs->network->securityGroups->addRule($ruleToAdd);
             $this->assertNotEmpty($rule);
             $this->assertNotEmpty($rule->id);
             $this->assertInternalType('object', $rule);
             //Verifies that all properties are set properly
             foreach ($ruleToAdd as $property => $value) {
                 $this->assertObjectHasAttribute($property, $rule);
                 $this->assertEquals($value, $rule->{$property});
             }
             //Checks that new rule does exist
             $rulesList = $rs->network->securityGroups->listRules(null, ['securityGroupId' => $sg->id]);
             $this->assertEquals(1, count($rulesList));
             unset($rulesList);
             //Removes rule
             $ret = $rs->network->securityGroups->deleteRule($rule->id);
             $this->assertTrue($ret);
             //Checks whether rule is removed properly
             $rulesList = $rs->network->securityGroups->listRules(null, ['securityGroupId' => $sg->id]);
             $this->assertEquals(0, count($rulesList));
             unset($rulesList);
             //Delete security group test
             $ret = $rs->network->securityGroups->delete($sg->id);
             $this->assertTrue($ret);
             unset($sg);
         }
     }
     //List snapshots test
     $snList = $rs->volume->snapshots->list();
     $this->assertTrue($snList instanceof \ArrayIterator);
     foreach ($snList as $v) {
         if ($v->display_name == self::getTestSnapshotName()) {
             $rs->volume->snapshots->delete($v->id);
         }
     }
     unset($snList);
     //List Volume Types test
     $volumeTypes = $rs->volume->listVolumeTypes();
     $this->assertTrue($volumeTypes instanceof \ArrayIterator);
     foreach ($volumeTypes as $v) {
         $volumeTypeDesc = $rs->volume->getVolumeType($v->id);
         $this->assertTrue(is_object($volumeTypeDesc));
         unset($volumeTypeDesc);
         break;
     }
     //List Volumes test
     $aVolumes = $rs->volume->listVolumes();
     $this->assertTrue($aVolumes instanceof \ArrayIterator);
     foreach ($aVolumes as $v) {
         if ($v->display_name == self::getTestVolumeName()) {
             if (in_array($v->status, array(VolumeStatus::STATUS_AVAILABLE, VolumeStatus::STATUS_ERROR))) {
                 $ret = $rs->volume->deleteVolume($v->id);
             }
         }
     }
     //Create Volume test
     $volume = $rs->volume->createVolume(self::VOLUME_SIZE, self::getTestVolumeName());
     $this->assertTrue(is_object($volume));
     $this->assertNotEmpty($volume->id);
     for ($t = time(), $s = 1; time() - $t < 300 && !in_array($volume->status, array(VolumeStatus::STATUS_AVAILABLE, VolumeStatus::STATUS_ERROR)); $s += 5) {
         sleep($s);
         $volume = $rs->volume->getVolume($volume->id);
         $this->assertTrue(is_object($volume));
         $this->assertNotEmpty($volume->id);
     }
     $this->assertContains($volume->status, array(VolumeStatus::STATUS_AVAILABLE, VolumeStatus::STATUS_ERROR));
     //         //Create snapshot test
     //         //WARNING! It takes too long time.
     //         $snap = $rs->volume->snapshots->create($volume->id, self::getTestSnapshotName());
     //         $this->assertTrue(is_object($snap));
     //         $this->assertNotEmpty($snap->id);
     //         for ($t = time(), $s = 1; (time() - $t) < 600 && !in_array($snap->status, array('available', 'error')); $s += 5) {
     //             sleep($s);
     //             $snap = $rs->volume->snapshots->get($snap->id);
     //             $this->assertNotEmpty($snap->id);
     //         }
     //         $this->assertContains($snap->status, array('available', 'error'));
     //         //Delete snapshot test
     //         $ret = $rs->volume->snapshots->delete($snap->id);
     //         $this->assertTrue($ret);
     //         unset($snap);
     //         sleep(5);
     //Delete Volume test
     $ret = $rs->volume->deleteVolume($volume->id);
     $this->assertTrue($ret);
     unset($volume);
     sleep(5);
     $pool = null;
     if ($rs->servers->isExtensionSupported(ServersExtension::floatingIpPools())) {
         $aFloatingIpPools = $rs->servers->listFloatingIpPools();
         $this->assertTrue($aFloatingIpPools instanceof \ArrayIterator);
         foreach ($aFloatingIpPools as $v) {
             $pool = $v->name;
             break;
         }
         $this->assertNotNull($pool);
         unset($aFloatingIpPools);
     }
     if ($rs->servers->isExtensionSupported(ServersExtension::floatingIps())) {
         $this->assertNotNull($pool);
         $aFloatingIps = $rs->servers->floatingIps->list();
         $this->assertTrue($aFloatingIps instanceof \ArrayIterator);
         foreach ($aFloatingIps as $v) {
             $r = $rs->servers->floatingIps->get($v->id);
             $this->assertTrue(is_object($r));
             break;
         }
         unset($aFloatingIps);
         //default pool for rackspase is 'nova'
         $fip = $rs->servers->floatingIps->create($pool);
         $this->assertTrue(is_object($fip));
         $r = $rs->servers->floatingIps->delete($fip->id);
         $this->assertTrue($r);
         try {
             //Verifies that ip has been successfully removed
             $res = $rs->servers->floatingIps->get($fip->id);
             $this->assertTrue(false, 'Exception must be thrown here');
         } catch (RestClientException $e) {
             if ($e->error->code == 404) {
                 $this->assertTrue(true);
             } else {
                 //OpenStack Grizzly fails with 500 error code.
                 //throw $e;
             }
         }
         unset($fip);
     }
     //List flavors test
     $flavorsList = $listFlavors = $rs->servers->listFlavors();
     $this->assertTrue($flavorsList instanceof \ArrayIterator);
     $flavorId = null;
     foreach ($flavorsList as $v) {
         $flavorId = $v->id;
         break;
     }
     $this->assertNotNull($flavorId);
     unset($flavorsList);
     //List servers test
     $ret = $rs->servers->list();
     if (!empty($ret) && $ret->count()) {
         foreach ($ret as $v) {
             if ($v->name == self::getTestServerName() || $v->name == self::getTestServerName('renamed')) {
                 //Removes servers
                 try {
                     $rs->servers->deleteServer($v->id);
                 } catch (RestClientException $e) {
                     echo $e->getMessage() . "\n";
                 }
             }
         }
     }
     $personality = new PersonalityList();
     $personality->append(new Personality('/etc/scalr/private.d/.user-data', base64_encode('super data')));
     $personality->append(new Personality('/etc/.scalr-user-data', base64_encode('super data')));
     $netList = null;
     //Create server test
     $srv = $rs->servers->createServer(self::getTestServerName(), $flavorId, $imageId, null, null, $personality, $netList);
     $this->assertInstanceOf('stdClass', $srv);
     $srv = $rs->servers->getServerDetails($srv->id);
     $this->assertInstanceOf('stdClass', $srv);
     $this->assertNotEmpty($srv->status);
     for ($t = time(), $s = 10; time() - $t < 600 && !in_array($srv->status, array('ACTIVE', 'ERROR')); $s += 1) {
         sleep($s);
         $srv = $rs->servers->getServerDetails($srv->id);
     }
     $this->assertContains($srv->status, array('ACTIVE', 'ERROR'));
     if ($rs->servers->isExtensionSupported(ServersExtension::consoleOutput())) {
         $consoleOut = $rs->servers->getConsoleOutput($srv->id, 50);
     }
     //List Addresses test
     $addresses = $rs->servers->listAddresses($srv->id);
     $this->assertTrue(is_object($addresses));
     //Get server details test
     $srvDetails = $rs->servers->getServerDetails($srv->id);
     $this->assertInstanceOf('stdClass', $srvDetails);
     unset($srvDetails);
     //Images List test
     $imagesList = $rs->servers->images->list();
     $this->assertTrue($imagesList instanceof DefaultPaginationList);
     foreach ($imagesList as $img) {
         if ($img->name == self::getTestName('image')) {
             $rs->servers->images->delete($img->id);
         }
         $imageDetails = $rs->servers->images->get($img->id);
         $this->assertTrue(is_object($imageDetails));
         unset($imageDetails);
         break;
     }
     unset($imagesList);
     //Keypairs extension test
     if ($rs->servers->isExtensionSupported(ServersExtension::keypairs())) {
         $aKeypairs = $rs->servers->keypairs->list();
         $this->assertTrue($aKeypairs instanceof \ArrayIterator);
         foreach ($aKeypairs as $v) {
             if ($v->keypair->name == self::getTestName('key')) {
                 $rs->servers->keypairs->delete($v->keypair->name);
             }
         }
         unset($aKeypairs);
         $kp = $rs->servers->keypairs->create(self::getTestName('key'));
         $this->assertNotEmpty($kp);
         $this->assertTrue(is_object($kp));
         $kptwin = $rs->servers->keypairs->get($kp->name);
         $this->assertNotEmpty($kptwin);
         $this->assertEquals($kp->public_key, $kptwin->public_key);
         unset($kptwin);
         $res = $rs->servers->keypairs->delete($kp->name);
         $this->assertTrue($res);
         unset($kp);
     }
     //Security Groups extension test
     if ($rs->servers->isExtensionSupported(ServersExtension::securityGroups())) {
         $listSecurityGroups = $rs->servers->securityGroups->list();
         $this->assertTrue($listSecurityGroups instanceof \ArrayIterator);
         foreach ($listSecurityGroups as $v) {
             if ($v->name == self::getTestName('security-group')) {
                 $rs->servers->securityGroups->delete($v->id);
             }
         }
         unset($listSecurityGroups);
         $listForSpecificServer = $rs->servers->securityGroups->list($srv->id);
         $this->assertTrue(is_array($listForSpecificServer) || $listForSpecificServer instanceof \ArrayIterator);
         unset($listForSpecificServer);
         $sg = $rs->servers->securityGroups->create(self::getTestName('security-group'), 'This is phpunit security group test.');
         $this->assertNotEmpty($sg);
         $this->assertTrue(is_object($sg));
         $sgmirror = $rs->servers->securityGroups->get($sg->id);
         $this->assertNotEmpty($sgmirror);
         $this->assertEquals($sg->id, $sgmirror->id);
         unset($sgmirror);
         $sgrule = $rs->servers->securityGroups->addRule(array("ip_protocol" => "tcp", "from_port" => "80", "to_port" => "8080", "cidr" => "0.0.0.0/0", "parent_group_id" => $sg->id));
         $this->assertNotEmpty($sgrule);
         $this->assertTrue(is_object($sgrule));
         $this->assertEquals($sg->id, $sgrule->parent_group_id);
         $ret = $rs->servers->securityGroups->deleteRule($sgrule->id);
         $this->assertTrue($ret);
         unset($sgrule);
         $ret = $rs->servers->securityGroups->delete($sg->id);
         $this->assertTrue($ret);
     }
     //Create image test
     $imageId = $rs->servers->images->create($srv->id, self::getTestName('image'));
     $this->assertTrue(is_string($imageId));
     //It requires ACTIVE state of the server
     //         $res = $rs->servers->resizeServer($srv->id, $srv->name, '3');
     //         $this->assertTrue($res);
     //         $res = $rs->servers->confirmResizedServer($srv->id);
     //         $this->assertTrue($res);
     $ret = $rs->servers->images->delete($imageId);
     $this->assertTrue($ret);
     //Update server test
     $renamedDetails = $rs->servers->updateServer($srv->id, self::getTestServerName('renamed'));
     $this->assertInstanceOf('stdClass', $renamedDetails);
     $this->assertEquals(self::getTestServerName('renamed'), $renamedDetails->server->name);
     unset($renamedDetails);
     //Delete Server test
     $ret = $rs->servers->deleteServer($srv->id);
     $this->assertTrue($ret);
 }
Пример #4
0
 /**
  * {@inheritdoc}
  * @see \Scalr\Modules\PlatformModuleInterface::LaunchServer()
  */
 public function LaunchServer(DBServer $DBServer, \Scalr_Server_LaunchOptions $launchOptions = null)
 {
     $config = \Scalr::getContainer()->config;
     $environment = $DBServer->GetEnvironmentObject();
     $governance = new \Scalr_Governance($environment->id);
     if (!$launchOptions) {
         $launchOptions = new \Scalr_Server_LaunchOptions();
         $DBRole = $DBServer->GetFarmRoleObject()->GetRoleObject();
         $launchOptions->imageId = $DBRole->__getNewRoleObject()->getImage($this->platform, $DBServer->GetCloudLocation())->imageId;
         $launchOptions->serverType = $DBServer->GetFarmRoleObject()->GetSetting(Entity\FarmRoleSetting::OPENSTACK_FLAVOR_ID);
         $launchOptions->cloudLocation = $DBServer->GetFarmRoleObject()->CloudLocation;
         $launchOptions->userData = $DBServer->GetCloudUserData();
         $launchOptions->userData['region'] = $launchOptions->cloudLocation;
         $launchOptions->userData['platform'] = 'openstack';
         $launchOptions->networks = @json_decode($DBServer->GetFarmRoleObject()->GetSetting(Entity\FarmRoleSetting::OPENSTACK_NETWORKS));
         $gevernanceNetworks = $governance->getValue($this->platform, 'openstack.networks');
         if (count($launchOptions->networks) == 0 && $gevernanceNetworks) {
             $launchOptions->networks = $gevernanceNetworks[$launchOptions->cloudLocation];
         }
         foreach ($launchOptions->userData as $k => $v) {
             if (!$v) {
                 unset($launchOptions->userData[$k]);
             }
         }
         $launchOptions->architecture = 'x86_64';
         $isWindows = $DBServer->osType == 'windows' || $DBRole->getOs()->family == 'windows';
         if ($DBServer->GetFarmRoleObject()->GetSetting('openstack.boot_from_volume') == 1) {
             $deviceMapping = new \stdClass();
             $deviceMapping->device_name = 'vda';
             $deviceMapping->source_type = 'image';
             $deviceMapping->destination_type = 'volume';
             $deviceMapping->delete_on_termination = true;
             $deviceMapping->guest_format = null;
             $deviceMapping->volume_size = 10;
             $deviceMapping->uuid = $launchOptions->imageId;
             $deviceMapping->boot_index = 0;
         }
         $customUserData = $DBServer->GetFarmRoleObject()->GetSetting('base.custom_user_data');
         $serverNameFormat = $governance->getValue($DBServer->platform, \Scalr_Governance::OPENSTACK_INSTANCE_NAME_FORMAT);
         if (!$serverNameFormat) {
             $serverNameFormat = $DBServer->GetFarmRoleObject()->GetSetting(\Scalr_Role_Behavior::ROLE_INSTANCE_NAME_FORMAT);
         }
         // Availability zone
         $launchOptions->availZone = $this->GetServerAvailZone($DBServer, $this->getOsClient($environment, $launchOptions->cloudLocation), $launchOptions);
     } else {
         $launchOptions->availZone = null;
         $launchOptions->userData = array();
         $customUserData = false;
         if (!$launchOptions->networks) {
             $launchOptions->networks = array();
         }
         $isWindows = $DBServer->osType == 'windows';
     }
     $client = $this->getOsClient($environment, $launchOptions->cloudLocation);
     // Prepare user data
     $u_data = "";
     foreach ($launchOptions->userData as $k => $v) {
         $u_data .= "{$k}={$v};";
     }
     $u_data = trim($u_data, ";");
     if ($customUserData) {
         $repos = $DBServer->getScalarizrRepository();
         $extProperties["user_data"] = base64_encode(str_replace(array('{SCALR_USER_DATA}', '{RPM_REPO_URL}', '{DEB_REPO_URL}'), array($u_data, $repos['rpm_repo_url'], $repos['deb_repo_url']), $customUserData));
     }
     $personality = new PersonalityList();
     if ($isWindows) {
         $personality->append(new Personality('C:\\Program Files\\Scalarizr\\etc\\private.d\\.user-data', base64_encode($u_data)));
     } else {
         $personality->append(new Personality('/etc/scalr/private.d/.user-data', base64_encode($u_data)));
     }
     /* @var $ccProps SettingsCollection */
     $ccProps = $environment->cloudCredentials($this->platform)->properties;
     //Check SecurityGroups
     $securityGroupsEnabled = $ccProps[Entity\CloudCredentialsProperty::OPENSTACK_EXT_SECURITYGROUPS_ENABLED];
     $extProperties['security_groups'] = array();
     if ($securityGroupsEnabled) {
         $securityGroups = $this->GetServerSecurityGroupsList($DBServer, $client, $governance);
         foreach ($securityGroups as $sg) {
             $itm = new \stdClass();
             $itm->name = $sg;
             $extProperties['security_groups'][] = $itm;
         }
     }
     if ($launchOptions->availZone) {
         $extProperties['availability_zone'] = $launchOptions->availZone;
     }
     if ($deviceMapping) {
         $extProperties['block_device_mapping_v2'][] = $deviceMapping;
     }
     //Check key-pairs
     $keyPairsEnabled = $ccProps[Entity\CloudCredentialsProperty::OPENSTACK_EXT_KEYPAIRS_ENABLED];
     if ($keyPairsEnabled === null || $keyPairsEnabled === false) {
         if ($client->servers->isExtensionSupported(ServersExtension::EXT_KEYPAIRS)) {
             $keyPairsEnabled = 1;
         } else {
             $keyPairsEnabled = 0;
         }
         $ccProps->saveSettings([Entity\CloudCredentialsProperty::OPENSTACK_EXT_KEYPAIRS_ENABLED => $keyPairsEnabled]);
     }
     //Check config-drive
     $configDriveEnabled = $ccProps[Entity\CloudCredentialsProperty::OPENSTACK_EXT_CONFIG_DRIVE_ENABLED];
     if ($configDriveEnabled === null || $configDriveEnabled === false) {
         if ($client->servers->isExtensionSupported(ServersExtension::EXT_CONFIG_DRIVE)) {
             $configDriveEnabled = 1;
         } else {
             $configDriveEnabled = 0;
         }
         $ccProps->saveSettings([Entity\CloudCredentialsProperty::OPENSTACK_EXT_CONFIG_DRIVE_ENABLED => $configDriveEnabled]);
     }
     $extProperties['config_drive'] = $configDriveEnabled;
     if ($keyPairsEnabled) {
         if ($DBServer->status == \SERVER_STATUS::TEMPORARY) {
             $keyName = "SCALR-ROLESBUILDER-" . SCALR_ID;
             $farmId = NULL;
         } else {
             $keyName = "FARM-{$DBServer->farmId}-" . SCALR_ID;
             $farmId = $DBServer->farmId;
         }
         $sshKey = (new SshKey())->loadGlobalByName($DBServer->envId, \SERVER_PLATFORMS::OPENSTACK, $launchOptions->cloudLocation, $keyName);
         if (!$sshKey && !($sshKey = (new SshKey())->loadGlobalByName($DBServer->envId, $DBServer->platform, $launchOptions->cloudLocation, $keyName))) {
             $result = $client->servers->createKeypair($keyName);
             if ($result->private_key) {
                 $sshKey = new SshKey();
                 $sshKey->farmId = $farmId;
                 $sshKey->envId = $DBServer->envId;
                 $sshKey->type = SshKey::TYPE_GLOBAL;
                 $sshKey->platform = $DBServer->platform;
                 $sshKey->cloudLocation = $launchOptions->cloudLocation;
                 $sshKey->cloudKeyName = $keyName;
                 $sshKey->privateKey = $result->private_key;
                 $sshKey->publicKey = $result->public_key;
                 $sshKey->save();
             }
         }
         $extProperties['key_name'] = $keyName;
     }
     //TODO: newtorks
     $networks = new NetworkList();
     foreach ((array) $launchOptions->networks as $network) {
         if ($network) {
             $networks->append(new Network($network));
         }
     }
     $osUserData = null;
     $osPersonality = null;
     $userDataMethod = $config->defined("scalr.{$this->platform}.user_data_method") ? $config("scalr.{$this->platform}.user_data_method") : null;
     if (!$userDataMethod || $userDataMethod == 'both' || $userDataMethod == 'personality') {
         $osPersonality = $personality;
     }
     if (!$userDataMethod || $userDataMethod == 'both' || $userDataMethod == 'meta-data' || $isWindows) {
         $osUserData = $launchOptions->userData;
     }
     $serverName = $serverNameFormat ? $DBServer->applyGlobalVarsToValue($serverNameFormat) : $DBServer->serverId;
     try {
         $result = $client->servers->createServer($serverName, $launchOptions->serverType, $launchOptions->imageId, null, $osUserData, $osPersonality, $networks, $extProperties);
         $instanceTypeInfo = $this->getInstanceType($launchOptions->serverType, $environment, $launchOptions->cloudLocation);
         /* @var $instanceTypeInfo CloudInstanceType */
         $DBServer->SetProperties([\OPENSTACK_SERVER_PROPERTIES::SERVER_ID => $result->id, \OPENSTACK_SERVER_PROPERTIES::IMAGE_ID => $launchOptions->imageId, \OPENSTACK_SERVER_PROPERTIES::ADMIN_PASS => $launchOptions->userData['vzc.adminpassword'] ? $launchOptions->userData['vzc.adminpassword'] : $result->adminPass, \OPENSTACK_SERVER_PROPERTIES::NAME => $DBServer->serverId, \SERVER_PROPERTIES::ARCHITECTURE => $launchOptions->architecture, \OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION => $launchOptions->cloudLocation, \OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION_ZONE => $launchOptions->availZone, \SERVER_PROPERTIES::SYSTEM_USER_DATA_METHOD => $userDataMethod, \SERVER_PROPERTIES::INFO_INSTANCE_VCPUS => $instanceTypeInfo ? $instanceTypeInfo->vcpus : null]);
         if ($DBServer->farmRoleId) {
             $ipPool = $DBServer->GetFarmRoleObject()->GetSetting(Entity\FarmRoleSetting::OPENSTACK_IP_POOL);
             if ($ipPool) {
                 $DBServer->SetProperty(\SERVER_PROPERTIES::SYSTEM_IGNORE_INBOUND_MESSAGES, 1);
             }
         }
         $params = ['type' => $launchOptions->serverType];
         if ($instanceTypeInfo) {
             $params['instanceTypeName'] = $instanceTypeInfo->name;
         }
         $DBServer->setOsType($isWindows ? 'windows' : 'linux');
         $DBServer->cloudLocation = $launchOptions->cloudLocation;
         $DBServer->cloudLocationZone = $launchOptions->availZone;
         $DBServer->update($params);
         $DBServer->imageId = $launchOptions->imageId;
         // we set server history here
         $DBServer->getServerHistory();
         return $DBServer;
     } catch (\Exception $e) {
         if (stripos($e->getMessage(), 'Invalid key_name provided')) {
             $sshKey->delete();
             throw new \Exception(sprintf(_("Cannot launch new instance: KeyPair was removed from cloud. Re-generating it."), $e->getMessage()));
         }
         throw new \Exception(sprintf(_("Cannot launch new instance. %s"), $e->getMessage()));
     }
 }
Пример #5
0
 /**
  * @test
  * @dataProvider providerRs
  */
 public function testFunctionalOpenStack($platform, $region, $imageId)
 {
     if ($this->isSkipFunctionalTests() || $platform === self::EMPTY_CONFIG) {
         $this->markTestSkipped();
     }
     /* @var $rs OpenStack */
     if ($this->getContainer()->environment->isPlatformEnabled($platform)) {
         $rs = $this->getContainer()->openstack($platform, $region);
         //             $rs->setDebug();
         $this->assertInstanceOf($this->getOpenStackClassName('OpenStack'), $rs);
     } else {
         //Environment has not been activated yet.
         $this->markTestSkipped(sprintf('Environment for the "%s" platform has not been activated.', $platform));
     }
     $os = $this->getContainer()->openstack($platform, 'INVALID-REGION-TEST');
     try {
         $ext = $os->servers->listExtensions();
         unset($os);
         $this->assertTrue(false, 'An exception must be thrown in this test');
     } catch (OpenStackException $e) {
         $this->assertTrue(true);
     }
     unset($os);
     // security groups test
     $sgTestName = self::getTestName(self::NAME_SECURITY_GROUP);
     $listSecurityGroups = $rs->listSecurityGroups();
     $this->assertTrue($listSecurityGroups instanceof \ArrayIterator);
     foreach ($listSecurityGroups as $v) {
         if ($v->name == self::getTestName('security-group')) {
             $rs->deleteSecurityGroup($v->id);
         }
     }
     unset($listSecurityGroups);
     //Create security group test
     $sg = $rs->createSecurityGroup($sgTestName, 'phpunit test security group');
     $this->assertNotEmpty($sg);
     $this->assertInternalType('object', $sg);
     $this->assertNotEmpty($sg->id);
     $this->assertEquals($sgTestName, $sg->name);
     $this->assertNotEmpty($sg->description);
     $ruleToAdd = ["security_group_id" => $sg->id, "protocol" => 'tcp', "remote_group_id" => $sg->id, "direction" => "ingress", "port_range_max" => null, "port_range_min" => null];
     //Add a new rule to security group
     $rule = $rs->createSecurityGroupRule($ruleToAdd);
     $this->assertNotEmpty($rule);
     $this->assertNotEmpty($rule->id);
     $this->assertInternalType('object', $rule);
     //Removes rule
     $ret = $rs->deleteSecurityGroupRule($rule->id);
     $this->assertTrue($ret);
     //Delete security group test
     $ret = $rs->deleteSecurityGroup($sg->id);
     $this->assertTrue($ret);
     unset($sg);
     //Pagination test
     $list = $rs->servers->listImages(true, array('limit' => 10));
     $this->assertInstanceOf(self::ABSTRACT_PAGINATION_CLASS, $list);
     do {
         foreach ($list as $image) {
             $this->assertNotEmpty($image->id);
         }
     } while (false !== ($list = $list->getNextPage()));
     $one = $rs->servers;
     $this->assertInstanceOf($this->getOpenStackClassName('Services\\ServersService'), $one);
     $two = $rs->servers;
     $this->assertInstanceOf($this->getOpenStackClassName('Services\\ServersService'), $two);
     $this->assertSame($one, $two, 'Service interface is expected to be cached within each separate OpenStack instance.');
     $aZones = $rs->listZones();
     $this->assertNotEmpty($aZones);
     unset($aZones);
     //List tenants test
     $tenants = $rs->listTenants();
     $this->assertNotEmpty($tenants);
     $this->assertTrue(is_array($tenants));
     unset($tenants);
     //Contrail related tests
     if ($rs->hasService(OpenStack::SERVICE_CONTRAIL)) {
         //Look at SCALRCORE-726 for more info about Contrail responses
         $testFqName = self::getTestName(self::NAME_FQ);
         $testDomainName = self::getTestName(self::NAME_DOMAIN) . '.com';
         $testFqNetworkName = self::getTestName(self::NAME_FQ_NETWORK);
         $testNetworkPolicyName = self::getTestName(self::NAME_NETWORK_POLICY);
         $tenant = $rs->getConfig()->getTenantName();
         //Lists virtual networks
         $listVirtualNetworks = $rs->contrail->listVirtualNetworks();
         $this->assertTrue($listVirtualNetworks instanceof DefaultPaginationList, 'The list of virtual networks is expected to be DefaultPaginationList instance.');
         //Removes previously created test virtual networks
         foreach ($listVirtualNetworks as $v) {
             if (isset($v->fq_name) && is_array($v->fq_name) && in_array($testFqNetworkName, $v->fq_name)) {
                 $ret = $rs->contrail->deleteVirtualNetwork($v->uuid);
                 $this->assertTrue($ret);
             }
         }
         unset($listVirtualNetworks);
         //Describes network policies
         $listNetworkPolicies = $rs->contrail->listNetworkPolicies();
         $this->assertTrue($listNetworkPolicies instanceof DefaultPaginationList, 'The list of network policies is expected to be DefaultPaginationList instance.');
         foreach ($listNetworkPolicies as $v) {
             if (isset($v->fq_name) && is_array($v->fq_name) && in_array($testNetworkPolicyName, $v->fq_name)) {
                 $ret = $rs->contrail->deleteNetworkPolicy($v->uuid);
                 $this->assertTrue($ret);
             }
         }
         unset($listNetworkPolicies);
         //Select IPAMs
         $listIpams = $rs->contrail->listIpam();
         $this->assertTrue($listIpams instanceof DefaultPaginationList, 'The list of IPAMs is expected to be DefaultPaginationList instance.');
         //Removes previously created IPAM if it does exist
         foreach ($listIpams as $ipam) {
             if (isset($ipam->fq_name) && is_array($ipam->fq_name) && in_array($testFqName, $ipam->fq_name)) {
                 $ret = $rs->contrail->deleteIpam($ipam->uuid);
                 $this->assertTrue($ret);
             }
         }
         unset($listIpams);
         //Lists virtual DNSs
         $dnsList = $rs->contrail->listVirtualDns();
         $this->assertTrue($dnsList instanceof DefaultPaginationList, 'The list of virtual DNSs is expected to be DefaultPaginationList instance.');
         //Removes previously created virtual dns
         foreach ($dnsList as $v) {
             if (!empty($v->fq_name) && is_array($v->fq_name) && in_array($testFqName, $v->fq_name)) {
                 $ret = $rs->contrail->deleteVirtualDns($v->uuid);
                 $this->assertTrue($ret);
             }
         }
         unset($dnsList);
         //Creates a virtual DNS
         $virtualDns = $rs->contrail->createVirtualDns(array('parent_type' => 'domain', 'fq_name' => array('default-domain', $testFqName), 'virtual_DNS_data' => array("default_ttl_seconds" => 8144, "domain_name" => $testDomainName, "dynamic_records_from_client" => true, "next_virtual_DNS" => self::NEXT_VIRTUAL_DNS_ADDRESS, "record_order" => "random")));
         $this->assertInternalType('object', $virtualDns);
         foreach (array('fq_name', 'parent_uuid', 'parent_href', 'uuid', 'href', 'name') as $attr) {
             $this->assertObjectHasAttribute('href', $virtualDns);
         }
         $this->assertNotEmpty($virtualDns->uuid);
         $this->assertEquals($testFqName, $virtualDns->name);
         //List of the specified virtual DNS
         $vdns = $rs->contrail->listVirtualDns($virtualDns->uuid);
         $this->assertInternalType('object', $vdns);
         foreach (array('fq_name', 'parent_uuid', 'parent_href', 'uuid', 'href', 'name', 'virtual_DNS_data', 'id_perms') as $attr) {
             $this->assertObjectHasAttribute('href', $virtualDns);
         }
         $this->assertEquals($virtualDns->name, $vdns->name);
         $this->assertEquals($virtualDns->uuid, $vdns->uuid);
         unset($virtualDns);
         //Creates IPAM
         $ipam = $rs->contrail->createIpam(array("parent_type" => "project", "fq_name" => array("default-domain", $tenant, $testFqName), "network_ipam_mgmt" => array("dhcp_option_list" => array("dhcp_option" => array(array("dhcp_option_name" => "15", "dhcp_option_value" => $testDomainName))), "ipam_dns_method" => "tenant-dns-server", "ipam_dns_server" => array("tenant_dns_server_address" => array("ip_address" => array(self::DNS_SERVER_ADDRESS)), "virtual_dns_server_name" => null))));
         $this->assertInternalType('object', $ipam);
         //Show specified IPAM
         $ipam2 = $rs->contrail->listIpam($ipam->uuid);
         $this->assertInternalType('object', $ipam2);
         $this->assertEquals($ipam2->uuid, $ipam->uuid);
         unset($ipam2);
         //Creates virtual network
         $virtualNetwork = $rs->contrail->createVirtualNetwork(array("parent_type" => "project", "fq_name" => array("default-domain", $tenant, $testFqNetworkName)));
         $this->assertInternalType('object', $virtualNetwork);
         $this->assertNotEmpty($virtualNetwork->uuid);
         //Show specified virtual network
         $vn2 = $rs->contrail->listVirtualNetworks($virtualNetwork->uuid);
         $this->assertInternalType('object', $vn2);
         $this->assertEquals($virtualNetwork->uuid, $vn2->uuid);
         unset($vn2);
         //Creating network policy
         $networkPolicy = $rs->contrail->createNetworkPolicy(["parent_type" => "project", "fq_name" => ["default-domain", $tenant, $testNetworkPolicyName], "network_policy_entries" => ["policy_rule" => [["direction" => "<>", "protocol" => "any", "src_addresses" => [["virtual_network" => "default-domain:" . $tenant . ":" . $testFqNetworkName]], "dst_ports" => [["start_port" => -1, "end_port" => -1]], "action_list" => ["apply_service" => null], "dst_addresses" => [["virtual_network" => "default-domain:" . $tenant . ":" . $testFqNetworkName]], "src_ports" => [["end_port" => -1, "start_port" => -1]]]]]]);
         $this->assertInternalType('object', $networkPolicy);
         $this->assertNotEmpty($networkPolicy->uuid);
         //Show detailed info of the specified network policy
         $np2 = $rs->contrail->listNetworkPolicies($networkPolicy->uuid);
         $this->assertInternalType('object', $np2);
         $this->assertEquals($networkPolicy->uuid, $np2->uuid);
         unset($np2);
         //Associates IPAM and Network Policy to virtual network
         $rs->contrail->updateVirtualNetwork($virtualNetwork->uuid, ["fq_name" => $virtualNetwork->fq_name, "network_ipam_refs" => [["attr" => ["ipam_subnets" => [["default_gateway" => "192.168.80.6", "subnet" => ["ip_prefix" => "192.168.80.1", "ip_prefix_len" => 29]]]], "to" => ["default-domain", $tenant, $testFqName]]], "network_policy_refs" => [["to" => ["default-domain", $tenant, $testNetworkPolicyName], "attr" => ["sequence" => ["major" => 0, "minor" => 0], "timer" => null]]]]);
         //Removing Virtual Network
         $ret = $rs->contrail->deleteVirtualNetwork($virtualNetwork->uuid);
         $this->assertTrue($ret);
         //Removing network policy
         $ret = $rs->contrail->deleteNetworkPolicy($networkPolicy->uuid);
         $this->assertTrue($ret);
         //Removing IPAM
         $ret = $rs->contrail->deleteIpam($ipam->uuid);
         $this->assertTrue($ret);
         //Removing virtual DNS
         $ret = $rs->contrail->deleteVirtualDns($vdns->uuid);
         $this->assertTrue($ret);
         $this->markTestSkipped('For Contrail to check only its API and nothing more.');
         return;
     }
     //Get Limits test
     $limits = $rs->servers->getLimits();
     $this->assertTrue(is_object($limits));
     unset($limits);
     $aExtensions = $rs->servers->listExtensions();
     $this->assertTrue(is_array($aExtensions));
     unset($aExtensions);
     $aExtensions = $rs->volume->listExtensions();
     $this->assertTrue(is_array($aExtensions));
     unset($aExtensions);
     $hasNetwork = $rs->hasService(OpenStack::SERVICE_NETWORK);
     if ($hasNetwork) {
         $aExtensions = $rs->network->listExtensions();
         $this->assertTrue(is_array($aExtensions));
         unset($aExtensions);
         //Quantum API tests
         $testNetworkName = self::getTestName(self::NAME_NETWORK);
         $testSubnetName = self::getTestName(self::NAME_SUBNET);
         $testPortName = self::getTestName(self::NAME_PORT);
         $testRouterName = self::getTestName(self::NAME_ROUTER);
         $testLbPoolName = self::getTestName(self::NAME_LB_POOL);
         $testLbVipName = self::getTestName(self::NAME_LB_VIP);
         //ListNetworks test
         $networks = $rs->network->networks->list(null, array('status' => 'ACTIVE', 'shared' => false));
         $this->assertTrue($networks instanceof \ArrayIterator);
         if (isset($networks[0])) {
             $this->assertInternalType('object', $networks[0]);
             $this->assertNotEmpty($networks[0]->id);
             //Show Network test
             $network = $rs->network->networks->list($networks[0]->id);
             $this->assertEquals($networks[0], $network);
             unset($network);
         }
         $publicNetworkId = null;
         foreach ($networks as $network) {
             if ($network->{"router:external"} == true) {
                 $publicNetworkId = $network->id;
             }
         }
         unset($networks);
         $this->assertNotEmpty($publicNetworkId, 'Could not find public network to continue.');
         //ListSubnets test
         $subnets = $rs->network->subnets->list();
         $this->assertTrue($subnets instanceof \ArrayIterator);
         if (isset($subnets[0])) {
             $this->assertInternalType('object', $subnets[0]);
             $this->assertNotEmpty($subnets[0]->id);
             //Show Subnet test
             $subnet = $rs->network->subnets->list($subnets[0]->id);
             $this->assertEquals($subnets[0], $subnet);
             unset($subnet);
         }
         unset($subnets);
         //ListPorts test
         $ports = $rs->network->ports->list();
         $this->assertTrue($ports instanceof \ArrayIterator);
         if (isset($ports[0])) {
             $this->assertInternalType('object', $ports[0]);
             $this->assertNotEmpty($ports[0]->id);
             //Show Port test
             $port = $rs->network->ports->list($ports[0]->id);
             $this->assertEquals($ports[0], $port);
             unset($port);
         }
         unset($ports);
         if ($rs->network->isExtensionSupported(NetworkExtension::loadbalancingService())) {
             //Removes previously created LBaaS VIP if it exists
             $lbVips = $rs->network->lbVips->list(null, array('name' => $testLbVipName));
             foreach ($lbVips as $lbVip) {
                 $ret = $rs->network->lbVips->delete($lbVip->id);
                 $this->assertTrue($ret, 'Could not remove previously created Load balancer VIP (id:' . $lbVip->id . ').');
             }
             $this->assertTrue($lbVips instanceof \ArrayIterator);
             unset($lbVips);
             //Removes previously created pools if they exist.
             $lbPools = $rs->network->lbPools->list(null, array('name' => $testLbPoolName));
             $this->assertTrue($lbPools instanceof \ArrayIterator);
             foreach ($lbPools as $lbPool) {
                 if (!empty($lbPool->health_monitors)) {
                     foreach ($lbPool->health_monitors as $healthMonitorId) {
                         //Removes previously associated health monitors with test pools
                         $ret = $rs->network->lbPools->disassociateHealthMonitor($lbPool->id, $healthMonitorId);
                         $this->assertTrue($ret);
                         $ret = $rs->network->lbHealthMonitors->delete($healthMonitorId);
                         $this->assertTrue($ret);
                     }
                 }
                 if (!empty($lbPool->members)) {
                     foreach ($lbPool->members as $memberId) {
                         //Remove previously created members
                         $ret = $rs->network->lbMembers->delete($memberId);
                         $this->assertTrue($ret, 'Could not remove previously created LBaas member (id:' . $memberId . ').');
                     }
                 }
                 $ret = $rs->network->lbPools->delete($lbPool->id);
                 $this->assertTrue($ret, 'Could not remove previously created LBaaS pool.');
             }
             unset($lbPools);
         }
         //Tries to find the ports which have been created recently by this test
         $ports = $rs->network->ports->list(null, array('name' => array($testPortName, $testPortName . '1')));
         foreach ($ports as $port) {
             //Removes previously created ports
             $rs->network->ports->delete($port->id);
         }
         unset($ports);
         //Tries to find the networks that have been created recently by this test
         $networks = $rs->network->networks->list(null, array('name' => $testNetworkName));
         foreach ($networks as $network) {
             //Removes previously created networks
             $rs->network->networks->update($network->id, null, false);
             //Trying to remove allocated ports
             $portsToRemove = $rs->network->ports->list(null, array('networkId' => $network->id));
             foreach ($portsToRemove as $p) {
                 if (isset($p->device_owner) && isset($p->device_id) && $p->device_owner == 'network:router_interface') {
                     $rs->network->ports->update($p->id, array('admin_state_up' => false));
                     $rs->network->routers->removeInterface($p->device_id, null, $p->id);
                 }
             }
             $rs->network->networks->delete($network->id);
         }
         unset($networks);
         //Tries to find the subnets that where created by this test but hadn't been removed yet.
         $subnets = $rs->network->subnets->list(null, array('name' => array($testSubnetName, $testSubnetName . '1')));
         $this->assertTrue($subnets instanceof \ArrayIterator);
         foreach ($subnets as $subnet) {
             //Removes previously created subnets
             $rs->network->subnets->delete($subnet->id);
         }
         //Creates new network
         $network = $rs->network->networks->create($testNetworkName, false, false);
         $this->assertInternalType('object', $network);
         $this->assertNotEmpty($network->id);
         $this->assertEquals(false, $network->admin_state_up);
         $this->assertEquals(false, $network->shared);
         //Updates newtork state
         $network = $rs->network->networks->update($network->id, null, true);
         $this->assertInternalType('object', $network);
         $this->assertEquals(true, $network->admin_state_up);
         //Creates subnet
         $subnet = $rs->network->subnets->create(array('network_id' => $network->id, 'cidr' => self::SUBNET_CIDR, 'name' => $testSubnetName));
         $this->assertInternalType('object', $subnet);
         $this->assertEquals($testSubnetName, $subnet->name);
         $this->assertNotEmpty($subnet->id);
         //Updates the subnet
         $subnet = $rs->network->subnets->update($subnet->id, array('name' => $testSubnetName . '1'));
         $this->assertInternalType('object', $subnet);
         $this->assertNotEmpty($subnet->name);
         $this->assertEquals($testSubnetName . '1', $subnet->name);
         //Quantum L3 Router related tests
         if ($platform !== \SERVER_PLATFORMS::ECS && $rs->network->isExtensionSupported(NetworkExtension::quantumL3Router())) {
             //ListRouters test
             $routers = $rs->network->routers->list(null, array('status' => array('ACTIVE', 'PENDING')), array('id', 'name'));
             $this->assertTrue($routers instanceof \ArrayIterator);
             foreach ($routers as $r) {
                 $router = $rs->network->routers->list($r->id);
                 $this->assertInternalType('object', $router);
                 if ($r->name == $testRouterName) {
                     //Removes the router which is created by phpunit test before and is still alive by any reason.
                     //It requires all internal interfaces to be removed from router.
                     $ret = $rs->network->routers->delete($r->id);
                     $this->assertTrue($ret);
                 }
             }
             unset($routers);
             //Creates router
             $router = $rs->network->routers->create(new CreateRouter($testRouterName, true, $publicNetworkId));
             $this->assertInternalType('object', $router);
             $this->assertObjectHasAttribute('name', $router);
             $this->assertNotEmpty($router->name);
             $this->assertEquals($testRouterName, $router->name);
             $this->assertObjectHasAttribute('id', $router);
             $this->assertNotEmpty($router->id);
             $this->assertObjectHasAttribute('admin_state_up', $router);
             $this->assertTrue($router->admin_state_up);
             //Updates the router
             $r2 = $rs->network->routers->update($router->id, array('admin_state_up' => false));
             $this->assertInternalType('object', $r2);
             $this->assertObjectHasAttribute('admin_state_up', $r2);
             $this->assertEquals(false, $r2->admin_state_up);
             //Adds interface to router
             $routerInterface1 = $rs->network->routers->addInterface($router->id, $subnet->id);
             $this->assertInternalType('object', $routerInterface1);
             $this->assertObjectHasAttribute('subnet_id', $routerInterface1);
             $this->assertEquals($subnet->id, $routerInterface1->subnet_id);
             $this->assertObjectHasAttribute('port_id', $routerInterface1);
             //Removes interface from router
             $obj = $rs->network->routers->removeInterface($router->id, $subnet->id);
             //Removes router
             $ret = $rs->network->routers->delete($router->id);
             $this->assertTrue($ret);
             unset($router);
         }
         //Load Balancing Service (LBaaS) tests
         if ($rs->network->isExtensionSupported(NetworkExtension::loadbalancingService())) {
             $this->assertNotEmpty($subnet->id, 'Subnet is needed to proceed.');
             //The tenant creates a pool, which is initially empty
             $lbPool = $rs->network->lbPools->create(array('subnet_id' => $subnet->id, 'lb_method' => 'ROUND_ROBIN', 'protocol' => 'TCP', 'name' => $testLbPoolName));
             $this->assertNotEmpty($lbPool);
             $this->assertInstanceOf('stdClass', $lbPool);
             $this->assertEquals($testLbPoolName, $lbPool->name);
             $this->assertNotEmpty($lbPool->id);
             //Tests update pool method
             $lbPool = $rs->network->lbPools->update($lbPool->id, array('name' => $testLbPoolName));
             $this->assertNotEmpty($lbPool);
             $this->assertInstanceOf('stdClass', $lbPool);
             $this->assertEquals($testLbPoolName, $lbPool->name);
             //The tenant creates one or several members in the pool
             $lbMember = $rs->network->lbMembers->create(array('pool_id' => $lbPool->id, 'protocol_port' => 8080, 'address' => self::LB_MEMBER_ADDRESS, 'weight' => 2));
             $this->assertNotEmpty($lbMember);
             $this->assertInternalType('object', $lbMember);
             $this->assertEquals($lbPool->id, $lbMember->pool_id);
             $this->assertTrue($lbMember->admin_state_up);
             //Tests update member method
             $lbMember = $rs->network->lbMembers->update($lbMember->id, array('weight' => 3));
             $this->assertNotEmpty($lbMember);
             $this->assertInternalType('object', $lbMember);
             $this->assertEquals(3, $lbMember->weight);
             //The tenant create one or several health monitors
             $lbHealthMonitor = $rs->network->lbHealthMonitors->create(array('delay' => 4, 'max_retries' => 3, 'type' => 'TCP', 'timeout' => 1));
             $this->assertNotEmpty($lbHealthMonitor);
             $this->assertInternalType('object', $lbHealthMonitor);
             $this->assertNotEmpty($lbHealthMonitor->id);
             $this->assertTrue($lbHealthMonitor->admin_state_up);
             $this->assertEquals(4, $lbHealthMonitor->delay);
             $this->assertEquals(3, $lbHealthMonitor->max_retries);
             $this->assertEquals('TCP', $lbHealthMonitor->type);
             $this->assertEquals(1, $lbHealthMonitor->timeout);
             //Tests update health monitor
             $lbHealthMonitor = $rs->network->lbHealthMonitors->update($lbHealthMonitor->id, array('max_retries' => 4));
             $this->assertNotEmpty($lbHealthMonitor);
             $this->assertInternalType('object', $lbHealthMonitor);
             $this->assertNotEmpty($lbHealthMonitor->id);
             $this->assertEquals(4, $lbHealthMonitor->max_retries);
             //The tenant associates the Health Monitors with the Pool
             $ret = $rs->network->lbPools->associateHealthMonitor($lbPool->id, $lbHealthMonitor->id);
             $this->assertInternalType('object', $ret);
             //Checks if health monitor is successfully associated
             $tmpPool = $rs->network->lbPools->list($lbPool->id);
             $this->assertNotEmpty($tmpPool);
             $this->assertInternalType('object', $tmpPool);
             $this->assertEquals($lbPool->id, $tmpPool->id);
             $this->assertNotEmpty($tmpPool->health_monitors);
             $this->assertContains($lbHealthMonitor->id, $tmpPool->health_monitors);
             $lbPool = $tmpPool;
             unset($tmpPool);
             //The tenant finally creates a VIP associated with the Pool
             $lbVip = $rs->network->lbVips->create(array('protocol' => 'TCP', 'protocol_port' => 8080, 'name' => $testLbVipName, 'subnet_id' => $subnet->id, 'pool_id' => $lbPool->id));
             $this->assertNotEmpty($lbVip);
             $this->assertInternalType('object', $lbVip);
             $this->assertEquals('TCP', $lbVip->protocol);
             $this->assertEquals(8080, $lbVip->protocol_port);
             $this->assertEquals($testLbVipName, $lbVip->name);
             $this->assertEquals($subnet->id, $lbVip->subnet_id);
             $this->assertEquals($lbPool->id, $lbVip->pool_id);
             //Tests update method
             $lbVip = $rs->network->lbVips->update($lbVip->id, array('name' => $testLbVipName));
             $this->assertNotEmpty($lbVip);
             $this->assertInternalType('object', $lbVip);
             sleep(1);
             //Deletes VIP
             $ret = $rs->network->lbVips->delete($lbVip->id);
             $this->assertTrue($ret);
             //Disassotiates the Health Monitors with the pool
             $ret = $rs->network->lbPools->disassociateHealthMonitor($lbPool->id, $lbHealthMonitor->id);
             $this->assertTrue($ret);
             //Checks if health monitor is successfully disassociated
             $tmpPool = $rs->network->lbPools->list($lbPool->id);
             $this->assertNotEmpty($tmpPool);
             $this->assertInternalType('object', $tmpPool);
             $this->assertEquals($lbPool->id, $tmpPool->id);
             $this->assertNotContains($lbHealthMonitor->id, $tmpPool->health_monitors);
             $lbPool = $tmpPool;
             unset($tmpPool);
             //Deletes LBaaS health monitor
             $ret = $rs->network->lbHealthMonitors->delete($lbHealthMonitor->id);
             $this->assertTrue($ret);
             //Delete LBaaS member
             $ret = $rs->network->lbMembers->delete($lbMember->id);
             $this->assertTrue($ret);
             //Delete LBaaS pool
             $ret = $rs->network->lbPools->delete($lbPool->id);
             $this->assertTrue($ret);
         }
         //Removes subnet
         $ret = $rs->network->subnets->delete($subnet->id);
         $this->assertTrue($ret);
         //Removes created network
         $rs->network->networks->update($network->id, null, false);
         $ret = $rs->network->networks->delete($network->id);
         $this->assertTrue($ret);
         unset($network);
         //Security group extension test
         if ($rs->network->isExtensionSupported(NetworkExtension::securityGroup())) {
             $sgTestName = self::getTestName(self::NAME_SECURITY_GROUP);
             //Removes previously created test security group if it actually exists
             $sgList = $rs->network->securityGroups->list(null, ['name' => $sgTestName]);
             $this->assertInstanceOf(self::ABSTRACT_PAGINATION_CLASS, $sgList);
             foreach ($sgList as $sg) {
                 $this->assertNotEmpty($sg->name);
                 $this->assertNotEmpty($sg->id);
                 if ($sg->name === $sgTestName) {
                     //Removes previously created test security group
                     $res = $rs->network->securityGroups->delete($sg->id);
                     $this->assertTrue($res);
                 }
             }
             unset($sgList);
             //List Security groups test
             $sgList = $rs->network->securityGroups->list();
             $this->assertInstanceOf(self::ABSTRACT_PAGINATION_CLASS, $sgList);
             unset($sgList);
             //Create security group test
             $sg = $rs->network->securityGroups->create($sgTestName, 'phpunit test security group');
             $this->assertNotEmpty($sg);
             $this->assertInternalType('object', $sg);
             $this->assertNotEmpty($sg->id);
             $this->assertEquals($sgTestName, $sg->name);
             $this->assertNotEmpty($sg->description);
             //Update security group test
             //ListRules test
             //Gets the rules set for the created security group
             $rulesList = $rs->network->securityGroups->listRules(null, ['securityGroupId' => $sg->id]);
             $this->assertInstanceOf(self::ABSTRACT_PAGINATION_CLASS, $rulesList);
             $this->assertEquals(0, count($rulesList), 'New security group is expected to have empty set of the rules.');
             $ruleToAdd = ["security_group_id" => $sg->id, "remote_group_id" => null, "direction" => "ingress", "remote_ip_prefix" => "0.0.0.0/0", "port_range_max" => null, "port_range_min" => null];
             //Add a new rule to security group
             $rule = $rs->network->securityGroups->addRule($ruleToAdd);
             $this->assertNotEmpty($rule);
             $this->assertNotEmpty($rule->id);
             $this->assertInternalType('object', $rule);
             //Verifies that all properties are set properly
             foreach ($ruleToAdd as $property => $value) {
                 $this->assertObjectHasAttribute($property, $rule);
                 $this->assertEquals($value, $rule->{$property});
             }
             //Checks that new rule does exist
             $rulesList = $rs->network->securityGroups->listRules(null, ['securityGroupId' => $sg->id]);
             $this->assertEquals(1, count($rulesList));
             unset($rulesList);
             //Removes rule
             $ret = $rs->network->securityGroups->deleteRule($rule->id);
             $this->assertTrue($ret);
             //Checks whether rule is removed properly
             $rulesList = $rs->network->securityGroups->listRules(null, ['securityGroupId' => $sg->id]);
             $this->assertEquals(0, count($rulesList));
             unset($rulesList);
             //Delete security group test
             $ret = $rs->network->securityGroups->delete($sg->id);
             $this->assertTrue($ret);
             unset($sg);
         }
     }
     //List snapshots test
     $snList = $rs->volume->snapshots->list();
     $this->assertTrue($snList instanceof \ArrayIterator);
     foreach ($snList as $v) {
         if ($v->display_name == self::getTestSnapshotName()) {
             $rs->volume->snapshots->delete($v->id);
         }
     }
     unset($snList);
     //List Volume Types test
     $volumeTypes = $rs->volume->listVolumeTypes();
     $this->assertTrue($volumeTypes instanceof \ArrayIterator);
     foreach ($volumeTypes as $v) {
         $volumeTypeDesc = $rs->volume->getVolumeType($v->id);
         $this->assertTrue(is_object($volumeTypeDesc));
         unset($volumeTypeDesc);
         break;
     }
     //List Volumes test
     $aVolumes = $rs->volume->listVolumes();
     $this->assertTrue($aVolumes instanceof \ArrayIterator);
     foreach ($aVolumes as $v) {
         if ($v->display_name == self::getTestVolumeName()) {
             if (in_array($v->status, array(VolumeStatus::STATUS_AVAILABLE, VolumeStatus::STATUS_ERROR))) {
                 $ret = $rs->volume->deleteVolume($v->id);
             }
         }
     }
     //Create Volume test
     $volume = $rs->volume->createVolume(self::VOLUME_SIZE, self::getTestVolumeName());
     $this->assertTrue(is_object($volume));
     $this->assertNotEmpty($volume->id);
     for ($t = time(), $s = 1; time() - $t < 300 && !in_array($volume->status, array(VolumeStatus::STATUS_AVAILABLE, VolumeStatus::STATUS_ERROR)); $s += 5) {
         sleep($s);
         $volume = $rs->volume->getVolume($volume->id);
         $this->assertTrue(is_object($volume));
         $this->assertNotEmpty($volume->id);
     }
     $this->assertContains($volume->status, array(VolumeStatus::STATUS_AVAILABLE, VolumeStatus::STATUS_ERROR));
     //         //Create snapshot test
     //         //WARNING! It takes too long time.
     //         $snap = $rs->volume->snapshots->create($volume->id, self::getTestSnapshotName());
     //         $this->assertTrue(is_object($snap));
     //         $this->assertNotEmpty($snap->id);
     //         for ($t = time(), $s = 1; (time() - $t) < 600 && !in_array($snap->status, array('available', 'error')); $s += 5) {
     //             sleep($s);
     //             $snap = $rs->volume->snapshots->get($snap->id);
     //             $this->assertNotEmpty($snap->id);
     //         }
     //         $this->assertContains($snap->status, array('available', 'error'));
     //         //Delete snapshot test
     //         $ret = $rs->volume->snapshots->delete($snap->id);
     //         $this->assertTrue($ret);
     //         unset($snap);
     //         sleep(5);
     //Delete Volume test
     $ret = $rs->volume->deleteVolume($volume->id);
     $this->assertTrue($ret);
     unset($volume);
     sleep(5);
     $pool = null;
     if ($rs->servers->isExtensionSupported(ServersExtension::floatingIpPools())) {
         $aFloatingIpPools = $rs->servers->listFloatingIpPools();
         $this->assertTrue($aFloatingIpPools instanceof \ArrayIterator);
         foreach ($aFloatingIpPools as $v) {
             $pool = $v->name;
             break;
         }
         $this->assertNotNull($pool);
         unset($aFloatingIpPools);
     }
     if ($rs->servers->isExtensionSupported(ServersExtension::floatingIps())) {
         $this->assertNotNull($pool);
         $aFloatingIps = $rs->servers->floatingIps->list();
         $this->assertTrue($aFloatingIps instanceof \ArrayIterator);
         foreach ($aFloatingIps as $v) {
             $r = $rs->servers->floatingIps->get($v->id);
             $this->assertTrue(is_object($r));
             break;
         }
         unset($aFloatingIps);
         //default pool for rackspase is 'nova'
         $fip = $rs->servers->floatingIps->create($pool);
         $this->assertTrue(is_object($fip));
         $r = $rs->servers->floatingIps->delete($fip->id);
         $this->assertTrue($r);
         try {
             //Verifies that ip has been successfully removed
             $res = $rs->servers->floatingIps->get($fip->id);
             $this->assertTrue(false, 'Exception must be thrown here');
         } catch (RestClientException $e) {
             if ($e->error->code == 404) {
                 $this->assertTrue(true);
             } else {
                 //OpenStack Grizzly fails with 500 error code.
                 //throw $e;
             }
         }
         unset($fip);
     }
     //List flavors test
     $flavorsList = $listFlavors = $rs->servers->listFlavors();
     $this->assertTrue($flavorsList instanceof \ArrayIterator);
     $flavorId = null;
     foreach ($flavorsList as $v) {
         $flavorId = $v->id;
         break;
     }
     $this->assertNotNull($flavorId);
     unset($flavorsList);
     //List servers test
     $ret = $rs->servers->list();
     if (!empty($ret) && $ret->count()) {
         foreach ($ret as $v) {
             if ($v->name == self::getTestServerName() || $v->name == self::getTestServerName('renamed')) {
                 //Removes servers
                 try {
                     $rs->servers->deleteServer($v->id);
                 } catch (RestClientException $e) {
                     echo $e->getMessage() . "\n";
                 }
             }
         }
     }
     $personality = new PersonalityList();
     $personality->append(new Personality('/etc/scalr/private.d/.user-data', base64_encode('super data')));
     $personality->append(new Personality('/etc/.scalr-user-data', base64_encode('super data')));
     $netList = null;
     //Create server test
     $srv = $rs->servers->createServer(self::getTestServerName(), $flavorId, $imageId, null, null, $personality, $netList);
     $this->assertInstanceOf('stdClass', $srv);
     $srv = $rs->servers->getServerDetails($srv->id);
     $this->assertInstanceOf('stdClass', $srv);
     $this->assertNotEmpty($srv->status);
     for ($t = time(), $s = 10; time() - $t < 600 && !in_array($srv->status, array('ACTIVE', 'ERROR')); $s += 1) {
         sleep($s);
         $srv = $rs->servers->getServerDetails($srv->id);
     }
     $this->assertContains($srv->status, array('ACTIVE', 'ERROR'));
     if ($rs->servers->isExtensionSupported(ServersExtension::consoleOutput())) {
         $consoleOut = $rs->servers->getConsoleOutput($srv->id, 50);
     }
     //List Addresses test
     $addresses = $rs->servers->listAddresses($srv->id);
     $this->assertTrue(is_object($addresses));
     //Get server details test
     $srvDetails = $rs->servers->getServerDetails($srv->id);
     $this->assertInstanceOf('stdClass', $srvDetails);
     unset($srvDetails);
     //Images List test
     $imagesList = $rs->servers->images->list();
     $this->assertTrue($imagesList instanceof DefaultPaginationList);
     foreach ($imagesList as $img) {
         if ($img->name == self::getTestName('image')) {
             $rs->servers->images->delete($img->id);
         }
         $imageDetails = $rs->servers->images->get($img->id);
         $this->assertTrue(is_object($imageDetails));
         unset($imageDetails);
         break;
     }
     unset($imagesList);
     //Keypairs extension test
     if ($rs->servers->isExtensionSupported(ServersExtension::keypairs())) {
         $aKeypairs = $rs->servers->keypairs->list();
         $this->assertTrue($aKeypairs instanceof \ArrayIterator);
         foreach ($aKeypairs as $v) {
             if ($v->keypair->name == self::getTestName('key')) {
                 $rs->servers->keypairs->delete($v->keypair->name);
             }
         }
         unset($aKeypairs);
         $kp = $rs->servers->keypairs->create(self::getTestName('key'));
         $this->assertNotEmpty($kp);
         $this->assertTrue(is_object($kp));
         $kptwin = $rs->servers->keypairs->get($kp->name);
         $this->assertNotEmpty($kptwin);
         $this->assertEquals($kp->public_key, $kptwin->public_key);
         unset($kptwin);
         $res = $rs->servers->keypairs->delete($kp->name);
         $this->assertTrue($res);
         unset($kp);
     }
     //Security Groups extension test
     if ($rs->servers->isExtensionSupported(ServersExtension::securityGroups())) {
         $listSecurityGroups = $rs->servers->securityGroups->list();
         $this->assertTrue($listSecurityGroups instanceof \ArrayIterator);
         foreach ($listSecurityGroups as $v) {
             if ($v->name == self::getTestName('security-group')) {
                 $rs->servers->securityGroups->delete($v->id);
             }
         }
         unset($listSecurityGroups);
         $listForSpecificServer = $rs->servers->securityGroups->list($srv->id);
         $this->assertTrue(is_array($listForSpecificServer) || $listForSpecificServer instanceof \ArrayIterator);
         unset($listForSpecificServer);
         $sg = $rs->servers->securityGroups->create(self::getTestName('security-group'), 'This is phpunit security group test.');
         $this->assertNotEmpty($sg);
         $this->assertTrue(is_object($sg));
         $sgmirror = $rs->servers->securityGroups->get($sg->id);
         $this->assertNotEmpty($sgmirror);
         $this->assertEquals($sg->id, $sgmirror->id);
         unset($sgmirror);
         $sgrule = $rs->servers->securityGroups->addRule(array("ip_protocol" => "tcp", "from_port" => "80", "to_port" => "8080", "cidr" => "0.0.0.0/0", "parent_group_id" => $sg->id));
         $this->assertNotEmpty($sgrule);
         $this->assertTrue(is_object($sgrule));
         $this->assertEquals($sg->id, $sgrule->parent_group_id);
         $ret = $rs->servers->securityGroups->deleteRule($sgrule->id);
         $this->assertTrue($ret);
         unset($sgrule);
         $ret = $rs->servers->securityGroups->delete($sg->id);
         $this->assertTrue($ret);
     }
     //Create image test
     $imageId = $rs->servers->images->create($srv->id, self::getTestName('image'));
     $this->assertTrue(is_string($imageId));
     //It requires ACTIVE state of server
     //         $res = $rs->servers->resizeServer($srv->id, $srv->name, '3');
     //         $this->assertTrue($res);
     //         $res = $rs->servers->confirmResizedServer($srv->id);
     //         $this->assertTrue($res);
     $ret = $rs->servers->images->delete($imageId);
     $this->assertTrue($ret);
     //Update server test
     $renamedDetails = $rs->servers->updateServer($srv->id, self::getTestServerName('renamed'));
     $this->assertInstanceOf('stdClass', $renamedDetails);
     $this->assertEquals(self::getTestServerName('renamed'), $renamedDetails->server->name);
     unset($renamedDetails);
     //Delete Server test
     $ret = $rs->servers->deleteServer($srv->id);
     $this->assertTrue($ret);
 }
Пример #6
0
 /**
  * {@inheritdoc}
  * @see \Scalr\Modules\PlatformModuleInterface::LaunchServer()
  */
 public function LaunchServer(DBServer $DBServer, \Scalr_Server_LaunchOptions $launchOptions = null)
 {
     $config = \Scalr::getContainer()->config;
     $environment = $DBServer->GetEnvironmentObject();
     $governance = new \Scalr_Governance($environment->id);
     if (!$launchOptions) {
         $launchOptions = new \Scalr_Server_LaunchOptions();
         $DBRole = $DBServer->GetFarmRoleObject()->GetRoleObject();
         $launchOptions->imageId = $DBRole->__getNewRoleObject()->getImage($this->platform, $DBServer->GetCloudLocation())->imageId;
         $launchOptions->serverType = $DBServer->GetFarmRoleObject()->GetSetting(Entity\FarmRoleSetting::INSTANCE_TYPE);
         $launchOptions->cloudLocation = $DBServer->GetFarmRoleObject()->CloudLocation;
         $launchOptions->userData = $DBServer->GetCloudUserData();
         $launchOptions->userData['region'] = $launchOptions->cloudLocation;
         $launchOptions->userData['vzc.adminpassword'] = \Scalr::GenerateRandomKey(20);
         $launchOptions->userData['platform'] = \SERVER_PLATFORMS::VERIZON;
         // Apply tags
         $launchOptions->userData = array_merge($DBServer->getOpenstackTags(), $launchOptions->userData);
         $launchOptions->networks = @json_decode($DBServer->GetFarmRoleObject()->GetSetting(Entity\FarmRoleSetting::OPENSTACK_NETWORKS));
         $gevernanceNetworks = $governance->getValue($this->platform, 'openstack.networks');
         if (count($launchOptions->networks) == 0 && $gevernanceNetworks) {
             $launchOptions->networks = $gevernanceNetworks[$launchOptions->cloudLocation];
         }
         foreach ($launchOptions->userData as $k => $v) {
             if (!$v) {
                 unset($launchOptions->userData[$k]);
             }
         }
         $launchOptions->architecture = 'x86_64';
         $isWindows = $DBServer->osType == 'windows' || $DBRole->getOs()->family == 'windows';
         $customUserData = $DBServer->GetFarmRoleObject()->GetSetting('base.custom_user_data');
         $serverNameFormat = $governance->getValue($DBServer->platform, \Scalr_Governance::OPENSTACK_INSTANCE_NAME_FORMAT);
         if (!$serverNameFormat) {
             $serverNameFormat = $DBServer->GetFarmRoleObject()->GetSetting(\Scalr_Role_Behavior::ROLE_INSTANCE_NAME_FORMAT);
         }
     } else {
         $launchOptions->userData = array();
         $customUserData = false;
         if (!$launchOptions->networks) {
             $launchOptions->networks = array();
         }
         $isWindows = $DBServer->osType == 'windows';
     }
     $client = $this->getOsClient($environment, $launchOptions->cloudLocation);
     // Prepare user data
     $u_data = "";
     foreach ($launchOptions->userData as $k => $v) {
         $u_data .= "{$k}={$v};";
     }
     $u_data = trim($u_data, ";");
     if ($customUserData) {
         $repos = $DBServer->getScalarizrRepository();
         $extProperties["user_data"] = base64_encode(str_replace(array('{SCALR_USER_DATA}', '{RPM_REPO_URL}', '{DEB_REPO_URL}'), array($u_data, $repos['rpm_repo_url'], $repos['deb_repo_url']), $customUserData));
     }
     $personality = new PersonalityList();
     if ($isWindows) {
         $personality->append(new Personality('C:\\Program Files\\Scalarizr\\etc\\private.d\\.user-data', base64_encode($u_data)));
     } else {
         $personality->append(new Personality('/etc/scalr/private.d/.user-data', base64_encode($u_data)));
     }
     //TODO: newtorks
     $networks = new NetworkList();
     foreach ((array) $launchOptions->networks as $network) {
         if ($network) {
             $networks->append(new Network($network));
         }
     }
     //$osUserData = null;
     $osPersonality = null;
     $userDataMethod = 'meta-data';
     $osPersonality = null;
     $userDataMethod = $config->defined("scalr.{$this->platform}.user_data_method") ? $config("scalr.{$this->platform}.user_data_method") : null;
     if (!$userDataMethod || $userDataMethod == 'both' || $userDataMethod == 'personality') {
         $osPersonality = $personality;
     }
     if (!$userDataMethod || $userDataMethod == 'both' || $userDataMethod == 'meta-data' || $isWindows) {
         $osUserData = $launchOptions->userData;
     }
     $serverName = $serverNameFormat ? $DBServer->applyGlobalVarsToValue($serverNameFormat) : $DBServer->serverId;
     try {
         $result = $client->servers->createServer($serverName, $launchOptions->serverType, $launchOptions->imageId, null, $osUserData, $osPersonality, $networks, $extProperties);
         $instanceTypeInfo = $this->getInstanceType($launchOptions->serverType, $environment, $launchOptions->cloudLocation);
         /* @var $instanceTypeInfo CloudInstanceType */
         $DBServer->SetProperties([\OPENSTACK_SERVER_PROPERTIES::SERVER_ID => $result->id, \OPENSTACK_SERVER_PROPERTIES::IMAGE_ID => $launchOptions->imageId, \OPENSTACK_SERVER_PROPERTIES::ADMIN_PASS => $launchOptions->userData['vzc.adminpassword'] ? $launchOptions->userData['vzc.adminpassword'] : $result->adminPass, \OPENSTACK_SERVER_PROPERTIES::NAME => $DBServer->serverId, \SERVER_PROPERTIES::ARCHITECTURE => $launchOptions->architecture, \OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION => $launchOptions->cloudLocation, \SERVER_PROPERTIES::SYSTEM_USER_DATA_METHOD => $userDataMethod, \SERVER_PROPERTIES::INFO_INSTANCE_VCPUS => $instanceTypeInfo ? $instanceTypeInfo->vcpus : null]);
         if ($DBServer->farmRoleId) {
             $ipPool = $DBServer->GetFarmRoleObject()->GetSetting(Entity\FarmRoleSetting::OPENSTACK_IP_POOL);
             if ($ipPool) {
                 $DBServer->SetProperty(\SERVER_PROPERTIES::SYSTEM_IGNORE_INBOUND_MESSAGES, 1);
             }
         }
         $params = ['type' => $launchOptions->serverType];
         if ($instanceTypeInfo) {
             $params['instanceTypeName'] = $instanceTypeInfo->name;
         }
         $DBServer->setOsType($isWindows ? 'windows' : 'linux');
         $DBServer->cloudLocation = $launchOptions->cloudLocation;
         $DBServer->cloudLocationZone = "";
         // Not supported by openstack
         $DBServer->imageId = $launchOptions->imageId;
         $DBServer->update($params);
         // we set server history here
         $DBServer->getServerHistory()->update(['cloudServerId' => $result->id]);
         return $DBServer;
     } catch (\Exception $e) {
         throw new \Exception(sprintf(_("Cannot launch new instance. %s"), $e->getMessage()));
     }
 }
Пример #7
0
 /**
  * @test
  * @dataProvider providerRs
  */
 public function testFunctionalOpenStack($platform, $region, $imageId)
 {
     if ($this->isSkipFunctionalTests()) {
         $this->markTestSkipped();
     }
     /* @var $rs OpenStack */
     if ($this->getContainer()->environment->isPlatformEnabled($platform)) {
         $rs = $this->getContainer()->openstack($platform, $region);
         //             $rs->setDebug();
         $this->assertInstanceOf($this->getOpenStackClassName('OpenStack'), $rs);
     } else {
         //Environment has not been activated yet.
         $this->markTestSkipped(sprintf('Environment for the "%s" platform has not been activated.', $platform));
     }
     $os = $this->getContainer()->openstack($platform, 'INVALID-REGION-TEST');
     try {
         $ext = $os->servers->listExtensions();
         unset($os);
         $this->assertTrue(false, 'An exception must be thrown in this test');
     } catch (OpenStackException $e) {
         $this->assertTrue(true);
     }
     unset($os);
     //Activates rest client debug output
     $one = $rs->servers;
     $this->assertInstanceOf($this->getOpenStackClassName('Services\\ServersService'), $one);
     $two = $rs->servers;
     $this->assertInstanceOf($this->getOpenStackClassName('Services\\ServersService'), $two);
     $this->assertSame($one, $two, 'Service interface is expected to be cached within each separate OpenStack instance.');
     $aZones = $rs->listZones();
     $this->assertNotEmpty($aZones);
     unset($aZones);
     //List tenants test
     $tenants = $rs->listTenants();
     $this->assertNotEmpty($tenants);
     $this->assertTrue(is_array($tenants));
     unset($tenants);
     //Get Limits test
     $limits = $rs->servers->getLimits();
     $this->assertTrue(is_object($limits));
     unset($limits);
     $aExtensions = $rs->servers->listExtensions();
     $this->assertTrue(is_array($aExtensions));
     unset($aExtensions);
     $aExtensions = $rs->volume->listExtensions();
     $this->assertTrue(is_array($aExtensions));
     unset($aExtensions);
     $hasNetwork = $rs->hasService(OpenStack::SERVICE_NETWORK);
     if ($platform != SERVER_PLATFORMS::ECS && $hasNetwork) {
         $aExtensions = $rs->network->listExtensions();
         $this->assertTrue(is_array($aExtensions));
         unset($aExtensions);
         //Quantum API tests
         $testNetworkName = self::getTestName(self::NAME_NETWORK);
         $testSubnetName = self::getTestName(self::NAME_SUBNET);
         $testPortName = self::getTestName(self::NAME_PORT);
         $testRouterName = self::getTestName(self::NAME_ROUTER);
         //ListNetworks test
         $networks = $rs->network->networks->list(null, array('status' => 'ACTIVE', 'shared' => false));
         $this->assertInternalType('array', $networks);
         if (isset($networks[0])) {
             $this->assertInternalType('object', $networks[0]);
             $this->assertNotEmpty($networks[0]->id);
             //Show Network test
             $network = $rs->network->networks->list($networks[0]->id);
             $this->assertEquals($networks[0], $network);
             unset($network);
         }
         unset($networks);
         //ListSubnets test
         $subnets = $rs->network->subnets->list();
         $this->assertInternalType('array', $subnets);
         if (isset($subnets[0])) {
             $this->assertInternalType('object', $subnets[0]);
             $this->assertNotEmpty($subnets[0]->id);
             //Show Subnet test
             $subnet = $rs->network->subnets->list($subnets[0]->id);
             $this->assertEquals($subnets[0], $subnet);
             unset($subnet);
         }
         unset($subnets);
         //ListPorts test
         $ports = $rs->network->ports->list();
         $this->assertInternalType('array', $ports);
         if (isset($ports[0])) {
             $this->assertInternalType('object', $ports[0]);
             $this->assertNotEmpty($ports[0]->id);
             //Show Port test
             $port = $rs->network->ports->list($ports[0]->id);
             $this->assertEquals($ports[0], $port);
             unset($port);
         }
         unset($ports);
         //Tries to find the ports that were created recently by this test
         //but hadn't been removed at any reason.
         $ports = $rs->network->ports->list(null, array('name' => array($testPortName, $testPortName . '1')));
         foreach ($ports as $port) {
             //Removes previously created ports
             $rs->network->ports->delete($port->id);
         }
         unset($ports);
         //Tries to find the networks that were created recently by this test
         //but hadn't been removed at any reason.
         $networks = $rs->network->networks->list(null, array('name' => $testNetworkName));
         foreach ($networks as $network) {
             //Removes previously created networks
             $rs->network->networks->update($network->id, null, false);
             //Trying to remove allocated ports
             $portsToRemove = $rs->network->ports->list(null, array('networkId' => $network->id));
             foreach ($portsToRemove as $p) {
                 if (isset($p->device_owner) && isset($p->device_id) && $p->device_owner == 'network:router_interface') {
                     $rs->network->ports->update($p->id, array('admin_state_up' => false));
                     $rs->network->routers->removeInterface($p->device_id, null, $p->id);
                 }
             }
             $rs->network->networks->delete($network->id);
         }
         unset($networks);
         //Tries to find the subnets that where created by this test but hadn't been removed yet.
         $subnets = $rs->network->subnets->list(null, array('name' => array($testSubnetName, $testSubnetName . '1')));
         $this->assertInternalType('array', $subnets);
         foreach ($subnets as $subnet) {
             //Removes previously created subnets
             $rs->network->subnets->delete($subnet->id);
         }
         //Creates new network
         $network = $rs->network->networks->create($testNetworkName, false, false);
         $this->assertInternalType('object', $network);
         $this->assertNotEmpty($network->id);
         $this->assertEquals(false, $network->admin_state_up);
         $this->assertEquals(false, $network->shared);
         //Updates newtork state
         $network = $rs->network->networks->update($network->id, null, true);
         $this->assertInternalType('object', $network);
         $this->assertEquals(true, $network->admin_state_up);
         //Creates subnet
         $subnet = $rs->network->subnets->create(array('network_id' => $network->id, 'cidr' => '10.0.3.0/24', 'name' => $testSubnetName, 'allocation_pools' => array(new AllocationPool('10.0.3.20', '10.0.3.22'))));
         $this->assertInternalType('object', $subnet);
         $this->assertEquals($testSubnetName, $subnet->name);
         $this->assertNotEmpty($subnet->id);
         $this->assertInternalType('array', $subnet->allocation_pools);
         $this->assertNotEmpty($subnet->allocation_pools);
         $this->assertEquals('10.0.3.22', $subnet->allocation_pools[0]->end);
         //Updates the subnet
         $subnet = $rs->network->subnets->update($subnet->id, array('name' => $testSubnetName . '1'));
         $this->assertInternalType('object', $subnet);
         $this->assertNotEmpty($subnet->name);
         $this->assertEquals($testSubnetName . '1', $subnet->name);
         //Creates port
         //Let's use object here
         $req = new CreatePort($network->id);
         $req->name = $testPortName;
         //You may pass object aw well as array
         $port = $rs->network->ports->create($req);
         $this->assertInternalType('object', $port);
         $this->assertEquals($network->id, $port->network_id);
         $this->assertEquals($testPortName, $port->name);
         $this->assertNotEmpty($port->id);
         //Updates port
         $port = $rs->network->ports->update($port->id, array('name' => $testPortName . '1'));
         $this->assertInternalType('object', $port);
         $this->assertEquals($testPortName . '1', $port->name);
         //Quantum L3 Router related tests
         if ($rs->network->isExtensionSupported(NetworkExtension::quantumL3Router())) {
             //ListRouters test
             $routers = $rs->network->routers->list(null, array('status' => array('ACTIVE', 'PENDING')), array('id', 'name'));
             $this->assertInternalType('array', $routers);
             foreach ($routers as $r) {
                 $router = $rs->network->routers->list($r->id);
                 $this->assertInternalType('object', $router);
                 if ($r->name == $testRouterName) {
                     //Removes the router which is created by phpunit test before and is still alive by any reason.
                     //It requires all internal interfaces to be removed from router.
                     $ret = $rs->network->routers->delete($r->id);
                     $this->assertTrue($ret);
                 }
             }
             unset($routers);
             //Creates router
             $router = $rs->network->routers->create(new CreateRouter($testRouterName));
             $this->assertInternalType('object', $router);
             $this->assertObjectHasAttribute('name', $router);
             $this->assertNotEmpty($router->name);
             $this->assertEquals($testRouterName, $router->name);
             $this->assertObjectHasAttribute('id', $router);
             $this->assertNotEmpty($router->id);
             $this->assertObjectHasAttribute('admin_state_up', $router);
             $this->assertTrue($router->admin_state_up);
             //Updates the router
             $r2 = $rs->network->routers->update($router->id, array('admin_state_up' => false));
             $this->assertInternalType('object', $r2);
             $this->assertObjectHasAttribute('admin_state_up', $r2);
             $this->assertEquals(false, $r2->admin_state_up);
             //Adds interface to router
             $routerInterface1 = $rs->network->routers->addInterface($router->id, $subnet->id);
             $this->assertInternalType('object', $routerInterface1);
             $this->assertObjectHasAttribute('subnet_id', $routerInterface1);
             $this->assertEquals($subnet->id, $routerInterface1->subnet_id);
             $this->assertObjectHasAttribute('port_id', $routerInterface1);
             //Removes interface from router
             $obj = $rs->network->routers->removeInterface($router->id, $subnet->id);
             //                 It returns nothing NULL
             //                 $this->assertInternalType('object', $obj);
             //                 $this->assertObjectHasAttribute('subnet_id', $obj);
             //                 $this->assertEquals($subnet->id, $obj->subnet_id);
             //                 $this->assertObjectHasAttribute('port_id', $obj);
             //                 unset($obj);
             //Removes router
             $ret = $rs->network->routers->delete($router->id);
             $this->assertTrue($ret);
             unset($router);
         }
         //Removes port
         $ret = $rs->network->ports->delete($port->id);
         $this->assertTrue($ret);
         //Removes subnet
         $ret = $rs->network->subnets->delete($subnet->id);
         $this->assertTrue($ret);
         //Removes created network
         $rs->network->networks->update($network->id, null, false);
         $ret = $rs->network->networks->delete($network->id);
         $this->assertTrue($ret);
         unset($network);
     }
     //List snapshots test
     $snList = $rs->volume->snapshots->list();
     $this->assertTrue(is_array($snList));
     foreach ($snList as $v) {
         if ($v->display_name == self::getTestSnapshotName()) {
             $rs->volume->snapshots->delete($v->id);
         }
     }
     unset($snList);
     //List Volume Types test
     $volumeTypes = $rs->volume->listVolumeTypes();
     $this->assertTrue(is_array($volumeTypes));
     foreach ($volumeTypes as $v) {
         $volumeTypeDesc = $rs->volume->getVolumeType($v->id);
         $this->assertTrue(is_object($volumeTypeDesc));
         unset($volumeTypeDesc);
         break;
     }
     //List Volumes test
     $aVolumes = $rs->volume->listVolumes();
     $this->assertTrue(is_array($aVolumes));
     foreach ($aVolumes as $v) {
         if ($v->display_name == self::getTestVolumeName()) {
             if (in_array($v->status, array(VolumeStatus::STATUS_AVAILABLE, VolumeStatus::STATUS_ERROR))) {
                 $ret = $rs->volume->deleteVolume($v->id);
             }
         }
     }
     //Create Volume test
     $volume = $rs->volume->createVolume(self::VOLUME_SIZE, self::getTestVolumeName());
     $this->assertTrue(is_object($volume));
     $this->assertNotEmpty($volume->id);
     for ($t = time(), $s = 1; time() - $t < 300 && !in_array($volume->status, array(VolumeStatus::STATUS_AVAILABLE, VolumeStatus::STATUS_ERROR)); $s += 5) {
         sleep($s);
         $volume = $rs->volume->getVolume($volume->id);
         $this->assertTrue(is_object($volume));
         $this->assertNotEmpty($volume->id);
     }
     $this->assertContains($volume->status, array(VolumeStatus::STATUS_AVAILABLE, VolumeStatus::STATUS_ERROR));
     //         //Create snapshot test
     //         //WARNING! It takes too long time.
     //         $snap = $rs->volume->snapshots->create($volume->id, self::getTestSnapshotName());
     //         $this->assertTrue(is_object($snap));
     //         $this->assertNotEmpty($snap->id);
     //         for ($t = time(), $s = 1; (time() - $t) < 600 && !in_array($snap->status, array('available', 'error')); $s += 5) {
     //             sleep($s);
     //             $snap = $rs->volume->snapshots->get($snap->id);
     //             $this->assertNotEmpty($snap->id);
     //         }
     //         $this->assertContains($snap->status, array('available', 'error'));
     //         //Delete snapshot test
     //         $ret = $rs->volume->snapshots->delete($snap->id);
     //         $this->assertTrue($ret);
     //         unset($snap);
     //         sleep(5);
     //Delete Volume test
     $ret = $rs->volume->deleteVolume($volume->id);
     $this->assertTrue($ret);
     unset($volume);
     sleep(5);
     $pool = null;
     if ($rs->servers->isExtensionSupported(ServersExtension::floatingIpPools())) {
         $aFloatingIpPools = $rs->servers->listFloatingIpPools();
         $this->assertTrue(is_array($aFloatingIpPools));
         foreach ($aFloatingIpPools as $v) {
             $pool = $v->name;
             break;
         }
         $this->assertNotNull($pool);
         unset($aFloatingIpPools);
     }
     if ($rs->servers->isExtensionSupported(ServersExtension::floatingIps())) {
         $this->assertNotNull($pool);
         $aFloatingIps = $rs->servers->floatingIps->list();
         $this->assertTrue(is_array($aFloatingIps));
         foreach ($aFloatingIps as $v) {
             $r = $rs->servers->floatingIps->get($v->id);
             $this->assertTrue(is_object($r));
             break;
         }
         unset($aFloatingIps);
         //default pool for rackspase is 'nova'
         $fip = $rs->servers->floatingIps->create($pool);
         $this->assertTrue(is_object($fip));
         $r = $rs->servers->floatingIps->delete($fip->id);
         $this->assertTrue($r);
         try {
             //Verifies that ip has been successfully removed
             $res = $rs->servers->floatingIps->get($fip->id);
             $this->assertTrue(false, 'Exception must be thrown here');
         } catch (RestClientException $e) {
             if ($e->error->code == 404) {
                 $this->assertTrue(true);
             } else {
                 //OpenStack Grizzly fails with 500 error code.
                 //throw $e;
             }
         }
         unset($fip);
     }
     //List flavors test
     $flavorsList = $listFlavors = $rs->servers->listFlavors();
     $this->assertTrue(is_array($flavorsList));
     $flavorId = null;
     foreach ($flavorsList as $v) {
         $flavorId = $v->id;
         break;
     }
     $this->assertNotNull($flavorId);
     unset($flavorsList);
     //List servers test
     $ret = $rs->servers->list();
     $this->assertTrue(is_array($ret));
     if (!empty($ret)) {
         foreach ($ret as $v) {
             if ($v->name == self::getTestServerName() || $v->name == self::getTestServerName('renamed')) {
                 //Removes servers
                 try {
                     $rs->servers->deleteServer($v->id);
                 } catch (RestClientException $e) {
                     echo $e->getMessage() . "\n";
                 }
             }
         }
     }
     $personality = new PersonalityList();
     $personality->append(new Personality('/etc/scalr/private.d/.user-data', base64_encode('super data')));
     $personality->append(new Personality('/etc/.scalr-user-data', base64_encode('super data')));
     $netList = null;
     //Create server test
     $srv = $rs->servers->createServer(self::getTestServerName(), $flavorId, $imageId, null, null, $personality, $netList);
     $this->assertInstanceOf('stdClass', $srv);
     $srv = $rs->servers->getServerDetails($srv->id);
     $this->assertInstanceOf('stdClass', $srv);
     $this->assertNotEmpty($srv->status);
     for ($t = time(), $s = 10; time() - $t < 600 && !in_array($srv->status, array('ACTIVE', 'ERROR')); $s += 1) {
         sleep($s);
         $srv = $rs->servers->getServerDetails($srv->id);
     }
     $this->assertContains($srv->status, array('ACTIVE', 'ERROR'));
     if ($rs->servers->isExtensionSupported(ServersExtension::consoleOutput())) {
         $consoleOut = $rs->servers->getConsoleOutput($srv->id, 50);
     }
     //List Addresses test
     $addresses = $rs->servers->listAddresses($srv->id);
     $this->assertTrue(is_object($addresses));
     //Get server details test
     $srvDetails = $rs->servers->getServerDetails($srv->id);
     $this->assertInstanceOf('stdClass', $srvDetails);
     unset($srvDetails);
     //Images List test
     $imagesList = $rs->servers->images->list();
     $this->assertTrue(is_array($imagesList));
     foreach ($imagesList as $img) {
         if ($img->name == self::getTestName('image')) {
             $rs->servers->images->delete($img->id);
         }
         $imageDetails = $rs->servers->images->get($img->id);
         $this->assertTrue(is_object($imageDetails));
         unset($imageDetails);
         break;
     }
     unset($imagesList);
     //Keypairs extension test
     if ($rs->servers->isExtensionSupported(ServersExtension::keypairs())) {
         $aKeypairs = $rs->servers->keypairs->list();
         $this->assertTrue(is_array($aKeypairs));
         foreach ($aKeypairs as $v) {
             if ($v->keypair->name == self::getTestName('key')) {
                 $rs->servers->keypairs->delete($v->keypair->name);
             }
         }
         unset($aKeypairs);
         $kp = $rs->servers->keypairs->create(self::getTestName('key'));
         $this->assertNotEmpty($kp);
         $this->assertTrue(is_object($kp));
         $kptwin = $rs->servers->keypairs->get($kp->name);
         $this->assertNotEmpty($kptwin);
         $this->assertEquals($kp->public_key, $kptwin->public_key);
         unset($kptwin);
         $res = $rs->servers->keypairs->delete($kp->name);
         $this->assertTrue($res);
         unset($kp);
     }
     //Security Groups extension test
     if ($rs->servers->isExtensionSupported(ServersExtension::securityGroups())) {
         $listSecurityGroups = $rs->servers->securityGroups->list();
         $this->assertTrue(is_array($listSecurityGroups));
         foreach ($listSecurityGroups as $v) {
             if ($v->name == self::getTestName('security-group')) {
                 $rs->servers->securityGroups->delete($v->id);
             }
         }
         unset($listSecurityGroups);
         $listForSpecificServer = $rs->servers->securityGroups->list($srv->id);
         $this->assertTrue(is_array($listForSpecificServer));
         unset($listForSpecificServer);
         $sg = $rs->servers->securityGroups->create(self::getTestName('security-group'), 'This is phpunit security group test.');
         $this->assertNotEmpty($sg);
         $this->assertTrue(is_object($sg));
         $sgmirror = $rs->servers->securityGroups->get($sg->id);
         $this->assertNotEmpty($sgmirror);
         $this->assertEquals($sg->id, $sgmirror->id);
         unset($sgmirror);
         $sgrule = $rs->servers->securityGroups->addRule(array("ip_protocol" => "tcp", "from_port" => "80", "to_port" => "8080", "cidr" => "0.0.0.0/0", "parent_group_id" => $sg->id));
         $this->assertNotEmpty($sgrule);
         $this->assertTrue(is_object($sgrule));
         $this->assertEquals($sg->id, $sgrule->parent_group_id);
         $ret = $rs->servers->securityGroups->deleteRule($sgrule->id);
         $this->assertTrue($ret);
         unset($sgrule);
         $ret = $rs->servers->securityGroups->delete($sg->id);
         $this->assertTrue($ret);
     }
     //Create image test
     $imageId = $rs->servers->images->create($srv->id, self::getTestName('image'));
     $this->assertTrue(is_string($imageId));
     //It requires ACTIVE state of server
     //         $res = $rs->servers->resizeServer($srv->id, $srv->name, '3');
     //         $this->assertTrue($res);
     //         $res = $rs->servers->confirmResizedServer($srv->id);
     //         $this->assertTrue($res);
     $ret = $rs->servers->images->delete($imageId);
     $this->assertTrue($ret);
     //Update server test
     $renamedDetails = $rs->servers->updateServer($srv->id, self::getTestServerName('renamed'));
     $this->assertInstanceOf('stdClass', $renamedDetails);
     $this->assertEquals(self::getTestServerName('renamed'), $renamedDetails->server->name);
     unset($renamedDetails);
     //Delete Server test
     $ret = $rs->servers->deleteServer($srv->id);
     $this->assertTrue($ret);
 }