Ejemplo n.º 1
0
    def test_04_edit_display_name(self):
        """ Test Edit the Display name Through the UI.
        """

        # Validate the following
        # 1) Set the Global Setting vm.instancename.flag to true
        # 2) Create a VM give a Display name.
        # 3) Once the VM is created stop the VM.
        # 4) Edit the VM Display name. The Display name will be changed but the
        #    internal name will not be changed. The VM functionality must not
        #    be effected.

        self.services["virtual_machine"]["name"] = "TestVM4"
        # Spawn an instance in that network
        self.debug("Deploying VM in account: %s" % self.account.name)
        virtual_machine = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
        )
        self.debug("Checking if the virtual machine is created properly or not?")
        vms = VirtualMachine.list(self.apiclient, id=virtual_machine.id, listall=True)

        self.assertEqual(isinstance(vms, list), True, "List vms should retuen a valid name")
        vm = vms[0]
        self.assertEqual(vm.state, "Running", "Vm state should be running after deployment")

        self.assertEqual(
            vm.displayname,
            self.services["virtual_machine"]["displayname"],
            "Vm display name should match the given name",
        )

        old_internal_name = vm.instancename
        self.debug("Stopping the instance: %s" % vm.name)
        try:
            virtual_machine.stop(self.apiclient)
        except Exception as e:
            self.fail("Failed to stop instance: %s, %s" % (vm.name, e))

        self.debug("Update the display name of the instance")
        try:
            virtual_machine.update(self.apiclient, displayname=random_gen())
        except Exception as e:
            self.fail("Failed to update the virtual machine name: %s, %s" % (virtual_machine.name, e))

        self.debug("Start the instance: %s" % virtual_machine.name)
        virtual_machine.start(self.apiclient)

        self.debug("Checking if the instance is working properly after update")
        vms = VirtualMachine.list(self.apiclient, id=virtual_machine.id, listall=True)

        self.assertEqual(isinstance(vms, list), True, "List vms should retuen a valid name")
        vm = vms[0]
        self.assertEqual(vm.state, "Running", "Vm state should be running after deployment")

        self.assertEqual(vm.instancename, old_internal_name, "Vm internal name should not be changed after update")
        return
Ejemplo n.º 2
0
    def createInstance(self, service_off, networks=None, api_client=None):
        """Creates an instance in account"""
        self.debug("Deploying an instance in account: %s" %
                                                self.account.name)

        if api_client is None:
	        api_client = self.apiclient

        try:
            vm = VirtualMachine.create(
                                api_client,
                                self.services["virtual_machine"],
                                templateid=self.template.id,
                                accountid=self.account.name,
                                domainid=self.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_01_create_template_volume(self):
        """Test Create template from volume
        """

        # Validate the following:
        # 1. Deploy new VM using the template created from Volume
        # 2. VM should be in Up and Running state

        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.debug("creating an instance with template ID: %s" % self.template.id)
        self.cleanup.append(virtual_machine)
        vm_response = VirtualMachine.list(
            self.apiclient, id=virtual_machine.id, account=self.account.name, domainid=self.account.domainid
        )
        # Verify VM response to check whether VM deployment was successful
        self.assertNotEqual(len(vm_response), 0, "Check VMs available in List VMs response")
        vm = vm_response[0]
        self.assertEqual(vm.state, "Running", "Check the state of VM created from Template")
        return
Ejemplo n.º 4
0
    def test_03_vm_per_project(self):
        """Test VM limit per project
        """
        # Validate the following
        # 1. Set max VM per project to 2
        # 2. Create account and start 2 VMs. Verify VM state is Up and Running
        # 3. Try to create 3rd VM instance. The appropriate error or alert
        #    should be raised

        self.debug(
            "Updating instance resource limits for project: %s" %
                                                        self.project.id)
        # Set usage_vm=1 for Account 1
        update_resource_limit(
                              self.apiclient,
                              0, # Instance
                              max=2,
                              projectid=self.project.id
                              )

        self.debug("Deploying VM for project: %s" % self.project.id)
        virtual_machine_1 = VirtualMachine.create(
                                self.apiclient,
                                self.services["server"],
                                templateid=self.template.id,
                                serviceofferingid=self.service_offering.id,
                                projectid=self.project.id
                                )
        self.cleanup.append(virtual_machine_1)
        # Verify VM state
        self.assertEqual(
                            virtual_machine_1.state,
                            'Running',
                            "Check VM state is Running or not"
                        )
        self.debug("Deploying VM for project: %s" % self.project.id)
        virtual_machine_2 = VirtualMachine.create(
                                self.apiclient,
                                self.services["server"],
                                templateid=self.template.id,
                                serviceofferingid=self.service_offering.id,
                                projectid=self.project.id
                                )
        self.cleanup.append(virtual_machine_2)
        # Verify VM state
        self.assertEqual(
                            virtual_machine_2.state,
                            'Running',
                            "Check VM state is Running or not"
                        )
        # Exception should be raised for second instance
        with self.assertRaises(Exception):
            VirtualMachine.create(
                                self.apiclient,
                                self.services["server"],
                                templateid=self.template.id,
                                serviceofferingid=self.service_offering.id,
                                projectid=self.project.id
                                )
        return
Ejemplo n.º 5
0
    def test_instance_name_with_hyphens(self):
        """ Test the instance  name with hyphens
        """

        # Validate the following
        # 1. Set the vm.instancename.flag to true.
        # 2. Add the virtual machine with display name with hyphens

        # Reading display name property
        if not is_config_suitable(apiclient=self.apiclient, name="vm.instancename.flag", value="true"):
            self.skipTest("vm.instancename.flag should be true. skipping")

        self.services["virtual_machine"]["displayname"] = "TestVM-test-name"
        self.services["virtual_machine"]["name"] = "TestVM"

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

        virtual_machine = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
        )
        self.debug("Checking if the virtual machine is created properly or not?")
        vms = VirtualMachine.list(self.apiclient, id=virtual_machine.id, listall=True)

        self.assertEqual(isinstance(vms, list), True, "List vms should retuen a valid name")
        vm = vms[0]
        self.assertEqual(vm.state, "Running", "Vm state should be running after deployment")
        self.debug("Display name: %s" % vm.displayname)
        return
Ejemplo n.º 6
0
    def test_05_unsupported_chars_in_display_name(self):
        """ Test Unsupported chars in the display name
            (eg: Spaces,Exclamation,yet to get unsupported chars from the dev)
        """

        # Validate the following
        # 1) Set the Global Setting vm.instancename.flag to true
        # 2) While creating VM give a Display name which has unsupported chars
        #    Gives an error message "Instance name can not be longer than 63
        #    characters. Only ASCII letters a~z, A~Z, digits 0~9, hyphen are
        #    allowed. Must start with a letter and end with a letter or digit

        self.debug("Creating VM with unsupported chars in display name")
        display_names = ["!hkzs566", "asdh asd", "!dsf d"]

        for display_name in display_names:
            self.debug("Display name: %s" % display_name)
            self.services["virtual_machine"]["displayname"] = display_name

            with self.assertRaises(Exception):
                # Spawn an instance in that network
                VirtualMachine.create(
                    self.apiclient,
                    self.services["virtual_machine"],
                    accountid=self.account.name,
                    domainid=self.account.domainid,
                    serviceofferingid=self.service_offering.id,
                )
        return
Ejemplo n.º 7
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 validate_vm_deployment(self):
        """Validates VM deployment on different hosts"""

        vms = VirtualMachine.list(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
            networkid=self.network_1.id,
            listall=True,
        )
        self.assertEqual(isinstance(vms, list), True, "List VMs shall return a valid response")
        host_1 = vms[0].hostid
        self.debug("Host for network 1: %s" % vms[0].hostid)

        vms = VirtualMachine.list(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
            networkid=self.network_2.id,
            listall=True,
        )
        self.assertEqual(isinstance(vms, list), True, "List VMs shall return a valid response")
        host_2 = vms[0].hostid
        self.debug("Host for network 2: %s" % vms[0].hostid)

        self.assertNotEqual(host_1, host_2, "Both the virtual machines should be deployed on diff hosts ")
        return
Ejemplo n.º 9
0
    def test_06_pt_startvm_false_attach_iso(self):
        """ Positive test for stopped VM test path - T5

        # 1.  Deploy VM in the network with specifying startvm parameter
        #     as False
        # 2.  List VMs and verify that VM is in stopped state
        # 3.  Register an ISO and attach it to the VM
        # 4.  Verify that ISO is attached to the VM
        """

        # Create VM in account
        virtual_machine = VirtualMachine.create(
            self.userapiclient,
            self.testdata["small"],
            templateid=self.defaultTemplateId,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            networkids=[self.networkid, ] if self.networkid else None,
            zoneid=self.zone.id,
            startvm=False,
            mode=self.zone.networktype
        )
        self.cleanup.append(virtual_machine)

        response = virtual_machine.getState(
            self.apiclient,
            VirtualMachine.STOPPED)
        self.assertEqual(response[0], PASS, response[1])

        iso = Iso.create(
            self.userapiclient,
            self.testdata["iso"],
            account=self.account.name,
            domainid=self.account.domainid,
            zoneid=self.zone.id
        )

        iso.download(self.userapiclient)
        virtual_machine.attach_iso(self.userapiclient, iso)

        vms = VirtualMachine.list(
            self.userapiclient,
            id=virtual_machine.id,
            listall=True
        )
        self.assertEqual(
            validateList(vms)[0],
            PASS,
            "List vms should return a valid list"
        )
        vm = vms[0]
        self.assertEqual(
            vm.isoid,
            iso.id,
            "The ISO status should be reflected in list Vm call"
        )
        return
def MigrateRootVolume(self,
                      vm,
                      destinationHost,
                      expectexception=False):
    """ Migrate given volume to type of storage pool mentioned in migrateto:

        Inputs:
            1. vm:               VM to be migrated
                                 is to be migrated
            2. expectexception:  If exception is expected while migration
            3. destinationHost:  Destination host where the VM\
                                 should get migrated
    """

    if expectexception:
        with self.assertRaises(Exception):
            VirtualMachine.migrate(
                vm,
                self.apiclient,
                hostid=destinationHost.id,
            )
    else:
        VirtualMachine.migrate(
            vm,
            self.apiclient,
            hostid=destinationHost.id,
        )

        migrated_vm_response = list_virtual_machines(
            self.apiclient,
            id=vm.id
        )

        self.assertEqual(
            isinstance(migrated_vm_response, list),
            True,
            "Check list virtual machines response for valid list"
        )

        self.assertNotEqual(
            migrated_vm_response,
            None,
            "Check if virtual machine exists in ListVirtualMachines"
        )

        migrated_vm = migrated_vm_response[0]

        vm_list = VirtualMachine.list(
            self.apiclient,
            id=migrated_vm.id
        )

        self.assertEqual(
            vm_list[0].hostid,
            destinationHost.id,
            "Check volume is on migrated pool"
        )
    return
    def test_02_nicira_controller_redirect(self):
        """
            Nicira clusters will redirect clients (in this case ACS) to the master node.
            This test assumes that a Nicira cluster is present and configured properly, and
            that it has at least two controller nodes. The test will check that ASC follows
            redirects by:
                - adding a Nicira Nvp device that points to one of the cluster's slave controllers,
                - create a VM in a Nicira backed network
            If all is well, no matter what controller is specified (slaves or master), the vm (and respective router VM)
            should be created without issues.
        """
        nicira_slave = self.determine_slave_conroller(self.nicira_hosts, self.nicira_master_controller)
        self.debug("Nicira slave controller is: %s " % nicira_slave)

        nicira_device = NiciraNvp.add(
            self.api_client,
            None,
            self.physical_network_id,
            hostname=nicira_slave,
            username=self.nicira_credentials['username'],
            password=self.nicira_credentials['password'],
            transportzoneuuid=self.transport_zone_uuid)
        self.test_cleanup.append(nicira_device)

        network_services = {
            'name'            : 'nicira_enabled_network',
            'displaytext'     : 'nicira_enabled_network',
            'zoneid'          : self.zone.id,
            'networkoffering' : self.network_offering.id
        }
        network = Network.create(
            self.api_client,
            network_services,
            accountid='admin',
            domainid=self.domain.id,
        )
        self.test_cleanup.append(network)

        virtual_machine = VirtualMachine.create(
            self.api_client,
            self.vm_services['small'],
            accountid='admin',
            domainid=self.domain.id,
            serviceofferingid=self.service_offering.id,
            networkids=[network.id],
            mode=self.vm_services['mode']
        )
        self.test_cleanup.append(virtual_machine)

        list_vm_response = VirtualMachine.list(self.api_client, id=virtual_machine.id)
        self.debug("Verify listVirtualMachines response for virtual machine: %s" % virtual_machine.id)

        self.assertEqual(isinstance(list_vm_response, list), True, 'Response did not return a valid list')
        self.assertNotEqual(len(list_vm_response), 0, 'List of VMs is empty')

        vm_response = list_vm_response[0]
        self.assertEqual(vm_response.id, virtual_machine.id, 'Virtual machine in response does not match request')
        self.assertEqual(vm_response.state, 'Running', 'VM is not in Running state')
Ejemplo n.º 12
0
    def test_03_duplicate_name(self):
        """ Test the duplicate name when old VM is in non-expunged state
        """

        # Validate the following
        # 1. Set the vm.instancename.flag to true.
        # 2. Add the virtual machine with display name same as that of
        #   non-expunged virtual machine. The proper error should pop
        #   out saying the duplicate names are not allowed

        # Reading display name property
        if not is_config_suitable(apiclient=self.apiclient, name='vm.instancename.flag', value='true'):
            self.skipTest('vm.instancename.flag should be true. skipping')

        self.services["virtual_machine"]["displayname"] = "TestVM"
        self.services["virtual_machine"]["name"] = "TestVM"

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

        virtual_machine = VirtualMachine.create(
                                  self.apiclient,
                                  self.services["virtual_machine"],
                                  accountid=self.account.name,
                                  domainid=self.account.domainid,
                                  serviceofferingid=self.service_offering.id,
                                  )
        self.cleanup.append(virtual_machine)
        self.debug(
            "Checking if the virtual machine is created properly or not?")
        vms = VirtualMachine.list(
                                  self.apiclient,
                                  id=virtual_machine.id,
                                  listall=True
                                  )

        self.assertEqual(
                         isinstance(vms, list),
                         True,
                         "List vms should retuen a valid name"
                         )
        vm = vms[0]
        self.assertEqual(
                         vm.state,
                         "Running",
                         "Vm state should be running after deployment"
                         )
        self.debug("Display name: %s" % vm.displayname)
        self.debug("Deplying another virtual machine with same name")
        with self.assertRaises(Exception):
            VirtualMachine.create(
                                  self.apiclient,
                                  self.services["virtual_machine"],
                                  accountid=self.account.name,
                                  domainid=self.account.domainid,
                                  serviceofferingid=self.service_offering.id,
                                  )
        return
Ejemplo n.º 13
0
    def test_01_positive_tests_usage(self):
        """ Check events in usage_events table when VM creation fails

        Steps:
        1. Create service offering with large resource numbers
        2. Try to deploy a VM
        3. VM creation should fail and VM should be in error state
        4. Destroy the VM with expunge parameter True
        5. Check the events for the account in usage_events table
        6. There should be VM.CREATE, VM.DESTROY, VOLUME.CREATE and
            VOLUME.DELETE events present in the table
        """
        # Create VM in account
        with self.assertRaises(Exception):
            VirtualMachine.create(
                self.apiclient,
                self.testdata["small"],
                templateid=self.template.id,
                accountid=self.account.name,
                domainid=self.account.domainid,
                serviceofferingid=self.service_offering.id,
                zoneid=self.zone.id,
            )

        vms = VirtualMachine.list(self.apiclient, account=self.account.name, domaind=self.account.domainid)

        self.assertEqual(validateList(vms)[0], PASS, "Vm list validation failed")

        self.assertEqual(vms[0].state.lower(), "error", "VM should be in error state")

        qresultset = self.dbclient.execute("select id from account where uuid = '%s';" % self.account.id)
        self.assertEqual(isinstance(qresultset, list), True, "Check DB query result set for valid data")

        self.assertNotEqual(len(qresultset), 0, "Check DB Query result set")
        qresult = qresultset[0]

        account_id = qresult[0]
        self.debug("select type from usage_event where account_id = '%s';" % account_id)

        qresultset = self.dbclient.execute("select type from usage_event where account_id = '%s';" % account_id)
        self.assertEqual(isinstance(qresultset, list), True, "Check DB query result set for valid data")

        self.assertNotEqual(len(qresultset), 0, "Check DB Query result set")
        qresult = str(qresultset)
        self.debug("Query result: %s" % qresult)

        # Check if VM.CREATE, VM.DESTROY events present in usage_event table
        self.assertEqual(qresult.count("VM.CREATE"), 1, "Check VM.CREATE event in events table")

        self.assertEqual(qresult.count("VM.DESTROY"), 1, "Check VM.DESTROY in list events")

        # Check if VOLUME.CREATE, VOLUME.DELETE events present in usage_event
        # table
        self.assertEqual(qresult.count("VOLUME.CREATE"), 1, "Check VOLUME.CREATE in events table")

        self.assertEqual(qresult.count("VOLUME.DELETE"), 1, "Check VM.DELETE in events table")
        return
    def test_deployvm_userdispersing(self):
        """Test deploy VMs using user dispersion planner
        """
        self.service_offering_userdispersing = ServiceOffering.create(
            self.apiclient,
            self.services["service_offerings"]["tiny"],
            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))
Ejemplo n.º 15
0
    def test_validateState_succeeds_at_retry_limit(self):
        retries = 3
        timeout = 3
        api_client = MockApiClient(retries, 'initial state', 'final state')
        vm = VirtualMachine({'id': 'vm_id', 'nic': [NIC({'ipaddress': '192.168.0.100'})]}, {})
        state = vm.validateState(api_client, 'final state', timeout=timeout, interval=1)

        self.assertEqual(state, [PASS, None])
        self.assertEqual(retries, api_client.retry_counter)
