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")
Пример #2
0
    def createInstance(self, account, service_off, networks=None, api_client=None):
        """Creates an instance in account"""

        if api_client is None:
            api_client = self.apiclient

        self.debug("Deploying an instance in account: %s" %
                       account.name)
        try:
            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)
            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)
Пример #3
0
    def createInstance(self,
                       account,
                       service_off,
                       networks=None,
                       api_client=None):
        """Creates an instance in account"""

        if api_client is None:
            api_client = self.apiclient

        self.debug("Deploying an instance in account: %s" % account.name)
        try:
            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)
            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_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 DestroyVM(self, id):
        mocnictouse = mocnic("127.0.0.1")
        vm = VirtualMachine({"id": id, "nic": [mocnictouse]}, self.services)
        vm.delete(self.apiclient)

        list_vm_response = VirtualMachine.list(
                                            self.apiclient,
                                            id=id
                                            )
        self.assertEqual(
                            isinstance(list_vm_response, list),
                            True,
                            "Check list response returns a valid list"
                        )

        self.assertNotEqual(
                            len(list_vm_response),
                            0,
                            "Check VM avaliable in List Virtual Machines"
                        )

        self.assertEqual(
                            list_vm_response[0].state,
                            "Destroyed",
                            "Check virtual machine is in destroyed state"
                        )
        return
Пример #6
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.virtual_machine_2 = 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"])

        NATRule.create(self.apiclient,
                       self.virtual_machine,
                       self.services["natrule"],
                       ipaddressid=self.public_ip.ipaddress.id)

        self.cleanup = [
            self.account,
        ]
        return
    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_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")
        vm1clusterid = filter(lambda c: c.id == vm1.hostid,
                              self.hosts)[0].clusterid
        vm2clusterid = filter(lambda c: c.id == vm2.hostid,
                              self.hosts)[0].clusterid

        vm1podid = filter(lambda p: p.id == vm1clusterid,
                          self.clusters)[0].podid
        vm2podid = filter(lambda p: p.id == vm2clusterid,
                          self.clusters)[0].podid
        self.assertEqual(
            vm1podid,
            vm2podid,
            msg=
            "VMs (%s, %s) meant to be pod concentrated are deployed on different pods (%s, %s)"
            % (vm1.id, vm2.id, vm1clusterid, vm2clusterid))
    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
Пример #11
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"])

        #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"]["small"])
        #build cleanup list
        self.cleanup = [self.service_offering, self.account]

        # 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")
Пример #12
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_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 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
Пример #15
0
    def test_01_deploy_instance_with_is_volatile_offering(self):
        """ Test deploy an instance with service offerings with IsVolatile set.
        """

        # Validate the following
        # 1. Service offerings were created successfully
        # 2. Vms were successfully deployed with the service offerings.

        self.debug("Checking if deployed VMs are in running state...")
        vms = VirtualMachine.list(
                                  self.apiclient,
                                  account=self.account.name,
                                  domainid=self.account.domainid,
                                  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])

        for vm in vms:
            self.debug("VM name: %s, VM state: %s" % (vm.name, vm.state))
            self.debug("%s" %vm)
            self.assertEqual(
                             vm.state,
                             "Running",
                             "Vm state should be running for each VM deployed"
                             )
        return
Пример #16
0
    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
