def createInstance(self, service_off, account=None,
                        project=None, networks=None, api_client=None):
        """Creates an instance in account"""

        if api_client is None:
            api_client = self.apiclient

        self.debug("Deploying instance")
        try:
            if account:
                vm = VirtualMachine.create(
                     api_client,
                     self.services["virtual_machine"],
                     templateid=self.template.id,
                     accountid=account.name,
                     domainid=account.domainid,
                     networkids=networks,
                     serviceofferingid=service_off.id)
            elif project:
                vm = VirtualMachine.create(
                     api_client,
                     self.services["virtual_machine"],
                     templateid=self.template.id,
                     projectid=project.id,
                     networkids=networks,
                     serviceofferingid=service_off.id)
            vms = VirtualMachine.list(api_client, id=vm.id, listall=True)
            self.assertIsInstance(vms,
                                  list,
                                  "List VMs should return a valid response")
            self.assertEqual(vms[0].state, "Running",
                             "Vm state should be running after deployment")
            return vm
        except Exception as e:
            self.fail("Failed to deploy an instance: %s" % e)
    def test_deployvm_userdispersing(self):
        """Test deploy VMs using user dispersion planner
        """
        self.service_offering_userdispersing = ServiceOffering.create(
            self.apiclient,
            self.services["service_offering"],
            deploymentplanner='UserDispersingPlanner'
        )

        self.virtual_machine_1 = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            zoneid=self.zone.id,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering_userdispersing.id,
            templateid=self.template.id
        )
        self.virtual_machine_2 = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            zoneid=self.zone.id,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering_userdispersing.id,
            templateid=self.template.id
        )

        list_vm_1 = VirtualMachine.list(self.apiclient, id=self.virtual_machine_1.id)
        list_vm_2 = VirtualMachine.list(self.apiclient, id=self.virtual_machine_2.id)
        self.assertEqual(
            isinstance(list_vm_1, list),
            True,
            "List VM response was not a valid list"
        )
        self.assertEqual(
            isinstance(list_vm_2, list),
            True,
            "List VM response was not a valid list"
        )
        vm1 = list_vm_1[0]
        vm2 = list_vm_2[0]
        self.assertEqual(
            vm1.state,
            "Running",
            msg="VM is not in Running state"
        )
        self.assertEqual(
            vm2.state,
            "Running",
            msg="VM is not in Running state"
        )
        vm1clusterid = filter(lambda c: c.id == vm1.hostid, self.hosts)[0].clusterid
        vm2clusterid = filter(lambda c: c.id == vm2.hostid, self.hosts)[0].clusterid
        if vm1clusterid == vm2clusterid:
            self.debug("VMs (%s, %s) meant to be dispersed are deployed in the same cluster %s" % (
            vm1.id, vm2.id, vm1clusterid))
    def test_deployvm_userconcentrated(self):
        """Test deploy VMs using user concentrated planner
        """
        self.service_offering_userconcentrated = ServiceOffering.create(
            self.apiclient,
            self.services["service_offering"],
            deploymentplanner='UserConcentratedPodPlanner'
        )

        self.virtual_machine_1 = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            zoneid=self.zone.id,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering_userconcentrated.id,
            templateid=self.template.id
        )
        self.virtual_machine_2 = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            zoneid=self.zone.id,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering_userconcentrated.id,
            templateid=self.template.id
        )

        list_vm_1 = VirtualMachine.list(self.apiclient, id=self.virtual_machine_1.id)
        list_vm_2 = VirtualMachine.list(self.apiclient, id=self.virtual_machine_2.id)
        self.assertEqual(
            isinstance(list_vm_1, list),
            True,
            "List VM response was not a valid list"
        )
        self.assertEqual(
            isinstance(list_vm_2, list),
            True,
            "List VM response was not a valid list"
        )
        vm1 = list_vm_1[0]
        vm2 = list_vm_2[0]
        self.assertEqual(
            vm1.state,
            "Running",
            msg="VM is not in Running state"
        )
        self.assertEqual(
            vm2.state,
            "Running",
            msg="VM is not in Running state"
        )
        self.assertNotEqual(
            vm1.hostid,
            vm2.hostid,
            msg="VMs meant to be concentrated are deployed on the different hosts"
        )
    def test_deploy_virtual_machines_static_offering(self, value):
        """Test deploy VM with static offering"""

        # Steps:
        # 1. Create admin/user account and create its user api client
        # 2. Create a static compute offering
        # 3. Deploy a VM with account api client and static service offering
        # 4. Repeat step 3 but also pass custom values for cpu number, cpu speed and memory
        #    while deploying VM

        # Validations:
        # 1. Step 3 should succeed
        # 2. Step 4 should fail

        isadmin=True
        if value == USER_ACCOUNT:
            isadmin=False

        # Create Account
        self.account = Account.create(self.apiclient,self.services["account"],domainid=self.domain.id, admin=isadmin)
        apiclient = self.testClient.createUserApiClient(
                                    UserName=self.account.name,
                                    DomainName=self.account.domain)
        self.cleanup.append(self.account)

        # Create service offering
        self.services["service_offering"]["cpunumber"] = 2
        self.services["service_offering"]["cpuspeed"] = 256
        self.services["service_offering"]["memory"] = 128

        serviceOffering = ServiceOffering.create(self.apiclient,
                                                 self.services["service_offering"])

        self.cleanup_co.append(serviceOffering)

        # Deploy VM with static service offering
        try:
            VirtualMachine.create(apiclient,self.services["virtual_machine"],
                                                    serviceofferingid=serviceOffering.id,
                                                    accountid=self.account.name,domainid=self.account.domainid)
        except Exception as e:
            self.fail("vm creation failed: %s" % e)

        # Deploy VM with static service offering, also with custom values
        try:
            VirtualMachine.create(apiclient,self.services["virtual_machine"],
                serviceofferingid=serviceOffering.id,
                customcpunumber=4,
                customcpuspeed=512,
                custommemory=256,
                accountid=self.account.name,domainid=self.account.domainid)
            self.fail("VM creation should have failed, it succeeded")
        except Exception as e:
            self.debug("vm creation failed as expected: %s" % e)
        return
    def test_deployvm_firstfit(self):
        """Test to deploy vm with a first fit offering
        """
        # FIXME: How do we know that first fit actually happened?
        self.service_offering_firstfit = ServiceOffering.create(
            self.apiclient, self.services["service_offering"], deploymentplanner="FirstFitPlanner"
        )

        self.virtual_machine = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            zoneid=self.zone.id,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering_firstfit.id,
            templateid=self.template.id,
        )

        list_vms = VirtualMachine.list(self.apiclient, id=self.virtual_machine.id)
        self.debug("Verify listVirtualMachines response for virtual machine: %s" % self.virtual_machine.id)
        self.assertEqual(isinstance(list_vms, list), True, "List VM response was not a valid list")
        self.assertNotEqual(len(list_vms), 0, "List VM response was empty")

        vm = list_vms[0]
        self.assertEqual(vm.state, "Running", msg="VM is not in Running state")
    def test_05_remove_used_range(self):
        """
        Test removing used vlan range
        """
        # 1. Use a vlan id from existing range by deploying an instance which
        #    will create a network with vlan id from this range
        # 4. Now try to remove this vlan range
        # 5. Vlan range should not get removed, should throw error

        account = Account.create(self.apiclient,self.services["account"],
                                 domainid=self.domain.id)

        self.debug("Deploying instance in the account: %s" % account.name)

        try:

            self.virtual_machine = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
                                                     accountid=account.name,domainid=account.domainid,
                                                     serviceofferingid=self.service_offering.id,
                                                     mode=self.zone.networktype)
            self.debug("Deployed instance in account: %s" % account.name)
            self.debug("Trying to remove vlan range : %s , This should fail" % self.vlan["partial_range"][0])

            with self.assertRaises(Exception) as e:
                self.physicalnetwork.update(self.apiClient, id = self.physicalnetworkid, vlan = self.vlan["partial_range"][0])

            self.debug("operation failed with exception: %s" % e.exception)
            account.delete(self.apiclient)

        except Exception as e:
            self.fail("Exception in test case: %s" % e)

        return
 def setUp(self):
     self.apiclient = self.testClient.getApiClient()
     self.dbclient = self.testClient.getDbConnection()
     self.account = Account.create(
                         self.apiclient,
                         self.services["account"],
                         domainid=self.domain.id
                         )
     self.virtual_machine = VirtualMachine.create(
                             self.apiclient,
                             self.services["virtual_machine"],
                             templateid=self.template.id,
                             accountid=self.account.name,
                             domainid=self.account.domainid,
                             serviceofferingid=self.service_offering.id
                             )
     self.public_ip = PublicIPAddress.create(
                                        self.apiclient,
                                        self.virtual_machine.account,
                                        self.virtual_machine.zoneid,
                                        self.virtual_machine.domainid,
                                        self.services["virtual_machine"]
                                        )
     self.cleanup = [
                     self.account,
                     ]
     return
    def test_01_deploy_vm_root_resize(self):
        """Test proper failure to deploy virtual machine with rootdisksize of 0 
        """
        if (self.apiclient.hypervisor == 'kvm'):
            newrootsize = 0
            success = False
            try:
                self.virtual_machine = VirtualMachine.create(
                    self.apiclient,
                    self.testdata["virtual_machine"],
                    accountid=self.account.name,
                    zoneid=self.zone.id,
                    domainid=self.account.domainid,
                    serviceofferingid=self.service_offering.id,
                    templateid=self.template.id,
                    rootdisksize=newrootsize
                )
            except Exception as ex:
                if "rootdisk size should be a non zero number" in str(ex):
                    success = True
                else:
                    self.debug("virtual machine create did not fail appropriately. Error was actually : " + str(ex));

            self.assertEqual(success, True, "Check if passing 0 as rootdisksize fails appropriately")
        else:
            self.debug("test 01 does not support hypervisor type " + self.apiclient.hypervisor);
    def create_vm(self, pfrule=False, egress_policy=True, RR=False):
        self.create_network_offering(egress_policy, RR)
         # Creating network using the network offering created
        self.debug("Creating network with network offering: %s" %
                                                    self.network_offering.id)
        self.network = Network.create(self.apiclient,
                                      self.services["network"],
                                      accountid=self.account.name,
                                      domainid=self.account.domainid,
                                      networkofferingid=self.network_offering.id,
                                      zoneid=self.zone.id)
        self.debug("Created network with ID: %s" % self.network.id)
        self.debug("Deploying instance in the account: %s" % self.account.name)

        project = None
        try:
            self.virtual_machine = VirtualMachine.create(self.apiclient,
                                                         self.services["virtual_machine"],
                                                         accountid=self.account.name,
                                                         domainid=self.domain.id,
                                                         serviceofferingid=self.service_offering.id,
                                                         mode=self.zone.networktype if pfrule else 'basic',
                                                         networkids=[str(self.network.id)],
                                                         projectid=project.id if project else None)
        except Exception as e:
            self.fail("Virtual machine deployment failed with exception: %s" % e)
        self.debug("Deployed instance in account: %s" % self.account.name)