Ejemplo n.º 16
0
    def test_validateState_fails_after_retry_limit(self):
        retries = 3
        timeout = 2
        api_client = MockApiClient(retries, 'initial state', 'final state')
        vm = VirtualMachine({'id': 'vm_id', 'nic': [NIC({'ipaddress': '192.168.0.100'})]}, {})
        state = vm.validateState(api_client, 'final state', timeout=timeout, interval=1)

        self.assertEqual(state, [FAIL, 'VirtualMachine state not transited to final state, operation timed out'])
        self.assertEqual(retries, api_client.retry_counter)
    def test_Scale_VM(self):
        """
        @desc:
        1. Enable dynamic scaling in Global settings
        2. Register an CentOS 7 tempplate(with tools) and tick dynamic scaling
        3. Deploy VM with this template
        4.Start the VM and try to change service offering

        """
        self.hypervisor = str(get_hypervisor_type(self.api_client)).lower()
        if self.hypervisor != "xenserver":
            self.skipTest("This test can be run only on xenserver")
        self.updateConfigurAndRestart("enable.dynamic.scale.vm","true")
        template = Template.register(
           self.userapiclient,
          self.services["CentOS7template"],
            zoneid=self.zone.id,
           account=self.account.name,
           domainid=self.account.domainid
        )
        self.assertIsNotNone(template,"Failed to register CentOS 7 template")
        self.debug(
           "Registered a template with format {} and id {}".format(
              self.services["CentOS7template"]["format"],template.id)
        )
        template.download(self.userapiclient)
        self.cleanup.append(template)
        vm = VirtualMachine.create(
            self.userapiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            templateid=template.id,
            zoneid=self.zone.id
        )
        self.assertIsNotNone(vm,"Failed to deploy virtual machine")
        self.cleanup.append(vm)
        response = VirtualMachine.list(self.userapiclient,id=vm.id)
        status = validateList(response)
        self.assertEqual(status[0],PASS,"list vm response returned invalid list")
        self.assertEqual(status[1].state,"Running", "vm is not running")

        service_offering = ServiceOffering.create(
                self.apiClient,
                self.services["service_offerings"]["big"]
            )
        time.sleep(self.services["sleep"])
        vm.scale(self.userapiclient,service_offering.id)
        scaleresponse = VirtualMachine.list(self.userapiclient,id=vm.id)
        scalestatus = validateList(scaleresponse)
        self.assertEqual(scalestatus[0],PASS,"list vm response returned invalid list")
        self.assertEqual(scalestatus[1].serviceofferingname,service_offering.name, " service offering is not same")
        self.assertEqual(scalestatus[1].serviceofferingid,service_offering.id, " service offering ids are not same")


        return
Ejemplo n.º 18
0
    def test_deploy_vm_start_failure(self):
        """Test Deploy Virtual Machine - start operation failure and retry

        # Validate the following:
        # 1. 1st VM creation failed
        # 2. Check there were 4 failed start operation retries (mock count = (6-4) = 2)
        # 3. 2nd VM creation succeeded
        # 4. Check there were 2 failed start operation retries (mock count = (2-2) = 0)
        # 5. ListVM returns accurate information
        """
        self.virtual_machine = None
        with self.assertRaises(Exception):
            self.virtual_machine = 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)

        self.mock_start_failure = self.mock_start_failure.query(self.apiclient)
        self.assertEqual(
            self.mock_start_failure.count,
            2,
            msg="Start failure mock not executed")

        self.virtual_machine = VirtualMachine.create(
            self.apiclient,
            self.testdata["virtual_machine3"],
            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.assertTrue(isinstance(list_vms, list) and len(list_vms) > 0, msg="List VM response empty")
        vm = list_vms[0]
        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.mock_start_failure = self.mock_start_failure.query(self.apiclient)
        self.assertEqual(
            self.mock_start_failure.count,
            0,
            msg="Start failure mock not executed")
Ejemplo n.º 19
0
    def test_05_use_private_template_in_project(self):
        """Test use of private template in a project
        """
        # 1. Create a project
        # 2. Verify that in order to use somebody's Private template for vm
        #    creation in the project, permission to use the template has to
        #    be granted to the Project (use API 'updateTemplatePermissions'
        #    with project id to achieve that).

        try:
            self.debug("Deploying VM for with public template: %s" % self.template.id)
            virtual_machine_1 = VirtualMachine.create(
                self.apiclient,
                self.services["server"],
                templateid=self.template.id,
                serviceofferingid=self.service_offering.id,
                projectid=self.project.id,
            )
            self.cleanup.append(virtual_machine_1)
            # Verify VM state
            self.assertEqual(virtual_machine_1.state, "Running", "Check VM state is Running or not")
            virtual_machine_1.stop(self.apiclient)
            # Get the Root disk of VM
            volumes = list_volumes(self.apiclient, projectid=self.project.id, type="ROOT", listall=True)
            self.assertEqual(isinstance(volumes, list), True, "Check for list volume response return valid data")
            volume = volumes[0]

            self.debug("Creating template from volume: %s" % volume.id)
            # Create a template from the ROOTDISK
            template_1 = Template.create(self.userapiclient, self.services["template"], volumeid=volume.id)

            self.cleanup.append(template_1)
            # Verify Template state
            self.assertEqual(template_1.isready, True, "Check Template is in ready state or not")

            # Update template permissions to grant permission to project
            self.debug(
                "Updating template permissions:%s to grant access to project: %s" % (template_1.id, self.project.id)
            )

            template_1.updatePermissions(self.apiclient, op="add", projectids=self.project.id)
            self.debug("Deploying VM for with privileged template: %s" % self.template.id)
            virtual_machine_2 = VirtualMachine.create(
                self.apiclient,
                self.services["server"],
                templateid=template_1.id,
                serviceofferingid=self.service_offering.id,
                projectid=self.project.id,
            )
            self.cleanup.append(virtual_machine_2)
            # Verify VM state
            self.assertEqual(virtual_machine_2.state, "Running", "Check VM state is Running or not")
        except Exception as e:
            self.fail("Exception occured: %s" % e)
        return
Ejemplo n.º 20
0
    def test_deploy_vm(self):
        """Test Deploy Virtual Machine
 
        # Validate the following:
        # - listVirtualMachines returns accurate information
        """
        self.debug(
            "templatess: %s"\
            % self.template
        )
 
        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 setUp(self):
     self.apiclient = self.testClient.getApiClient()
     self.dbclient = self.testClient.getDbConnection()
     self.cleanup = []
     # Deploy guest vm
     try:
         self.virtual_machine = VirtualMachine.create(
             self.apiclient,
             self.testdata["server_without_disk"],
             templateid=self.template.id,
             accountid=self.account.name,
             domainid=self.testdata["domainid"],
             zoneid=self.testdata["zoneid"],
             serviceofferingid=self.service_offering.id,
             mode=self.testdata["mode"],
         )
     except Exception as e:
         raise Exception(
             "Warning: Exception during vm deployment: {}".format(e))
     self.vm_response = VirtualMachine.list(
         self.apiclient,
         id=self.virtual_machine.id
     )
     self.assertEqual(
         isinstance(self.vm_response, list),
         True,
         "Check VM list response returned a valid list"
     )
     self.ip_range = list(
         netaddr.iter_iprange(
             unicode(
                 self.testdata["vlan_ip_range"]["startip"]), unicode(
                 self.testdata["vlan_ip_range"]["endip"])))
     self.nic_ip = netaddr.IPAddress(
         unicode(
             self.vm_response[0].nic[0].ipaddress))
     self.debug("vm got {} as ip address".format(self.nic_ip))
     self.assertIn(
         self.nic_ip,
         self.ip_range,
         "VM did not get the ip address from the new ip range"
     )
     ip_alias = self.dbclient.execute(
         "select ip4_address from nic_ip_alias;"
     )
     self.alias_ip = str(ip_alias[0][0])
     self.debug("alias ip : %s" % self.alias_ip)
     self.assertNotEqual(
         self.alias_ip,
         None,
         "Error in creating ip alias. Please check MS logs"
     )
     self.cleanup.append(self.virtual_machine)
     return
Ejemplo n.º 22
0
    def test_deploy_multiple_vm(self, value):
        """Test Deploy multiple VMs with & verify the usage
        # Validate the following
        # 1. Deploy multiple VMs with this service offering
        # 2. Update Resource count for the root admin Primary Storage usage
        # 3. Primary Storage usage should list properly
        # 4. Destroy one VM among multiple VM's and verify that primary storage count
        #  decreases by equivalent amount
        """

        response = self.setupAccount(value)
        self.assertEqual(response[0], PASS, response[1])

        self.virtualMachine_2 = VirtualMachine.create(self.api_client, self.services["virtual_machine"],
                            accountid=self.account.name, domainid=self.account.domainid,
                            diskofferingid=self.disk_offering.id,
                            serviceofferingid=self.service_offering.id)

        expectedCount = (self.initialResourceCount * 2) #Total 2 vms
        response = matchResourceCount(
                        self.apiclient, expectedCount,
                        RESOURCE_PRIMARY_STORAGE,
                        accountid=self.account.id)
        self.assertEqual(response[0], PASS, response[1])

        self.virtualMachine_3 = VirtualMachine.create(self.api_client, self.services["virtual_machine"],
                            accountid=self.account.name, domainid=self.account.domainid,
                            diskofferingid=self.disk_offering.id,
                            serviceofferingid=self.service_offering.id)

        expectedCount = (self.initialResourceCount * 3) #Total 3 vms
        response = matchResourceCount(
                        self.apiclient, expectedCount,
                        RESOURCE_PRIMARY_STORAGE,
                        accountid=self.account.id)
        self.assertEqual(response[0], PASS, response[1])

        self.debug("Destroying instance: %s" % self.virtualMachine_2.name)
        try:
    	    self.virtualMachine_2.delete(self.apiclient)
        except Exception as e:
            self.fail("Failed to delete instance: %s" % e)

        self.assertTrue(isVmExpunged(self.apiclient, self.virtualMachine_2.id), "VM not expunged \
                in allotted time")

        expectedCount -= (self.template.size / (1024 ** 3))
        response = matchResourceCount(
                        self.apiclient, expectedCount,
                        RESOURCE_PRIMARY_STORAGE,
                        accountid=self.account.id)
        self.assertEqual(response[0], PASS, response[1])
	return
Ejemplo n.º 23
0
    def test_01_deploy_vm_no_startvm(self):
        """Test Deploy Virtual Machine with no startVM parameter
        """

        # Validate the following:
        # 1. deploy Vm  without specifying the startvm parameter
        # 2. Should be able to login to the VM.
        # 3. listVM command should return the deployed VM.State of this VM
        #    should be "Running".

        self.debug("Deploying instance in the account: %s" % self.account.name)
        self.virtual_machine_1 = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            diskofferingid=self.disk_offering.id,
            startvm=False,
        )

        response = self.virtual_machine_1.getState(self.apiclient, VirtualMachine.STOPPED)
        self.assertEqual(response[0], PASS, response[1])
        self.debug("Checking the router state after VM deployment")
        routers = Router.list(self.apiclient, account=self.account.name, domainid=self.account.domainid, listall=True)
        self.assertEqual(routers, None, "List routers should return empty response")
        self.debug("Deploying another instance (startvm=true) in the account: %s" % self.account.name)
        self.virtual_machine_2 = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            diskofferingid=self.disk_offering.id,
            startvm=True,
        )

        response = self.virtual_machine_2.getState(self.apiclient, VirtualMachine.RUNNING)
        self.assertEqual(response[0], PASS, response[1])
        self.debug("Checking the router state after VM deployment")
        routers = Router.list(self.apiclient, account=self.account.name, domainid=self.account.domainid, listall=True)
        self.assertEqual(isinstance(routers, list), True, "List routers should not return empty response")
        for router in routers:
            self.debug("Router state: %s" % router.state)
            self.assertEqual(
                router.state, "Running", "Router should be in running state when instance is running in the account"
            )
        self.debug("Destroying the running VM:%s" % self.virtual_machine_2.name)
        self.virtual_machine_2.delete(self.apiclient, expunge=True)
        routers = Router.list(self.apiclient, account=self.account.name, domainid=self.account.domainid, listall=True)
        self.assertNotEqual(routers, None, "Router should get deleted after expunge delay+wait")
        return
    def test_04_template_from_snapshot(self):
        """Create Template from snapshot
        """

        # Validate the following
        # 2. Snapshot the Root disk
        # 3. Create Template from snapshot
        # 4. Deploy Virtual machine using this template
        # 5. VM should be in running state

        userapiclient = self.testClient.getUserApiClient(UserName=self.account.name, DomainName=self.account.domain)

        volumes = Volume.list(userapiclient, virtualmachineid=self.virtual_machine.id, type="ROOT", listall=True)
        volume = volumes[0]

        self.debug("Creating a snapshot from volume: %s" % volume.id)
        # Create a snapshot of volume
        snapshot = Snapshot.create(userapiclient, volume.id, account=self.account.name, domainid=self.account.domainid)
        self.debug("Creating a template from snapshot: %s" % snapshot.id)
        # Generate template from the snapshot
        template = Template.create_from_snapshot(userapiclient, snapshot, self.services["template"])
        self.cleanup.append(template)
        # Verify created template
        templates = Template.list(
            userapiclient, templatefilter=self.services["template"]["templatefilter"], id=template.id
        )
        self.assertNotEqual(templates, None, "Check if result exists in list item call")

        self.assertEqual(templates[0].id, template.id, "Check new template id in list resources call")
        self.debug("Deploying a VM from template: %s" % template.id)
        # Deploy new virtual machine using template
        virtual_machine = VirtualMachine.create(
            userapiclient,
            self.services["virtual_machine"],
            templateid=template.id,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
        )
        self.cleanup.append(virtual_machine)

        vm_response = VirtualMachine.list(
            userapiclient, id=virtual_machine.id, account=self.account.name, domainid=self.account.domainid
        )
        self.assertEqual(isinstance(vm_response, list), True, "Check for list VM response return valid list")

        # Verify VM response to check whether VM deployment was successful
        self.assertNotEqual(len(vm_response), 0, "Check VMs available in List VMs response")
        vm = vm_response[0]
        self.assertEqual(vm.state, "Running", "Check the state of VM created from Template")
        return
Ejemplo n.º 25
0
    def test_01_list_routers_admin(self):
        """TS_BUG_007-Check listRouters() using Admin User
        """


        # Validate the following
        # 1. PreReq: have rounters that are owned by other account
        # 2. Create domain and create accounts in that domain
        # 3. Create one VM for each account
        # 4. Using Admin , run listRouters. It should return all the routers

        vm_1 = VirtualMachine.create(
                                  self.apiclient,
                                  self.services["virtual_machine"],
                                  accountid=self.admin_account.name,
                                  domainid=self.admin_account.domainid,
                                  serviceofferingid=self.service_offering.id
                                  )
        self.debug("Deployed VM with ID: %s" % vm_1.id)
        vm_2 = VirtualMachine.create(
                                  self.apiclient,
                                  self.services["virtual_machine"],
                                  accountid=self.user_account.name,
                                  domainid=self.user_account.domainid,
                                  serviceofferingid=self.service_offering.id
                                  )
        self.debug("Deployed VM with ID: %s" % vm_2.id)
        routers = list_routers(
                               self.apiclient,
                               account=self.admin_account.name,
                               domainid=self.admin_account.domainid,
                               )
        self.assertEqual(
                            isinstance(routers, list),
                            True,
                            "Check list response returns a valid list"
                        )
        # ListRouter Should return 2 records
        self.assertEqual(
                             len(routers),
                             1,
                             "Check list router response"
                             )
        for router in routers:
            self.assertEqual(
                        router.state,
                        'Running',
                        "Check list router response for router state"
                    )
        return
Ejemplo n.º 26
0
    def deploy_vGPU_windows_vm(self,vgpuofferingid):
        """
        Validate vGPU K1 windows instances
        """
        self.virtual_machine = VirtualMachine.create(
            self.apiclient,
            self.testdata["virtual_machine"],
            accountid=self.account.name,
            zoneid=self.zone.id,
            domainid=self.account.domainid,
            serviceofferingid=vgpuofferingid,
            templateid=self.template.id
            )
        time.sleep(600)
        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"
        )
        return
Ejemplo n.º 27
0
    def setUpClass(cls):

        cls.testClient = super(TestRouterServices, cls).getClsTestClient()
        cls.api_client = cls.testClient.getApiClient()

        cls.services = cls.testClient.getParsedTestDataConfig()
        # Get Zone, Domain and templates
        cls.domain = get_domain(cls.api_client)
        cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
        cls.services['mode'] = cls.zone.networktype
        cls.template = get_template(
            cls.api_client,
            cls.zone.id,
            cls.services["ostype"]
        )
        cls.services["virtual_machine"]["zoneid"] = cls.zone.id

        # Create an account, network, VM and IP addresses
        cls.account = Account.create(
            cls.api_client,
            cls.services["account"],
            admin=True,
            domainid=cls.domain.id
        )
        cls.service_offering = ServiceOffering.create(
            cls.api_client,
            cls.services["service_offering"]
        )
        cls.vm_1 = VirtualMachine.create(
            cls.api_client,
            cls.services["virtual_machine"],
            templateid=cls.template.id,
            accountid=cls.account.name,
            domainid=cls.account.domainid,
            serviceofferingid=cls.service_offering.id
        )
        cls.vm_2 = VirtualMachine.create(
            cls.api_client,
            cls.services["virtual_machine"],
            templateid=cls.template.id,
            accountid=cls.account.name,
            domainid=cls.account.domainid,
            serviceofferingid=cls.service_offering.id
        )
        cls._cleanup = [
            cls.account,
            cls.service_offering
        ]
        return