Пример #17
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
Пример #18
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
Пример #19
0
    def test_02_VPC_LBRulesAndVMListing(self):
        """ Test case no 211 and 228: List only VMs suitable for the Virtual Network on VPC for LB Rule
        """

        # Validate the following
        # 1. Create a VPC with cidr - 10.1.1.1/16
        # 2. Create a Network offering - NO1 with all supported services
        # 3. Add network1(10.1.1.1/24) using N01 to this VPC.
        # 4. Add network2(10.1.2.1/24) using N01 to this VPC.
        # 5. Deploy vm1 and vm2 in network1 on primary host.
        # 6. Deploy vm3 and vm4 in network2 on secondary host.
        # 7. Use the Create LB rule for vm1 and vm2 in network1.
        # 9. List LB rule for network1 list vms on network1 for selection of LB rule.

        network_1 = self.create_Network(self.services["network_offering"])
        network_2 = self.create_Network(
            self.services["network_offering_no_lb"], '10.1.2.1')
        vm_1 = self.create_VM_in_Network(network_1)
        vm_2 = self.create_VM_in_Network(network_1)
        vm_3 = self.create_VM_in_Network(network_2)
        self.debug('vm_3=%s' % vm_3.id)
        vm_4 = self.create_VM_in_Network(network_2)
        self.debug('vm_4=%s' % vm_4.id)
        public_ip_1 = self.acquire_Public_IP(network_1)
        lb_rule = self.create_LB_Rule(public_ip_1, network_1, [vm_1, vm_2])
        lb_rules = LoadBalancerRule.list(self.apiclient,
                                         id=lb_rule.id,
                                         listall=True)
        self.failIfEqual(lb_rules, None, "Failed to list the LB Rule")
        vms = VirtualMachine.list(self.apiclient,
                                  networkid=network_1.id,
                                  listall=True)
        self.failIfEqual(
            vms, None, "Failed to list the VMs in network=%s" % network_1.name)
        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)
Пример #22
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_01_deploy_instance_with_is_volatile_offering(self):
        """ Test deploy an instance with service offerings with IsVolatile set.
        """

        # Validate the following
        # 1. Service offerings were created successfully
        # 2. Vms were successfully deployed with the service offerings.

        self.debug("Checking if deployed VMs are in running state...")
        vms = VirtualMachine.list(self.apiclient,
                                  account=self.account.name,
                                  domainid=self.account.domainid,
                                  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])

        for vm in vms:
            self.debug("VM name: %s, VM state: %s" % (vm.name, vm.state))
            self.debug("%s" % vm)
            self.assertEqual(
                vm.state, "Running",
                "Vm state should be running for each VM deployed")
        return
Пример #24
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.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.debug('error=%s' % e)
        self.debug("Deployed instance in account: %s" % self.account.name)
    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);
Пример #26
0
    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
Пример #27
0
    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
Пример #28
0
    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
Пример #31
0
    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
Пример #32
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"
        )
Пример #33
0
    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 test_nic_secondaryip_add_remove(self):
        list_vms = VirtualMachine.list(self.apiclient, id=self.virtual_machine.id)
        vm = list_vms[0]
        nicid = vm.nic[0].id
        cmd = addIpToNicCmd()
        cmd.nicid = nicid
        response =  self.apiclient.addIpToNic(cmd)
        self.debug('IP address acquired to nic is =%s' % response.ipaddress)

        #remove the ip from nic
        list_vms = VirtualMachine.list(self.apiclient, id=self.virtual_machine.id)
        vmid = self.virtual_machine.id
        cmd = listNicsCmd()
        cmd.virtualmachineid = vmid
        list_nics =  self.apiclient.listNics(cmd)

        nic = list_nics[0]
        ipid = nic.secondaryip[0].id;

        cmd = removeIpFromNicCmd()
        cmd.id = ipid
        response =  self.apiclient.removeIpFromNic(cmd)
Пример #35
0
    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
Пример #36
0
    def test_nic_secondaryip_add_remove(self):
        list_vms = VirtualMachine.list(self.apiclient,
                                       id=self.virtual_machine.id)
        vm = list_vms[0]
        nicid = vm.nic[0].id
        cmd = addIpToNicCmd()
        cmd.nicid = nicid
        response = self.apiclient.addIpToNic(cmd)
        self.debug('IP address acquired to nic is =%s' % response.ipaddress)

        #remove the ip from nic
        list_vms = VirtualMachine.list(self.apiclient,
                                       id=self.virtual_machine.id)
        vmid = self.virtual_machine.id
        cmd = listNicsCmd()
        cmd.virtualmachineid = vmid
        list_nics = self.apiclient.listNics(cmd)

        nic = list_nics[0]
        ipid = nic.secondaryip[0].id

        cmd = removeIpFromNicCmd()
        cmd.id = ipid
        response = self.apiclient.removeIpFromNic(cmd)
    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