Beispiel #10
0
 def setUp(self):
     try:
         self.apiclient = self.testClient.getApiClient()
         self.dbclient = self.testClient.getDbConnection()
         self.account = Account.create(
                             self.apiclient,
                             self.services["account"],
                             domainid=self.domain.id
                             )
         self.cleanup = [
                         self.account,
                         ]
         self.virtual_machine = VirtualMachine.create(
                                 self.apiclient,
                                 self.services["virtual_machine"],
                                 templateid=self.template.id,
                                 accountid=self.account.name,
                                 domainid=self.account.domainid,
                                 serviceofferingid=self.service_offering.id
                                 )
         self.public_ip = PublicIPAddress.create(
                                            self.apiclient,
                                            accountid=self.virtual_machine.account,
                                            zoneid=self.virtual_machine.zoneid,
                                            domainid=self.virtual_machine.domainid,
                                            services=self.services["virtual_machine"]
                                            )
         return
     except cloudstackAPIException as e:
             self.tearDown()
             raise e
    def test_02_deploy_vm_root_resize(self):
        """Test proper failure to deploy virtual machine with rootdisksize less than template size
        """
        if (self.apiclient.hypervisor == 'kvm'):
            newrootsize = (self.template.size >> 30) - 1
            
            self.assertEqual(newrootsize > 0, True, "Provided template is less than 1G in size, cannot run test")

            success = False
            try:
                self.virtual_machine = VirtualMachine.create(
                    self.apiclient,
                    self.testdata["virtual_machine"],
                    accountid=self.account.name,
                    zoneid=self.zone.id,
                    domainid=self.account.domainid,
                    serviceofferingid=self.service_offering.id,
                    templateid=self.template.id,
                    rootdisksize=newrootsize
                )
            except Exception as ex:
                if "rootdisksize override is smaller than template size" in str(ex):
                    success = True
                else:
                    self.debug("virtual machine create did not fail appropriately. Error was actually : " + str(ex));

            self.assertEqual(success, True, "Check if passing rootdisksize < templatesize fails appropriately")
        else:
            self.debug("test 01 does not support hypervisor type " + self.apiclient.hypervisor);
    def test_operations_non_root_admin_api_client(self, value):
        """Test basic operations using non root admin apii client"""

        # Steps:
        # 1. Create Domain and Account in it
        # 2. Create network in it (isoalted/ shared/ vpc)
        # 3. Create User API client of this account
        # 4. Deploy a VM in this network and account
        # 5. Add secondary IP to the default nic of VM using non root admin api client
        # 6. List secondary IPs using non root admin api client
        # 7. Remove secondary IP using non root admin api client

        # Validations:
        # 1. All the operations should be successful

        child_domain = Domain.create(self.apiclient,services=self.services["domain"],
                                     parentdomainid=self.domain.id)

        self.account = Account.create(self.apiclient,self.services["account"],domainid=child_domain.id)
        self.cleanup.append(self.account)
        self.cleanup.append(child_domain)

        apiclient = self.testClient.createUserApiClient(UserName=self.account.name, DomainName=self.account.domain)

        if(shouldTestBeSkipped(networkType=value, zoneType=self.mode)):
            self.skipTest("Skipping test as %s network is not supported in basic zone" % value)

        network = createNetwork(self, value)

        try:
            virtual_machine = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
                                                    networkids=[network.id],serviceofferingid=self.service_offering.id,
                                                    accountid=self.account.name,domainid=self.account.domainid)
        except Exception as e:
            self.fail("vm creation failed: %s" % e)

        try:
            ipaddress_1 = NIC.addIp(apiclient, id=virtual_machine.nic[0].id)
        except Exception as e:
            self.fail("Failed while adding secondary IP to NIC of vm %s" % virtual_machine.id)

        try:
            NIC.list(apiclient, virtualmachineid=virtual_machine.id)
        except Exception as e:
            self.fail("Listing NICs for virtual machine %s failed with Exception %s" % (virtual_machine.id, e))

        try:
            NIC.list(apiclient, virtualmachineid=virtual_machine.id, nicid=virtual_machine.nic[0].id)
        except Exception as e:
            self.fail("Listing NICs for virtual machine %s and nic id %s failed with Exception %s" %
                    (virtual_machine.id, virtual_machine.nic[0].id, e))

        try:
            NIC.removeIp(apiclient, ipaddressid=ipaddress_1.id)
        except Exception as e:
            self.fail("Removing seondary IP %s from NIC failed as expected with Exception %s" % (ipaddress_1.id,e))

        return
    def test_add_static_nat_rule(self, value):
        """ Add secondary IP to NIC of a VM"""

        # Steps:
        # 1. Create Account and create network in it (isoalted/ shared/ vpc)
        # 2. Deploy a VM in this network and account
        # 3. Add 2 secondary IPs to the default nic of VM
        # 4. Acquire public IP, open firewall for it, and
        #    create static NAT rule for this public IP to the 1st secondary IP
        # 5. Repeat step 4 for another public IP
        # 6. Repeat step 4 for 2nd secondary IP
        # 7. Repeat step 4 for invalid secondary IP
        # 8. Try to remove 1st secondary IP (with active static nat rule)

        # Validations:
        # 1. Step 4 should succeed
        # 2. Step 5 should succeed
        # 3. Step 6 should succeed
        # 4. Step 7 should fail
        # 5. Step 8 should succeed

        self.account = Account.create(self.apiclient,self.services["account"],domainid=self.domain.id)
        self.cleanup.append(self.account)

        network = createNetwork(self, value)

        try:
            virtual_machine = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
                                                    networkids=[network.id],serviceofferingid=self.service_offering.id,
                                                    accountid=self.account.name,domainid=self.account.domainid)
        except Exception as e:
            self.fail("vm creation failed: %s" % e)

        try:
            ipaddress_1 = NIC.addIp(self.apiclient, id=virtual_machine.nic[0].id)
        except Exception as e:
            self.fail("Failed while adding secondary IP to NIC of vm %s" % virtual_machine.id)

        try:
            ipaddress_2 = NIC.addIp(self.apiclient, id=virtual_machine.nic[0].id)
        except Exception as e:
            self.fail("Failed while adding secondary IP to NIC of vm %s" % virtual_machine.id)

        self.assertEqual(createNetworkRules(self, virtual_machine, network, ipaddress_1.ipaddress, value, ruletype="staticnat"),
                PASS, "Failure in creating NAT rule")
        self.assertEqual(createNetworkRules(self, virtual_machine, network, ipaddress_1.ipaddress, value, ruletype="staticnat"),
                FAIL, "Failure in creating NAT rule")
        self.assertEqual(createNetworkRules(self, virtual_machine, network, ipaddress_2.ipaddress, value, ruletype="staticnat"),
                PASS, "Failure in creating NAT rule")
        self.assertEqual(createNetworkRules(self, virtual_machine, network, "255.255.255.300", value, ruletype="staticnat"),
                FAIL, "Failure in NAT rule creation")

        try:
            NIC.removeIp(self.apiclient, ipaddress_1.id)
            self.fail("Ip address should not get removed when active static NAT rule is defined for it")
        except Exception as e:
            self.debug("Exception while removing secondary ip address as expected because static nat rule is present for it")
        return
    def test_disable_static_nat(self, value):
        """ Add secondary IP to NIC of a VM"""

        # Steps:
        # 1. Create Account and create network in it (isoalted/ shared/ vpc)
        # 2. Deploy a VM in this network and account
        # 3. Add 2 secondary IPs to the default nic of VM
        # 4. Acquire public IP, open firewall for it, and
        #    enable static NAT rule for this public IP to the 1st secondary IP
        # 5. Disable the static nat rule and enable it again

        # Validations:
        # 1. Verify step 5 by listing seconday IP and checking the appropriate flag

        self.account = Account.create(self.apiclient,self.services["account"],domainid=self.domain.id)
        self.cleanup.append(self.account)

        network = createNetwork(self, value)

        try:
            virtual_machine = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
                                                    networkids=[network.id],serviceofferingid=self.service_offering.id,
                                                    accountid=self.account.name,domainid=self.account.domainid)
        except Exception as e:
            self.fail("vm creation failed: %s" % e)

        try:
            ipaddress_1 = NIC.addIp(self.apiclient, id=virtual_machine.nic[0].id)
        except Exception as e:
            self.fail("Failed while adding secondary IP to NIC of vm %s" % virtual_machine.id)

        public_ip = PublicIPAddress.create(self.api_client,accountid=self.account.name,
                                           zoneid=self.zone.id,domainid=self.account.domainid,
                                           networkid=network.id, vpcid = network.vpcid if value == VPC_NETWORK else None)

        if value != VPC_NETWORK:
            FireWallRule.create(self.apiclient,ipaddressid=public_ip.ipaddress.id,
                                      protocol='TCP', cidrlist=[self.services["fwrule"]["cidr"]],
                                      startport=self.services["fwrule"]["startport"],endport=self.services["fwrule"]["endport"])

        StaticNATRule.enable(self.apiclient, public_ip.ipaddress.id, virtual_machine.id,
                    network.id, vmguestip=ipaddress_1.ipaddress)

        self.VerifyStaticNatForPublicIp(public_ip.ipaddress.id, True)

        # Disabling static NAT
        StaticNATRule.disable(self.apiclient, public_ip.ipaddress.id)

        self.VerifyStaticNatForPublicIp(public_ip.ipaddress.id, False)

        StaticNATRule.enable(self.apiclient, public_ip.ipaddress.id, virtual_machine.id,
                    network.id, vmguestip=ipaddress_1.ipaddress)

        self.VerifyStaticNatForPublicIp(public_ip.ipaddress.id, True)

        public_ip.delete(self.apiclient)
        return
    def setUpClass(cls):
        cls.api_client = super(TestServiceOfferings, cls).getClsTestClient().getApiClient()
        cls.services = Services().services
        domain = get_domain(cls.api_client, cls.services)
        cls.zone = get_zone(cls.api_client, cls.services)
        cls.services['mode'] = cls.zone.networktype

        cls.service_offering_1 = ServiceOffering.create(
            cls.api_client,
            cls.services["off"]
        )
        cls.service_offering_2 = ServiceOffering.create(
            cls.api_client,
            cls.services["off"]
        )
        template = get_template(
                            cls.api_client,
                            cls.zone.id,
                            cls.services["ostype"]
                            )
        # Set Zones and disk offerings
        cls.services["small"]["zoneid"] = cls.zone.id
        cls.services["small"]["template"] = template.id

        cls.services["medium"]["zoneid"] = cls.zone.id
        cls.services["medium"]["template"] = template.id

        # Create VMs, NAT Rules etc
        cls.account = Account.create(
                            cls.api_client,
                            cls.services["account"],
                            domainid=domain.id
                            )

        cls.small_offering = ServiceOffering.create(
                                    cls.api_client,
                                    cls.services["service_offerings"]["small"]
                                    )

        cls.medium_offering = ServiceOffering.create(
                                    cls.api_client,
                                    cls.services["service_offerings"]["medium"]
                                    )
        cls.medium_virtual_machine = VirtualMachine.create(
                                       cls.api_client,
                                       cls.services["medium"],
                                       accountid=cls.account.name,
                                       domainid=cls.account.domainid,
                                       serviceofferingid=cls.medium_offering.id,
                                       mode=cls.services["mode"]
                                    )
        cls._cleanup = [
                        cls.small_offering,
                        cls.medium_offering,
                        cls.account
                        ]
        return
    def setUpClass(cls):
        cls.api_client = super(TestBaseImageUpdate, cls).getClsTestClient().getApiClient()
        cls.services = Services().services
        # Get Zone, Domain and templates
        cls.domain = get_domain(cls.api_client, cls.services)
        cls.zone = get_zone(cls.api_client, cls.services)
        cls.template = get_template(cls.api_client, cls.zone.id, cls.services["ostype"])
        cls.services["virtual_machine"]["zoneid"] = cls.zone.id
        cls.services["virtual_machine"]["template"] = cls.template.id

        cls.service_offering_with_reset = ServiceOffering.create(
            cls.api_client, cls.services["service_offering_with_reset"]
        )

        cls.service_offering_without_reset = ServiceOffering.create(
            cls.api_client, cls.services["service_offering_without_reset"]
        )

        cls.account = Account.create(cls.api_client, cls.services["account"], admin=True, domainid=cls.domain.id)

        cls.vm_with_reset = VirtualMachine.create(
            cls.api_client,
            cls.services["virtual_machine"],
            accountid=cls.account.name,
            domainid=cls.account.domainid,
            serviceofferingid=cls.service_offering_with_reset.id,
        )
        cls.vm_with_reset_root_disk_id = cls.get_root_device_uuid_for_vm(
            cls.vm_with_reset.id, cls.vm_with_reset.rootdeviceid
        )

        cls.vm_without_reset = VirtualMachine.create(
            cls.api_client,
            cls.services["virtual_machine"],
            accountid=cls.account.name,
            domainid=cls.account.domainid,
            serviceofferingid=cls.service_offering_without_reset.id,
        )
        cls.vm_without_reset_root_disk_id = cls.get_root_device_uuid_for_vm(
            cls.vm_without_reset.id, cls.vm_without_reset.rootdeviceid
        )

        cls._cleanup = [cls.account, cls.service_offering_with_reset, cls.service_offering_without_reset]
        return
    def test_add_ip_to_nic(self, value):
        """ Add secondary IP to NIC of a VM"""

        # Steps:
        # 1. Create Account and create network in it (isoalted/ shared/ vpc)
        # 2. Deploy a VM in this network and account
        # 3. Add secondary IP to the default nic of VM
        # 4. Try to add the same IP again
        # 5. Try to add secondary IP providing wrong virtual machine id
        # 6. Try to add secondary IP with correct virtual machine id but wrong IP address

        # Validations:
        # 1. Step 3 should succeed
        # 2. Step 4 should fail
        # 3. Step 5 should should fail
        # 4. Step 6 should fail

        self.account = Account.create(self.apiclient,self.services["account"],domainid=self.domain.id)
        self.cleanup.append(self.account)

        if(shouldTestBeSkipped(networkType=value, zoneType=self.mode)):
            self.skipTest("Skipping test as %s network is not supported in basic zone" % value)

        network = createNetwork(self, value)

        try:
            virtual_machine = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
                                                    networkids=[network.id],serviceofferingid=self.service_offering.id,
                                                    accountid=self.account.name,domainid=self.account.domainid)
        except Exception as e:
            self.fail("vm creation failed: %s" % e)

        try:
            ipaddress_1 = NIC.addIp(self.apiclient, id=virtual_machine.nic[0].id)
        except Exception as e:
            self.fail("Failed while adding secondary IP to NIC of vm %s" % virtual_machine.id)

        try:
            NIC.addIp(self.apiclient, id=virtual_machine.nic[0].id, ipaddress=ipaddress_1.ipaddress)
            self.debug("Adding already added secondary IP %s to NIC of vm %s succeeded, should have failed" %
                    (ipaddress_1.ipaddress, virtual_machine.id))
        except Exception as e:
            self.debug("Failed while adding already added secondary IP to NIC of vm %s" % virtual_machine.id)

        try:
            NIC.addIp(self.apiclient, id=(virtual_machine.nic[0].id + random_gen()))
            self.fail("Adding secondary IP with wrong NIC id succeded, it shoud have failed")
        except Exception as e:
            self.debug("Failed while adding secondary IP to wrong NIC")

        try:
            NIC.addIp(self.apiclient, id=virtual_machine.nic[0].id, ipaddress = "255.255.255.300")
            self.fail("Adding secondary IP with wrong ipaddress succeded, it should have failed")
        except Exception as e:
            self.debug("Failed while adding wrong secondary IP to NIC of VM %s" % virtual_machine.id)
        return