Ejemplo n.º 28
0
    def test_vms_with_same_name(self):
        """ Test vm deployment with same name

        # 1. Deploy a VM on with perticular name from account_1
        # 2. Try to deploy another vm with same name from account_2
        # 3. Verify that second VM deployment fails

        """
        # Step 1
        # Create VM on cluster wide
        configs = Configurations.list(
            self.apiclient,
            name="vm.instancename.flag")
        orig_value = configs[0].value

        if orig_value == "false":
            Configurations.update(self.apiclient,
                                  name="vm.instancename.flag",
                                  value="true"
                                  )

            # Restart management server
            self.RestartServer()
            time.sleep(120)

        self.testdata["small"]["displayname"]="TestName"
        self.testdata["small"]["name"]="TestName"
        VirtualMachine.create(
            self.userapiclient_1,
            self.testdata["small"],
            templateid=self.template.id,
            accountid=self.account_1.name,
            domainid=self.account_1.domainid,
            serviceofferingid=self.service_offering.id,
            zoneid=self.zone.id,
        )

        with self.assertRaises(Exception):
            VirtualMachine.create(
                self.userapiclient_2,
                self.testdata["small"],
                templateid=self.template.id,
                accountid=self.account_2.name,
                domainid=self.account_2.domainid,
                serviceofferingid=self.service_offering.id,
                zoneid=self.zone.id,
            )
        return
    def test_02_create_template_snapshot(self, value):
        """Test create snapshot and templates from volume

        # Validate the following
        1. Create root domain/child domain admin account
        2. Deploy VM in the account
        3. Create snapshot from the virtual machine root volume
        4. Create template from the snapshot
        5. Verify that the secondary storage count of the account equals
           the size of the template"""

        response = self.setupAccount(value)
        self.assertEqual(response[0], PASS, response[1])

        self.virtualMachine = VirtualMachine.create(
            self.api_client,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
        )

        self.assertNotEqual(self.virtualMachine, FAILED, "VM deployment failed")

        apiclient = self.testClient.getUserApiClient(UserName=self.account.name, DomainName=self.account.domain)
        self.assertNotEqual(apiclient, FAILED, "Failed to create api client for account: %s" % self.account.name)

        try:
            self.virtualMachine.stop(apiclient)
        except Exception as e:
            self.fail("Failed to stop instance: %s" % e)

        self.debug("Creating snapshot from ROOT volume: %s" % self.virtualMachine.name)
        response = createSnapshotFromVirtualMachineVolume(apiclient, self.account, self.virtualMachine.id)
        self.assertEqual(response[0], PASS, response[1])
        snapshot = response[1]

        snapshotSize = snapshot.physicalsize / (1024 ** 3)

        try:
            template = Template.create_from_snapshot(apiclient, snapshot=snapshot, services=self.services["template_2"])
        except Exception as e:
            self.fail("Failed to create template: %s" % e)

        templates = Template.list(
            apiclient, templatefilter=self.services["template_2"]["templatefilter"], id=template.id
        )
        self.assertEqual(validateList(templates)[0], PASS, "templates list validation failed")

        templateSize = templates[0].size / (1024 ** 3)

        expectedSecondaryStorageCount = int(templateSize + snapshotSize)
        response = matchResourceCount(
            self.apiclient,
            expectedSecondaryStorageCount,
            resourceType=RESOURCE_SECONDARY_STORAGE,
            accountid=self.account.id,
        )
        self.assertEqual(response[0], PASS, response[1])
        return