Пример #38
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)
Пример #39
0
    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)
Пример #40
0
    def test_01_VPC_LBRulesListing(self):
        """ Test case no 210 and 227: List Load Balancing Rules belonging to a VPC
        """

        # Validate the following
        # 1. Create a VPC with cidr - 10.1.1.1/16
        # 2. Create a Network offering - NO1 with all supported services
        # 3. Add network1(10.1.1.1/24) using N01 to this VPC.
        # 4. Add network2(10.1.2.1/24) using N01 to this VPC.
        # 5. Deploy vm1 and vm2 in network1.
        # 6. Deploy vm3 and vm4 in network2.
        # 7. Use the Create LB rule for vm1 and vm2 in network1.
        # 8. Use the Create LB rule for vm3 amd vm4 in network2, should fail
        # because it's no_lb offering
        # 9. List LB rule

        network_1 = self.create_Network(self.services["network_offering"])
        network_2 = self.create_Network(self.services["network_offering_no_lb"], '10.1.2.1')
        self.debug("deploying VMs in network: %s" % network_2.name)
        vm_1 = self.create_VM_in_Network(network_1)
        vm_2 = self.create_VM_in_Network(network_1)
        vm_3 = self.create_VM_in_Network(network_2)
        vm_4 = self.create_VM_in_Network(network_2)
        public_ip_1 = self.acquire_Public_IP(network_1)
        lb_rule1 = self.create_LB_Rule(public_ip_1, network_1, [vm_1, vm_2]) #
        public_ip_2 = self.acquire_Public_IP(network_2)
        with self.assertRaises(Exception):
            self.create_LB_Rule(public_ip_2, network_2, [vm_3, vm_4])

        lb_rules = LoadBalancerRule.list(self.apiclient,
                                        id=lb_rule1.id,
                                        listall=True
                                        )
        self.failIfEqual(lb_rules,
                        None,
                        "Failed to list the LB Rule"
                        )
        vms = VirtualMachine.list(self.apiclient,
                                networkid=network_1.id,
                                listall=True
                                )
        self.failIfEqual(vms,
                        None,
                        "Failed to list the VMs in network=%s" % network_1.name
                        )
        return
Пример #41
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
Пример #42
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))
Пример #43
0
    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))
Пример #45
0
    def test_vm_ha(self):
        """Test VM HA

        # Validate the following:
        # VM started on other host in cluster
        """

        #wait for VM to HA
        ping_timeout = Configurations.list(self.apiclient, name="ping.timeout")
        ping_interval = Configurations.list(self.apiclient, name="ping.interval")
        total_duration = int(float(ping_timeout[0].value) * float(ping_interval[0].value))
        time.sleep(total_duration)

        duration = 0
        vm = None
        while duration < total_duration:
            list_vms = VirtualMachine.list(self.apiclient, id=self.virtual_machine.id)
            self.assertTrue(isinstance(list_vms, list) and len(list_vms) == 1, msg = "List VM response was empty")
            vm = list_vms[0]
            if vm.hostid != self.virtual_machine.hostid:
                break
            else:
                time.sleep(10)
                duration = duration + 10

        self.assertEqual(
            vm.id,
            self.virtual_machine.id,
            "VM ids do not match")
        self.assertEqual(
            vm.name,
            self.virtual_machine.name,
            "VM names do not match")
        self.assertEqual(
            vm.state,
            "Running",
            msg="VM is not in Running state")
        self.assertNotEqual(
            vm.hostid,
            self.virtual_machine.hostid,
            msg="VM is not started on another host as part of HA")