Beispiel #18
0
    def test_deploy_vm_multiple(self):
        """Test Multiple Deploy Virtual Machine

        # Validate the following:
        # 1. deploy 2 virtual machines 
        # 2. listVirtualMachines using 'ids' parameter returns accurate information
        """
        self.virtual_machine = VirtualMachine.create(
            self.apiclient,
            self.testdata["virtual_machine"],
            accountid=self.account.name,
            zoneid=self.zone.id,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            templateid=self.template.id
        )

        self.virtual_machine2 = VirtualMachine.create(
            self.apiclient,
            self.testdata["virtual_machine2"],
            accountid=self.account.name,
            zoneid=self.zone.id,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            templateid=self.template.id
        )

        list_vms = VirtualMachine.list(self.apiclient, ids=[self.virtual_machine.id, self.virtual_machine2.id], listAll=True)
        self.debug(
            "Verify listVirtualMachines response for virtual machines: %s, %s" % (self.virtual_machine.id, self.virtual_machine2.id)
        )

        self.assertEqual(
            isinstance(list_vms, list),
            True,
            "List VM response was not a valid list"
        )
        self.assertEqual(
            len(list_vms),
            2,
            "List VM response was empty, expected 2 VMs"
        )
    def setUpClass(cls):
        cls.services = Services().services
        cls.apiclient = super(TestDeployVM, cls).getClsTestClient().getApiClient()
        # Get Zone, Domain and templates
        domain = get_domain(cls.apiclient, cls.services)
        cls.zone = get_zone(cls.apiclient, cls.services)
        cls.services['mode'] = cls.zone.networktype

        #If local storage is enabled, alter the offerings to use localstorage
        #this step is needed for devcloud
        if cls.zone.localstorageenabled == True:
            cls.services["service_offerings"]["tiny"]["storagetype"] = 'local'
            cls.services["service_offerings"]["small"]["storagetype"] = 'local'
            cls.services["service_offerings"]["medium"]["storagetype"] = 'local'

        template = get_template(
            cls.apiclient,
            cls.zone.id,
            cls.services["ostype"]
        )
        # Set Zones and disk offerings
        cls.services["small"]["zoneid"] = cls.zone.id
        cls.services["small"]["template"] = template.id

        cls.services["medium"]["zoneid"] = cls.zone.id
        cls.services["medium"]["template"] = template.id
        cls.services["iso"]["zoneid"] = cls.zone.id

        cls.account = Account.create(
            cls.apiclient,
            cls.services["account"],
            domainid=domain.id
        )
        cls.debug(cls.account.id)

        cls.service_offering = ServiceOffering.create(
            cls.apiclient,
            cls.services["service_offerings"]["tiny"]
        )

        cls.virtual_machine = VirtualMachine.create(
            cls.apiclient,
            cls.services["small"],
            accountid=cls.account.name,
            domainid=cls.account.domainid,
            serviceofferingid=cls.service_offering.id,
            mode=cls.services['mode']
        )

        cls.cleanup = [
            cls.service_offering,
            cls.account
        ]
Beispiel #20
0
    def test_deploy_vm(self):
        """Test Deploy Virtual Machine

        # Validate the following:
        # 1. Virtual Machine is accessible via SSH
        # 2. listVirtualMachines returns accurate information
        """
        self.virtual_machine = VirtualMachine.create(
            self.apiclient,
            self.testdata["virtual_machine"],
            accountid=self.account.name,
            zoneid=self.zone.id,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            templateid=self.template.id
        )

        list_vms = VirtualMachine.list(self.apiclient, id=self.virtual_machine.id)

        self.debug(
            "Verify listVirtualMachines response for virtual machine: %s"\
            % self.virtual_machine.id
        )

        self.assertEqual(
            isinstance(list_vms, list),
            True,
            "List VM response was not a valid list"
        )
        self.assertNotEqual(
            len(list_vms),
            0,
            "List VM response was empty"
        )

        vm = list_vms[0]
        self.assertEqual(
            vm.id,
            self.virtual_machine.id,
            "Virtual Machine ids do not match"
        )
        self.assertEqual(
            vm.name,
            self.virtual_machine.name,
            "Virtual Machine names do not match"
        )
        self.assertEqual(
            vm.state,
            "Running",
            msg="VM is not in Running state"
        )
    def test_disassociate_ip_mapped_to_secondary_ip_through_PF_rule(self, value):
        """ Add secondary IP to NIC of a VM"""

        ## Steps:
        # 1. Create Account and create network in it (isoalted/ shared/ vpc)
        # 2. Deploy a VM in this network and account
        # 3. Add secondary IP to the default nic of VM
        # 4. Acquire public IP, open firewall for it, and
        #    create NAT rule for this public IP to the 1st secondary IP
        # 5. Try to delete the public IP used for NAT rule

        # Validations:
        # 1. Step 5 should succeed

        self.account = Account.create(self.apiclient,self.services["account"],domainid=self.domain.id)
        self.cleanup.append(self.account)

        network = createNetwork(self, value)

        try:
            virtual_machine = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
                                                    networkids=[network.id],serviceofferingid=self.service_offering.id,
                                                    accountid=self.account.name,domainid=self.account.domainid)
        except Exception as e:
            self.fail("vm creation failed: %s" % e)

        try:
            ipaddress_1 = NIC.addIp(self.apiclient, id=virtual_machine.nic[0].id)
        except Exception as e:
            self.fail("Failed while adding secondary IP to NIC of vm %s" % virtual_machine.id)

        public_ip = PublicIPAddress.create(self.api_client,accountid=self.account.name,
                                           zoneid=self.zone.id,domainid=self.account.domainid,
                                           networkid=network.id, vpcid = network.vpcid if value == VPC_NETWORK else None)

        if value != VPC_NETWORK:
            FireWallRule.create(self.apiclient,ipaddressid=public_ip.ipaddress.id,
                                      protocol='TCP', cidrlist=[self.services["fwrule"]["cidr"]],
                                      startport=self.services["fwrule"]["startport"],endport=self.services["fwrule"]["endport"])

        # Create NAT rule
        natrule = NATRule.create(self.api_client, virtual_machine,
                       self.services["natrule"],ipaddressid=public_ip.ipaddress.id,
                       networkid=network.id, vmguestip = ipaddress_1.ipaddress)

        try:
            public_ip.delete(self.apiclient)
        except Exception as e:
            self.fail("Exception while deleting nat rule %s: %s" % (natrule.id, e))
        return
Beispiel #22
0
    def createInstance(self,
                       service_off,
                       account=None,
                       project=None,
                       networks=None,
                       api_client=None):
        """Creates an instance in account"""

        if api_client is None:
            api_client = self.apiclient

        self.debug("Deploying instance")
        try:
            if account:
                vm = VirtualMachine.create(api_client,
                                           self.services["virtual_machine"],
                                           templateid=self.template.id,
                                           accountid=account.name,
                                           domainid=account.domainid,
                                           networkids=networks,
                                           serviceofferingid=service_off.id)
            elif project:
                vm = VirtualMachine.create(api_client,
                                           self.services["virtual_machine"],
                                           templateid=self.template.id,
                                           projectid=project.id,
                                           networkids=networks,
                                           serviceofferingid=service_off.id)
            vms = VirtualMachine.list(api_client, id=vm.id, listall=True)
            self.assertIsInstance(vms, list,
                                  "List VMs should return a valid response")
            self.assertEqual(vms[0].state, "Running",
                             "Vm state should be running after deployment")
            return vm
        except Exception as e:
            self.fail("Failed to deploy an instance: %s" % e)