Ejemplo n.º 30
0
    def test_06_destroy_vm(self):
        """Test destroy Virtual Machine
        """

        # Validate the following
        # 1. Should not be able to login to the VM.
        # 2. listVM command should return this VM.State
        #    of this VM should be "Destroyed".

        self.debug("Destroy VM - ID: %s" % self.small_virtual_machine.id)
        self.small_virtual_machine.delete(self.apiclient, expunge=False)

        list_vm_response = VirtualMachine.list(
                                            self.apiclient,
                                            id=self.small_virtual_machine.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
    def test_04_cant_migrate_vm_to_host_with_ha_negative(self):
        """ Verify you can not migrate VMs to hosts with an ha.tag (negative) """

        # Steps,
        # 1. Create a Compute service offering with the 'Offer HA' option selected.
        # 2. Create a Guest VM with the compute service offering created above.
        # 3. Select the VM and migrate VM to another host. Choose a 'Not Suitable' host.
        # Validations,
        # The option from the 'Migrate instance to another host' dialog box should list host3 as 'Not Suitable' for migration.
        # By design, The Guest VM can STILL can be migrated to host3 if the admin chooses to do so.

        # create and verify virtual machine with HA enabled service offering
        self.hypervisor = self.testClient.getHypervisorInfo()
        virtual_machine_with_ha = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering_with_ha.id
        )

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

        self.assertEqual(
            isinstance(vms, list),
            True,
            "The listVirtualMachines returned invalid object in response."
        )

        self.assertNotEqual(
            len(vms),
            0,
            "The listVirtualMachines returned empty response."
        )

        vm = vms[0]

        self.debug("Deployed VM on host: %s" % vm.hostid)

        # Find out Non-Suitable host for VM migration
        list_hosts_response = list_hosts(
            self.apiclient,
            type="Routing"
        )
        self.assertEqual(
            isinstance(list_hosts_response, list),
            True,
            "listHosts returned invalid object in response."
        )

        self.assertNotEqual(
            len(list_hosts_response),
            0,
            "listHosts returned empty response."
        )

        notSuitableHost = None
        for host in list_hosts_response:
            if not host.suitableformigration and host.id != vm.hostid:
                notSuitableHost = host
                break

        self.assertTrue(notSuitableHost is not None, "notsuitablehost should not be None")

        # Migrate VM to Non-Suitable host
        self.debug("Migrating VM-ID: %s to Host: %s" % (vm.id, notSuitableHost.id))

        cmd = migrateVirtualMachine.migrateVirtualMachineCmd()
        cmd.hostid = notSuitableHost.id
        cmd.virtualmachineid = vm.id
        self.apiclient.migrateVirtualMachine(cmd)

        # Verify that the virtual machine got migrated to targeted Non-Suitable host
        list_vm_response = list_virtual_machines(
            self.apiclient,
            id=vm.id
        )
        self.assertEqual(
            isinstance(list_vm_response, list),
            True,
            "listVirtualMachine returned invalid object in response."
        )

        self.assertNotEqual(
            len(list_vm_response),
            0,
            "listVirtualMachines returned empty response."
        )

        self.assertEqual(
            list_vm_response[0].id,
            vm.id,
            "Virtual machine id with the virtual machine from listVirtualMachine is not matching."
        )

        self.assertEqual(
            list_vm_response[0].hostid,
            notSuitableHost.id,
            "The detination host id of migrated VM is not matching."
        )
    def test_06_no_vm_without_ha_gets_migrated_to_ha_host_in_live_migration(self):
        """ Verify that none of the VMs without HA enabled migrate to an ha tagged host during live migration """

        # Steps,
        # 1. Fresh install CS that supports this feature
        # 2. Create Basic zone, pod, cluster, add 3 hosts to cluster (host1, host2, host3), secondary & primary Storage
        # 3. When adding host3, assign the HA host tag.
        # 4. Create VMs with and without the Compute Service Offering with the HA tag.
        # 5. Note the VMs on host1 and whether any of the VMs have their 'HA enabled' flags enabled.
        # 6. Put host1 into maintenance mode.
        # Validations,
        # 1. Make sure the VMs are created on either host1 or host2 and not on host3
        # 2. Putting host1 into maintenance mode should trigger a live migration. Make sure the VMs are not migrated to HA enabled host3.

        # create and verify virtual machine with HA disabled service offering
        self.hypervisor = self.testClient.getHypervisorInfo()
        virtual_machine_without_ha = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering_without_ha.id
        )

        vms = VirtualMachine.list(
            self.apiclient,
            id=virtual_machine_without_ha.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_with_ha_disabled = vms[0]

        # Verify the virtual machine got created on non HA host
        list_hosts_response = list_hosts(
            self.apiclient,
            id=vm_with_ha_disabled.hostid
        )
        self.assertEqual(
            isinstance(list_hosts_response, list),
            True,
            "Check list response returns a valid list"
        )

        self.assertNotEqual(
            len(list_hosts_response),
            0,
            "Check Host is available"
        )

        self.assertEqual(
            list_hosts_response[0].hahost,
            False,
            "The virtual machine is not ha enabled so check if VM is created on host which is also not ha enabled"
        )

        # put the Host in maintenance mode
        self.debug("Enabling maintenance mode for host %s" % vm_with_ha_disabled.hostid)
        cmd = prepareHostForMaintenance.prepareHostForMaintenanceCmd()
        cmd.id = vm_with_ha_disabled.hostid
        self.apiclient.prepareHostForMaintenance(cmd)

        timeout = self.services["timeout"]

        # verify the VM live migration happened to another running host
        self.debug("Waiting for VM to come up")
        time.sleep(timeout)

        vms = VirtualMachine.list(
            self.apiclient,
            id=vm_with_ha_disabled.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"
        )

        list_hosts_response = list_hosts(
            self.apiclient,
            id=vms[0].hostid
        )
        self.assertEqual(
            isinstance(list_hosts_response, list),
            True,
            "Check list response returns a valid list"
        )

        self.assertNotEqual(
            len(list_hosts_response),
            0,
            "Check Host is available"
        )

        self.assertEqual(
            list_hosts_response[0].hahost,
            False,
            "The virtual machine is not ha enabled so check if VM is created on host which is also not ha enabled"
        )

        self.debug("Disabling the maintenance mode for host %s" % vm_with_ha_disabled.hostid)
        cmd = cancelHostMaintenance.cancelHostMaintenanceCmd()
        cmd.id = vm_with_ha_disabled.hostid
        self.apiclient.cancelHostMaintenance(cmd)
Ejemplo n.º 33
0
    def test_04_reoccuring_snapshot_rules(self):
        """
        1) Create a VM using the Service offering IsVolatile enabled
        2) Apply a recurring snapshot rule on the  Volume.
        3) After a couple of snapshots are taken reboot the VM.

        Verify the following conditions
        1) New root disk should be formed
        2) The recurring snapshot rule should be deleted
        """
        self.hypervisor = self.testClient.getHypervisorInfo()
        if self.hypervisor.lower() in ['lxc']:
            self.skipTest("snapshot creation is not supported in LXC")
        vms = VirtualMachine.list(self.apiclient,
                                  id=self.vm_with_reset.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_with_reset = vm_list_validation_result[1]
        vm_with_reset_root_disk_id = self.get_root_device_uuid_for_vm(
            vm_with_reset.id, vm_with_reset.rootdeviceid)

        self.debug(
            "Creating recurring snapshot policy for root disk on vm created with IsVolatile=True"
        )
        self.debug("Snapshot Policy - Type : %s Scheduled Hours : %s" %
                   (self.services["recurring_snapshot"]["intervaltype"],
                    self.services["recurring_snapshot"]["schedule"]))

        recurring_snapshot = SnapshotPolicy.create(
            self.apiclient, vm_with_reset_root_disk_id,
            self.services["recurring_snapshot"])

        #ListSnapshotPolicy should return newly created policy
        list_snapshots_policy = SnapshotPolicy.list(
            self.apiclient,
            id=recurring_snapshot.id,
            volumeid=vm_with_reset_root_disk_id)

        snapshot_list_validation_result = validateList(list_snapshots_policy)

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

        snapshots_policy = snapshot_list_validation_result[1]

        self.assertEqual(snapshots_policy.id, recurring_snapshot.id,
                         "Check recurring snapshot id in list resources call")
        self.assertEqual(snapshots_policy.maxsnaps,
                         self.services["recurring_snapshot"]["maxsnaps"],
                         "Check interval type in list resources call")
        sleep_seconds = (
            self.services["recurring_snapshot"]["schedule"]) * 3600 + 600
        sleep_minutes = sleep_seconds / 60
        self.debug("Sleeping for %s minutes till the volume is snapshoted" %
                   sleep_minutes)
        time.sleep(sleep_seconds)

        retriesCount = self.services["retriesCount"]
        while True:
            snapshots = Snapshot.list(
                        self.apiclient,
                        volumeid=vm_with_reset_root_disk_id,
                        intervaltype=\
                        self.services["recurring_snapshot"]["intervaltype"],
                        snapshottype=RECURRING,
                        listall=True
                        )

            snapshot_list_validation_result = validateList(snapshots)

            if snapshot_list_validation_result[0] == PASS:
                break

            elif retriesCount == 0:
                self.fail("Failed to get snapshots list")

            time.sleep(60)
            retriesCount = retriesCount - 1

        # rebooting the vm with isVolatile = True
        try:
            self.vm_with_reset.reboot(self.apiclient)
        except Exception as e:
            self.fail("Failed to reboot the virtual machine. Error: %s" % e)

        # Check if the the root disk was destroyed and recreated for isVolatile=True
        self.debug(
            "Checking whether root disk of VM with isVolatile=True was destroyed"
        )
        vms = VirtualMachine.list(self.apiclient,
                                  id=self.vm_with_reset.id,
                                  listall=True)

        vm_list_validation_result = validateList(vms)

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

        vm_with_reset_after_reboot = vm_list_validation_result[1]

        vm_with_reset_root_disk_id_after_reboot = self.get_root_device_uuid_for_vm(
            vm_with_reset_after_reboot.id,
            vm_with_reset_after_reboot.rootdeviceid)

        self.assertNotEqual(
            vm_with_reset_root_disk_id,
            vm_with_reset_root_disk_id_after_reboot,
            "VM created with IsVolatile=True has same rootdeviceid : %s after reboot"
            % vm_with_reset_root_disk_id_after_reboot)
        # Make sure it has the same IP after reboot
        self.assertEqual(
            vm_with_reset.nic[0].ipaddress,
            vm_with_reset_after_reboot.nic[0].ipaddress,
            "VM created with IsVolatile=True doesn't have same ip after reboot. Got : %s Expected : %s"
            % (vm_with_reset_after_reboot.nic[0].ipaddress,
               vm_with_reset.nic[0].ipaddress))

        # Check whether the recurring policy has been deleted from the database
        self.debug(
            "Checking whether snapshot rule for VM with isVolatile=True was destroyed \
                   Here we are passing root disk id of vm before reboot which does not exist hence\
                   listing should fail")

        with self.assertRaises(Exception):
            listSnapshotPolicies = SnapshotPolicy.list(
                self.apiclient, volumeid=vm_with_reset_root_disk_id)
            self.assertEqual(
                validateList(listSnapshotPolicies)[0], PASS,
                "snapshot policies list validation failed")
        return
Ejemplo n.º 34
0
    def setUpClass(cls):
        
        testClient = super(TestCreateTemplate, cls).getClsTestClient()
        cls.apiclient = testClient.getApiClient()
        cls.services = testClient.getParsedTestDataConfig()

        # Get Zone, Domain and templates
        cls.domain = get_domain(cls.apiclient)
        cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
        cls.services['mode'] = cls.zone.networktype

        cls._cleanup = []
        try:
            cls.disk_offering = DiskOffering.create(
                                    cls.apiclient,
                                    cls.services["disk_offering"]
                                    )
            cls._cleanup.append(cls.disk_offering)
            template = get_template(
                            cls.apiclient,
                            cls.zone.id,
                            cls.services["ostype"]
                            )
            if template == FAILED:
                assert False, "get_template() failed to return template with description %s" % cls.services["ostype"]

            cls.services["template"]["ostypeid"] = template.ostypeid
            cls.services["template_2"]["ostypeid"] = template.ostypeid
            cls.services["ostypeid"] = template.ostypeid

            cls.services["virtual_machine"]["zoneid"] = cls.zone.id
            cls.services["volume"]["diskoffering"] = cls.disk_offering.id
            cls.services["volume"]["zoneid"] = cls.zone.id
            cls.services["sourcezoneid"] = cls.zone.id
            cls.account = Account.create(
                            cls.apiclient,
                            cls.services["account"],
                            domainid=cls.domain.id
                            )
            cls._cleanup.append(cls.account)
            cls.service_offering = ServiceOffering.create(
                                            cls.apiclient,
                                            cls.services["service_offerings"]
                                            )
            cls._cleanup.append(cls.service_offering)
            #create virtual machine
            cls.virtual_machine = VirtualMachine.create(
                                    cls.apiclient,
                                    cls.services["virtual_machine"],
                                    templateid=template.id,
                                    accountid=cls.account.name,
                                    domainid=cls.account.domainid,
                                    serviceofferingid=cls.service_offering.id,
                                    mode=cls.services["mode"]
                                    )
            #Stop virtual machine
            cls.virtual_machine.stop(cls.apiclient)

            list_volume = Volume.list(
                                   cls.apiclient,
                                   virtualmachineid=cls.virtual_machine.id,
                                   type='ROOT',
                                   listall=True
                                   )

            cls.volume = list_volume[0]
        except Exception as e:
            cls.tearDownClass()
            raise unittest.SkipTest("Exception in setUpClass: %s" % e)
        return
    def setUpClass(cls):
        cls.testClient = super(TestMulipleNicSupport, cls).getClsTestClient()
        cls.apiclient = cls.testClient.getApiClient()
        cls.testdata = cls.testClient.getParsedTestDataConfig()
        cls.services = cls.testClient.getParsedTestDataConfig()
        zone = get_zone(cls.apiclient, cls.testClient.getZoneForTests())
        cls.zone = Zone(zone.__dict__)
        cls._cleanup = []

        cls.skip = False
        if str(cls.zone.securitygroupsenabled) != "True":
            cls.skip = True
            return

        cls.logger = logging.getLogger("TestMulipleNicSupport")
        cls.stream_handler = logging.StreamHandler()
        cls.logger.setLevel(logging.DEBUG)
        cls.logger.addHandler(cls.stream_handler)

        # Get Domain and templates
        cls.domain = get_domain(cls.apiclient)
        cls.services['mode'] = cls.zone.networktype

        cls.template = get_template(cls.apiclient,
                                    cls.zone.id,
                                    hypervisor="KVM")
        if cls.template == FAILED:
            cls.skip = True
            return

        # Create new domain, account, network and VM
        cls.user_domain = Domain.create(
            cls.apiclient,
            services=cls.testdata["acl"]["domain2"],
            parentdomainid=cls.domain.id)
        cls._cleanup.append(cls.user_domain)

        cls.account1 = Account.create(cls.apiclient,
                                      cls.testdata["acl"]["accountD2"],
                                      admin=True,
                                      domainid=cls.user_domain.id)
        cls._cleanup.append(cls.account1)

        cls.service_offering = ServiceOffering.create(
            cls.apiclient, cls.testdata["service_offerings"]["small"])
        cls._cleanup.append(cls.service_offering)

        cls.services["network"]["zoneid"] = cls.zone.id
        cls.network_offering = NetworkOffering.create(
            cls.apiclient,
            cls.services["network_offering"],
        )
        cls._cleanup.append(cls.network_offering)
        cls.network_offering.update(cls.apiclient, state='Enabled')

        cls.testdata["virtual_machine"]["zoneid"] = cls.zone.id
        cls.testdata["virtual_machine"]["template"] = cls.template.id

        if cls.zone.securitygroupsenabled:
            # Enable networking for reaching to VM thorugh SSH
            security_group = SecurityGroup.create(
                cls.apiclient,
                cls.testdata["security_group"],
                account=cls.account1.name,
                domainid=cls.account1.domainid)
            cls._cleanup.append(security_group)

            # Authorize Security group to SSH to VM
            ingress_rule = security_group.authorize(
                cls.apiclient,
                cls.testdata["ingress_rule"],
                account=cls.account1.name,
                domainid=cls.account1.domainid)

            # Authorize Security group to SSH to VM
            ingress_rule2 = security_group.authorize(
                cls.apiclient,
                cls.testdata["ingress_rule_ICMP"],
                account=cls.account1.name,
                domainid=cls.account1.domainid)

        cls.testdata["shared_network_offering_sg"]["specifyVlan"] = 'True'
        cls.testdata["shared_network_offering_sg"]["specifyIpRanges"] = 'True'
        cls.shared_network_offering = NetworkOffering.create(
            cls.apiclient,
            cls.testdata["shared_network_offering_sg"],
            conservemode=False)
        cls._cleanup.append(cls.shared_network_offering)

        NetworkOffering.update(cls.shared_network_offering,
                               cls.apiclient,
                               id=cls.shared_network_offering.id,
                               state="enabled")

        physical_network, vlan = get_free_vlan(cls.apiclient, cls.zone.id)
        cls.testdata["shared_network_sg"][
            "physicalnetworkid"] = physical_network.id

        random_subnet_number = random.randrange(90, 99)
        cls.testdata["shared_network_sg"][
            "name"] = "Shared-Network-SG-Test-vlan" + str(random_subnet_number)
        cls.testdata["shared_network_sg"][
            "displaytext"] = "Shared-Network-SG-Test-vlan" + str(
                random_subnet_number)
        cls.testdata["shared_network_sg"]["vlan"] = "vlan://" + str(
            random_subnet_number)
        cls.testdata["shared_network_sg"]["startip"] = "192.168." + str(
            random_subnet_number) + ".240"
        cls.testdata["shared_network_sg"]["endip"] = "192.168." + str(
            random_subnet_number) + ".250"
        cls.testdata["shared_network_sg"]["gateway"] = "192.168." + str(
            random_subnet_number) + ".254"
        cls.network1 = Network.create(
            cls.apiclient,
            cls.testdata["shared_network_sg"],
            networkofferingid=cls.shared_network_offering.id,
            zoneid=cls.zone.id,
            accountid=cls.account1.name,
            domainid=cls.account1.domainid)
        cls._cleanup.append(cls.network1)

        random_subnet_number = random.randrange(100, 110)
        cls.testdata["shared_network_sg"][
            "name"] = "Shared-Network-SG-Test-vlan" + str(random_subnet_number)
        cls.testdata["shared_network_sg"][
            "displaytext"] = "Shared-Network-SG-Test-vlan" + str(
                random_subnet_number)
        cls.testdata["shared_network_sg"]["vlan"] = "vlan://" + str(
            random_subnet_number)
        cls.testdata["shared_network_sg"]["startip"] = "192.168." + str(
            random_subnet_number) + ".240"
        cls.testdata["shared_network_sg"]["endip"] = "192.168." + str(
            random_subnet_number) + ".250"
        cls.testdata["shared_network_sg"]["gateway"] = "192.168." + str(
            random_subnet_number) + ".254"
        cls.network2 = Network.create(
            cls.apiclient,
            cls.testdata["shared_network_sg"],
            networkofferingid=cls.shared_network_offering.id,
            zoneid=cls.zone.id,
            accountid=cls.account1.name,
            domainid=cls.account1.domainid)
        cls._cleanup.append(cls.network2)

        random_subnet_number = random.randrange(111, 120)
        cls.testdata["shared_network_sg"][
            "name"] = "Shared-Network-SG-Test-vlan" + str(random_subnet_number)
        cls.testdata["shared_network_sg"][
            "displaytext"] = "Shared-Network-SG-Test-vlan" + str(
                random_subnet_number)
        cls.testdata["shared_network_sg"]["vlan"] = "vlan://" + str(
            random_subnet_number)
        cls.testdata["shared_network_sg"]["startip"] = "192.168." + str(
            random_subnet_number) + ".240"
        cls.testdata["shared_network_sg"]["endip"] = "192.168." + str(
            random_subnet_number) + ".250"
        cls.testdata["shared_network_sg"]["gateway"] = "192.168." + str(
            random_subnet_number) + ".254"
        cls.network3 = Network.create(
            cls.apiclient,
            cls.testdata["shared_network_sg"],
            networkofferingid=cls.shared_network_offering.id,
            zoneid=cls.zone.id,
            accountid=cls.account1.name,
            domainid=cls.account1.domainid)
        cls._cleanup.append(cls.network3)

        try:
            cls.virtual_machine1 = VirtualMachine.create(
                cls.apiclient,
                cls.testdata["virtual_machine"],
                accountid=cls.account1.name,
                domainid=cls.account1.domainid,
                serviceofferingid=cls.service_offering.id,
                templateid=cls.template.id,
                securitygroupids=[security_group.id],
                networkids=cls.network1.id)
            cls._cleanup.append(cls.virtual_machine1)
            for nic in cls.virtual_machine1.nic:
                if nic.isdefault:
                    cls.virtual_machine1.ssh_ip = nic.ipaddress
                    cls.virtual_machine1.default_network_id = nic.networkid
                    break
        except Exception as e:
            cls.fail("Exception while deploying virtual machine: %s" % {e})

        try:
            cls.virtual_machine2 = VirtualMachine.create(
                cls.apiclient,
                cls.testdata["virtual_machine"],
                accountid=cls.account1.name,
                domainid=cls.account1.domainid,
                serviceofferingid=cls.service_offering.id,
                templateid=cls.template.id,
                securitygroupids=[security_group.id],
                networkids=[str(cls.network1.id),
                            str(cls.network2.id)])
            cls._cleanup.append(cls.virtual_machine2)
            for nic in cls.virtual_machine2.nic:
                if nic.isdefault:
                    cls.virtual_machine2.ssh_ip = nic.ipaddress
                    cls.virtual_machine2.default_network_id = nic.networkid
                    break
        except Exception as e:
            cls.fail("Exception while deploying virtual machine: %s" % {e})
    def test_01_create_delete_portforwarding_fornonvpc(self):
        """
        @summary: Test to list, create and delete Port Forwarding for
        IP Address associated to Non VPC network
        @Steps:
        Step1: Creating a Network for the user
        Step2: Associating an IP Addresses for Network
        Step3: Launching Virtual Machine in network created in step 2
        Step4: Listing Port Forwarding Rules for the IP Address associated
               in Step2
        Step5: Verifying that no Port Forwarding Rules are listed
        Step6: Creating a Port Forwarding Rule for IP Address associated in
               Step2
        Step7: Listing Port Forwarding Rules for the IP Address associated in
               Step2
        Step8: Verifying 1 Port Forwarding Rule is listed
        Step9: Deleting the Port Forwarding Rule created in Step6
        Step10: Listing Port Forwarding Rules for the IP Address associated in
               Step2
        Step11: Verifying that no Port Forwarding Rules are listed
        """
        # Listing all the Networks's for a user
        list_networks_before = Network.list(
            self.userapiclient,
            listall=self.services["listall"],
            type="Isolated"
        )
        # Verifying No Networks are listed
        self.assertIsNone(
            list_networks_before,
            "Networks listed for newly created User"
        )
        # Listing Network Offerings
        network_offerings_list = NetworkOffering.list(
            self.apiClient,
            forvpc="false",
            guestiptype="Isolated",
            state="Enabled",
            supportedservices="SourceNat,PortForwarding",
            zoneid=self.zone.id
        )
        status = validateList(network_offerings_list)
        self.assertEquals(
            PASS,
            status[0],
            "Isolated Network Offerings with sourceNat,\
                    PortForwarding enabled are not found"
        )
        # Creating a network
        network = Network.create(
            self.userapiclient,
            self.services["network"],
            accountid=self.account.name,
            domainid=self.domain.id,
            networkofferingid=network_offerings_list[0].id,
            zoneid=self.zone.id
        )
        self.assertIsNotNone(
            network,
            "Network creation failed"
        )
        # Listing all the IP Addresses for a user
        list_ipaddresses_before = PublicIPAddress.list(
            self.userapiclient,
            listall=self.services["listall"]
        )
        # Verifying no IP Addresses are listed
        self.assertIsNone(
            list_ipaddresses_before,
            "IP Addresses listed for newly created User"
        )
        # Associating an IP Addresses to Network created
        associated_ipaddress = PublicIPAddress.create(
            self.userapiclient,
            services=self.services["network"],
            networkid=network.id
        )
        self.assertIsNotNone(
            associated_ipaddress,
            "Failed to Associate IP Address"
        )
        # Listing all the IP Addresses for a user
        list_ipaddresses_after = PublicIPAddress.list(
            self.userapiclient,
            listall=self.services["listall"]
        )
        status = validateList(list_ipaddresses_after)
        self.assertEquals(
            PASS,
            status[0],
            "IP Addresses Association Failed"
        )
        # Verifying the length of the list is 1
        self.assertEqual(
            1,
            len(list_ipaddresses_after),
            "Number of IP Addresses associated are not matching expected"
        )
        # Launching a Virtual Machine with above created Network
        vm_created = VirtualMachine.create(
            self.userapiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            networkids=network.id,
            serviceofferingid=self.service_offering.id,
        )
        self.assertIsNotNone(
            vm_created,
            "Failed to launch a VM under network created"
        )
        self.cleanup.append(network)
        # Listing Virtual Machines in running state in above created network
        list_vms_running = VirtualMachine.list(
            self.userapiclient,
            listall=self.services["listall"],
            state="Running",
            networkid=network.id
        )
        status = validateList(list_vms_running)
        self.assertEquals(
            PASS,
            status[0],
            "VM Created is not in Running state"
        )
        # Verifying the length of the list is 1
        self.assertEqual(
            1,
            len(list_ipaddresses_after),
            "VM Created is not in Running state"
        )
        self.assertEquals(
            vm_created.id,
            list_vms_running[0].id,
            "VM Created is not in Running state"
        )
        # Listing Virtual Machines in stopped state in above created network
        list_vms_stopped = VirtualMachine.list(
            self.userapiclient,
            listall=self.services["listall"],
            state="Stopped",
            networkid=network.id
        )
        # Verifying no VMs are in stopped state
        self.assertIsNone(
            list_vms_stopped,
            "VM Created is in stopped state"
        )
        # Listing Port Forwarding Rules for the IP Address associated
        list_prtfwdrule_before = NATRule.list(
            self.userapiclient,
            listall=self.services["listall"],
            ipaddressid=associated_ipaddress.ipaddress.id
        )
        # Verifying no port forwarding rules are listed
        self.assertIsNone(
            list_prtfwdrule_before,
            "Port Forwarding Rules listed for newly associated IP Address"
        )
        # Creating a Port Forwarding rule
        portfwd_rule = NATRule.create(
            self.userapiclient,
            virtual_machine=vm_created,
            services=self.services["natrule"],
            ipaddressid=associated_ipaddress.ipaddress.id,
        )
        self.assertIsNotNone(
            portfwd_rule,
            "Failed to create Port Forwarding Rule"
        )
        # Verifying details of Sticky Policy created
        # Creating expected and actual values dictionaries
        expected_dict = {
            "ipaddressid": associated_ipaddress.ipaddress.id,
            "privateport": str(self.services["natrule"]["privateport"]),
            "publicport": str(self.services["natrule"]["publicport"]),
            "protocol": str(self.services["natrule"]["protocol"]).lower(),
        }
        actual_dict = {
            "ipaddressid": portfwd_rule.ipaddressid,
            "privateport": str(portfwd_rule.privateport),
            "publicport": str(portfwd_rule.publicport),
            "protocol": portfwd_rule.protocol,
        }
        portfwd_status = self.__verify_values(
            expected_dict,
            actual_dict
        )
        self.assertEqual(
            True,
            portfwd_status,
            "Created Port Forward Rule details are not as expected"
        )
        # Listing Port Forwarding Rules for the IP Address associated
        list_prtfwdrule_after = NATRule.list(
            self.userapiclient,
            listall=self.services["listall"],
            ipaddressid=associated_ipaddress.ipaddress.id
        )
        status = validateList(list_prtfwdrule_after)
        self.assertEquals(
            PASS,
            status[0],
            "Failed to create Port Forwarding Rule"
        )
        # Verifying the length of the list is 1
        self.assertEqual(
            1,
            len(list_prtfwdrule_after),
            "Failed to create Port Forwarding Rule"
        )
        # Deleting Port Forwarding Rule
        portfwd_rule.delete(self.userapiclient)


        # Creating a Port Forwarding rule with port range
        portfwd_rule = NATRule.create(
            self.userapiclient,
            virtual_machine=vm_created,
            services=self.services["natrulerange"],
            ipaddressid=associated_ipaddress.ipaddress.id,
            )
        self.assertIsNotNone(
            portfwd_rule,
            "Failed to create Port Forwarding Rule"
        )
        #update the private port for port forwarding rule
        updatefwd_rule = portfwd_rule.update(self.userapiclient,
                            portfwd_rule.id,
                            virtual_machine=vm_created,
                            services=self.services["updatenatrulerange"],
                            )

        # Verifying details of Sticky Policy created
        # Creating expected and actual values dictionaries
        expected_dict = {
            "privateport": str(self.services["updatenatrulerange"]["privateport"]),
            "privateendport": str(self.services["updatenatrulerange"]["privateendport"]),
            }
        actual_dict = {
            "privateport": str(updatefwd_rule.privateport),
            "privateendport": str(updatefwd_rule.privateendport),
            }
        portfwd_status = self.__verify_values(
            expected_dict,
            actual_dict
        )
        self.assertEqual(
            True,
            portfwd_status,
            "Updated Port Forward Rule details are not as expected"
        )
        # Deleting Port Forwarding Rule
        portfwd_rule.delete(self.userapiclient)
        # Listing Port Forwarding Rules for the IP Address associated
        list_prtfwdrule_after = NATRule.list(
            self.userapiclient,
            listall=self.services["listall"],
            ipaddressid=associated_ipaddress.ipaddress.id
        )
        # Verifying no port forwarding rules are listed
        self.assertIsNone(
            list_prtfwdrule_after,
            "Port Forwarding Rules listed after deletion"
        )
        # Destroying the VM Launched
        vm_created.delete(self.apiClient)
        self.cleanup.append(self.account)
        return
    def test_02_no_vm_creation_on_host_with_haenabled(self):
        """ Verify you can not create new VMs on hosts with an ha.tag """

        # Steps,
        # 1. Fresh install CS (Bonita) that supports this feature
        # 2. Create Basic zone, pod, cluster, add 3 hosts to cluster (host1, host2, host3), secondary & primary Storage
        # 3. When adding host3, assign the HA host tag.
        # 4. You should already have a compute service offering with HA already create from above. If not, create one for HA.
        # 5. Create VMs with the service offering with and without the HA tag
        # Validations,
        # Check to make sure the newly created VM is not on any HA enabled hosts
        # The  VM should be created only on host1 or host2 and never host3 (HA enabled)

        # create and verify virtual machine with HA enabled service offering
        virtual_machine_with_ha = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering_with_ha.id
        )

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

        self.assertEqual(
            isinstance(vms, list),
            True,
            "listVirtualMachines returned invalid object in response."
        )

        self.assertNotEqual(
            len(vms),
            0,
            "listVirtualMachines returned empty list."
        )

        vm = vms[0]

        self.debug("Deployed VM on host: %s" % vm.hostid)

        # validate the virtual machine created is host Ha enabled
        list_hosts_response = list_hosts(
            self.apiclient,
            id=vm.hostid
        )
        self.assertEqual(
            isinstance(list_hosts_response, list),
            True,
            "listHosts returned invalid object in response."
        )

        self.assertNotEqual(
            len(list_hosts_response),
            0,
            "listHosts retuned empty list in response."
        )

        self.assertEqual(
            list_hosts_response[0].hahost,
            False,
            "VM created on HA enabled host."
        )

        # create and verify virtual machine with Ha disabled service offering
        virtual_machine_without_ha = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering_without_ha.id
        )

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

        self.assertEqual(
            isinstance(vms, list),
            True,
            "listVirtualMachines returned invalid object in response."
        )

        self.assertNotEqual(
            len(vms),
            0,
            "listVirtualMachines returned empty list."
        )

        vm = vms[0]

        self.debug("Deployed VM on host: %s" % vm.hostid)

        # verify that the virtual machine created on the host is Ha disabled
        list_hosts_response = list_hosts(
            self.apiclient,
            id=vm.hostid
        )
        self.assertEqual(
            isinstance(list_hosts_response, list),
            True,
            "listHosts returned invalid object in response."
        )

        self.assertNotEqual(
            len(list_hosts_response),
            0,
            "listHosts returned empty list."
        )

        host = list_hosts_response[0]

        self.assertEqual(
            host.hahost,
            False,
            "VM migrated to HA enabled host."
        )