Пример #46
0
    def test_02_VPC_LBRulesAndVMListing(self):
        """ Test case no 211 and 228: List only VMs suitable for the Virtual Network on VPC for LB Rule
        """

        # Validate the following
        # 1. Create a VPC with cidr - 10.1.1.1/16
        # 2. Create a Network offering - NO1 with all supported services
        # 3. Add network1(10.1.1.1/24) using N01 to this VPC.
        # 4. Add network2(10.1.2.1/24) using N01 to this VPC.
        # 5. Deploy vm1 and vm2 in network1 on primary host.
        # 6. Deploy vm3 and vm4 in network2 on secondary host.
        # 7. Use the Create LB rule for vm1 and vm2 in network1.
        # 9. List LB rule for network1 list vms on network1 for selection of LB rule.

        network_1 = self.create_Network(self.services["network_offering"])
        network_2 = self.create_Network(self.services["network_offering_no_lb"], '10.1.2.1')
        vm_1 = self.create_VM_in_Network(network_1)
        vm_2 = self.create_VM_in_Network(network_1)
        vm_3 = self.create_VM_in_Network(network_2)
        self.debug('vm_3=%s' % vm_3.id)
        vm_4 = self.create_VM_in_Network(network_2)
        self.debug('vm_4=%s' % vm_4.id)
        public_ip_1 = self.acquire_Public_IP(network_1)
        lb_rule = self.create_LB_Rule(public_ip_1, network_1, [vm_1, vm_2])
        lb_rules = LoadBalancerRule.list(self.apiclient,
                                        id=lb_rule.id,
                                        listall=True
                                        )
        self.failIfEqual(lb_rules,
                        None,
                        "Failed to list the LB Rule"
                        )
        vms = VirtualMachine.list(self.apiclient,
                                networkid=network_1.id,
                                listall=True
                                )
        self.failIfEqual(vms,
                        None,
                        "Failed to list the VMs in network=%s" % network_1.name
                        )
        return
Пример #47
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
Пример #48
0
    def test_01_VPC_LBRulesListing(self):
        """ Test case no 210 and 227: List Load Balancing Rules belonging to a VPC
        """

        # Validate the following
        # 1. Create a VPC with cidr - 10.1.1.1/16
        # 2. Create a Network offering - NO1 with all supported services
        # 3. Add network1(10.1.1.1/24) using N01 to this VPC.
        # 4. Add network2(10.1.2.1/24) using N01 to this VPC.
        # 5. Deploy vm1 and vm2 in network1.
        # 6. Deploy vm3 and vm4 in network2.
        # 7. Use the Create LB rule for vm1 and vm2 in network1.
        # 8. Use the Create LB rule for vm3 amd vm4 in network2, should fail
        # because it's no_lb offering
        # 9. List LB rule

        network_1 = self.create_Network(self.services["network_offering"])
        network_2 = self.create_Network(
            self.services["network_offering_no_lb"], '10.1.2.1')
        self.debug("deploying VMs in network: %s" % network_2.name)
        vm_1 = self.create_VM_in_Network(network_1)
        vm_2 = self.create_VM_in_Network(network_1)
        vm_3 = self.create_VM_in_Network(network_2)
        vm_4 = self.create_VM_in_Network(network_2)
        public_ip_1 = self.acquire_Public_IP(network_1)
        lb_rule1 = self.create_LB_Rule(public_ip_1, network_1, [vm_1, vm_2])  #
        public_ip_2 = self.acquire_Public_IP(network_2)
        with self.assertRaises(Exception):
            self.create_LB_Rule(public_ip_2, network_2, [vm_3, vm_4])

        lb_rules = LoadBalancerRule.list(self.apiclient,
                                         id=lb_rule1.id,
                                         listall=True)
        self.failIfEqual(lb_rules, None, "Failed to list the LB Rule")
        vms = VirtualMachine.list(self.apiclient,
                                  networkid=network_1.id,
                                  listall=True)
        self.failIfEqual(
            vms, None, "Failed to list the VMs in network=%s" % network_1.name)
        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")
Пример #50
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 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