Beispiel #23
0
    def create_VM_in_Network(self, network, host_id=None):
        try:
            self.debug('Creating VM in network=%s' % network.name)
            vm = VirtualMachine.create(
                self.apiclient,
                self.services["virtual_machine"],
                accountid=self.account.name,
                domainid=self.account.domainid,
                serviceofferingid=self.service_offering.id,
                networkids=[str(network.id)],
                hostid=host_id)
            self.debug('Created VM=%s in network=%s' % (vm.id, network.name))

            return vm
        except:
            self.fail('Unable to create VM in a Network=%s' % network.name)
    def deployvm_in_network(self, network, host_id=None):
        try:
                self.debug('Creating VM in network=%s' % network.name)
                vm = VirtualMachine.create(
                                                self.apiclient,
                                                self.services["virtual_machine"],
                                                accountid=self.account.name,
                                                domainid=self.account.domainid,
                                                serviceofferingid=self.service_offering.id,
                                                networkids=[str(network.id)],
                                                hostid=host_id
                                                )
                self.debug('Created VM=%s in network=%s' % (vm.id, network.name))

                return vm
        except:
                self.fail('Unable to create VM in a Network=%s' % network.name)
Beispiel #25
0
    def test_remove_ip_from_nic(self, value):
        """ Remove secondary IP from NIC of a VM"""

        # Steps:
        # 1. Create Account and create network in it (isoalted/ shared/ vpc)
        # 2. Deploy a VM in this network and account
        # 3. Add secondary IP to the default nic of VM
        # 4. Remove the secondary IP
        # 5. Try to remove secondary ip by giving incorrect ipaddress id

        # Validations:
        # 1. Step 4 should succeed
        # 2. Step 5 should fail

        self.account = Account.create(self.apiclient,self.services["account"],domainid=self.domain.id)
        self.cleanup.append(self.account)

        if(shouldTestBeSkipped(networkType=value, zoneType=self.mode)):
            self.skipTest("Skipping test as %s network is not supported in basic zone" % value)

        network = createNetwork(self, value)

        try:
            virtual_machine = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
                                                    networkids=[network.id],serviceofferingid=self.service_offering.id,
                                                    accountid=self.account.name,domainid=self.account.domainid)
        except Exception as e:
            self.fail("vm creation failed: %s" % e)

        try:
            ipaddress_1 = NIC.addIp(self.apiclient, id=virtual_machine.nic[0].id)
        except Exception as e:
            self.fail("Failed while adding secondary IP to NIC of vm %s" % virtual_machine.id)

        try:
            NIC.removeIp(self.apiclient, ipaddressid=ipaddress_1.id)
        except Exception as e:
            self.fail("Removing seondary IP %s from NIC failed as expected with Exception %s" % (ipaddress_1.id,e))

        try:
            NIC.removeIp(self.apiclient, ipaddressid=(ipaddress_1.id + random_gen()))
            self.fail("Removing invalid IP address, it should have failed")
        except Exception as e:
            self.debug("Removing invalid IP failed as expected with Exception %s" % e)
        return
Beispiel #26
0
 def create_VM(self, host_id=None):
     try:
         self.debug('Creating VM for account=%s' % self.account.name)
         vm = VirtualMachine.create(
             self.apiclient,
             self.services["virtual_machine"],
             templateid=self.template.id,
             accountid=self.account.name,
             domainid=self.account.domainid,
             serviceofferingid=self.service_offering.id,
             hostid=host_id,
             mode=self.services["mode"])
         self.debug('Created VM=%s in account=%s' %
                    (vm.id, self.account.name))
         return vm
     except Exception as e:
         self.fail('Unable to deploy VM in a account=%s - %s' %
                   (self.account.name, e))
    def setUpClass(cls):
        cls.services = Services().services
        cls.apiclient = super(TestDeployVM,
                              cls).getClsTestClient().getApiClient()
        # Get Zone, Domain and templates
        domain = get_domain(cls.apiclient, cls.services)
        cls.zone = get_zone(cls.apiclient, cls.services)
        cls.services['mode'] = cls.zone.networktype

        #If local storage is enabled, alter the offerings to use localstorage
        #this step is needed for devcloud
        if cls.zone.localstorageenabled == True:
            cls.services["service_offerings"]["tiny"]["storagetype"] = 'local'
            cls.services["service_offerings"]["small"]["storagetype"] = 'local'
            cls.services["service_offerings"]["medium"][
                "storagetype"] = 'local'

        template = get_template(cls.apiclient, cls.zone.id,
                                cls.services["ostype"])
        # Set Zones and disk offerings
        cls.services["small"]["zoneid"] = cls.zone.id
        cls.services["small"]["template"] = template.id

        cls.services["medium"]["zoneid"] = cls.zone.id
        cls.services["medium"]["template"] = template.id
        cls.services["iso"]["zoneid"] = cls.zone.id

        cls.account = Account.create(cls.apiclient,
                                     cls.services["account"],
                                     domainid=domain.id)
        cls.debug(cls.account.id)

        cls.service_offering = ServiceOffering.create(
            cls.apiclient, cls.services["service_offerings"]["tiny"])

        cls.virtual_machine = VirtualMachine.create(
            cls.apiclient,
            cls.services["small"],
            accountid=cls.account.name,
            domainid=cls.account.domainid,
            serviceofferingid=cls.service_offering.id,
            mode=cls.services['mode'])

        cls.cleanup = [cls.service_offering, cls.account]
 def create_VM(self, host_id=None):
     try:
         self.debug('Creating VM for account=%s' %
                                         self.account.name)
         vm = VirtualMachine.create(
                                 self.apiclient,
                                 self.services["virtual_machine"],
                                 templateid=self.template.id,
                                 accountid=self.account.name,
                                 domainid=self.account.domainid,
                                 serviceofferingid=self.service_offering.id,
                                 hostid=host_id,
                                 mode=self.services["mode"]
                                 )
         self.debug('Created VM=%s in account=%s' %
                                     (vm.id, self.account.name))
         return vm
     except Exception as e:
         self.fail('Unable to deploy VM in a account=%s - %s' %
                                             (self.account.name, e))
Beispiel #29
0
 def setUp(self):
     self.apiclient = self.testClient.getApiClient()
     self.dbclient = self.testClient.getDbConnection()
     self.account = Account.create(self.apiclient,
                                   self.services["account"],
                                   domainid=self.domain.id)
     self.virtual_machine = VirtualMachine.create(
         self.apiclient,
         self.services["virtual_machine"],
         templateid=self.template.id,
         accountid=self.account.name,
         domainid=self.account.domainid,
         serviceofferingid=self.service_offering.id)
     self.public_ip = PublicIPAddress.create(
         self.apiclient, self.virtual_machine.account,
         self.virtual_machine.zoneid, self.virtual_machine.domainid,
         self.services["virtual_machine"])
     self.cleanup = [
         self.account,
     ]
     return
Beispiel #30
0
    def setUpClass(cls):
        cls.api_client = super(TestServiceOfferings,
                               cls).getClsTestClient().getApiClient()
        cls.services = Services().services
        domain = get_domain(cls.api_client, cls.services)
        cls.zone = get_zone(cls.api_client, cls.services)
        cls.services['mode'] = cls.zone.networktype

        cls.service_offering_1 = ServiceOffering.create(
            cls.api_client, cls.services["off"])
        cls.service_offering_2 = ServiceOffering.create(
            cls.api_client, cls.services["off"])
        template = get_template(cls.api_client, cls.zone.id,
                                cls.services["ostype"])
        # Set Zones and disk offerings
        cls.services["small"]["zoneid"] = cls.zone.id
        cls.services["small"]["template"] = template.id

        cls.services["medium"]["zoneid"] = cls.zone.id
        cls.services["medium"]["template"] = template.id

        # Create VMs, NAT Rules etc
        cls.account = Account.create(cls.api_client,
                                     cls.services["account"],
                                     domainid=domain.id)

        cls.small_offering = ServiceOffering.create(
            cls.api_client, cls.services["service_offerings"]["small"])

        cls.medium_offering = ServiceOffering.create(
            cls.api_client, cls.services["service_offerings"]["medium"])
        cls.medium_virtual_machine = VirtualMachine.create(
            cls.api_client,
            cls.services["medium"],
            accountid=cls.account.name,
            domainid=cls.account.domainid,
            serviceofferingid=cls.medium_offering.id,
            mode=cls.services["mode"])
        cls._cleanup = [cls.small_offering, cls.medium_offering, cls.account]
        return
 def test_deployvm_userdata(self):
     """Test userdata as GET, size > 2k
     """
     deployVmResponse = VirtualMachine.create(
         self.apiClient,
         services=self.services["virtual_machine"],
         accountid=self.account.name,
         domainid=self.account.domainid,
         serviceofferingid=self.service_offering.id,
         templateid=self.template.id,
         zoneid=self.zone.id
     )
     vms = list_virtual_machines(
         self.apiClient,
         account=self.account.name,
         domainid=self.account.domainid,
         id=deployVmResponse.id
     )
     self.assert_(len(vms) > 0, "There are no Vms deployed in the account %s" % self.account.name)
     vm = vms[0]
     self.assert_(vm.id == str(deployVmResponse.id), "Vm deployed is different from the test")
     self.assert_(vm.state == "Running", "VM is not in Running state")
 def test_deployvm_userdata(self):
     """Test userdata as GET, size > 2k
     """
     deployVmResponse = VirtualMachine.create(
         self.apiClient,
         services=self.services["virtual_machine"],
         accountid=self.account.name,
         domainid=self.account.domainid,
         serviceofferingid=self.service_offering.id,
         templateid=self.template.id,
         zoneid=self.zone.id)
     vms = list_virtual_machines(self.apiClient,
                                 account=self.account.name,
                                 domainid=self.account.domainid,
                                 id=deployVmResponse.id)
     self.assert_(
         len(vms) > 0,
         "There are no Vms deployed in the account %s" % self.account.name)
     vm = vms[0]
     self.assert_(vm.id == str(deployVmResponse.id),
                  "Vm deployed is different from the test")
     self.assert_(vm.state == "Running", "VM is not in Running state")
 def create_vm(self,
               account,
               domain,
               isRunning=False,
               project  =None,
               limit    =None,
               pfrule   =False,
               lbrule   =None,
               natrule  =None,
               volume   =None,
               snapshot =False):
     #TODO: Implemnt pfrule/lbrule/natrule
     self.debug("Deploying instance in the account: %s" % account.name)
     self.virtual_machine = VirtualMachine.create(self.apiclient,
                                                  self.services["virtual_machine"],
                                                  accountid=account.name,
                                                  domainid=domain.id,
                                                  serviceofferingid=self.service_offering.id,
                                                  mode=self.zone.networktype if pfrule else 'basic',
                                                  projectid=project.id if project else None)
     self.debug("Deployed instance in account: %s" % account.name)
     list_virtual_machines(self.apiclient,
                           id=self.virtual_machine.id)
     if snapshot:
        volumes = list_volumes(self.apiclient,
                               virtualmachineid=self.virtual_machine.id,
                               type='ROOT',
                               listall=True)
        self.snapshot = Snapshot.create(self.apiclient,
                                   volumes[0].id,
                                   account=account.name,
                                   domainid=account.domainid)
     if volume:
         self.virtual_machine.attach_volume(self.apiclient,
                                            volume)
     if not isRunning:
         self.virtual_machine.stop(self.apiclient)
     self.cleanup.append(self.virtual_machine)