Ejemplo n.º 38
0
    def test_02_reboot_instance_with_is_volatile_offering(self):
        """ Test rebooting instances created with isVolatile service offerings
        """

        # Validate the following
        # 1. Reboot the virtual machines.
        # 2. Validate the following
        #     a. VM with created with isVolatile=True should have new Root disk but same IP
        #     b. VM with created with isVolatile=False should have same Root disk and IP as before reboot

        self.debug("Rebooting the virtual machines in account: %s" %
                   self.account.name)
        try:
            self.vm_with_reset.reboot(self.apiclient)
            self.vm_without_reset.reboot(self.apiclient)
        except Exception as e:
            self.fail("Failed to reboot the virtual machines, %s" % e)

        # Check if the the root disk was destroyed and recreated for isVolatile=True
        self.debug("Checking root disk of VM with isVolatile=True")
        vms = VirtualMachine.list(self.apiclient,
                                  id=self.vm_with_reset.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_with_reset = vm_list_validation_result[1]
        vm_with_reset_root_disk_id = self.get_root_device_uuid_for_vm(
            vm_with_reset.id, vm_with_reset.rootdeviceid)

        self.assertNotEqual(
            self.vm_with_reset_root_disk_id, vm_with_reset_root_disk_id,
            "VM created with IsVolatile=True has same rootdeviceid : %s after reboot"
            % vm_with_reset_root_disk_id)
        # Make sure it has the same IP after reboot
        self.assertEqual(
            self.vm_with_reset.nic[0].ipaddress,
            vm_with_reset.nic[0].ipaddress,
            "VM created with IsVolatile=True doesn't have same ip after reboot. Got : %s Expected : %s"
            % (vm_with_reset.nic[0].ipaddress,
               self.vm_with_reset.nic[0].ipaddress))

        # Check if the the root disk was not destroyed for isVolatile=False
        self.debug("Checking root disk of VM with isVolatile=False")
        vms = VirtualMachine.list(self.apiclient,
                                  id=self.vm_without_reset.id,
                                  listall=True)
        vm_list_validation_result = validateList(vms)

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

        vm_without_reset = vm_list_validation_result[1]

        vm_without_reset_root_disk_id = self.get_root_device_uuid_for_vm(
            vm_without_reset.id, vm_without_reset.rootdeviceid)

        self.assertEqual(
            self.vm_without_reset_root_disk_id, vm_without_reset_root_disk_id,
            "VM created with IsVolatile=False has different rootdeviceid after reboot Got: %s Expected : %s"
            % (vm_without_reset_root_disk_id,
               self.vm_without_reset_root_disk_id))

        # Make sure it has the same IP after reboot
        self.assertEqual(
            self.vm_without_reset.nic[0].ipaddress,
            vm_without_reset.nic[0].ipaddress,
            "VM created with IsVolatile=True doesn't have same ip after reboot. Got : %s Expected : %s"
            % (vm_without_reset.nic[0].ipaddress,
               self.vm_without_reset.nic[0].ipaddress))

        return
Ejemplo n.º 39
0
    def test_03_restore_vm_with_new_template(self):
        """ Test restoring a vm with different template than the one it was created with
        """

        hosts = Host.list(self.apiclient, type="Routing", listall=True)

        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])

        hypervisor = host_list_validation_result[1].hypervisor

        for k, v in list(self.services["templates"].items()):
            if k.lower() == hypervisor.lower():
                # Register new template
                template = Template.register(self.apiclient,
                                             v,
                                             zoneid=self.zone.id,
                                             account=self.account.name,
                                             domainid=self.account.domainid,
                                             hypervisor=self.hypervisor)
                self.debug("Registered a template of format: %s with ID: %s" %
                           (v["format"], template.id))
                self.debug("Downloading template with ID: %s" % (template.id))
                template.download(self.apiclient)
                self._cleanup.append(template)

                # Wait for template status to be changed across
                time.sleep(self.services["sleep"])

                self.verify_template_listing(template)

                # Restore a vm with the new template.
                self.vm_with_reset.restore(self.apiclient,
                                           templateid=template.id)
                self.vm_without_reset.restore(self.apiclient,
                                              templateid=template.id)

                # Make sure the VMs now have the new template ID
                # Make sure the Ip address of the VMs haven't changed
                self.debug("Checking template id of VM with isVolatile=True")
                vms = VirtualMachine.list(self.apiclient,
                                          id=self.vm_with_reset.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_with_reset = vm_list_validation_result[1]

                self.assertNotEqual(
                    self.vm_with_reset.templateid, vm_with_reset.templateid,
                    "VM created with IsVolatile=True has same templateid : %s after restore"
                    % vm_with_reset.templateid)

                self.assertNotEqual(
                    self.vm_with_reset.templateid, template.id,
                    "VM created with IsVolatile=True has wrong templateid after restore Got:%s Expected: %s"
                    % (self.vm_with_reset.templateid, template.id))
                # Make sure it has the same IP after reboot
                self.assertEqual(
                    self.vm_with_reset.nic[0].ipaddress,
                    vm_with_reset.nic[0].ipaddress,
                    "VM created with IsVolatile=True doesn't have same ip after restore. Got : %s Expected : %s"
                    % (vm_with_reset.nic[0].ipaddress,
                       self.vm_with_reset.nic[0].ipaddress))

                # Check if the the root disk was not destroyed for isVolatile=False
                self.debug("Checking template id of VM with isVolatile=False")
                vms = VirtualMachine.list(self.apiclient,
                                          id=self.vm_without_reset.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_without_reset = vm_list_validation_result[1]

                self.assertNotEqual(
                    self.vm_without_reset.templateid,
                    vm_without_reset.templateid,
                    "VM created with IsVolatile=False has same templateid : %s after restore"
                    % vm_with_reset.templateid)

                self.assertNotEqual(
                    self.vm_without_reset.templateid, template.id,
                    "VM created with IsVolatile=False has wrong templateid after restore Got:%s Expected: %s"
                    % (self.vm_without_reset.templateid, template.id))
                # Make sure it has the same IP after reboot
                self.assertEqual(
                    self.vm_without_reset.nic[0].ipaddress,
                    vm_without_reset.nic[0].ipaddress,
                    "VM created with IsVolatile=False doesn't have same ip after restore. Got : %s Expected : %s"
                    % (vm_without_reset.nic[0].ipaddress,
                       self.vm_without_reset.nic[0].ipaddress))
        return
Ejemplo n.º 40
0
    def test_03_RVR_Network_check_router_state(self):
        """ Test redundant router internals """
        self.logger.debug("Starting test_03_RVR_Network_check_router_state...")

        hypervisor = self.testClient.getHypervisorInfo()

        self.logger.debug("Creating Network Offering with default egress FALSE")
        network_offering_egress_false = NetworkOffering.create(
                                            self.apiclient,
                                            self.services["nw_off_persistent_RVR_egress_false"],
                                            conservemode=True
                                            )
        network_offering_egress_false.update(self.apiclient, state='Enabled')

        self.logger.debug("Creating network with network offering: %s" % network_offering_egress_false.id)
        network = Network.create(
                                self.apiclient,
                                self.services["network"],
                                accountid=self.account.name,
                                domainid=self.account.domainid,
                                networkofferingid=network_offering_egress_false.id,
                                zoneid=self.zone.id
                                )
        self.logger.debug("Created network with ID: %s" % network.id)

        networks = Network.list(
                                self.apiclient,
                                id=network.id,
                                listall=True
                                )
        self.assertEqual(
            isinstance(networks, list),
            True,
            "List networks should return a valid response for created network"
             )
        nw_response = networks[0]

        self.logger.debug("Deploying VM in account: %s" % self.account.name)
        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,
                                  networkids=[str(network.id)]
                                  )

        self.logger.debug("Deployed VM in network: %s" % network.id)

        self.cleanup.insert(0, network_offering_egress_false)
        self.cleanup.insert(0, network)
        self.cleanup.insert(0, virtual_machine)

        vms = VirtualMachine.list(
                                  self.apiclient,
                                  id=virtual_machine.id,
                                  listall=True
                                  )
        self.assertEqual(
                         isinstance(vms, list),
                         True,
                         "List Vms should return a valid list"
                         )
        vm = vms[0]
        self.assertEqual(
                         vm.state,
                         "Running",
                         "VM should be in running state after deployment"
                         )

        self.logger.debug("Listing routers for network: %s" % network.name)
        routers = Router.list(
                              self.apiclient,
                              networkid=network.id,
                              listall=True
                              )
        self.assertEqual(
                    isinstance(routers, list),
                    True,
                    "list router should return Primary and backup routers"
                    )
        self.assertEqual(
                    len(routers),
                    2,
                    "Length of the list router should be 2 (Backup & Primary)"
                    )

        vals = ["PRIMARY", "BACKUP", "UNKNOWN"]
        cnts = [0, 0, 0]

        result = "UNKNOWN"
        for router in routers:
            if router.state == "Running":
                hosts = list_hosts(
                    self.apiclient,
                    zoneid=router.zoneid,
                    type='Routing',
                    state='Up',
                    id=router.hostid
                )
                self.assertEqual(
                    isinstance(hosts, list),
                    True,
                    "Check list host returns a valid list"
                )
                host = hosts[0]

                if hypervisor.lower() in ('vmware', 'hyperv'):
                        result = str(get_process_status(
                            self.apiclient.connection.mgtSvr,
                            22,
                            self.apiclient.connection.user,
                            self.apiclient.connection.passwd,
                            router.linklocalip,
                            "sh /opt/cloud/bin/checkrouter.sh ",
                            hypervisor=hypervisor
                        ))
                else:
                    try:
                        host.user, host.passwd = get_host_credentials(
                            self.config, host.ipaddress)
                        result = str(get_process_status(
                            host.ipaddress,
                            22,
                            host.user,
                            host.passwd,
                            router.linklocalip,
                            "sh /opt/cloud/bin/checkrouter.sh "
                        ))

                    except KeyError:
                        self.skipTest(
                            "Marvin configuration has no host credentials to\
                                    check router services")

                if result.count(vals[0]) == 1:
                    cnts[vals.index(vals[0])] += 1

        if cnts[vals.index('PRIMARY')] != 1:
            self.fail("No Primary or too many primary routers found %s" % cnts[vals.index('PRIMARY')])

        return
Ejemplo n.º 41
0
    def test_03_RouterStartOnVmDeploy(self):
        """Test router start on VM deploy
        """
        # Validate the following
        # 1. deployVirtualMachine in the account
        # 2. listVirtualMachines account=user, domainid=1
        # 3. when listVirtualMachines reports the userVM to be in state=Running
        # 4. listRouters should report router to have come back to "Running"
        #    state
        # 5. All other VMs in the account should remain in "Stopped" state

        # stop all pre-existing virtual machines if they are in 'Running' state
        virtual_machines = list_virtual_machines(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
        )

        self.assertEqual(
            isinstance(virtual_machines, list), True,
            "Check for list virtual machines response return valid data")
        self.assertNotEqual(len(virtual_machines), 0,
                            "Check list virtual machines response")
        for virtual_machine in virtual_machines:
            self.debug("VM ID: %s & VM state: %s" %
                       (virtual_machine.id, virtual_machine.state))
            if virtual_machine.state == 'Running':
                # Stop virtual machine
                cmd = stopVirtualMachine.stopVirtualMachineCmd()
                cmd.id = virtual_machine.id
                self.apiclient.stopVirtualMachine(cmd)

        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)
        self.debug("Deployed a VM with ID: %s" % vm.id)

        virtual_machines = list_virtual_machines(
            self.apiclient,
            id=vm.id,
            account=self.account.name,
            domainid=self.account.domainid,
        )

        self.assertEqual(
            isinstance(virtual_machines, list), True,
            "Check for list virtual machines response return valid data")

        self.assertNotEqual(len(virtual_machines), 0,
                            "Check list virtual machines response")
        # VM state should be 'Running'
        for virtual_machine in virtual_machines:
            self.assertEqual(virtual_machine.state, 'Running',
                             "Check list VM response for Running state")

        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
        )

        self.assertEqual(isinstance(routers, list), True,
                         "Check for list routers response return valid data")

        self.assertNotEqual(len(routers), 0, "Check list router response")
        # Routers associated with account should be 'Running' after deployment
        # of VM
        for router in routers:
            self.debug("Router ID: %s & Router state: %s" %
                       (router.id, router.state))
            self.assertEqual(router.state, 'Running',
                             "Check list router response for router state")

        # All other VMs (VM_1) should be in 'Stopped'
        virtual_machines = list_virtual_machines(
            self.apiclient,
            id=self.vm_1.id,
            account=self.account.name,
            domainid=self.account.domainid,
        )

        self.assertEqual(isinstance(virtual_machines, list), True,
                         "Check for list VMs response return valid data")

        self.assertNotEqual(len(virtual_machines), 0,
                            "Check list virtual machines response")
        for virtual_machine in virtual_machines:
            self.debug("VM ID: %s & VM state: %s" %
                       (virtual_machine.id, virtual_machine.state))
            self.assertEqual(virtual_machine.state, 'Stopped',
                             "Check list VM response for Stopped state")

        return
Ejemplo n.º 42
0
    def test_05_extract_root_volume_and_destroy_vm(self):
        """Create VM, extract root volume, then destroy vm and volume

            Steps:
            # 1. create vm without data disk, resource count increases.
            # 2. stop vm
            # 3. extract root volume
            # 4. expunge vm, root volume in Expunged state. resource count decreased with size of root disk.
            # 5. destroy volume (expunge = false), Exception happened. resource count no changes
            # 6. destroy volume (expunge = true). volume is not found. resource count no changes.
        """

        # Create vm
        try:
            virtual_machine_4 = VirtualMachine.create(
                self.apiclient,
                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)
            self.cleanup.append(virtual_machine_4)
        except Exception as e:
            self.fail("Exception while deploying virtual machine: %s" % e)

        self.expectedCount = self.expectedCount + self.templatesize
        self.volumeTotal = self.volumeTotal + 1
        self.verify_resource_count_primary_storage(self.expectedCount,
                                                   self.volumeTotal)

        # Get id of root disk
        root_volumes_list = Volume.list(self.apiclient,
                                        virtualmachineid=virtual_machine_4.id,
                                        type='ROOT',
                                        listall=True)
        status = validateList(root_volumes_list)
        self.assertEqual(status[0], PASS, "ROOT Volume List Validation Failed")
        root_volume_id = root_volumes_list[0].id

        # Stop vm
        virtual_machine_4.stop(self.apiclient)

        # extract root volume
        cmd = extractVolume.extractVolumeCmd()
        cmd.id = root_volume_id
        cmd.mode = "HTTP_DOWNLOAD"
        cmd.zoneid = self.zone.id
        self.apiclient.extractVolume(cmd)

        # Destroy VM (expunge=True)
        virtual_machine_4.delete(self.apiclient, expunge=True)
        self.cleanup.remove(virtual_machine_4)
        self.expectedCount = self.expectedCount - self.templatesize
        self.volumeTotal = self.volumeTotal - 1
        self.verify_resource_count_primary_storage(self.expectedCount,
                                                   self.volumeTotal)

        # check root disk state
        root_volumes_list = Volume.list(self.apiclient,
                                        id=root_volume_id,
                                        listall=True)
        status = validateList(root_volumes_list)
        self.assertEqual(status[0], PASS, "ROOT Volume List Validation Failed")
        root_volume = root_volumes_list[0]
        self.assertEqual(root_volume['state'], 'Expunged',
                         "ROOT volume should be Destroy after restorevm")

        # delete root disk
        cmd = deleteVolume.deleteVolumeCmd()
        cmd.id = root_volume.id
        self.apiclient.deleteVolume(cmd)
        self.verify_resource_count_primary_storage(self.expectedCount,
                                                   self.volumeTotal)
Ejemplo n.º 43
0
    def test_04_recover_root_volume_after_restorevm(self):
        """Restore VM, recover/delete old root disk

            Steps:
            # 1. create vm without data disk, resource count increases.
            # 2. restore vm. resource count no changes. 
            # 3. check old root disk , should be Destroy state
            # 4. recover old root disk. resource count increases.
            # 5. delete old root disk . resource count decreases.
            # 6. destroy vm (expunge=True). resource count decreased with size of root disk
        """

        # Create vm
        try:
            virtual_machine_3 = VirtualMachine.create(
                self.apiclient,
                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)
            self.cleanup.append(virtual_machine_3)
        except Exception as e:
            self.fail("Exception while deploying virtual machine: %s" % e)

        self.expectedCount = self.expectedCount + self.templatesize
        self.volumeTotal = self.volumeTotal + 1
        self.verify_resource_count_primary_storage(self.expectedCount,
                                                   self.volumeTotal)

        # Get id of root disk
        root_volumes_list = Volume.list(self.apiclient,
                                        virtualmachineid=virtual_machine_3.id,
                                        type='ROOT',
                                        listall=True)
        status = validateList(root_volumes_list)
        self.assertEqual(status[0], PASS, "ROOT Volume List Validation Failed")
        root_volume_id = root_volumes_list[0].id

        # restore vm
        virtual_machine_3.restore(self.apiclient)
        self.verify_resource_count_primary_storage(self.expectedCount,
                                                   self.volumeTotal)

        # check old root disk state
        root_volumes_list = Volume.list(self.apiclient,
                                        id=root_volume_id,
                                        listall=True)
        status = validateList(root_volumes_list)
        self.assertEqual(status[0], PASS, "ROOT Volume List Validation Failed")
        root_volume = root_volumes_list[0]
        self.assertEqual(root_volume['state'], 'Destroy',
                         "ROOT volume should be Destroy after restorevm")

        # recover old root disk
        cmd = recoverVolume.recoverVolumeCmd()
        cmd.id = root_volume.id
        self.apiclient.recoverVolume(cmd)
        self.expectedCount = self.expectedCount + self.templatesize
        self.volumeTotal = self.volumeTotal + 1
        self.verify_resource_count_primary_storage(self.expectedCount,
                                                   self.volumeTotal)

        # delete old root disk
        cmd = deleteVolume.deleteVolumeCmd()
        cmd.id = root_volume.id
        self.apiclient.deleteVolume(cmd)
        self.expectedCount = self.expectedCount - self.templatesize
        self.volumeTotal = self.volumeTotal - 1
        self.verify_resource_count_primary_storage(self.expectedCount,
                                                   self.volumeTotal)

        # Destroy VM (expunge=True)
        virtual_machine_3.delete(self.apiclient, expunge=True)
        self.cleanup.remove(virtual_machine_3)
        self.expectedCount = self.expectedCount - self.templatesize
        self.volumeTotal = self.volumeTotal - 1
        self.verify_resource_count_primary_storage(self.expectedCount,
                                                   self.volumeTotal)
    def test_03_cant_migrate_vm_to_host_with_ha_positive(self):
        """ Verify you can not migrate VMs to hosts with an ha.tag (positive) """

        # Steps,
        # 1. Create a Compute service offering with the 'Offer HA' option selected.
        # 2. Create a Guest VM with the compute service offering created above.
        # 3. Select the VM and migrate VM to another host. Choose a 'Suitable' host (i.e. host2)
        # Validations
        # The option from the 'Migrate instance to another host' dialog box' should list host3 as 'Not Suitable' for migration.
        # Confirm that the VM is migrated to the 'Suitable' host you selected
        # (i.e. host2)

        # create and verify the virtual machine with HA enabled service
        # offering
        self.hypervisor = self.testClient.getHypervisorInfo()

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

        vms = VirtualMachine.list(
            self.apiclient,
            id=virtual_machine_with_ha.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.debug("Deployed VM on host: %s" % vm.hostid)

        # Find out a Suitable host for VM migration
        list_hosts_response = list_hosts(
            self.apiclient,
            virtualmachineid=vm.id
        )
        self.assertEqual(
            isinstance(list_hosts_response, list),
            True,
            "The listHosts API returned the invalid list"
        )

        self.assertNotEqual(
            len(list_hosts_response),
            0,
            "The listHosts returned nothing."
        )
        suitableHost = None
        for host in list_hosts_response:
            if host.suitableformigration and host.hostid != vm.hostid:
                suitableHost = host
                break

        self.assertTrue(
            suitableHost is not None,
            "suitablehost should not be None")

        # Migration of the VM to a suitable host
        self.debug(
            "Migrating VM-ID: %s to Host: %s" %
            (vm.id, suitableHost.id))

        cmd = migrateVirtualMachine.migrateVirtualMachineCmd()
        cmd.hostid = suitableHost.id
        cmd.virtualmachineid = vm.id
        self.apiclient.migrateVirtualMachine(cmd)

        # Verify that the VM migrated to a targeted Suitable host
        list_vm_response = list_virtual_machines(
            self.apiclient,
            id=vm.id
        )
        self.assertEqual(
            isinstance(list_vm_response, list),
            True,
            "The listVirtualMachines returned the invalid list."
        )

        self.assertNotEqual(
            list_vm_response,
            None,
            "The listVirtualMachines API returned nothing."
        )

        vm_response = list_vm_response[0]

        self.assertEqual(
            vm_response.id,
            vm.id,
            "The virtual machine id and the the virtual machine from listVirtualMachines is not matching."
        )

        self.assertEqual(
            vm_response.hostid,
            suitableHost.id,
            "The VM is not migrated to targeted suitable host."
        )
Ejemplo n.º 45
0
    def setUpClass(cls):
        testClient = super(TestVolumes, cls).getClsTestClient()
        cls.apiclient = testClient.getApiClient()
        cls.services = testClient.getParsedTestDataConfig()
        cls._cleanup = []
        # Get Zone, Domain and templates
        cls.domain = get_domain(cls.apiclient)
        cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
        cls.services['mode'] = cls.zone.networktype
        cls.hypervisor = testClient.getHypervisorInfo()
        cls.invalidStoragePoolType = False
        #for LXC if the storage pool of type 'rbd' ex: ceph is not available, skip the test
        if cls.hypervisor.lower() == 'lxc':
            if not find_storage_pool_type(cls.apiclient, storagetype='rbd'):
                # RBD storage type is required for data volumes for LXC
                cls.invalidStoragePoolType = True
                return
        cls.disk_offering = DiskOffering.create(cls.apiclient,
                                                cls.services["disk_offering"])
        cls.resized_disk_offering = DiskOffering.create(
            cls.apiclient, cls.services["resized_disk_offering"])
        cls.custom_resized_disk_offering = DiskOffering.create(
            cls.apiclient, cls.services["resized_disk_offering"], custom=True)

        template = get_template(cls.apiclient, cls.zone.id,
                                cls.services["ostype"])
        if template == FAILED:
            assert False, "get_template() failed to return template with description %s" % cls.services[
                "ostype"]

        cls.services["domainid"] = cls.domain.id
        cls.services["zoneid"] = cls.zone.id
        cls.services["template"] = template.id
        cls.services["diskofferingid"] = cls.disk_offering.id
        cls.services['resizeddiskofferingid'] = cls.resized_disk_offering.id
        cls.services[
            'customresizeddiskofferingid'] = cls.custom_resized_disk_offering.id

        # Create VMs, VMs etc
        cls.account = Account.create(cls.apiclient,
                                     cls.services["account"],
                                     domainid=cls.domain.id)
        cls.service_offering = ServiceOffering.create(
            cls.apiclient, cls.services["service_offerings"]["tiny"])
        cls.virtual_machine = VirtualMachine.create(
            cls.apiclient,
            cls.services,
            accountid=cls.account.name,
            domainid=cls.account.domainid,
            serviceofferingid=cls.service_offering.id,
            mode=cls.services["mode"])
        pools = StoragePool.list(cls.apiclient)
        # cls.assertEqual(
        #         validateList(pools)[0],
        #         PASS,
        #         "storage pool list validation failed")

        if cls.hypervisor.lower(
        ) == 'lxc' and cls.storage_pools.type.lower() != 'rbd':
            raise unittest.SkipTest(
                "Snapshots not supported on Hyper-V or LXC")
        cls.volume = Volume.create(cls.apiclient,
                                   cls.services,
                                   account=cls.account.name,
                                   domainid=cls.account.domainid)
        cls._cleanup = [
            cls.resized_disk_offering, cls.custom_resized_disk_offering,
            cls.service_offering, cls.disk_offering, cls.volume, cls.account
        ]
Ejemplo n.º 46
0
    def test_01_create_template_snampshot(self):

        builtin_info = get_builtin_template_info(self.apiclient, self.zone.id)
        self.services["templates"][0]["url"] = builtin_info[0]
        self.services["templates"][0]["hypervisor"] = builtin_info[1]
        self.services["templates"][0]["format"] = builtin_info[2]

        # Register new template
        template = Template.register(
            self.apiclient,
            self.services["templates"][0],
            zoneid=self.zone.id,
            account=self.account.name,
            domainid=self.account.domainid,
            hypervisor=self.hypervisor,
            details=[{"keyboard":"us","nicAdapter":"e1000","rootDiskController":"scsi"}]
        )
        self.debug(
            "Registered a template of format: %s with ID: %s" % (
                self.services["templates"][0]["format"],
                template.id
            ))
        # Wait for template to download
        template.download(self.apiclient)
        self.cleanup.append(template)

        # Wait for template status to be changed across
        time.sleep(self.services["sleep"])
        timeout = self.services["timeout"]
        while True:
            list_template_response = Template.list(
                self.apiclient,
                templatefilter='all',
                id=template.id,
                zoneid=self.zone.id,
                account=self.account.name,
                domainid=self.account.domainid)
            if isinstance(list_template_response, list):
                break
            elif timeout == 0:
                raise Exception("List template failed!")

            time.sleep(5)
            timeout = timeout - 1
        # Verify template response to check whether template added successfully
        self.assertEqual(
            isinstance(list_template_response, list),
            True,
            "Check for list template response return valid data"
        )

        self.assertNotEqual(
            len(list_template_response),
            0,
            "Check template available in List Templates"
        )

        template_response = list_template_response[0]
        self.assertEqual(
            template_response.isready,
            True,
            "Template state is not ready, it is %s" % template_response.isready
        )

        self.assertIsNotNone(
            template_response.details,
            "Template details is %s" % template_response.details
        )

        # Deploy new virtual machine using template
        virtual_machine = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            templateid=template.id,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            mode=self.services["mode"]
        )
        self.debug("creating an instance with template ID: %s" % template.id)
        vm_response = VirtualMachine.list(self.apiclient,
                                          id=virtual_machine.id,
                                          account=self.account.name,
                                          domainid=self.account.domainid)
        self.assertEqual(
            isinstance(vm_response, list),
            True,
            "Check for list VMs response after VM deployment"
        )
        # Verify VM response to check whether VM deployment was successful
        self.assertNotEqual(
            len(vm_response),
            0,
            "Check VMs available in List VMs response"
        )
        vm = vm_response[0]
        self.assertEqual(
            vm.state,
            'Running',
            "Check the state of VM created from Template"
        )

        volumes = list_volumes(
            self.apiclient,
            virtualmachineid=vm.id,
            type='ROOT',
            listall=True
        )

        snapshot = Snapshot.create(
            self.apiclient,
            volumes[0].id,
            account=self.account.name,
            domainid=self.account.domainid
        )
        time.sleep(self.services["sleep"])
        self.cleanup.append(snapshot)
        self.debug("Snapshot created: ID - %s" % snapshot.id)

        snapshots = list_snapshots(
            self.apiclient,
            id=snapshot.id
        )
        self.assertEqual(
            isinstance(snapshots, list),
            True,
            "Check list response returns a valid list"
        )

        self.assertNotEqual(
            snapshots,
            None,
            "Check if result exists in list item call"
        )
        self.assertEqual(
            snapshots[0].id,
            snapshot.id,
            "Check resource id in list resources call"
        )

        virtual_machine.delete(self.apiclient, expunge=False)

        list_vm_response = VirtualMachine.list(
            self.apiclient,
            id=virtual_machine.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"
        )

        template = Template.create_from_snapshot(
            self.apiclient,
            snapshot,
            self.services["template"]
        )
        self.cleanup.append(template)
        # Verify created template
        templates = Template.list(
            self.apiclient     ,
            templatefilter=self.services["template"]["templatefilter"],
            id=template.id
        )
        self.assertNotEqual(
            templates,
            None,
            "Check if result exists in list item call"
        )

        self.assertEqual(
            templates[0].id,
            template.id,
            "Check new template id in list resources call"
        )


        self.assertIsNotNone(
            templates[0].details,
            "Template details is %s" % template_response.details
        )

        return
    def test_01_vm_deployment_with_compute_offering_with_ha_enabled(self):
        """ Test VM deployments (Create HA enabled Compute Service Offering and VM) """

        # Steps,
        # 1. Create a Compute service offering with the 'Offer HA' option selected.
        # 2. Create a Guest VM with the compute service offering created above.
        # Validations,
        # 1. Ensure that the offering is created and that in the UI the 'Offer HA' field is enabled (Yes)
        # The listServiceOffering API should list 'offerha' as true.
        # 2. Select the newly created VM and ensure that the Compute offering field value lists the compute service offering that was selected.
        #    Also, check that the HA Enabled field is enabled 'Yes'.

        # list and validate above created service offering with Ha enabled
        list_service_response = list_service_offering(
            self.apiclient,
            id=self.service_offering_with_ha.id
        )
        self.assertEqual(
            isinstance(list_service_response, list),
            True,
            "listServiceOfferings returned invalid object in response."
        )
        self.assertNotEqual(
            len(list_service_response),
            0,
            "listServiceOfferings returned empty list."
        )
        self.assertEqual(
            list_service_response[0].offerha,
            True,
            "The service offering is not HA enabled"
        )

        # create virtual machine with the service offering with Ha enabled
        virtual_machine = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering_with_ha.id
        )
        vms = VirtualMachine.list(
            self.apiclient,
            id=virtual_machine.id,
            listall=True
        )
        self.assertEqual(
            isinstance(vms, list),
            True,
            "listVirtualMachines returned invalid object in response."
        )
        self.assertNotEqual(
            len(vms),
            0,
            "listVirtualMachines returned empty list."
        )
        self.debug("Deployed VM on host: %s" % vms[0].hostid)
        self.assertEqual(
            vms[0].haenable,
            True,
            "VM not created with HA enable tag"
        )
Ejemplo n.º 48
0
    def setUpClass(cls):

        testClient = super(TestTemplates, cls).getClsTestClient()
        cls.apiclient = testClient.getApiClient()
        cls.services = testClient.getParsedTestDataConfig()

        # Get Zone, Domain and templates
        cls.domain = get_domain(cls.apiclient)
        cls.zone = get_zone(cls.apiclient, cls.testClient.getZoneForTests())
        cls.services['mode'] = cls.zone.networktype
        #populate second zone id for iso copy
        cmd = listZones.listZonesCmd()
        cls.zones = cls.apiclient.listZones(cmd)
        if not isinstance(cls.zones, list):
            raise Exception("Failed to find zones.")

        cls.disk_offering = DiskOffering.create(
                                    cls.apiclient,
                                    cls.services["disk_offering"]
                                    )
        template = get_template(
                            cls.apiclient,
                            cls.zone.id,
                            cls.services["ostype"]
                            )
        if template == FAILED:
            assert False, "get_template() failed to return template with description %s" % cls.services["ostype"]

        cls.services["virtual_machine"]["zoneid"] = cls.zone.id
        cls.services["volume"]["diskoffering"] = cls.disk_offering.id
        cls.services["volume"]["zoneid"] = cls.zone.id
        cls.services["template_2"]["zoneid"] = cls.zone.id
        cls.services["sourcezoneid"] = cls.zone.id

        cls.services["template"]["ostypeid"] = template.ostypeid
        cls.services["template_2"]["ostypeid"] = template.ostypeid
        cls.services["ostypeid"] = template.ostypeid
        cls.account = Account.create(
                            cls.apiclient,
                            cls.services["account"],
                            admin=True,
                            domainid=cls.domain.id
                            )
        print "After:",cls.services
        cls.user = Account.create(
                            cls.apiclient,
                            cls.services["account"],
                            domainid=cls.domain.id
                            )
        cls.service_offering = ServiceOffering.create(
                                            cls.apiclient,
                                            cls.services["service_offerings"]
                                        )
        #create virtual machine
        cls.virtual_machine = VirtualMachine.create(
                                    cls.apiclient,
                                    cls.services["virtual_machine"],
                                    templateid=template.id,
                                    accountid=cls.account.name,
                                    domainid=cls.account.domainid,
                                    serviceofferingid=cls.service_offering.id,
                                    mode=cls.services["mode"]
                                    )
        #Stop virtual machine
        cls.virtual_machine.stop(cls.apiclient)

        list_volume = Volume.list(
                                   cls.apiclient,
                                   virtualmachineid=cls.virtual_machine.id,
                                   type='ROOT',
                                   listall=True
                                   )
        try:
            cls.volume = list_volume[0]
        except Exception as e:
            raise Exception(
                "Exception: Unable to find root volume foe VM: %s - %s" %
                 (cls.virtual_machine.id, e))

        #Create templates for Edit, Delete & update permissions testcases
        cls.template_1 = Template.create(
                                         cls.apiclient,
                                         cls.services["template"],
                                         cls.volume.id,
                                         account=cls.account.name,
                                         domainid=cls.account.domainid
                                         )
        cls.template_2 = Template.create(
                                         cls.apiclient,
                                         cls.services["template_2"],
                                         cls.volume.id,
                                         account=cls.account.name,
                                         domainid=cls.account.domainid
                                         )
        cls._cleanup = [
                        cls.service_offering,
                        cls.disk_offering,
                        cls.account,
                        cls.user
                        ]