Beispiel #34
0
 def create_vm(self,
               account,
               domain,
               isRunning=False,
               project=None,
               limit=None,
               pfrule=False,
               lbrule=None,
               natrule=None,
               volume=None,
               snapshot=False):
     #TODO: Implemnt pfrule/lbrule/natrule
     self.debug("Deploying instance in the account: %s" % account.name)
     self.virtual_machine = VirtualMachine.create(
         self.apiclient,
         self.services["virtual_machine"],
         accountid=account.name,
         domainid=domain.id,
         serviceofferingid=self.service_offering.id,
         mode=self.zone.networktype if pfrule else 'basic',
         projectid=project.id if project else None)
     self.debug("Deployed instance in account: %s" % account.name)
     list_virtual_machines(self.apiclient, id=self.virtual_machine.id)
     if snapshot:
         volumes = list_volumes(self.apiclient,
                                virtualmachineid=self.virtual_machine.id,
                                type='ROOT',
                                listall=True)
         self.snapshot = Snapshot.create(self.apiclient,
                                         volumes[0].id,
                                         account=account.name,
                                         domainid=account.domainid)
     if volume:
         self.virtual_machine.attach_volume(self.apiclient, volume)
     if not isRunning:
         self.virtual_machine.stop(self.apiclient)
     self.cleanup.append(self.virtual_machine)
    def CreateVM(self, newvm):

        virtual_machine = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            zoneid=self.zone.id,
            domainid=self.domain.id,
            templateid=self.template.id,
            accountid=self.find_account(newvm["account"]).__dict__["name"],
            serviceofferingid=self.find_service_offering(newvm["service_offering"]).id
        )

        list_vms = VirtualMachine.list(self.apiclient, id=virtual_machine.id)
        self.debug(
            "Verify listVirtualMachines response for virtual machine: %s"\
            % virtual_machine.id
        )
        self.assertEqual(
            isinstance(list_vms, list),
            True,
            "List VM response was not a valid list"
        )
        self.assertNotEqual(
            len(list_vms),
            0,
            "List VM response was empty"
        )

        vm = list_vms[0]
        self.assertEqual(
            vm.state,
            "Running",
            msg="VM is not in Running state"
        )

        return virtual_machine.id
    def setUpClass(cls):
        cls.api_client = super(
                               TestBaseImageUpdate,
                               cls
                               ).getClsTestClient().getApiClient()
        cls.services = Services().services
        # Get Zone, Domain and templates
        cls.domain = get_domain(cls.api_client, cls.services)
        cls.zone = get_zone(cls.api_client, cls.services)
        cls.template = get_template(
                            cls.api_client,
                            cls.zone.id,
                            cls.services["ostype"]
                            )
        cls.services["virtual_machine"]["zoneid"] = cls.zone.id
        cls.services["virtual_machine"]["template"] = cls.template.id

        cls.service_offering_with_reset = ServiceOffering.create(
                                            cls.api_client,
                                            cls.services["service_offering_with_reset"]
                                            )

        cls.service_offering_without_reset = ServiceOffering.create(
                                                cls.api_client,
                                                cls.services["service_offering_without_reset"]
                                                )

        cls.account = Account.create(
                                     cls.api_client,
                                     cls.services["account"],
                                     admin=True,
                                     domainid=cls.domain.id
                                     )

        cls.vm_with_reset = VirtualMachine.create(
                                  cls.api_client,
                                  cls.services["virtual_machine"],
                                  accountid=cls.account.name,
                                  domainid=cls.account.domainid,
                                  serviceofferingid=cls.service_offering_with_reset.id,
                                  )
        cls.vm_with_reset_root_disk_id = cls.get_root_device_uuid_for_vm(cls.vm_with_reset.id,
                                                cls.vm_with_reset.rootdeviceid)


        cls.vm_without_reset = VirtualMachine.create(
                                  cls.api_client,
                                  cls.services["virtual_machine"],
                                  accountid=cls.account.name,
                                  domainid=cls.account.domainid,
                                  serviceofferingid=cls.service_offering_without_reset.id,
                                  )
        cls.vm_without_reset_root_disk_id = cls.get_root_device_uuid_for_vm(cls.vm_without_reset.id,
                                                cls.vm_without_reset.rootdeviceid)

        cls._cleanup = [
                        cls.account,
                        cls.service_offering_with_reset,
                        cls.service_offering_without_reset,
                        ]
        return