Ejemplo n.º 49
0
    def test_01_create_volume(self):
        """Test Volume creation for all Disk Offerings (incl. custom)
        """

        # Validate the following
        # 1. Create volumes from the different sizes
        # 2. Verify the size of volume with actual size allocated

        self.volumes = []
        for k, v in self.services["volume_offerings"].items():
            volume = Volume.create(self.apiClient,
                                   v,
                                   zoneid=self.zone.id,
                                   account=self.account.name,
                                   domainid=self.account.domainid,
                                   diskofferingid=self.disk_offering.id)
            self.debug("Created a volume with ID: %s" % volume.id)
            self.volumes.append(volume)

        if self.virtual_machine.hypervisor == "KVM":
            sparse_volume = Volume.create(
                self.apiClient,
                self.services,
                zoneid=self.zone.id,
                account=self.account.name,
                domainid=self.account.domainid,
                diskofferingid=self.sparse_disk_offering.id)
            self.debug("Created a sparse volume: %s" % sparse_volume.id)
            self.volumes.append(sparse_volume)

        volume = Volume.create_custom_disk(
            self.apiClient,
            self.services,
            account=self.account.name,
            domainid=self.account.domainid,
        )
        self.debug("Created a volume with custom offering: %s" % volume.id)
        self.volumes.append(volume)

        #Attach a volume with different disk offerings
        #and check the memory allocated to each of them
        for volume in self.volumes:
            list_volume_response = Volume.list(self.apiClient, id=volume.id)
            self.assertEqual(isinstance(list_volume_response, list), True,
                             "Check list response returns a valid list")
            self.assertNotEqual(list_volume_response, None,
                                "Check if volume exists in ListVolumes")
            self.debug("Attaching volume (ID: %s) to VM (ID: %s)" %
                       (volume.id, self.virtual_machine.id))
            self.virtual_machine.attach_volume(self.apiClient, volume)
            try:
                ssh = self.virtual_machine.get_ssh_client()
                self.debug("Rebooting VM %s" % self.virtual_machine.id)
                ssh.execute("reboot")
            except Exception as e:
                self.fail("SSH access failed for VM %s - %s" %
                          (self.virtual_machine.ipaddress, e))

            # Poll listVM to ensure VM is started properly
            timeout = self.services["timeout"]
            while True:
                time.sleep(self.services["sleep"])

                # Ensure that VM is in running state
                list_vm_response = VirtualMachine.list(
                    self.apiClient, id=self.virtual_machine.id)

                if isinstance(list_vm_response, list):
                    vm = list_vm_response[0]
                    if vm.state == 'Running':
                        self.debug("VM state: %s" % vm.state)
                        break

                if timeout == 0:
                    raise Exception("Failed to start VM (ID: %s) " % vm.id)
                timeout = timeout - 1

            vol_sz = str(list_volume_response[0].size)
            ssh = self.virtual_machine.get_ssh_client(reconnect=True)
            # Get the updated volume information
            list_volume_response = Volume.list(self.apiClient, id=volume.id)
            if list_volume_response[0].hypervisor.lower() == XEN_SERVER.lower(
            ):
                volume_name = "/dev/xvd" + chr(
                    ord('a') + int(list_volume_response[0].deviceid))
                self.debug(" Using XenServer volume_name: %s" % (volume_name))
                ret = checkVolumeSize(ssh_handle=ssh,
                                      volume_name=volume_name,
                                      size_to_verify=vol_sz)
            elif list_volume_response[0].hypervisor.lower() == "kvm":
                volume_name = "/dev/vd" + chr(
                    ord('a') + int(list_volume_response[0].deviceid))
                self.debug(" Using KVM volume_name: %s" % (volume_name))
                ret = checkVolumeSize(ssh_handle=ssh,
                                      volume_name=volume_name,
                                      size_to_verify=vol_sz)
            elif list_volume_response[0].hypervisor.lower() == "hyperv":
                ret = checkVolumeSize(ssh_handle=ssh,
                                      volume_name="/dev/sdb",
                                      size_to_verify=vol_sz)
            else:
                ret = checkVolumeSize(ssh_handle=ssh,
                                      volume_name="/dev/sdb",
                                      size_to_verify=vol_sz)
            self.debug(" Volume Size Expected %s  Actual :%s" %
                       (vol_sz, ret[1]))
            self.virtual_machine.detach_volume(self.apiClient, volume)
            self.assertEqual(ret[0], SUCCESS,
                             "Check if promised disk size actually available")
            time.sleep(self.services["sleep"])
Ejemplo n.º 50
0
    def test_01_create_system_vms_on_managed_storage(self):
        self._disable_zone_and_delete_system_vms(None, False)

        primary_storage = self.testdata[TestData.primaryStorage]

        primary_storage_1 = StoragePool.create(
            self.apiClient,
            primary_storage
        )

        self._prepare_to_use_managed_storage_for_system_vms()

        enabled = "Enabled"

        self.zone.update(self.apiClient, id=self.zone.id, allocationstate=enabled)

        system_vms = self._wait_for_and_get_running_system_vms(2)

        virtual_machine = VirtualMachine.create(
            self.apiClient,
            self.testdata[TestData.virtualMachine],
            accountid=self.account.name,
            zoneid=self.zone.id,
            serviceofferingid=self.compute_offering.id,
            templateid=self.template.id,
            domainid=self.domain.id,
            startvm=True
        )

        # This virtual machine was only created and started so that the virtual router would be created and started.
        # Just delete this virtual machine once it has been created and started.
        virtual_machine.delete(self.apiClient, True)

        virtual_router = list_routers(self.apiClient, listall=True, state="Running")[0]

        system_vms.append(virtual_router)

        self._check_system_vms(system_vms, primary_storage_1.id)

        primary_storage[TestData.name] = TestData.get_name_for_solidfire_storage()

        primary_storage_2 = StoragePool.create(
            self.apiClient,
            primary_storage
        )

        StoragePool.enableMaintenance(self.apiClient, primary_storage_1.id)

        self._wait_for_storage_cleanup_thread(system_vms)

        sf_util.purge_solidfire_volumes(self.sfe)

        system_vms = self._wait_for_and_get_running_system_vms(2)

        virtual_router = list_routers(self.apiClient, listall=True, state="Running")[0]

        system_vms.append(virtual_router)

        self._check_system_vms(system_vms, primary_storage_2.id)

        StoragePool.cancelMaintenance(self.apiClient, primary_storage_1.id)

        primary_storage_1.delete(self.apiClient)

        self._disable_zone_and_delete_system_vms(virtual_router)

        self._wait_for_storage_cleanup_thread(system_vms)

        sf_util.purge_solidfire_volumes(self.sfe)

        primary_storage_2.delete(self.apiClient)

        self._verify_no_active_solidfire_volumes()

        self._prepare_to_stop_using_managed_storage_for_system_vms()

        self.zone.update(self.apiClient, id=self.zone.id, allocationstate=enabled)

        self._wait_for_and_get_running_system_vms(2)
Ejemplo n.º 51
0
    def test_local_storage_data_disk_tag(self):
        """
        @Desc: Test whether tags are honoured while creating
        data disks on local storage
        @Steps:
        This test needs multiple local storages
        Step1: create a tag 'loc' on the local storage
        Step2: create a disk offering with this storage tag 'loc'
        Step3: create a VM and create disk by selecting the disk offering
         created in step2
        step4: check whether the data disk created in step3 is created on
        local storage with tag 'loc'
        """
        if not self.zone.localstorageenabled:
            self.skipTest('Local storage is not enable for this '
                          'zone. skipping')

        local_storages = StoragePool.list(self.apiClient,
                                          zoneid=self.zone.id,
                                          scope='HOST')
        self.assertEqual(isinstance(local_storages, list), True,
                         "Check list response returns a valid list")
        self.assertNotEqual(
            local_storages, None,
            "Check if local storage pools exists in ListStoragePools")

        cmd = updateStoragePool.updateStoragePoolCmd()
        cmd.zoneid = self.zone.id
        cmd.tags = 'loc'
        cmd.id = local_storages[0].id
        self.apiClient.updateStoragePool(cmd)

        self.services["disk_offering"]["storagetype"] = 'local'
        self.services["disk_offering"]["tags"] = 'loc'
        disk_offering = DiskOffering.create(self.apiClient,
                                            self.services["disk_offering"])
        self.services["virtual_machine"]["zoneid"] = self.zone.id
        self.services["virtual_machine"]["template"] = self.template.id
        # Step3: Verifying that VM creation is successful
        virtual_machine = VirtualMachine.create(
            self.apiClient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            mode=self.services["mode"])
        self.cleanup.append(virtual_machine)
        self.cleanup.append(disk_offering)
        # Verify VM state
        self.assertEqual(virtual_machine.state, 'Running',
                         "Check VM state is Running or not")
        self.volume = Volume.create(self.apiClient,
                                    self.services["volume"],
                                    zoneid=self.zone.id,
                                    account=self.account.name,
                                    domainid=self.account.domainid,
                                    diskofferingid=disk_offering.id)
        virtual_machine.attach_volume(self.apiClient, self.volume)

        self.attached = True
        list_volume_response = Volume.list(self.apiClient, id=self.volume.id)
        self.assertEqual(isinstance(list_volume_response, list), True,
                         "Check list response returns a valid list")
        self.assertNotEqual(list_volume_response, None,
                            "Check if volume exists in ListVolumes")
        volume = list_volume_response[0]
        self.assertNotEqual(volume.virtualmachineid, None,
                            "Check if volume state (attached) is reflected")

        storage_pool = StoragePool.list(self.apiClient, id=volume.storageid)

        self.assertEqual(
            volume.storagetype, 'local',
            "Check list storage pool response has local as storage type")

        self.assertEqual(storage_pool[0].tags, 'loc',
                         "Check list storage pool response has tag")
        return
Ejemplo n.º 52
0
    def test_01_create_template(self):
        """Test create public & private template
        """
        # Validate the following:
        # 1. Upload a templates in raw img format. Create a Vm instances from
        #    raw img template.
        # 2. Upload a templates in  zip file format. Create a Vm instances from
        #    zip template.
        # 3. Upload a templates in tar format.Create a Vm instances from tar
        #    template.
        # 4. Upload a templates in tar gzip format.Create a Vm instances from
        #    tar gzip template.
        # 5. Upload a templates in  tar bzip format. Create a Vm instances from
        #    tar bzip template.
        # 6. Verify VMs & Templates is up and in ready state

        builtin_info = get_builtin_template_info(self.apiclient, self.zone.id)
        self.services["templates"][0]["url"] = builtin_info[0]
        self.services["templates"][0]["hypervisor"] = builtin_info[1]
        self.services["templates"][0]["format"] = builtin_info[2]

        # Register new template
        template = Template.register(self.apiclient,
                                     self.services["templates"][0],
                                     zoneid=self.zone.id,
                                     account=self.account.name,
                                     domainid=self.account.domainid,
                                     hypervisor=self.hypervisor)
        self.debug("Registered a template of format: %s with ID: %s" %
                   (self.services["templates"][0]["format"], template.id))
        # Wait for template to download
        template.download(self.apiclient)
        self.cleanup.append(template)

        # Wait for template status to be changed across
        time.sleep(self.services["sleep"])
        timeout = self.services["timeout"]
        while True:
            list_template_response = Template.list(
                self.apiclient,
                templatefilter='all',
                id=template.id,
                zoneid=self.zone.id,
                account=self.account.name,
                domainid=self.account.domainid)
            if isinstance(list_template_response, list):
                break
            elif timeout == 0:
                raise Exception("List template failed!")

            time.sleep(5)
            timeout = timeout - 1
        #Verify template response to check whether template added successfully
        self.assertEqual(isinstance(list_template_response, list), True,
                         "Check for list template response return valid data")

        self.assertNotEqual(len(list_template_response), 0,
                            "Check template available in List Templates")

        template_response = list_template_response[0]
        self.assertEqual(
            template_response.isready, True,
            "Template state is not ready, it is %s" %
            template_response.isready)

        # Deploy new virtual machine using template
        virtual_machine = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            templateid=template.id,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            mode=self.services["mode"])
        self.debug("creating an instance with template ID: %s" % template.id)
        vm_response = VirtualMachine.list(self.apiclient,
                                          id=virtual_machine.id,
                                          account=self.account.name,
                                          domainid=self.account.domainid)
        self.assertEqual(isinstance(vm_response, list), True,
                         "Check for list VMs response after VM deployment")
        #Verify VM response to check whether VM deployment was successful
        self.assertNotEqual(len(vm_response), 0,
                            "Check VMs available in List VMs response")
        vm = vm_response[0]
        self.assertEqual(vm.state, 'Running',
                         "Check the state of VM created from Template")
        return
    def test_04_try_delete_primary_with_template(self):
        virtual_machine = VirtualMachine.create(
            self.apiclient, {"name": "StorPool-%s" % uuid.uuid4()},
            zoneid=self.zone.id,
            templateid=self.template.id,
            serviceofferingid=self.serviceOfferings.id,
            hypervisor=self.hypervisor,
            rootdisksize=10)

        volume = list_volumes(self.apiclient,
                              virtualmachineid=virtual_machine.id,
                              type="ROOT",
                              listall=True)

        volume = volume[0]

        name = volume.path.split("/")[3]
        try:
            spvolume = self.spapi.volumeList(volumeName="~" + name)
            if spvolume[0].templateName != self.template_name:
                raise Exception(
                    "Storpool volume's template %s  is not with the same template %s"
                    % (spvolume[0].templateName, self.template_name))
        except spapi.ApiError as err:
            raise Exception(err)

        backup_config = list_configurations(self.apiclient,
                                            name="sp.bypass.secondary.storage")
        if (backup_config[0].value == "false"):
            backup_config = Configurations.update(
                self.apiclient,
                name="sp.bypass.secondary.storage",
                value="true")

        snapshot = Snapshot.create(
            self.apiclient,
            volume_id=volume.id,
        )
        self.debug("###################### %s" % snapshot)
        id = self.helper.get_snapshot_template_id(self.apiclient, snapshot,
                                                  self.storage_pool_id)
        if id is None:
            raise Exception("There isn't primary storgae id")
        virtual_machine.delete(self.apiclient, expunge=True)
        pool = list_storage_pools(self.apiclient, id=id)

        services = {
            "displaytext": "Template-1",
            "name": "Template-1-name",
            "ostypeid": self.template.ostypeid,
            "ispublic": "true"
        }
        template = Template.create_from_snapshot(self.apiclient,
                                                 snapshot=snapshot,
                                                 services=services)
        Snapshot.delete(snapshot, self.apiclient)

        try:
            StoragePool.delete(self.sp_primary_storage, self.apiclient)
        except Exception as err:
            StoragePool.cancelMaintenance(self.apiclient,
                                          id=self.sp_primary_storage.id)
            self.debug("Storge pool could not be delete due to %s" % err)

        Template.delete(template, self.apiclient)
Ejemplo n.º 54
0
    def test_01_create_vm_with_data_disk(self):
        """Create VM with DATA disk, then destroy it (expunge=False) and expunge it

            Steps:
            # 1. create vm with root disk and data disk
            # 2. destroy vm, resource count of primary storage is not changed
            # 3. expunge vm, resource count of primary storage decreased with size of root disk.
            # 4. delete volume (data disk), resource count of primary storage decreased with size of data disk
        """

        try:
            virtual_machine_1 = VirtualMachine.create(
                self.apiclient,
                self.services["virtual_machine"],
                accountid=self.account.name,
                domainid=self.account.domainid,
                serviceofferingid=self.service_offering.id,
                diskofferingid=self.disk_offering.id,
                templateid=self.template.id,
                zoneid=self.zone.id)
            self.cleanup.append(virtual_machine_1)
        except Exception as e:
            self.fail("Exception while deploying virtual machine: %s" % e)

        self.expectedCount = self.expectedCount + self.templatesize + self.disk_offering.disksize
        self.volumeTotal = self.volumeTotal + 2
        self.verify_resource_count_primary_storage(self.expectedCount,
                                                   self.volumeTotal)

        root_volumes_list = Volume.list(self.apiclient,
                                        virtualmachineid=virtual_machine_1.id,
                                        type='ROOT',
                                        listall=True)
        status = validateList(root_volumes_list)
        self.assertEqual(status[0], PASS, "ROOT Volume List Validation Failed")
        root_volume_id = root_volumes_list[0].id

        data_volumes_list = Volume.list(self.apiclient,
                                        virtualmachineid=virtual_machine_1.id,
                                        type='DATADISK',
                                        listall=True)
        status = validateList(data_volumes_list)
        self.assertEqual(status[0], PASS,
                         "DATADISK Volume List Validation Failed")
        data_volume_id = data_volumes_list[0].id

        # destroy vm
        virtual_machine_1.delete(self.apiclient, expunge=False)
        self.cleanup.remove(virtual_machine_1)
        self.verify_resource_count_primary_storage(self.expectedCount,
                                                   self.volumeTotal)

        # expunge vm
        virtual_machine_1.expunge(self.apiclient)
        self.expectedCount = self.expectedCount - self.templatesize
        self.volumeTotal = self.volumeTotal - 1
        self.verify_resource_count_primary_storage(self.expectedCount,
                                                   self.volumeTotal)

        # delete datadisk
        cmd = deleteVolume.deleteVolumeCmd()
        cmd.id = data_volume_id
        self.apiclient.deleteVolume(cmd)
        self.expectedCount = self.expectedCount - self.disk_offering.disksize
        self.volumeTotal = self.volumeTotal - 1
        self.verify_resource_count_primary_storage(self.expectedCount,
                                                   self.volumeTotal)
Ejemplo n.º 55
0
    def test_08_pt_startvm_false_password_enabled_template(self):
        """ Positive test for stopped VM test path - T10

        # 1   Create a password enabled template
        # 2.  Deploy a new VM with password enabled template
        # 3.  Verify that VM is in stopped state
        # 4.  Start the VM, verify that it is in running state
        # 5.  Verify that new password is generated for the VM
        """
        vm_for_template = VirtualMachine.create(
            self.userapiclient,
            self.testdata["small"],
            templateid=self.defaultTemplateId,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            zoneid=self.zone.id,
            mode=self.zone.networktype,
            networkids=[
                self.networkid,
            ] if self.networkid else None)

        vm_for_template.password = self.testdata["virtual_machine"]["password"]
        ssh = vm_for_template.get_ssh_client()

        # below steps are required to get the new password from
        # VR(reset password)
        # http://cloudstack.org/dl/cloud-set-guest-password
        # Copy this file to /etc/init.d
        # chmod +x /etc/init.d/cloud-set-guest-password
        # chkconfig --add cloud-set-guest-password
        # similar steps to get SSH key from web so as to make it ssh enabled

        cmds = [
            "cd /etc/init.d;wget http://people.apache.org/~tsp/\
                    cloud-set-guest-password",
            "chmod +x /etc/init.d/cloud-set-guest-password",
            "chkconfig --add cloud-set-guest-password"
        ]
        for c in cmds:
            ssh.execute(c)

        # Stop virtual machine
        vm_for_template.stop(self.userapiclient)

        list_volume = Volume.list(self.userapiclient,
                                  virtualmachineid=vm_for_template.id,
                                  type='ROOT',
                                  listall=True)

        if isinstance(list_volume, list):
            self.volume = list_volume[0]
        else:
            raise Exception(
                "Exception: Unable to find root volume for VM: %s" %
                vm_for_template.id)

        self.testdata["template"]["ostype"] = self.testdata["ostype"]
        # Create templates for Edit, Delete & update permissions testcases
        pw_ssh_enabled_template = Template.create(
            self.userapiclient,
            self.testdata["template"],
            self.volume.id,
            account=self.account.name,
            domainid=self.account.domainid)
        self.cleanup.append(pw_ssh_enabled_template)
        # Delete the VM - No longer needed
        vm_for_template.delete(self.apiclient)

        # Create VM in account
        virtual_machine = VirtualMachine.create(
            self.userapiclient,
            self.testdata["small"],
            templateid=self.defaultTemplateId,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            zoneid=self.zone.id,
            startvm=False,
            mode=self.zone.networktype,
            networkids=[
                self.networkid,
            ] if self.networkid else None)
        self.cleanup.append(virtual_machine)

        response = virtual_machine.getState(self.apiclient,
                                            VirtualMachine.STOPPED)
        self.assertEqual(response[0], PASS, response[1])

        virtual_machine.start(self.userapiclient)

        vms = virtual_machine.list(self.userapiclient,
                                   id=virtual_machine.id,
                                   listall=True)

        self.assertEqual(
            validateList(vms)[0], PASS, "vms list validation failed")
        self.assertNotEqual(str(vms[0].password),
                            str(virtual_machine.password),
                            "New password should be generated for the VM")
        return
Ejemplo n.º 56
0
    def test_02_RVR_Network_FW_PF_SSH_default_routes_egress_false(self):
        """ Test redundant router internals """
        self.logger.debug("Starting test_02_RVR_Network_FW_PF_SSH_default_routes_egress_false...")

        self.logger.debug("Creating Network Offering with default egress FALSE")
        network_offering_egress_false = NetworkOffering.create(
                                            self.apiclient,
                                            self.services["nw_off_persistent_RVR_egress_false"],
                                            conservemode=True
                                            )
        network_offering_egress_false.update(self.api_client, state='Enabled')

        self.logger.debug("Creating network with network offering: %s" % network_offering_egress_false.id)
        network = Network.create(
                                self.apiclient,
                                self.services["network"],
                                accountid=self.account.name,
                                domainid=self.account.domainid,
                                networkofferingid=network_offering_egress_false.id,
                                zoneid=self.zone.id
                                )
        self.logger.debug("Created network with ID: %s" % network.id)

        networks = Network.list(
                                self.apiclient,
                                id=network.id,
                                listall=True
                                )
        self.assertEqual(
            isinstance(networks, list),
            True,
            "List networks should return a valid response for created network"
             )
        nw_response = networks[0]

        self.logger.debug("Deploying VM in account: %s" % self.account.name)
        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,
                                  networkids=[str(network.id)]
                                  )

        self.logger.debug("Deployed VM in network: %s" % network.id)

        self.cleanup.insert(0, network_offering_egress_false)
        self.cleanup.insert(0, network)
        self.cleanup.insert(0, virtual_machine)

        vms = VirtualMachine.list(
                                  self.apiclient,
                                  id=virtual_machine.id,
                                  listall=True
                                  )
        self.assertEqual(
                         isinstance(vms, list),
                         True,
                         "List Vms should return a valid list"
                         )
        vm = vms[0]
        self.assertEqual(
                         vm.state,
                         "Running",
                         "VM should be in running state after deployment"
                         )

        self.logger.debug("Listing routers for network: %s" % network.name)
        routers = Router.list(
                              self.apiclient,
                              networkid=network.id,
                              listall=True
                              )
        self.assertEqual(
                    isinstance(routers, list),
                    True,
                    "list router should return Primary and backup routers"
                    )
        self.assertEqual(
                    len(routers),
                    2,
                    "Length of the list router should be 2 (Backup & Primary)"
                    )

        public_ips = list_publicIP(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
            zoneid=self.zone.id
        )

        self.assertEqual(
            isinstance(public_ips, list),
            True,
            "Check for list public IPs response return valid data"
        )

        public_ip = public_ips[0]

        self.logger.debug("Creating Firewall rule for VM ID: %s" % virtual_machine.id)
        FireWallRule.create(
            self.apiclient,
            ipaddressid=public_ip.id,
            protocol=self.services["natrule"]["protocol"],
            cidrlist=['0.0.0.0/0'],
            startport=self.services["natrule"]["publicport"],
            endport=self.services["natrule"]["publicport"]
        )

        self.logger.debug("Creating NAT rule for VM ID: %s" % virtual_machine.id)
        nat_rule = NATRule.create(
            self.apiclient,
            virtual_machine,
            self.services["natrule"],
            public_ip.id
        )

        expected = 0
        ssh_command = "ping -c 3 8.8.8.8"
        check_string = " 0% packet loss"
        result = check_router_command(virtual_machine, nat_rule.ipaddress, ssh_command, check_string, self)

        self.assertEqual(
                         result,
                         expected,
                         "Ping to outside world from VM should NOT be successful"
                         )

        expected = 0
        ssh_command = "wget -t 1 -T 1 www.google.com"
        check_string = "HTTP request sent, awaiting response... 200 OK"
        result = check_router_command(virtual_machine, nat_rule.ipaddress, ssh_command, check_string, self)

        self.assertEqual(
                         result,
                         expected,
                         "Attempt to retrieve google.com index page should NOT be successful"
                         )

        EgressFireWallRule.create(
                                 self.apiclient,
                                 networkid=network.id,
                                 protocol=self.services["egress_80"]["protocol"],
                                 startport=self.services["egress_80"]["startport"],
                                 endport=self.services["egress_80"]["endport"],
                                 cidrlist=self.services["egress_80"]["cidrlist"]
                                 )

        EgressFireWallRule.create(
                                 self.apiclient,
                                 networkid=network.id,
                                 protocol=self.services["egress_53"]["protocol"],
                                 startport=self.services["egress_53"]["startport"],
                                 endport=self.services["egress_53"]["endport"],
                                 cidrlist=self.services["egress_53"]["cidrlist"]
                                 )

        expected = 1
        ssh_command = "wget -t 1 -T 5 www.google.com"
        check_string = "HTTP request sent, awaiting response... 200 OK"
        result = check_router_command(virtual_machine, nat_rule.ipaddress, ssh_command, check_string, self)

        self.assertEqual(
                         result,
                         expected,
                         "Attempt to retrieve google.com index page should be successful once rule is added!"
                         )

        return
Ejemplo n.º 57
0
    def test_04_template_from_snapshot(self):
        """Create Template from snapshot
        """

        # Validate the following
        # 2. Snapshot the Root disk
        # 3. Create Template from snapshot
        # 4. Deploy Virtual machine using this template
        # 5. VM should be in running state

        if self.hypervisor.lower() in ['hyperv']:
            self.skipTest("Snapshots feature is not supported on Hyper-V")

        userapiclient = self.testClient.getUserApiClient(
            UserName=self.account.name, DomainName=self.account.domain)

        volumes = Volume.list(userapiclient,
                              virtualmachineid=self.virtual_machine.id,
                              type='ROOT',
                              listall=True)
        volume = volumes[0]

        self.debug("Creating a snapshot from volume: %s" % volume.id)
        #Create a snapshot of volume
        snapshot = Snapshot.create(userapiclient,
                                   volume.id,
                                   account=self.account.name,
                                   domainid=self.account.domainid)
        self.debug("Creating a template from snapshot: %s" % snapshot.id)
        # Generate template from the snapshot
        template = Template.create_from_snapshot(userapiclient, snapshot,
                                                 self.services["template"])
        self.cleanup.append(template)
        # Verify created template
        templates = Template.list(
                                userapiclient,
                                templatefilter=\
                                self.services["template"]["templatefilter"],
                                id=template.id
                                )
        self.assertNotEqual(templates, None,
                            "Check if result exists in list item call")

        self.assertEqual(templates[0].id, template.id,
                         "Check new template id in list resources call")
        self.debug("Deploying a VM from template: %s" % template.id)
        # Deploy new virtual machine using template
        virtual_machine = VirtualMachine.create(
            userapiclient,
            self.services["virtual_machine"],
            templateid=template.id,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
        )
        self.cleanup.append(virtual_machine)

        vm_response = VirtualMachine.list(userapiclient,
                                          id=virtual_machine.id,
                                          account=self.account.name,
                                          domainid=self.account.domainid)
        self.assertEqual(isinstance(vm_response, list), True,
                         "Check for list VM response return valid list")

        #Verify VM response to check whether VM deployment was successful
        self.assertNotEqual(len(vm_response), 0,
                            "Check VMs available in List VMs response")
        vm = vm_response[0]
        self.assertEqual(vm.state, 'Running',
                         "Check the state of VM created from Template")
        return
Ejemplo n.º 58
0
    def setUpClass(cls):

        cls.testClient = super(TestTemplates, cls).getClsTestClient()
        cls.api_client = cls.testClient.getApiClient()
        cls.hypervisor = cls.testClient.getHypervisorInfo()
        cls.services = Services().services
        # Get Zone, Domain and templates
        cls.domain = get_domain(cls.api_client)
        cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
        cls.services['mode'] = cls.zone.networktype
        #populate second zone id for iso copy
        cmd = listZones.listZonesCmd()
        zones = cls.api_client.listZones(cmd)
        if not isinstance(zones, list):
            raise Exception("Failed to find zones.")
        if len(zones) >= 2:
            cls.services["destzoneid"] = zones[1].id

        template = get_template(cls.api_client, cls.zone.id,
                                cls.services["ostype"])
        cls.services["virtual_machine"]["zoneid"] = cls.zone.id
        cls._cleanup = []
        try:
            cls.account = Account.create(cls.api_client,
                                         cls.services["account"],
                                         domainid=cls.domain.id)
            cls._cleanup.append(cls.account)

            cls.services["account"] = cls.account.name
            cls.service_offering = ServiceOffering.create(
                cls.api_client, cls.services["service_offering"])
            cls._cleanup.append(cls.service_offering)

            # create virtual machine
            cls.virtual_machine = VirtualMachine.create(
                cls.api_client,
                cls.services["virtual_machine"],
                templateid=template.id,
                accountid=cls.account.name,
                domainid=cls.account.domainid,
                serviceofferingid=cls.service_offering.id,
            )
            #Stop virtual machine
            cls.virtual_machine.stop(cls.api_client)

            timeout = cls.services["timeout"]

            while True:
                list_volume = Volume.list(
                    cls.api_client,
                    virtualmachineid=cls.virtual_machine.id,
                    type='ROOT',
                    listall=True)
                if isinstance(list_volume, list):
                    break
                elif timeout == 0:
                    raise Exception("List volumes failed.")

                time.sleep(5)
                timeout = timeout - 1

            cls.volume = list_volume[0]

            #Create template from volume
            cls.template = Template.create(cls.api_client,
                                           cls.services["template"],
                                           cls.volume.id)
        except Exception as e:
            cls.tearDownClass()
            raise unittest.SkipTest("Failure in setUpClass: %s" % e)
Ejemplo n.º 59
0
    def test_03_destroy_detached_volume(self):
        """Create volume, attach/detach it, then destroy it when expunge=false and expunge=true

            Steps:
            # 1. create vm without data disk, resource count increases.
            # 2. create volume, resource count increases.
            # 3. attach volume to a vm. resource count  no changes.
            # 4. detach volume from a vm. resource count no changes.
            # 5. destroy volume (expunge = false), volume is Destroy.  resource count decreased with size of volume.
            # 6. destroy volume (expunge = true), volume is not found. resource count no changes.
            # 7. destroy vm (expunge=True). resource count decreased with size of root disk
        """
        # Create vm
        try:
            virtual_machine_2 = VirtualMachine.create(
                self.apiclient,
                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)
            self.cleanup.append(virtual_machine_2)
        except Exception as e:
            self.fail("Exception while deploying virtual machine: %s" % e)

        self.expectedCount = self.expectedCount + self.templatesize
        self.volumeTotal = self.volumeTotal + 1
        self.verify_resource_count_primary_storage(self.expectedCount,
                                                   self.volumeTotal)

        # Create volume
        volume = Volume.create(self.apiclient,
                               self.services["volume"],
                               zoneid=self.zone.id,
                               account=self.account.name,
                               domainid=self.account.domainid,
                               diskofferingid=self.disk_offering.id)
        self.cleanup.append(volume)
        self.expectedCount = self.expectedCount + self.disk_offering.disksize
        self.volumeTotal = self.volumeTotal + 1
        self.verify_resource_count_primary_storage(self.expectedCount,
                                                   self.volumeTotal)

        # Attach volume to vm
        virtual_machine_2.attach_volume(self.apiclient, volume)
        self.verify_resource_count_primary_storage(self.expectedCount,
                                                   self.volumeTotal)

        # Detach volume from vm
        virtual_machine_2.stop(self.apiclient)
        virtual_machine_2.detach_volume(self.apiclient, volume)
        self.verify_resource_count_primary_storage(self.expectedCount,
                                                   self.volumeTotal)

        # save id for later recovery and expunge
        volumeUuid = volume.id

        # Destroy volume (expunge=False)
        volume.destroy(self.apiclient, expunge=False)
        self.cleanup.remove(volume)
        self.expectedCount = self.expectedCount - self.disk_offering.disksize
        self.volumeTotal = self.volumeTotal - 1
        self.verify_resource_count_primary_storage(self.expectedCount,
                                                   self.volumeTotal)

        # Destroy volume (expunge=True)
        volume.destroy(self.apiclient, expunge=True)
        self.verify_resource_count_primary_storage(self.expectedCount,
                                                   self.volumeTotal)

        # Destroy VM (expunge=True)
        virtual_machine_2.delete(self.apiclient, expunge=True)
        self.cleanup.remove(virtual_machine_2)
        self.expectedCount = self.expectedCount - self.templatesize
        self.volumeTotal = self.volumeTotal - 1
        self.verify_resource_count_primary_storage(self.expectedCount,
                                                   self.volumeTotal)
Ejemplo n.º 60
0
    def test_02_isolate_network_FW_PF_default_routes_egress_false(self):
        """ Test redundant router internals """
        self.logger.debug("Starting test_02_isolate_network_FW_PF_default_routes_egress_false...")

        self.logger.debug("Creating Network Offering with default egress FALSE")
        network_offering_egress_false = NetworkOffering.create(self.apiclient,
                                                       self.services["network_offering_egress_false"],
                                                       conservemode=True)

        network_offering_egress_false.update(self.apiclient, state='Enabled')

        self.logger.debug("Creating Network with Network Offering ID %s" % network_offering_egress_false.id)
        network = Network.create(self.apiclient,
                                      self.services["network"],
                                      accountid=self.account.name,
                                      domainid=self.account.domainid,
                                      networkofferingid=network_offering_egress_false.id,
                                      zoneid=self.zone.id)

        self.logger.debug("Deploying Virtual Machine on Network %s" % network.id)
        virtual_machine = VirtualMachine.create(self.apiclient,
                                         self.services["virtual_machine"],
                                         templateid=self.template.id,
                                         accountid=self.account.name,
                                         domainid=self.domain.id,
                                         serviceofferingid=self.service_offering.id,
                                         networkids=[str(network.id)])

        self.logger.debug("Deployed VM in network: %s" % network.id)

        self.cleanup.insert(0, network_offering_egress_false)
        self.cleanup.insert(0, network)
        self.cleanup.insert(0, virtual_machine)

        self.logger.debug("Starting test_isolate_network_FW_PF_default_routes...")
        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid
        )

        self.assertEqual(
            isinstance(routers, list),
            True,
            "Check for list routers response return valid data"
        )

        self.assertNotEqual(
            len(routers),
            0,
            "Check list router response"
        )

        router = routers[0]

        self.assertEqual(
            router.state,
            'Running',
            "Check list router response for router state"
        )

        public_ips = list_publicIP(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
            zoneid=self.zone.id
        )

        self.assertEqual(
            isinstance(public_ips, list),
            True,
            "Check for list public IPs response return valid data"
        )

        public_ip = public_ips[0]

        self.logger.debug("Creating Firewall rule for VM ID: %s" % virtual_machine.id)
        FireWallRule.create(
            self.apiclient,
            ipaddressid=public_ip.id,
            protocol=self.services["natrule"]["protocol"],
            cidrlist=['0.0.0.0/0'],
            startport=self.services["natrule"]["publicport"],
            endport=self.services["natrule"]["publicport"]
        )

        self.logger.debug("Creating NAT rule for VM ID: %s" % virtual_machine.id)
        # Create NAT rule
        nat_rule = NATRule.create(
            self.apiclient,
            virtual_machine,
            self.services["natrule"],
            public_ip.id
        )

        nat_rules = list_nat_rules(
            self.apiclient,
            id=nat_rule.id
        )
        self.assertEqual(
            isinstance(nat_rules, list),
            True,
            "Check for list NAT rules response return valid data"
        )
        self.assertEqual(
            nat_rules[0].state,
            'Active',
            "Check list port forwarding rules"
        )

        expected = 0
        ssh_command = "ping -c 3 8.8.8.8"
        check_string = " 0% packet loss"
        result = check_router_command(virtual_machine, nat_rule.ipaddress, ssh_command, check_string, self)

        self.assertEqual(
                         result,
                         expected,
                         "Ping to outside world from VM should NOT be successful"
                         )

        expected = 0
        ssh_command = "wget -t 1 -T 1 www.google.com"
        check_string = "HTTP request sent, awaiting response... 200 OK"
        result = check_router_command(virtual_machine, nat_rule.ipaddress, ssh_command, check_string, self)

        self.assertEqual(
                         result,
                         expected,
                         "Attempt to retrieve google.com index page should NOT be successful"
                         )

        EgressFireWallRule.create(
                                 self.apiclient,
                                 networkid=network.id,
                                 protocol=self.services["egress_80"]["protocol"],
                                 startport=self.services["egress_80"]["startport"],
                                 endport=self.services["egress_80"]["endport"],
                                 cidrlist=self.services["egress_80"]["cidrlist"]
                                 )

        expected = 1
        ssh_command = "wget -t 1 -T 5 www.google.com"
        check_string = "HTTP request sent, awaiting response... 200 OK"
        result = check_router_command(virtual_machine, nat_rule.ipaddress, ssh_command, check_string, self)

        self.assertEqual(
                         result,
                         expected,
                         "Attempt to retrieve google.com index page should be successful once rule is added!"
                         )

        return