Beispiel #37
0
    def setUp(self):
        self.testdata = TestData().testdata
        self.apiclient = self.testClient.getApiClient()

        # Get Zone, Domain and Default Built-in template
        self.domain = get_domain(self.apiclient, self.testdata)
        self.zone = get_zone(self.apiclient, self.testdata)
        self.testdata["mode"] = self.zone.networktype
        self.template = get_template(self.apiclient, self.zone.id, self.testdata["ostype"])

        self.hosts = []
        suitablecluster = None
        clusters = Cluster.list(self.apiclient)
        self.assertTrue(isinstance(clusters, list) and len(clusters) > 0, msg = "No clusters found")
        for cluster in clusters:
            self.hosts = Host.list(self.apiclient, clusterid=cluster.id, type='Routing')
            if isinstance(self.hosts, list) and len(self.hosts) >= 2:
                suitablecluster = cluster
                break
        self.assertTrue(isinstance(self.hosts, list) and len(self.hosts) >= 2, msg = "Atleast 2 hosts required in cluster for VM HA test")
        #update host tags
        for host in self.hosts:
            Host.update(self.apiclient, id=host.id, hosttags=self.testdata["service_offering"]["hasmall"]["hosttags"])

        #create a user account
        self.account = Account.create(
            self.apiclient,
            self.testdata["account"],
            domainid=self.domain.id
        )
        #create a service offering
        self.service_offering = ServiceOffering.create(
            self.apiclient,
            self.testdata["service_offering"]["hasmall"]
        )
        #deploy ha vm
        self.virtual_machine = VirtualMachine.create(
            self.apiclient,
            self.testdata["virtual_machine"],
            accountid=self.account.name,
            zoneid=self.zone.id,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            templateid=self.template.id
        )
        list_vms = VirtualMachine.list(self.apiclient, id=self.virtual_machine.id)
        self.debug(
            "Verify listVirtualMachines response for virtual machine: %s"\
            % self.virtual_machine.id
        )
        self.assertTrue(isinstance(list_vms, list) and len(list_vms) == 1, msg = "List VM response was empty")
        self.virtual_machine = list_vms[0]

        self.mock_checkhealth = SimulatorMock.create(
            apiclient=self.apiclient,
            command="CheckHealthCommand",
            zoneid=suitablecluster.zoneid,
            podid=suitablecluster.podid,
            clusterid=suitablecluster.id,
            hostid=self.virtual_machine.hostid,
            value="result:fail")
        self.mock_ping = SimulatorMock.create(
            apiclient=self.apiclient,
            command="PingCommand",
            zoneid=suitablecluster.zoneid,
            podid=suitablecluster.podid,
            clusterid=suitablecluster.id,
            hostid=self.virtual_machine.hostid,
            value="result:fail")
        self.mock_checkvirtualmachine = SimulatorMock.create(
            apiclient=self.apiclient,
            command="CheckVirtualMachineCommand",
            zoneid=suitablecluster.zoneid,
            podid=suitablecluster.podid,
            clusterid=suitablecluster.id,
            hostid=self.virtual_machine.hostid,
            value="result:fail")
        self.mock_pingtest = SimulatorMock.create(
            apiclient=self.apiclient,
            command="PingTestCommand",
            zoneid=suitablecluster.zoneid,
            podid=suitablecluster.podid,
            value="result:fail")
        self.mock_checkonhost_list = []
        for host in self.hosts:
            if host.id != self.virtual_machine.hostid:
                self.mock_checkonhost_list.append(SimulatorMock.create(
                    apiclient=self.apiclient,
                    command="CheckOnHostCommand",
                    zoneid=suitablecluster.zoneid,
                    podid=suitablecluster.podid,
                    clusterid=suitablecluster.id,
                    hostid=host.id,
                    value="result:fail"))
        #build cleanup list
        self.cleanup = [
            self.service_offering,
            self.account,
            self.mock_checkhealth,
            self.mock_ping,
            self.mock_checkvirtualmachine,
            self.mock_pingtest
        ]
        self.cleanup = self.cleanup + self.mock_checkonhost_list
    def test_vmware_affinity(self):
        """ Test Set up affinity rules

            The test requires following pre-requisites
            - VMWare cluster configured in fully automated mode
        """

        # Validate the following
        # 1. Deploy 2 VMs on same hosts
        # 2. Migrate one VM from one host to another
        # 3. The second VM should also get migrated

        hosts = Host.list(self.apiclient,
                          zoneid=self.zone.id,
                          resourcestate='Enabled',
                          type='Routing')
        self.assertEqual(isinstance(hosts, list), True,
                         "List hosts should return valid host response")
        self.assertGreaterEqual(
            len(hosts), 2, "There must be two hosts present in a cluster")

        host_1 = hosts[0].id

        host_2 = hosts[1].id

        aff_grp = self.create_aff_grp(aff_grp=self.services["host_affinity"],
                                      acc=self.account.name,
                                      domainid=self.domain.id)

        vm_1 = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.domain.id,
            serviceofferingid=self.service_offering.id,
            affinitygroupnames=[aff_grp.name],
            hostid=host_1)

        vm_2 = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.domain.id,
            serviceofferingid=self.service_offering.id,
            affinitygroupnames=[aff_grp.name])

        vms = VirtualMachine.list(self.apiclient, id=vm_1.id, listall=True)

        vm_list_validation_result = validateList(vms)

        self.assertEqual(
            vm_list_validation_result[0], PASS,
            "vm list validation failed due to %s" %
            vm_list_validation_result[2])

        virtual_machine_1 = vm_list_validation_result[1]

        self.assertEqual(virtual_machine_1.state, "Running",
                         "Deployed VM should be in RUnning state")

        self.debug("Deploying VM on account: %s" % self.account.name)

        vms = VirtualMachine.list(self.apiclient, id=vm_2.id, listall=True)
        vm_list_validation_result = validateList(vms)

        self.assertEqual(
            vm_list_validation_result[0], PASS,
            "vm list validation failed due to %s" %
            vm_list_validation_result[2])

        virtual_machine_2 = vm_list_validation_result[1]

        self.assertEqual(virtual_machine_2.state, "Running",
                         "Deployed VM should be in RUnning state")

        self.debug("Migrate VM from host_1 to host_2")
        cmd = migrateVirtualMachine.migrateVirtualMachineCmd()
        cmd.virtualmachineid = virtual_machine_2.id
        cmd.hostid = host_2
        self.apiclient.migrateVirtualMachine(cmd)
        self.debug("Migrated VM from host_1 to host_2")

        vms = VirtualMachine.list(self.apiclient, hostid=host_2, listall=True)
        vm_list_validation_result = validateList(vms)

        self.assertEqual(
            vm_list_validation_result[0], PASS,
            "vm list validation failed due to %s" %
            vm_list_validation_result[2])

        vmids = [vm.id for vm in vms]

        self.assertIn(virtual_machine_1.id, vmids,
                      "VM 1 should be successfully migrated to host 2")
        self.assertIn(virtual_machine_2.id, vmids,
                      "VM 2 should be automatically migrated to host 2")
        return
    def test_vmware_anti_affinity(self):
        """ Test Set up anti-affinity rules

            The test requires following pre-requisites
            - VMWare cluster configured in fully automated mode
        """

        # Validate the following
        # 1. Deploy VMs on host 1 and 2
        # 2. Enable maintenance mode for host 1
        # 3. VM should be migrated to 3rd host

        hosts = Host.list(self.apiclient,
                          zoneid=self.zone.id,
                          resourcestate='Enabled',
                          type='Routing')
        self.assertEqual(isinstance(hosts, list), True,
                         "List hosts should return valid host response")

        self.debug(len(hosts))

        self.assertGreaterEqual(
            len(hosts), 3,
            "There must be at least 3 hosts present in a cluster")

        aff_grp = self.create_aff_grp(
            aff_grp=self.services["host_anti_affinity"],
            acc=self.account.name,
            domainid=self.domain.id)

        vm_1 = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.domain.id,
            serviceofferingid=self.service_offering.id,
            affinitygroupnames=[aff_grp.name])

        vm_2 = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.domain.id,
            serviceofferingid=self.service_offering.id,
            affinitygroupnames=[aff_grp.name])

        host_1 = vm_1.hostid

        host_2 = vm_2.hostid

        vms = VirtualMachine.list(self.apiclient, id=vm_1.id, listall=True)
        vm_list_validation_result = validateList(vms)

        self.assertEqual(
            vm_list_validation_result[0], PASS,
            "vm list validation failed due to %s" %
            vm_list_validation_result[1])

        virtual_machine_1 = vm_list_validation_result[1]

        self.debug("VM State: %s" % virtual_machine_1.state)
        self.assertEqual(virtual_machine_1.state, "Running",
                         "Deployed VM should be in RUnning state")

        vms = VirtualMachine.list(self.apiclient, id=vm_2.id, listall=True)
        vm_list_validation_result = validateList(vms)

        self.assertEqual(
            vm_list_validation_result[0], PASS,
            "vm list validation failed due to %s" %
            vm_list_validation_result[1])

        virtual_machine_2 = vm_list_validation_result[1]

        self.debug("VM %s  State: %s" %
                   (virtual_machine_2.name, virtual_machine_2.state))
        self.assertEqual(virtual_machine_2.state, "Running",
                         "Deployed VM should be in RUnning state")
        self.debug("Enabling maintenance mode on host_1: %s" % host_1)

        cmd = prepareHostForMaintenance.prepareHostForMaintenanceCmd()
        cmd.id = host_1
        self.apiclient.prepareHostForMaintenance(cmd)

        timeout = self.services["timeout"]
        while True:
            hosts = Host.list(self.apiclient,
                              zoneid=self.zone.id,
                              type='Routing',
                              id=host_1)
            host_list_validation_result = validateList(hosts)

            self.assertEqual(
                host_list_validation_result[0], PASS,
                "host list validation failed due to %s" %
                host_list_validation_result[2])

            host = host_list_validation_result[1]

            if host.resourcestate == 'Maintenance':
                break
            elif timeout == 0:
                self.fail("Failed to put host: %s in maintenance mode" %
                          host.name)

            time.sleep(self.services["sleep"])
            timeout = timeout - 1

        vms = VirtualMachine.list(self.apiclient,
                                  id=virtual_machine_1.id,
                                  listall=True)
        vm_list_validation_result = validateList(vms)

        self.assertEqual(
            vm_list_validation_result[0], PASS,
            "vm list validation failed due to %s" %
            vm_list_validation_result[2])

        vm = vm_list_validation_result[0]

        self.assertEqual(vm.state, "Running",
                         "Deployed VM should be in RUnning state")
        self.assertNotEqual(
            vm.hostid, host_2,
            "The host name should not match with second host name")

        self.debug("Canceling host maintenance for ID: %s" % host_1.id)
        cmd = cancelHostMaintenance.cancelHostMaintenanceCmd()
        cmd.id = host_1.id
        self.apiclient.cancelHostMaintenance(cmd)
        self.debug("Maintenance mode canceled for host: %s" % host_1.id)

        return
    def test_vm_creation_in_fully_automated_mode(self):
        """ Test VM Creation in  automation mode = Fully automated
            This test requires following preconditions:
                - DRS Cluster is configured in "Fully automated" mode
        """
        # Validate the following
        # 1. Create a new VM in a host which is almost fully utilized
        # 2 Automatically places VM on the other host
        # 3. VM state is running after deployment

        hosts = Host.list(self.apiclient,
                          zoneid=self.zone.id,
                          resourcestate='Enabled',
                          type='Routing')
        self.assertEqual(isinstance(hosts, list), True,
                         "List hosts should return valid host response")
        self.assertGreaterEqual(
            len(hosts), 2, "There must be two hosts present in a cluster")

        host_1 = hosts[0]

        #Convert available memory( Keep some margin) into MBs and assign to service offering
        self.services["service_offering_max_memory"]["memory"] = int(
            (int(hosts[0].memorytotal) - int(hosts[0].memoryused)) / 1048576 -
            1024)

        self.debug("max memory: %s" %
                   self.services["service_offering_max_memory"]["memory"])

        service_offering_max_memory = ServiceOffering.create(
            self.apiclient, self.services["service_offering_max_memory"])

        VirtualMachine.create(self.apiclient,
                              self.services["virtual_machine"],
                              accountid=self.account.name,
                              domainid=self.account.domainid,
                              serviceofferingid=service_offering_max_memory.id,
                              hostid=host_1.id)

        # Host 1 has only 1024 MB memory available now after deploying the instance
        # We are trying to deploy an instance with 2048 MB memory, this should automatically
        # get deployed on other host which has the enough capacity

        self.debug(
            "Trying to deploy instance with memory requirement more than that is available on\
                     the first host")

        self.debug("Deploying VM in account: %s" % self.account.name)
        # Spawn an instance in that network
        virtual_machine = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id)
        vms = VirtualMachine.list(self.apiclient,
                                  id=virtual_machine.id,
                                  listall=True)
        self.assertEqual(
            isinstance(vms, list), True,
            "List VMs should return valid response for deployed VM")
        self.assertNotEqual(
            len(vms), 0,
            "List VMs should return valid response for deployed VM")
        vm = vms[0]
        self.assertEqual(vm.state, "Running",
                         "Deployed VM should be in RUnning state")
        self.assertNotEqual(
            vm.hostid, host_1.id,
            "Host Ids of two should not match as one host is full")

        self.debug(
            "The host ids of two virtual machines are different as expected\
                    they are %s and %s" % (vm.hostid, host_1.id))
        return
Beispiel #41
0
    def test_update_vm_name(self):
        """Test Update VirtualMachine Name

        # Validate the following:
        # 1. VirtualMachine has uuid name, displayname
        # 2. listVirtualMachines returns accurate information
        # 3. Stop the VM
        # 4. updateVirtualmachine no args and then new displayname
        # 5. listVirtualMachines nad check the displayName set
        # 6. start the VM
        # 7. Verify displayName is still set
        """
        self.virtual_machine = VirtualMachine.create(
            self.apiclient,
            self.testdata["virtual_machine"],
            accountid=self.account.name,
            zoneid=self.zone.id,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            templateid=self.template.id)

        list_vms = VirtualMachine.list(self.apiclient,
                                       id=self.virtual_machine.id)
        self.assertEqual(isinstance(list_vms, list), True,
                         "List VM response was not a valid list")
        self.assertNotEqual(len(list_vms), 0, "List VM response was empty")
        vm = list_vms[0]

        self.debug(
            "VirtualMachine launched with id, name, displayname: %s %s %s"\
            % (self.virtual_machine.id, vm.name, vm.displayname)
        )

        self.assertEqual(vm.state, "Running", msg="VM is not in Running state")
        self.debug("Stopping VirtualMachine to update displayname")

        self.virtual_machine.stop(self.apiclient)
        #CLOUDSTACK-3184: update without args as this results in an NPE
        self.virtual_machine.update(self.apiclient)

        self.virtual_machine.update(self.apiclient,
                                    displayname='newdisplayname')
        list_vms = VirtualMachine.list(self.apiclient, id=vm.id)
        vmnew = list_vms[0]

        self.assertNotEqual(
            vmnew.displayname,
            vm.displayname,
            msg="displayname remained the same after updateVirtualMachine")
        self.assertEqual(
            vmnew.displayname,
            'newdisplayname',
            msg="display name not updated successfully, displayname is %s" %
            vmnew.displayname)

        self.debug("Starting VirtualMachine after updated displayname")
        self.virtual_machine.start(self.apiclient)
        list_vms = VirtualMachine.list(self.apiclient, id=vm.id)
        vmnewstarted = list_vms[0]

        self.assertEqual(
            vmnew.displayname,
            vmnewstarted.displayname,
            msg="display name changed on start, displayname is %s" %
            vmnewstarted.displayname)
Beispiel #42
0
    def test_list_nics(self, value):
        """Test listing nics associated with the ip address"""

        # Steps:
        # 1. Create Account and create network in it (isoalted/ shared/ vpc)
        # 2. Deploy a VM in this network and account
        # 3. Add secondary IP to the default nic of VM
        # 4. Try to list the secondary ips without passing vm id
        # 5. Try to list secondary IPs by passing correct vm id
        # 6. Try to list secondary IPs by passing correct vm id and its nic id
        # 7. Try to list secondary IPs by passing incorrect vm id and correct nic id
        # 8. Try to list secondary IPs by passing correct vm id and incorrect nic id
        # 9. Try to list secondary IPs by passing incorrect vm id and incorrect nic id

        # Validations:
        # 1. Step 4 should fail
        # 2. Step 5 should succeed
        # 3. Step 6 should succeed
        # 4. Step 7 should fail
        # 5. Step 8 should fail
        # 6. Step 9 should fail


        self.account = Account.create(self.apiclient,self.services["account"],domainid=self.domain.id)
        self.cleanup.append(self.account)

        if(shouldTestBeSkipped(networkType=value, zoneType=self.mode)):
            self.skipTest("Skipping test as %s network is not supported in basic zone" % value)

        network = createNetwork(self, value)

        try:
            virtual_machine = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
                                                    networkids=[network.id],serviceofferingid=self.service_offering.id,
                                                    accountid=self.account.name,domainid=self.account.domainid)
        except Exception as e:
            self.fail("vm creation failed: %s" % e)

        try:
            NIC.addIp(self.apiclient, id=virtual_machine.nic[0].id)
        except Exception as e:
            self.fail("Failed while adding secondary IP to NIC of vm %s" % virtual_machine.id)

        try:
            nics = NIC.list(self.apiclient)
            self.fail("Listing NICs without passign VM id succeeded, it should have failed, list is %s" % nics)
        except Exception as e:
            self.debug("Listing NICs without passing virtual machine id failed as expected")

        try:
            NIC.list(self.apiclient, virtualmachineid=virtual_machine.id)
        except Exception as e:
            self.fail("Listing NICs for virtual machine %s failed with Exception %s" % (virtual_machine.id, e))

        try:
            NIC.list(self.apiclient, virtualmachineid=virtual_machine.id, nicid=virtual_machine.nic[0].id)
        except Exception as e:
            self.fail("Listing NICs for virtual machine %s and nic id %s failed with Exception %s" %
                    (virtual_machine.id, virtual_machine.nic[0].id, e))

        try:
            nics = NIC.list(self.apiclient, virtualmachineid=(virtual_machine.id + random_gen()), nicid=virtual_machine.nic[0].id)
            self.fail("Listing NICs with wrong virtual machine id and right nic id succeeded, should have failed")
        except Exception as e:
            self.debug("Listing NICs with wrong virtual machine id and right nic failed as expected with Exception %s" % e)

        try:
            nics = NIC.list(self.apiclient, virtualmachineid=virtual_machine.id, nicid=(virtual_machine.nic[0].id + random_gen()))
            self.fail("Listing NICs with correct virtual machine id but wrong nic id succeeded, should have failed")
        except Exception as e:
            self.debug("Listing NICs with correct virtual machine id but wrong nic id failed as expected with Exception %s" % e)

        try:
            nics = NIC.list(self.apiclient, virtualmachineid=(virtual_machine.id+random_gen()), nicid=(virtual_machine.nic[0].id + random_gen()))
            self.fail("Listing NICs with wrong virtual machine id and wrong nic id succeeded, should have failed")
        except Exception as e:
            self.debug("Listing NICs with wrong virtual machine id and wrong nic id failed as expected with Exception %s" % e)

        return
Beispiel #43
0
    def test_delete_PF_nat_rule(self, value):
        """ Add secondary IP to NIC of a VM"""

        # Steps:
        # 1. Create Account and create network in it (isoalted/ shared/ vpc)
        # 2. Deploy a VM in this network and account
        # 3. Add secondary IP to the default nic of VM
        # 4. Acquire public IP, open firewall for it, and
        #    create NAT rule for this public IP to the 1st secondary IP
        # 5. Try to delete secondary IP when NAT rule exists for it
        # 6. Delete firewall rule and NAT rule

        # Validations:
        # 1. Step 5 should fail
        # 2. Step 6 should succeed

        self.account = Account.create(self.apiclient,self.services["account"],domainid=self.domain.id)
        self.cleanup.append(self.account)

        network = createNetwork(self, value)
        firewallrule = None

        try:
            virtual_machine = VirtualMachine.create(self.apiclient,self.services["virtual_machine"],
                                                    networkids=[network.id],serviceofferingid=self.service_offering.id,
                                                    accountid=self.account.name,domainid=self.account.domainid)
        except Exception as e:
            self.fail("vm creation failed: %s" % e)

        try:
            ipaddress_1 = NIC.addIp(self.apiclient, id=virtual_machine.nic[0].id)
        except Exception as e:
            self.fail("Failed while adding secondary IP to NIC of vm %s" % virtual_machine.id)

        public_ip = PublicIPAddress.create(self.api_client,accountid=self.account.name,
                                           zoneid=self.zone.id,domainid=self.account.domainid,
                                           networkid=network.id, vpcid = network.vpcid if value == VPC_NETWORK else None)

        if value != VPC_NETWORK:
            firewallrule = FireWallRule.create(self.apiclient,ipaddressid=public_ip.ipaddress.id,
                                      protocol='TCP', cidrlist=[self.services["fwrule"]["cidr"]],
                                      startport=self.services["fwrule"]["startport"],endport=self.services["fwrule"]["endport"])

        # Create NAT rule
        natrule = NATRule.create(self.api_client, virtual_machine,
                       self.services["natrule"],ipaddressid=public_ip.ipaddress.id,
                       networkid=network.id, vmguestip = ipaddress_1.ipaddress)
        try:
            NIC.removeIp(self.apiclient, ipaddressid=ipaddress_1.id)
            self.fail("Removing secondary IP succeeded while it had active NAT rule on it, should have failed")
        except Exception as e:
            self.debug("Removing secondary IP with active NAT rule failed as expected")

        if firewallrule:
            try:
                firewallrule.delete(self.apiclient)
            except Exception as e:
                self.fail("Exception while deleting firewall rule %s: %s" % (firewallrule.id, e))

        try:
            natrule.delete(self.apiclient)
        except Exception as e:
            self.fail("Exception while deleting nat rule %s: %s" % (natrule.id, e))
        return
Beispiel #44
0
    def test_01_snapshot_on_rootVolume(self):
        """Test create VM with default cent os template and create snapshot
            on root disk of the vm
        """
        # Validate the following
        # 1. Deploy a Linux VM using default CentOS template, use small service
        #    offering, disk offering
        # 2. Create snapshot on the root disk of this newly cteated vm
        # 3. listSnapshots should list the snapshot that was created.
        # 4. verify that secondary storage NFS share contains the reqd
        # volume under /secondary/snapshots/$accountid/$volumeid/$snapshot_uuid
        # 5. verify backup_snap_id was non null in the `snapshots` table

        # Create virtual machine with small systerm offering and disk offering
        new_virtual_machine = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            templateid=self.template.id,
            zoneid=self.zone.id,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            diskofferingid=self.disk_offering.id,
        )
        self.debug("Virtual machine got created with id: %s" %
                   new_virtual_machine.id)
        list_virtual_machine_response = VirtualMachine.list(
            self.apiclient, id=new_virtual_machine.id)
        self.assertEqual(isinstance(list_virtual_machine_response, list), True,
                         "Check listVirtualMachines returns a valid list")

        self.assertNotEqual(len(list_virtual_machine_response), 0,
                            "Check listVirtualMachines response")
        self.cleanup.append(new_virtual_machine)

        # Getting root volume id of the vm created above
        list_volume_response = Volume.list(
            self.apiclient,
            virtualmachineid=list_virtual_machine_response[0].id,
            type="ROOT",
            account=self.account.name,
            domainid=self.account.domainid)

        self.assertEqual(isinstance(list_volume_response, list), True,
                         "Check listVolumes returns a valid list")
        self.assertNotEqual(len(list_volume_response), 0,
                            "Check listVolumes response")
        self.debug(
            "Snapshot will be created on the volume with voluem id: %s" %
            list_volume_response[0].id)

        # Perform snapshot on the root volume
        root_volume_snapshot = Snapshot.create(
            self.apiclient, volume_id=list_volume_response[0].id)
        self.debug(
            "Created snapshot: %s for vm: %s" %
            (root_volume_snapshot.id, list_virtual_machine_response[0].id))
        list_snapshot_response = Snapshot.list(self.apiclient,
                                               id=root_volume_snapshot.id,
                                               account=self.account.name,
                                               domainid=self.account.domainid)
        self.assertEqual(isinstance(list_snapshot_response, list), True,
                         "Check listSnapshots returns a valid list")

        self.assertNotEqual(len(list_snapshot_response), 0,
                            "Check listSnapshots response")
        # Verify Snapshot state
        self.assertEqual(
            list_snapshot_response[0].state
            in ['BackedUp', 'CreatedOnPrimary'], True,
            "Snapshot state is not as expected. It is %s" %
            list_snapshot_response[0].state)

        self.assertEqual(
            list_snapshot_response[0].volumeid, list_volume_response[0].id,
            "Snapshot volume id is not matching with the vm's volume id")
        self.cleanup.append(root_volume_snapshot)

        # Below code is to verify snapshots in the backend and in db.
        # Verify backup_snap_id field in the snapshots table for the snapshot created, it should not be null

        self.debug(
            "select id, removed, backup_snap_id from snapshots where uuid = '%s';"
            % root_volume_snapshot.id)
        qryresult = self.dbclient.execute(
            "select id, removed, backup_snap_id from snapshots where uuid = '%s';"
            % root_volume_snapshot.id)
        self.assertNotEqual(len(qryresult), 0,
                            "Check sql query to return snapshots list")
        snapshot_qry_response = qryresult[0]
        snapshot_id = snapshot_qry_response[0]
        is_removed = snapshot_qry_response[1]
        backup_snap_id = snapshot_qry_response[2]
        self.assertNotEqual(
            is_removed, "NULL",
            "Snapshot is removed from CS, please check the logs")
        msg = "Backup snapshot id is set to null for the backedup snapshot :%s" % snapshot_id
        self.assertNotEqual(backup_snap_id, "NULL", msg)

        # Check if the snapshot is present on the secondary storage
        self.assertTrue(
            is_snapshot_on_nfs(self.apiclient, self.dbclient, self.config,
                               self.zone.id, root_volume_snapshot.id))

        return
    def test_deploy_vgpu_enabled_vm(self):
        """Test Deploy Virtual Machine

        # Validate the following:
        # 1. Virtual Machine is accessible via SSH
        # 2. Virtual Machine is vGPU enabled (via SSH)
        # 3. listVirtualMachines returns accurate information
        """
        self.virtual_machine = VirtualMachine.create(
            self.apiclient,
            self.services["vgpu260q"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            mode=self.services['mode']
        )

        list_vms = VirtualMachine.list(self.apiclient, id=self.virtual_machine.id)

        self.debug(
            "Verify listVirtualMachines response for virtual machine: %s"\
            % self.virtual_machine.id
        )

        self.assertEqual(
            isinstance(list_vms, list),
            True,
            "List VM response was not a valid list"
        )
        self.assertNotEqual(
            len(list_vms),
            0,
            "List VM response was empty"
        )

        vm = list_vms[0]
        self.assertEqual(
            vm.id,
            self.virtual_machine.id,
            "Virtual Machine ids do not match"
        )
        self.assertEqual(
            vm.name,
            self.virtual_machine.name,
            "Virtual Machine names do not match"
        )
        self.assertEqual(
            vm.state,
            "Running",
            msg="VM is not in Running state"
        )
        list_hosts = list_hosts(
               self.apiclient,
               id=vm.hostid
               )
        hostip = list_hosts[0].ipaddress
        try:
            sshClient = SshClient(host=hostip, port=22, user='******',passwd=self.services["host_password"])
            res = sshClient.execute("xe vgpu-list vm-name-label=%s params=type-uuid %s" % (
                                   vm.instancename
                                 ))
            self.debug("SSH result: %s" % res)
        except Exception as e:
            self.fail("SSH Access failed for %s: %s" % \
                      (hostip, e)
                      )
        result = str(res)
        self.assertEqual(
                    result.count("type-uuid"),
                    1,
                    "VM is vGPU enabled."
                    )
Beispiel #46
0
    def create_vm(self, pfrule=False, egress_policy=True, RR=False):
        self.create_network_offering(egress_policy, RR)
         # Creating network using the network offering created
        self.debug("Creating network with network offering: %s" %
                                                    self.network_offering.id)
        self.network = Network.create(self.apiclient,
                                      self.services["network"],
                                      accountid=self.account.name,
                                      domainid=self.account.domainid,
                                      networkofferingid=self.network_offering.id,
                                      zoneid=self.zone.id)
        self.cleanup_networks.append(self.network)
        self.debug("Created network with ID: %s" % self.network.id)
        self.debug("Deploying instance in the account: %s" % self.account.name)

        project = None
        try:
            self.virtual_machine = VirtualMachine.create(self.apiclient,
                                                         self.services["virtual_machine"],
                                                         accountid=self.account.name,
                                                         domainid=self.domain.id,
                                                         serviceofferingid=self.service_offering.id,
                                                         mode=self.zone.networktype if pfrule else 'basic',
                                                         networkids=[str(self.network.id)],
                                                         projectid=project.id if project else None)
            self.cleanup_vms.append(self.virtual_machine)
        except Exception as e:
            self.fail("Virtual machine deployment failed with exception: %s" % e)
        self.debug("Deployed instance %s in account: %s" % (self.virtual_machine.id,self.account.name))

        # Checking if VM is running or not, in case it is deployed in error state, test case fails
        self.vm_list = list_virtual_machines(self.apiclient, id=self.virtual_machine.id)

        self.assertEqual(validateList(self.vm_list)[0], PASS, "vm list validation failed, vm list is %s" % self.vm_list)
        self.assertEqual(str(self.vm_list[0].state).lower(),'running',"VM state should be running, it is %s" % self.vm_list[0].state)

        self.public_ip = PublicIPAddress.create(
                                    self.apiclient,
                                    accountid=self.account.name,
                                    zoneid=self.zone.id,
                                    domainid=self.account.domainid,
                                    networkid=self.network.id
                                    )

        # Open up firewall port for SSH
        FireWallRule.create(
                            self.apiclient,
                            ipaddressid=self.public_ip.ipaddress.id,
                            protocol=self.services["natrule"]["protocol"],
                            cidrlist=['0.0.0.0/0'],
                            startport=self.services["natrule"]["publicport"],
                            endport=self.services["natrule"]["publicport"]
                            )

        self.debug("Creating NAT rule for VM ID: %s" % self.virtual_machine.id)
        #Create NAT rule
        NATRule.create(
                        self.apiclient,
                        self.virtual_machine,
                        self.services["natrule"],
                        self.public_ip.ipaddress.id
                        )
        return
    def test_01_snapshot_on_rootVolume(self):
        """Test create VM with default cent os template and create snapshot
            on root disk of the vm
        """
        # Validate the following
        # 1. Deploy a Linux VM using default CentOS template, use small service
        #    offering, disk offering
        # 2. Create snapshot on the root disk of this newly cteated vm
        # 3. listSnapshots should list the snapshot that was created.
        # 4. verify that secondary storage NFS share contains the reqd
        # volume under /secondary/snapshots/$accountid/$volumeid/$snapshot_uuid
        # 5. verify backup_snap_id was non null in the `snapshots` table

        # Create virtual machine with small systerm offering and disk offering
        new_virtual_machine = VirtualMachine.create(
                                    self.apiclient,
                                    self.services["virtual_machine"],
                                    templateid=self.template.id,
                                    zoneid=self.zone.id,
                                    accountid=self.account.name,
                                    domainid=self.account.domainid,
                                    serviceofferingid=self.service_offering.id,
                                    diskofferingid=self.disk_offering.id,
                                )
        self.debug("Virtual machine got created with id: %s" %
                                                    new_virtual_machine.id)
        list_virtual_machine_response = VirtualMachine.list(
                                                    self.apiclient,
                                                    id=new_virtual_machine.id)
        self.assertEqual(isinstance(list_virtual_machine_response, list),
                         True,
                         "Check listVirtualMachines returns a valid list")

        self.assertNotEqual(len(list_virtual_machine_response),
                            0,
                            "Check listVirtualMachines response")
        self.cleanup.append(new_virtual_machine)

        # Getting root volume id of the vm created above
        list_volume_response = Volume.list(
                                self.apiclient,
                                virtualmachineid=list_virtual_machine_response[0].id,
                                type="ROOT",
                                account=self.account.name,
                                domainid=self.account.domainid)

        self.assertEqual(isinstance(list_volume_response, list),
                         True,
                         "Check listVolumes returns a valid list")
        self.assertNotEqual(len(list_volume_response),
                            0,
                            "Check listVolumes response")
        self.debug(
            "Snapshot will be created on the volume with voluem id: %s" %
                                                    list_volume_response[0].id)

        # Perform snapshot on the root volume
        root_volume_snapshot = Snapshot.create(
                                        self.apiclient,
                                       volume_id=list_volume_response[0].id)
        self.debug("Created snapshot: %s for vm: %s" % (
                                        root_volume_snapshot.id,
                                        list_virtual_machine_response[0].id))
        list_snapshot_response = Snapshot.list(
                                        self.apiclient,
                                        id=root_volume_snapshot.id,
                                        account=self.account.name,
                                        domainid=self.account.domainid)
        self.assertEqual(isinstance(list_snapshot_response, list),
                         True,
                         "Check listSnapshots returns a valid list")

        self.assertNotEqual(len(list_snapshot_response),
                            0,
                            "Check listSnapshots response")
        # Verify Snapshot state
        self.assertEqual(
                            list_snapshot_response[0].state in [
                                                                'BackedUp',
                                                                'CreatedOnPrimary'
                                                                ],
                            True,
                            "Snapshot state is not as expected. It is %s" %
                            list_snapshot_response[0].state
                        )

        self.assertEqual(
                list_snapshot_response[0].volumeid,
                list_volume_response[0].id,
                "Snapshot volume id is not matching with the vm's volume id")
        self.cleanup.append(root_volume_snapshot)

        # Below code is to verify snapshots in the backend and in db.
        # Verify backup_snap_id field in the snapshots table for the snapshot created, it should not be null

        self.debug("select id, removed, backup_snap_id from snapshots where uuid = '%s';" % root_volume_snapshot.id)
        qryresult = self.dbclient.execute("select id, removed, backup_snap_id from snapshots where uuid = '%s';" % root_volume_snapshot.id)
        self.assertNotEqual(len(qryresult), 0, "Check sql query to return snapshots list")
        snapshot_qry_response = qryresult[0]
        snapshot_id = snapshot_qry_response[0]
        is_removed = snapshot_qry_response[1]
        backup_snap_id = snapshot_qry_response[2]
        self.assertNotEqual(is_removed, "NULL", "Snapshot is removed from CS, please check the logs")
        msg = "Backup snapshot id is set to null for the backedup snapshot :%s" % snapshot_id
        self.assertNotEqual(backup_snap_id, "NULL", msg )

        # Check if the snapshot is present on the secondary storage
        self.assertTrue(is_snapshot_on_nfs(self.apiclient, self.dbclient, self.config, self.zone.id, root_volume_snapshot.id))

        return
    def test_08_migrate_vm(self):
        """Test migrate VM
        """
        # Validate the following
        # 1. Environment has enough hosts for migration
        # 2. DeployVM on suitable host (with another host in the cluster)
        # 3. Migrate the VM and assert migration successful

        suitable_hosts = None

        hosts = Host.list(self.apiclient, zoneid=self.zone.id, type='Routing')
        self.assertEqual(
            validateList(hosts)[0], PASS, "hosts list validation failed")

        if len(hosts) < 2:
            self.skipTest(
                "At least two hosts should be present in the zone for migration"
            )

        hypervisor = str(get_hypervisor_type(self.apiclient)).lower()

        # For KVM, two hosts used for migration should  be present in same cluster
        # For XenServer and VMware, migration is possible between hosts belonging to different clusters
        # with the help of XenMotion and Vmotion respectively.

        if hypervisor == "kvm":
            #identify suitable host
            clusters = [h.clusterid for h in hosts]
            #find hosts withe same clusterid
            clusters = [
                cluster for index, cluster in enumerate(clusters)
                if clusters.count(cluster) > 1
            ]

            if len(clusters) <= 1:
                self.skipTest(
                    "In KVM, Live Migration needs two hosts within same cluster"
                )

            suitable_hosts = [
                host for host in hosts if host.clusterid == clusters[0]
            ]
        else:
            suitable_hosts = hosts

        target_host = suitable_hosts[0]
        migrate_host = suitable_hosts[1]

        #deploy VM on target host
        self.vm_to_migrate = VirtualMachine.create(
            self.api_client,
            self.services["small"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.small_offering.id,
            mode=self.services["mode"],
            hostid=target_host.id)
        self.debug("Migrating VM-ID: %s to Host: %s" %
                   (self.vm_to_migrate.id, migrate_host.id))

        self.vm_to_migrate.migrate(self.api_client, migrate_host.id)

        list_vm_response = list_virtual_machines(self.apiclient,
                                                 id=self.vm_to_migrate.id)
        self.assertNotEqual(list_vm_response, None,
                            "Check virtual machine is listed")

        vm_response = list_vm_response[0]

        self.assertEqual(vm_response.id, self.vm_to_migrate.id,
                         "Check virtual machine ID of migrated VM")

        self.assertEqual(vm_response.hostid, migrate_host.id,
                         "Check destination hostID of migrated VM")
        return
    def test_00_deploy_vm_root_resize(self):
        """Test deploy virtual machine with root resize

        # Validate the following:
        # 1. listVirtualMachines returns accurate information
        # 2. root disk has new size per listVolumes
        # 3. Rejects non-supported hypervisor types
        """
        if(self.apiclient.hypervisor == 'kvm'):
            newrootsize = (self.template.size >> 30) + 2 
            self.virtual_machine = VirtualMachine.create(
                self.apiclient,
                self.testdata["virtual_machine"],
                accountid=self.account.name,
                zoneid=self.zone.id,
                domainid=self.account.domainid,
                serviceofferingid=self.service_offering.id,
                templateid=self.template.id,
                rootdisksize=newrootsize
            )

            list_vms = VirtualMachine.list(self.apiclient, id=self.virtual_machine.id)

            self.debug(
                "Verify listVirtualMachines response for virtual machine: %s"\
                % self.virtual_machine.id
            )

            self.assertEqual(
                isinstance(list_vms, list),
                True,
                "List VM response was not a valid list"
            )
            self.assertNotEqual(
                len(list_vms),
                0,
                "List VM response was empty"
            )

            vm = list_vms[0]
            self.assertEqual(
                vm.id,
                self.virtual_machine.id,
                "Virtual Machine ids do not match"
            )
            self.assertEqual(
                vm.name,
                self.virtual_machine.name,
                "Virtual Machine names do not match"
            )
            self.assertEqual(
                vm.state,
                "Running",
                msg="VM is not in Running state"
            )

            # get root vol from created vm, verify it is correct size
            list_volume_response = list_volumes(
                                                self.apiclient,
                                                virtualmachineid=self.virtual_machine.id,
                                                type='ROOT',
                                                listall=True
                                                )

            rootvolume = list_volume_response[0]
            success = False
            if rootvolume is not None and rootvolume.size  == (newrootsize << 30):
                success = True

            self.assertEqual(
                             success,
                             True,
                             "Check if the root volume resized appropriately"
                            )
        else:
            self.debug("hypervisor %s unsupported for test 00, verifying it errors properly" % self.apiclient.hypervisor)

            newrootsize = (self.template.size >> 30) + 2
            success = False
            try:
                self.virtual_machine = VirtualMachine.create(
                    self.apiclient,
                    self.testdata["virtual_machine"],
                    accountid=self.account.name,
                    zoneid=self.zone.id,
                    domainid=self.account.domainid,
                    serviceofferingid=self.service_offering.id,
                    templateid=self.template.id,
                    rootdisksize=newrootsize
                )
            except Exception as ex:
                if "Hypervisor XenServer does not support rootdisksize override" in str(ex):
                    success = True
                else:
                    self.debug("virtual machine create did not fail appropriately. Error was actually : " + str(ex));

            self.assertEqual(success, True, "Check if unsupported hypervisor %s fails appropriately" % self.apiclient.hypervisor)