def test_vm_nic_adapter_vmxnet3(self):
        """

        # 1. Register a template for VMware with nicAdapter vmxnet3
        # 2. Deploy a VM using this template
        # 3. Create an isolated network
        # 4. Add network to VM
        # 5. Verify that the NIC adapter for VM for both the nics
        #    is vmxnet3
        """

        if self.hypervisor.lower() not in ["vmware"]:
            self.skipTest("This test case is written specifically\
                    for Vmware hypervisor")

        # Register a private template in the account with nic adapter vmxnet3
        template = Template.register(
            self.userapiclient,
            self.testdata["configurableData"]["vmxnet3template"],
            zoneid=self.zone.id,
            account=self.account.name,
            domainid=self.account.domainid,
            details=[{"nicAdapter": self.testdata["configurableData"]["vmxnet3template"]["nicadapter"]}]
        )
        self.cleanup.append(template)
        template.download(self.apiclient)

        templates = Template.list(
            self.userapiclient,
            listall=True,
            id=template.id,
            templatefilter="self")

        self.assertEqual(
            validateList(templates)[0],
            PASS,
            "Templates list validation failed")

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

        virtual_machine = VirtualMachine.create(
            self.apiclient,
            self.testdata["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id)

        isolated_network = Network.create(
            self.apiclient,
            self.testdata["isolated_network"],
            self.account.name,
            self.account.domainid,
            networkofferingid=self.isolated_network_offering.id)

        virtual_machine.add_nic(self.apiclient, isolated_network.id)

        # TODO: Add steps to check the Nic Adapter type in VCenter
        # using VCenter APIs
        return
    def registerTemplate(self, inProject=False):
        """Register and download template by default in the account/domain,
        in project if stated so"""

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

            template = Template.register(self.apiclient,
                                     self.services["template_2"],
                                     zoneid=self.zone.id,
                                     account=self.child_do_admin.name if not inProject else None,
                                     domainid=self.child_do_admin.domainid if not inProject else None,
                                     projectid=self.project.id if inProject else None)

            template.download(self.apiclient)

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

            self.templateSize = (templates[0].size / (1024**3))
        except Exception as e:
            return [FAIL, e]
        return [PASS, None]
    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
Exemple #4
0
    def test_es_1863_register_template_s3_domain_admin_user(self):
        """
        @Desc: Test whether cloudstack allows Domain admin or user
        to register a template using S3/Swift object store.
        @Steps:
        Step1: create a Domain and users in it.
        Step2: Register a template as Domain admin.
        Step3: Register a template as Domain user.
        Step4: Template should be registered successfully.
        """
        # Step1: create a Domain and users in it.
        self.newdomain = Domain.create(self.apiClient,
                                       self.services["domain"])

        # create account in the domain
        self.account_domain = Account.create(
            self.apiClient,
            self.services["account"],
            domainid=self.newdomain.id
        )
        self.cleanup.append(self.account_domain)
        self.cleanup.append(self.newdomain)
        # Getting authentication for user in newly created Account in domain
        self.domain_user = self.account_domain.user[0]
        self.domain_userapiclient = self.testClient.getUserApiClient(
            self.domain_user.username, self.newdomain.name
        )

        # Step2: Register a template as Domain admin.
        self.services["templateregister"]["ostype"] = self.services["ostype"]
        self.domain_template = Template.register(
            self.apiClient,
            self.services["templateregister"],
            zoneid=self.zone.id,
            account=self.account_domain.name,
            domainid=self.newdomain.id,
            hypervisor=self.hypervisor
        )
        # Wait for template to download
        self.domain_template.download(self.api_client)

        # Wait for template status to be changed across
        time.sleep(60)
        # Step3: Register a template as Domain user.
        self.domain_user_template = Template.register(
            self.domain_userapiclient,
            self.services["templateregister"],
            zoneid=self.zone.id,
            account=self.account_domain.name,
            domainid=self.newdomain.id,
            hypervisor=self.hypervisor
        )
        # Wait for template to download
        self.domain_user_template.download(self.api_client)

        # Wait for template status to be changed across
        time.sleep(60)

        # TODO: Step4: Template should be registered successfully.
        return
    def test_listtemplate(self):

        # Register template under one domain admin(root/domain1->account 1)

        template_register = Template.register(
            self.apiclient,
            self.testdata["privatetemplate"],
            zoneid=self.zone.id,
            hypervisor=self.hypervisor,
            account=self.account1.name,
            domainid=self.domain1.id)

        template_register.download(self.apiclient)

        self.download(self.apiclient, template_register.id)

        listtemplate = Template.list(
            self.apiclient,
            zoneid=self.zone.id,
            hypervisor=self.hypervisor,
            account=self.account2.name,
            domainid=self.account2.domainid,
            templatefilter="executable")

        self.assertEqual(
            listtemplate,
            None,
            "Check templates are not listed - CLOUDSTACK-10149"
        )
        return
    def test_01_create_template(self):
        """Test create public & private template
        """

        # Validate the following:
        # 1. database (vm_template table) should be updated
        #    with newly created template
        # 2. UI should show the newly added template
        # 3. ListTemplates API should show the newly added template

        #Create template from Virtual machine and Volume ID
        template = Template.create(
                                self.apiclient,
                                self.services["template"],
                                self.volume.id,
                                account=self.account.name,
                                domainid=self.account.domainid
                                )
        self.cleanup.append(template)

        self.debug("Created template with ID: %s" % template.id)

        list_template_response = Template.list(
                                    self.apiclient,
                                    templatefilter=\
                                    self.services["templatefilter"],
                                    id=template.id
                                    )

        self.assertEqual(
                            isinstance(list_template_response, list),
                            True,
                            "Check list response returns a valid list"
                        )
        #Verify template response to check whether template added successfully
        self.assertNotEqual(
                            len(list_template_response),
                            0,
                            "Check template available in List Templates"
                        )
        template_response = list_template_response[0]

        self.assertEqual(
                            template_response.displaytext,
                            self.services["template"]["displaytext"],
                            "Check display text of newly created template"
                        )
        name = template_response.name
        self.assertEqual(
                            name.count(self.services["template"]["name"]),
                            1,
                            "Check name of newly created template"
                        )
        self.assertEqual(
                            template_response.ostypeid,
                            self.services["template"]["ostypeid"],
                            "Check osTypeID of newly created template"
                        )
        return
Exemple #7
0
    def test_01_register_template(self, value):
        """Test register template
        # Validate the following:
        1. Create a root domain admin/ child domain admin account
        2. Register and download a template according to hypervisor type
        3. Verify that the template is listed
        4. Verify that the secondary storage count for the account equals the size
           of the template
        5. Delete the template
        6. Verify that the secondary storage resource count of the account equals 0
       """
        response = self.setupAccount(value)
        self.assertEqual(response[0], PASS, response[1])

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

        try:
            template = Template.register(self.apiclient,
                                     self.services["template_2"],
                                     zoneid=self.zone.id,
                                     account=self.account.name,
                                     domainid=self.account.domainid,
                                     hypervisor=self.hypervisor)

            template.download(self.apiclient)
        except Exception as e:
            self.fail("Failed to register template: %s" % e)

        templates = Template.list(self.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))
        expectedCount = templateSize
        response = matchResourceCount(
                        self.apiclient, expectedCount,
                        RESOURCE_SECONDARY_STORAGE,
                        accountid=self.account.id)
        self.assertEqual(response[0], PASS, response[1])

        try:
            template.delete(self.apiclient)
        except Exception as e:
            self.fail("Failed to delete template: %s" % e)

        expectedCount = 0
        response = matchResourceCount(
                        self.apiclient, expectedCount,
                        RESOURCE_SECONDARY_STORAGE,
                        accountid=self.account.id)
        self.assertEqual(response[0], PASS, response[1])
        return
Exemple #8
0
def get_builtin_template_info(apiclient, zoneid):
    """Returns hypervisor specific infor for templates"""

    list_template_response = Template.list(apiclient, templatefilter="featured", zoneid=zoneid)

    for b_template in list_template_response:
        if b_template.templatetype == "BUILTIN":
            break

    extract_response = Template.extract(apiclient, b_template.id, "HTTP_DOWNLOAD", zoneid)

    return extract_response.url, b_template.hypervisor, b_template.format
Exemple #9
0
    def test_03_delete_template(self):
        """Test Delete template
        """

        # Validate the following:
        # 1. Create a template and verify it is shown in list templates response
        # 2. Delete the created template and again verify list template response

        # Verify template response for updated attributes
        list_template_response = Template.list(
                                    self.apiclient,
                                    templatefilter=\
                                    self.services["template"]["templatefilter"],
                                    id=self.template.id,
                                    zoneid=self.zone.id)
        self.assertEqual(
                        isinstance(list_template_response, list),
                        True,
                        "Check for list template response return valid list"
                        )

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

        self.assertEqual(
                            template_response.id,
                            self.template.id,
                            "Template id %s in the list is not matching with created template id %s" %
                            (template_response.id, self.template.id)
                        )

        self.debug("Deleting template: %s" % self.template)
        # Delete the template
        self.template.delete(self.apiclient)
        self.debug("Delete template: %s successful" % self.template)

        list_template_response = Template.list(
                                    self.apiclient,
                                    templatefilter=\
                                    self.services["template"]["templatefilter"],
                                    id=self.template.id,
                                    zoneid=self.zone.id
                                    )
        self.assertEqual(
                            list_template_response,
                            None,
                            "Check template available in List Templates"
                        )
        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
    def setUpClass(cls):
        # We want to fail quicker if it's failure
        socket.setdefaulttimeout(60)

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

        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.hypervisor = cls.testClient.getHypervisorInfo()
        cls.template = Template.register(cls.api_client, cls.services["template"][cls.hypervisor.lower(
        )], cls.zone.id, hypervisor=cls.hypervisor.lower(), domainid=cls.domain.id)
        cls.template.download(cls.api_client)

        if cls.template == FAILED:
            assert False, "get_template() failed to return template"

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

        cls.service_offering = ServiceOffering.create(
            cls.api_client,
            cls.services["service_offering"])
        cls._cleanup = [cls.service_offering, cls.template]

        cls.logger = logging.getLogger('TestVPCRedundancy')
        cls.stream_handler = logging.StreamHandler()
        cls.logger.setLevel(logging.DEBUG)
        cls.logger.addHandler(cls.stream_handler)

        return
    def test_03_delete_template(self):
        """Test delete template
        """

        # Validate the following:
        # 1. UI should not show the deleted template
        # 2. database (vm_template table) should not contain deleted template

        self.debug("Deleting Template ID: %s" % self.template_1.id)

        self.template_1.delete(self.apiclient)

        list_template_response = Template.list(
                                    self.apiclient,
                                    templatefilter=\
                                    self.services["templatefilter"],
                                    id=self.template_1.id,
                                    account=self.account.name,
                                    domainid=self.account.domainid
                                    )
        # Verify template is deleted properly using ListTemplates
        self.assertEqual(
                         list_template_response,
                         None,
                         "Check if template exists in List Templates"
                         )
        return
    def test_08_list_system_templates(self):
        """Test System templates are not visible to normal user"""

        # Validate the following
        # 1. ListTemplates should not show 'SYSTEM' templates for normal user

        list_template_response = Template.list(
                                    self.apiclient,
                                    templatefilter='featured',
                                    account=self.user.name,
                                    domainid=self.user.domainid
                                    )
        self.assertEqual(
                            isinstance(list_template_response, list),
                            True,
                            "Check list response returns a valid list"
                        )

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

        for template in list_template_response:
            self.assertNotEqual(
                        template.templatetype,
                        'SYSTEM',
                        "ListTemplates should not list any system templates"
                        )
        return
    def test_01_check_template_size(self):
        """TS_BUG_009-Test the size of template created from root disk
        """


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

        #Create template from volume
        template = Template.create(
                                   self.apiclient,
                                   self.services["template"],
                                   self.volume.id,
                                   account=self.account.name,
                                   domainid=self.account.domainid
                                )
        self.debug("Creating template with ID: %s" % template.id)
        # Volume and Template Size should be same
        self.assertEqual(
                             template.size,
                             self.volume.size,
                             "Check if size of template and volume are same"
                             )
        return
    def test_02_deploy_vm_account_limit_reached(self):
        """Test Try to deploy VM with admin account where account has used
            the resources but @ domain they are available

        # Validate the following
        # 1. Try to register template with admin account where account has used the
        #    resources but @ domain they are available
        # 2. Template registration should fail"""

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

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

        expectedCount = self.templateSize
        response = matchResourceCount(
                        self.apiclient, expectedCount,
                        RESOURCE_SECONDARY_STORAGE,
                        accountid=self.child_do_admin.id)
        self.assertEqual(response[0], PASS, response[1])

        accountLimit = self.templateSize

        response = self.updateSecondaryStorageLimits(accountLimit=accountLimit)
        self.assertEqual(response[0], PASS, response[1])

        with self.assertRaises(Exception):
            template = Template.register(self.apiclient,
                                     self.services["template_2"],
                                     zoneid=self.zone.id,
                                     account=self.child_do_admin.name,
                                     domainid=self.child_do_admin.domainid)
        return
    def setUp(self):
        self.apiclient = self.testClient.getApiClient()
        self.hypervisor = self.testClient.getHypervisorInfo()
        self.dbclient = self.testClient.getDbConnection()
        self.services = Services().services
        self.services["virtual_machine"]["zoneid"] = self.zone.id
        self.account = Account.create(self.apiclient, self.services["account"], domainid=self.domain.id)

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

        # Register new template
        self.template = Template.register(
            self.apiclient,
            self.services["template"],
            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["template"]["format"], self.template.id)
        )
        try:
            self.template.download(self.apiclient)
        except Exception as e:
            raise Exception("Template download failed: %s" % e)

        self.cleanup = [self.account]
        return
    def test_07_list_public_templates(self):
        """Test only public templates are visible to normal user"""

        # Validate the following
        # 1. ListTemplates should show only 'public' templates for normal user

        list_template_response = Template.list(
                                    self.apiclient,
                                    templatefilter='featured',
                                    account=self.user.name,
                                    domainid=self.user.domainid
                                    )
        self.assertEqual(
                            isinstance(list_template_response, list),
                            True,
                            "Check list response returns a valid list"
                        )
        self.assertNotEqual(
                            len(list_template_response),
                            0,
                            "Check template available in List Templates"
                        )
        #Template response should list all 'public' templates
        for template in list_template_response:
            self.assertEqual(
                            template.ispublic,
                            True,
                            "ListTemplates should list only public templates"
                        )
        return
    def setUpClass(cls):
        cls.logger = logging.getLogger('TestVPCSite2SiteVPN')
        cls.stream_handler = logging.StreamHandler()
        cls.logger.setLevel(logging.DEBUG)
        cls.logger.addHandler(cls.stream_handler)

        testClient = super(TestVpcSite2SiteVpn, cls).getClsTestClient()
        cls.apiclient = testClient.getApiClient()
        cls.services = Services().services

        cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
        cls.domain = get_domain(cls.apiclient)
        cls.service_offering = ServiceOffering.create(
            cls.apiclient,
            cls.services["compute_offering"]
        )

        cls.account = Account.create(
            cls.apiclient, services=cls.services["account"])
        cls.hypervisor = cls.services["default_hypervisor"]
        cls.logger.debug("Downloading Template: %s from: %s" % (cls.services["template"][
                         cls.hypervisor]["name"], cls.services["template"][cls.hypervisor]["url"]))
        cls.template = Template.register(cls.apiclient, cls.services["template"][
                                         cls.hypervisor], cls.zone.id, hypervisor=cls.hypervisor, account=cls.account.name, domainid=cls.domain.id)
        cls.template.download(cls.apiclient)

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

        cls.services["virtual_machine"][
            "hypervisor"] = cls.services["default_hypervisor"]
        cls.cleanup = [cls.account]
    def setUpClass(cls):
        testClient = super(TestSnapshotRootDisk, 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.hypervisorNotSupported = False
        cls.hypervisor = cls.testClient.getHypervisorInfo()
        if cls.hypervisor.lower() in ['hyperv', 'lxc'] or 'kvm-centos6' in cls.testClient.getZoneForTests():
            cls.hypervisorNotSupported = True

        cls._cleanup = []
        if not cls.hypervisorNotSupported:
            macchinina = Templates().templates["macchinina"]
            cls.template = Template.register(cls.apiclient, macchinina[cls.hypervisor.lower()],
                        cls.zone.id, hypervisor=cls.hypervisor.lower(), domainid=cls.domain.id)
            cls.template.download(cls.apiclient)

            if cls.template == FAILED:
                assert False, "get_template() failed to return template"


            cls.services["domainid"] = cls.domain.id
            cls.services["small"]["zoneid"] = cls.zone.id
            cls.services["templates"]["ostypeid"] = cls.template.ostypeid
            cls.services["zoneid"] = cls.zone.id

            # Create VMs, NAT Rules 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 = cls.virtual_machine_with_disk = \
                VirtualMachine.create(
                    cls.apiclient,
                    cls.services["small"],
                    templateid=cls.template.id,
                    accountid=cls.account.name,
                    domainid=cls.account.domainid,
                    zoneid=cls.zone.id,
                    serviceofferingid=cls.service_offering.id,
                    mode=cls.services["mode"]
                )

            cls._cleanup.append(cls.virtual_machine)
            cls._cleanup.append(cls.service_offering)
            cls._cleanup.append(cls.account)
            cls._cleanup.append(cls.template)
        return
    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
    def test_03_concurrent_snapshots_create_template(self):
        """Test while parent concurrent snapshot job in progress,create
            template from completed snapshot

            1.Configure the concurrent.snapshots.threshold.perhost=3
            2.Deploy a Linux VM using default CentOS template, use small
            service offering, disk offering
            3.Perform snapshot on root disk of this newly created VMs(10 vms)
            4.while parent concurrent snapshot job in progress,create template
            from completed snapshot"""

        # Validate the following
        # a.Able to create Template from snapshots
        # b.check all snapshots jobs are running concurrently on back grounds
        # c.listSnapshots should list this newly created snapshot.

        self.debug("Create virtual machine and snapshot on ROOT disk")
        self.create_Snapshot_VM()

        self.debug("Verify whether snapshots were created properly or not?")
        self.verify_Snapshots()

        self.debug("Fetch the list of snapshots belong to account: %s" %
                                                    self.account.name)
        snapshots = self.get_Snapshots_For_Account(
                                                self.account.name,
                                                self.account.domainid)
        jobs = []
        for snapshot in snapshots:
            self.debug("Create a template from snapshot: %s" % snapshot.name)
            jobs.append(self.create_Template_from_Snapshot(snapshot))


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

        # Verify IO usage by submitting the concurrent jobs
        self.testClient.submitCmdsAndWait(jobs, apiclient=userapiclient)

        self.debug("Verifying if templates are created properly or not?")
        templates = Template.list(
                            self.apiclient,
                            templatefilter=self.services["template"]["templatefilter"],
                            account=self.account.name,
                            domainid=self.account.domainid,
                            listall=True)
        self.assertNotEqual(templates,
                            None,
                            "Check if result exists in list item call")
        for template in templates:
            self.assertEqual(template.isready,
                         True,
                        "Check new template state in list templates call")

        self.debug("Test completed successfully.")
        return
Exemple #22
0
    def test_es_47_list_os_types_win_2012(self):
        """
        @Desc: Test VM creation while "apply.allocation.algorithm.to.pods"
        is set to true
        @Reference: https://issues.apache.org/jira/browse/CLOUDSTACK-4947
        @Steps:
        Step1: register windows 2012 VM template as windows 8 template
        Step2: deploy a VM with windows2012 template and  Verify
        that VM creation is successful

         """

        if not is_config_suitable(apiclient=self.apiClient,
                                  name='apply.allocation.algorithm.to.pods',
                                  value='true'):
            self.skipTest('apply.allocation.algorithm.to.pods '
                          'should be true. skipping')

        # register windows 2012 VM template as windows 8 template
        self.hypervisor = self.testClient.getHypervisorInfo()
        if self.hypervisor.lower() in ['lxc']:
            self.skipTest(
                "windows VM is not supported on %s" %
                self.hypervisor.lower())
        self.win2012_template = Template.register(
            self.apiClient,
            self.services["win2012template"],
            zoneid=self.zone.id,
            account=self.account.name,
            domainid=self.domain.id,
            hypervisor=self.hypervisor
        )
        # Wait for template to download
        self.win2012_template.download(self.apiClient)
        self.cleanup.append(self.win2012_template)
        # Wait for template status to be changed across
        time.sleep(60)
        # Deploy
        self.debug("Deploying win 2012 VM in account: %s" % self.account.name)
        self.services["virtual_machine"]["displayname"] = "win2012"
        self.services["virtual_machine"]["zoneid"] = self.zone.id
        self.services["virtual_machine"]["template"] = self.win2012_template.id
        vm1 = VirtualMachine.create(
            self.apiClient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id
        )
        self.cleanup.append(vm1)
        # Verify VM state
        self.assertEqual(
            vm1.state,
            'Running',
            "Check VM state is Running or not"
        )
        return
Exemple #23
0
    def setUpClass(cls):

        cls.logger = logging.getLogger("TestVPCRemoteAccessVPN")
        cls.stream_handler = logging.StreamHandler()
        cls.logger.setLevel(logging.DEBUG)
        cls.logger.addHandler(cls.stream_handler)
        cls.startTime = time.time()

        testClient = super(TestVpcRemoteAccessVpn, cls).getClsTestClient()
        cls.apiclient = testClient.getApiClient()
        cls.services = Services().services

        cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
        cls.domain = get_domain(cls.apiclient)
        cls.compute_offering = ServiceOffering.create(cls.apiclient, cls.services["compute_offering"])
        cls.account = Account.create(cls.apiclient, services=cls.services["account"])

        if cls.services["default_hypervisor"] == "kvm":
            cls.template = Template.register(
                cls.apiclient,
                cls.services["template_kvm"],
                cls.zone.id,
                hypervisor=cls.services["template_kvm"]["hypervisor"],
                account=cls.account.name,
                domainid=cls.domain.id,
            )
        else:
            cls.template = Template.register(
                cls.apiclient,
                cls.services["template_xen"],
                cls.zone.id,
                hypervisor=cls.services["template_xen"]["hypervisor"],
                account=cls.account.name,
                domainid=cls.domain.id,
            )

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

        cls.services["virtual_machine"]["hypervisor"] = cls.services["default_hypervisor"]
        cls.cleanup = [cls.account]
    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
    def test_02_list_templates_with_templatefilter_all_domain_admin(self):
        """
            Test list templates with templatefilter=all is not permitted for domain admin
        """

        domain_user_api_client = self.testClient.getUserApiClient(
                                    UserName=self.newdomain_account.name,
                                    DomainName=self.newdomain_account.domain)
        try:
            list_template_response = Template.list(domain_user_api_client, templatefilter='all')
        except Exception as e:
            self.fail("Domain admin should be able to use templatefilter='all' in listTemplates API call")
    def test_listtemplate(self):

        # Register template under one domain admin(root/domain1->account 1)

        template_register = Template.register(
            self.apiclient,
            self.testdata["privatetemplate"],
            zoneid=self.zone.id,
            hypervisor=self.hypervisor,
            account=self.account1.name,
            domainid=self.domain1.id,
        )

        template_register.download(self.apiclient)
        # self.cleanup.append(self.template_register)

        time.sleep(self.testdata["sleep"])
        timeout = self.testdata["timeout"]
        while True:
            listTemplateResponse = Template.list(
                self.apiclient,
                templatefilter="all",
                id=template_register.id,
                account=self.account1.name,
                domainid=self.domain1.id,
            )
            status = validateList(listTemplateResponse)
            self.assertEquals(PASS, status[0], "Template creation failed")

        listtemplate = Template.list(
            self.apiclient,
            zoneid=self.zone.id,
            hypervisor=self.hypervisor,
            account=self.account2.name,
            domainid=self.account2.domainid,
            templatefilter=self.testdata["templatefilter"],
        )

        self.assertEqual(listtemplate, None, "Check templates are not listed")
        return
    def test_01_list_templates_with_templatefilter_all_normal_user(self):
        """
            Test list templates with templatefilter=all is not permitted for normal user
        """

        user_api_client = self.testClient.getUserApiClient(
                                    UserName=self.account.name,
                                    DomainName=self.account.domain)
        try:
            list_template_response = Template.list(self.user_api_client, templatefilter='all')
            self.fail("Regular User is able to use templatefilter='all' in listTemplates API call")
        except Exception as e:
            self.debug("ListTemplates API with templatefilter='all' is not permitted for normal user")
    def test_05_template_permissions(self):
        """Update & Test for template permissions"""

        # Validate the following
        # 1. listTemplatePermissions returns valid
        #    permissions set for template
        # 2. permission changes should be reflected in vm_template
        #    table in database

        self.debug("Updating Template permissions ID:%s" % self.template_2.id)

        cmd = updateTemplatePermissions.updateTemplatePermissionsCmd()
        # Update template permissions
        cmd.id = self.template_2.id
        cmd.isfeatured = self.services["isfeatured"]
        cmd.ispublic = self.services["ispublic"]
        cmd.isextractable = self.services["isextractable"]
        self.apiclient.updateTemplatePermissions(cmd)

        list_template_response = Template.list(
                                    self.apiclient,
                                    templatefilter='featured',
                                    id=self.template_2.id,
                                    account=self.account.name,
                                    domainid=self.account.domainid
                                    )
        self.assertEqual(
                            isinstance(list_template_response, list),
                            True,
                            "Check list response returns a valid list"
                        )
        # Verify template response for updated permissions for normal user
        template_response = list_template_response[0]

        self.assertEqual(
                            template_response.id,
                            self.template_2.id,
                            "Check template ID"
                        )
        self.assertEqual(
                            template_response.ispublic,
                            int(True),
                            "Check ispublic permission of template"
                        )

        self.assertNotEqual(
                        template_response.templatetype,
                        'SYSTEM',
                        "ListTemplates should not list any system templates"
                        )
        return
    def test_01_positive_tests_vm_deploy_shared_nw(self):
        """ Positive tests for VMLC test path - Advanced Zone in Shared Network

        # 1.  List created service offering in setUpClass by name
        # 2.  List registered template with name
        # 3.  Create VM in account
        """

        # List created service offering in setUpClass by name
        listServiceOfferings = ServiceOffering.list(
            self.apiclient,
            name=self.service_offering_1.name,
            listall=True
        )
        self.assertEqual(validateList(listServiceOfferings)[0], PASS,
                         "List validation failed for service offerings list")

        self.assertEqual(listServiceOfferings[0].name,
                         self.service_offering_1.name,
                         "Names of created service offering\
                         and listed service offering not matching")

        # List registered template with name
        listTemplates = Template.list(
            self.userapiclient,
            templatefilter="self",
            name=self.template.name,
            listall=True,
            zone=self.zone.id)
        self.assertEqual(validateList(listTemplates)[0], PASS,
                         "List validation failed for templates list")

        self.assertEqual(listTemplates[0].name, self.template.name,
                         "Names of created template and listed template\
                         not matching")

        network = CreateNetwork(self, SHARED_NETWORK)

        # Create VM in account
        self.virtual_machine = VirtualMachine.create(
            self.userapiclient,
            self.testdata["small"],
            templateid=self.template.id,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering_1.id,
            networkids=[network.id, ],
            zoneid=self.zone.id
        )
        self.cleanup.append(self.virtual_machine)
        return
Exemple #30
0
    def setUpClass(cls):

        cls.logger = logging.getLogger('TestInternalLb')
        cls.stream_handler = logging.StreamHandler()
        cls.logger.setLevel(logging.DEBUG)
        cls.logger.addHandler(cls.stream_handler)

        testClient = super(TestInternalLb, cls).getClsTestClient()
        cls.apiclient = testClient.getApiClient()
        cls.services = Services().services

        cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
        cls.domain = get_domain(cls.apiclient)
        cls.compute_offering = ServiceOffering.create(
            cls.apiclient,
            cls.services["compute_offering"]
        )

        cls.account = Account.create(
            cls.apiclient, services=cls.services["account"])

        if cls.services["default_hypervisor"] == "kvm":
            cls.template = Template.register(cls.apiclient, cls.services["template_kvm"], cls.zone.id, hypervisor=cls.services[
                                             "template_kvm"]["hypervisor"], account=cls.account.name, domainid=cls.domain.id)
        else:
            cls.template = Template.register(cls.apiclient, cls.services["template_xen"], cls.zone.id, hypervisor=cls.services[
                                             "template_xen"]["hypervisor"], account=cls.account.name, domainid=cls.domain.id)

        if cls.template == FAILED:
            assert False, "get_template() failed to return template"

        cls.logger.debug("Successfully created account: %s, id: \
                   %s" % (cls.account.name,
                          cls.account.id))

        cls.cleanup = [cls.account]
        return
    def test_02_check_size_snapshotTemplate(self):
        """TS_BUG_010-Test check size of snapshot and template
        """


        # Validate the following
        # 1. Deploy VM using default template, small service offering
        #    and small data disk offering.
        # 2. Perform snapshot on the root disk of this VM.
        # 3. Create a template from snapshot.
        # 4. Check the size of snapshot and template

        # Create a snapshot from the ROOTDISK
        if self.hypervisor.lower() in ['hyperv']:
            self.skipTest("Snapshots feature is not supported on Hyper-V")
        snapshot = Snapshot.create(
                                   self.apiclient,
                                   self.volume.id,
                                   account=self.account.name,
                                   domainid=self.account.domainid
                                   )

        response = snapshot.validateState(self.apiclient, Snapshot.BACKED_UP)
        self.assertEqual(response[0], PASS, response[1])

        # Generate template from the snapshot
        template = Template.create_from_snapshot(
                                    self.apiclient,
                                    snapshot,
                                    self.services["template"]
                                    )
        self.cleanup.append(template)

        self.debug("Created template from snapshot with ID: %s" % template.id)
        templates = Template.list(
                                self.apiclient,
                                templatefilter=\
                                self.services["template"]["templatefilter"],
                                id=template.id
                                )
        self.assertEqual(
                            isinstance(templates, list),
                            True,
                            "Check list response returns a valid list"
                        )
        self.assertNotEqual(
                            templates,
                            None,
                            "Check if result exists in list item call"
                            )

        self.assertEqual(
                            templates[0].isready,
                            True,
                            "Check new template state in list templates call"
                        )
        # check size of template with that of snapshot
        self.assertEqual(
                            templates[0].size,
                            self.volume.size,
                            "Derived template size (%s) does not match snapshot size (%s)" % (templates[0].size, self.volume.size)
                        )
        return
    def setUpClass(cls):
        testClient = super(TestXDCCPInterop, cls).getClsTestClient()
        cls.apiclient = testClient.getApiClient()
        cls.services = testClient.getParsedTestDataConfig()
        cls.hypervisor = cls.testClient.getHypervisorInfo()
        # 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

        hosts = list_hosts(cls.apiclient, type="Routing")

        if hosts is None:
            raise unittest.SkipTest(
                "There are no hypervisor's available.Check list hosts response"
            )
        for hypervisorhost in hosts:
            if hypervisorhost.hypervisor == "XenServer":
                cls.uploadtemplateformat = "VHD"
                break
            elif hypervisorhost.hypervisor == "VMware":
                cls.uploadtemplateformat = "OVA"
                break
            elif hypervisorhost.hypervisor == "KVM":
                cls.uploadtemplateformat = "KVM"
            break

        if cls.uploadtemplateformat == "KVM":
            raise unittest.SkipTest("Interop is not supported on KVM")

        cls.uploadurl = cls.services["interop"][
            cls.uploadtemplateformat]["url"]

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

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

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

        cls.template = get_windows_template(cls.apiclient,
                                            cls.zone.id,
                                            ostype_desc="Windows 8 (64-bit)")
        #cls.template = get_windows_template(cls.apiclient, cls.zone.id ,ostype_desc="Windows Server 2012 (64-bit)")

        if cls.template == FAILED:
            if "http://pleaseupdateURL/" in cls.uploadurl:
                raise unittest.SkipTest(
                    "Check Test Data file if it has the valid template URL")
            cls.template = Template.register(
                cls.apiclient,
                cls.services["interop"][cls.uploadtemplateformat],
                zoneid=cls.zone.id,
                domainid=cls.account.domainid,
                account=cls.account.name)
            timeout = cls.services["vgpu"]["timeout"]

            while True:
                time.sleep(cls.services["vgpu"]["sleep"])
                list_template_response = Template.list(
                    cls.apiclient,
                    templatefilter=cls.services["templatefilter"],
                    id=cls.template.id)
                if (isinstance(list_template_response, list)) is not True:
                    raise unittest.SkipTest(
                        "Check list template api response returns a valid list"
                    )

                if len(list_template_response) is None:
                    raise unittest.SkipTest(
                        "Check template registered is in List Templates")

                template_response = list_template_response[0]
                if template_response.isready:
                    break

                if timeout == 0:
                    raise unittest.SkipTest(
                        "Failed to download template(ID: %s). " %
                        template_response.id)

                timeout = timeout - 1
        cls.volume = []

        # Set Zones and disk offerings
        cls.services["small"]["zoneid"] = cls.zone.id
        cls.services["small"]["template"] = cls.template.id

        user_data = ''.join(
            random.choice(string.ascii_uppercase + string.digits)
            for x in range(2500))
        cls.services["virtual_machine"]["userdata"] = user_data

        #        cls.services["large"]["zoneid"] = cls.zone.id
        #        cls.services["large"]["template"] = cls.template.id

        cls.virtual_machine = VirtualMachine.create(
            cls.apiclient,
            cls.services["small"],
            accountid=cls.account.name,
            domainid=cls.account.domainid,
            serviceofferingid=cls.service_offering.id,
            mode=cls.services['mode'],
            startvm="false")
        cls.user_api_client = cls.testClient.getUserApiClient(
            UserName=cls.account.name, DomainName=cls.account.domain)

        cls.cleanup = [cls.service_offering, cls.account]
    def test_19_template_tag(self):
        """ Test creation, listing and deletion tag on templates
        """

        if self.hypervisor.lower() in ['lxc']:
            self.skipTest(
                "template creation from volume feature is not supported on %s"
                % self.hypervisor.lower())

        try:

            noffering = NetworkOffering.list(
                self.user_api_client,
                name="DefaultIsolatedNetworkOfferingWithSourceNatService")
            vm4network = Network.create(self.user_api_client,
                                        self.services["network"],
                                        accountid=self.account.name,
                                        domainid=self.account.domainid,
                                        networkofferingid=noffering[0].id,
                                        zoneid=self.zone.id)

            list_nw_response = Network.list(self.user_api_client,
                                            id=vm4network.id)
            self.assertEqual(
                isinstance(list_nw_response, list), True,
                "Check list response returns a valid networks list")

            vm_1 = VirtualMachine.create(
                self.user_api_client,
                self.services["small"],
                templateid=self.template.id,
                networkids=vm4network.id,
                serviceofferingid=self.service_offering.id,
                accountid=self.account.name,
                domainid=self.account.domainid,
                mode=self.services['mode'],
                startvm="true")
            time.sleep(600)
            self.debug("Stopping the virtual machine: %s" % vm_1.name)
            # Stop virtual machine
            vm_1.stop(self.user_api_client)
        except Exception as e:
            self.fail("Failed to stop VM: %s" % e)

        timeout = self.services["timeout"]
        while True:
            list_volume = Volume.list(self.user_api_client,
                                      virtualmachineid=vm_1.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

        self.volume = list_volume[0]

        self.debug("Creating template from ROOT disk of virtual machine: %s" %
                   vm_1.name)
        # Create template from volume
        template = Template.create(self.user_api_client,
                                   self.services["template"], self.volume.id)
        self.cleanup.append(template)
        self.debug("Created the template(%s). Now restarting the userVm: %s" %
                   (template.name, vm_1.name))
        vm_1.start(self.user_api_client)

        self.debug("Creating a tag for the template")
        tag = Tag.create(self.user_api_client,
                         resourceIds=template.id,
                         resourceType='Template',
                         tags={'OS': 'windows8'})
        self.debug("Tag created: %s" % tag.__dict__)

        tags = Tag.list(self.user_api_client,
                        listall=True,
                        resourceType='Template',
                        key='OS',
                        value='windows8')
        self.assertEqual(isinstance(tags, list), True,
                         "List tags should not return empty response")
        self.assertEqual(tags[0].value, 'windows8',
                         'The tag should have original value')

        Template.list(
            self.user_api_client,
            templatefilter=self.services["template"]["templatefilter"],
            listall=True,
            key='OS',
            value='windows8')

        self.debug("Deleting the created tag..")
        try:
            tag.delete(self.user_api_client,
                       resourceIds=template.id,
                       resourceType='Template',
                       tags={'OS': 'windows8'})
        except Exception as e:
            self.fail("Failed to delete the tag - %s" % e)

        self.debug("Verifying if tag is actually deleted!")
        tags = Tag.list(self.user_api_client,
                        listall=True,
                        resourceType='Template',
                        key='OS',
                        value='windows8')
        self.assertEqual(tags, None, "List tags should return empty response")
        return
Exemple #34
0
    def test_02_host_maintenance_mode_with_activities(self):
        """Test host maintenance mode with activities
        """

        # Validate the following
        # 1. Create Vms. Acquire IP. Create port forwarding & load balancing
        #    rules for Vms.
        # 2. While activities are ongoing: Create snapshots, recurring
        #    snapshots, create templates, download volumes, Host 1: put to
        #    maintenance mode. All Vms should failover to Host 2 in cluster
        #    Vms should be in running state. All port forwarding rules and
        #    load balancing Rules should work.
        # 3. After failover to Host 2 succeeds, deploy Vms. Deploy Vms on host
        #    2 should succeed. All ongoing activities in step 3 should succeed
        # 4. Host 1: cancel maintenance mode.
        # 5. While activities are ongoing: Create snapshots, recurring
        #    snapshots, create templates, download volumes, Host 2: put to
        #    maintenance mode. All Vms should failover to Host 1 in cluster.
        # 6. After failover to Host 1 succeeds, deploy VMs. Deploy Vms on
        #    host 1 should succeed. All ongoing activities in step 6 should
        #    succeed.

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

        self.debug("Checking HA with hosts: %s, %s" % (
            hosts[0].name,
            hosts[1].name
        ))
        self.debug("Deploying VM in account: %s" % self.account.name)
        # Spawn an instance in that network
        virtual_machine = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id
        )
        vms = VirtualMachine.list(
            self.apiclient,
            id=virtual_machine.id,
            listall=True
        )
        self.assertEqual(
            isinstance(vms, list),
            True,
            "List VMs should return valid response for deployed VM"
        )
        self.assertNotEqual(
            len(vms),
            0,
            "List VMs should return valid response for deployed VM"
        )
        vm = vms[0]
        self.debug("Deployed VM on host: %s" % vm.hostid)
        self.assertEqual(
            vm.state,
            "Running",
            "Deployed VM should be in RUnning state"
        )
        networks = Network.list(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
            listall=True
        )
        self.assertEqual(
            isinstance(networks, list),
            True,
            "List networks should return valid list for the account"
        )
        network = networks[0]

        self.debug("Associating public IP for account: %s" %
                   self.account.name)
        public_ip = PublicIPAddress.create(
            self.apiclient,
            accountid=self.account.name,
            zoneid=self.zone.id,
            domainid=self.account.domainid,
            networkid=network.id
        )

        self.debug("Associated %s with network %s" % (
            public_ip.ipaddress.ipaddress,
            network.id
        ))
        self.debug("Creating PF rule for IP address: %s" %
                   public_ip.ipaddress.ipaddress)
        NATRule.create(
            self.apiclient,
            virtual_machine,
            self.services["natrule"],
            ipaddressid=public_ip.ipaddress.id
        )

        self.debug("Creating LB rule on IP with NAT: %s" %
                   public_ip.ipaddress.ipaddress)

        # Create Load Balancer rule on IP already having NAT rule
        lb_rule = LoadBalancerRule.create(
            self.apiclient,
            self.services["lbrule"],
            ipaddressid=public_ip.ipaddress.id,
            accountid=self.account.name
        )
        self.debug("Created LB rule with ID: %s" % lb_rule.id)

        # Should be able to SSH VM
        try:
            self.debug("SSH into VM: %s" % virtual_machine.id)
            virtual_machine.get_ssh_client(
                ipaddress=public_ip.ipaddress.ipaddress)
        except Exception as e:
            self.fail("SSH Access failed for %s: %s" %
                      (virtual_machine.ipaddress, e)
                      )
        # Get the Root disk of VM
        volumes = list_volumes(
            self.apiclient,
            virtualmachineid=virtual_machine.id,
            type='ROOT',
            listall=True
        )
        volume = volumes[0]
        self.debug(
            "Root volume of VM(%s): %s" % (
                virtual_machine.name,
                volume.name
            ))
        # Create a snapshot from the ROOTDISK
        self.debug("Creating snapshot on ROOT volume: %s" % volume.name)
        snapshot = Snapshot.create(self.apiclient, volumes[0].id)
        self.debug("Snapshot created: ID - %s" % snapshot.id)

        snapshots = list_snapshots(
            self.apiclient,
            id=snapshot.id,
            listall=True
        )
        self.assertEqual(
            isinstance(snapshots, list),
            True,
            "Check list response returns a valid list"
        )
        self.assertNotEqual(
            snapshots,
            None,
            "Check if result exists in list snapshots call"
        )
        self.assertEqual(
            snapshots[0].id,
            snapshot.id,
            "Check snapshot id in list resources call"
        )

        # Generate template from the snapshot
        self.debug("Generating template from snapshot: %s" % snapshot.name)
        template = Template.create_from_snapshot(
            self.apiclient,
            snapshot,
            self.services["templates"]
        )
        self.debug("Created template from snapshot: %s" % template.id)

        templates = list_templates(
            self.apiclient,
            templatefilter=self.services["templates"]["templatefilter"],
            id=template.id
        )

        self.assertEqual(
            isinstance(templates, list),
            True,
            "List template call should return the newly created template"
        )

        self.assertEqual(
            templates[0].isready,
            True,
            "The newly created template should be in ready state"
        )

        first_host = vm.hostid
        self.debug("Enabling maintenance mode for host %s" % vm.hostid)
        cmd = prepareHostForMaintenance.prepareHostForMaintenanceCmd()
        cmd.id = first_host
        self.apiclient.prepareHostForMaintenance(cmd)

        self.debug("Waiting for SSVMs to come up")
        wait_for_ssvms(
            self.apiclient,
            zoneid=self.zone.id,
            podid=self.pod.id,
        )

        timeout = self.services["timeout"]
        # Poll and check state of VM while it migrates from one host to another
        while True:
            vms = VirtualMachine.list(
                self.apiclient,
                id=virtual_machine.id,
                listall=True
            )
            self.assertEqual(
                isinstance(vms, list),
                True,
                "List VMs should return valid response for deployed VM"
            )
            self.assertNotEqual(
                len(vms),
                0,
                "List VMs should return valid response for deployed VM"
            )
            vm = vms[0]

            self.debug("VM 1 state: %s" % vm.state)
            if vm.state in ["Stopping",
                            "Stopped",
                            "Running",
                            "Starting",
                            "Migrating"]:
                if vm.state == "Running":
                    break
                else:
                    time.sleep(self.services["sleep"])
                    timeout = timeout - 1
            else:
                self.fail(
                    "VM migration from one-host-to-other failed\
                            while enabling maintenance"
                )
        second_host = vm.hostid
        self.assertEqual(
            vm.state,
            "Running",
            "VM should be in Running state after enabling host maintenance"
        )
        # Should be able to SSH VM
        try:
            self.debug("SSH into VM: %s" % virtual_machine.id)
            virtual_machine.get_ssh_client(
                ipaddress=public_ip.ipaddress.ipaddress)
        except Exception as e:
            self.fail("SSH Access failed for %s: %s" %
                      (virtual_machine.ipaddress, e)
                      )
        self.debug("Deploying VM in account: %s" % self.account.name)
        # Spawn an instance on other host
        virtual_machine_2 = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id
        )
        vms = VirtualMachine.list(
            self.apiclient,
            id=virtual_machine_2.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)
        self.debug("VM 2 state: %s" % vm.state)
        self.assertEqual(
            vm.state,
            "Running",
            "Deployed VM should be in Running state"
        )

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

        # Get the Root disk of VM
        volumes = list_volumes(
            self.apiclient,
            virtualmachineid=virtual_machine_2.id,
            type='ROOT',
            listall=True
        )
        volume = volumes[0]
        self.debug(
            "Root volume of VM(%s): %s" % (
                virtual_machine_2.name,
                volume.name
            ))
        # Create a snapshot from the ROOTDISK
        self.debug("Creating snapshot on ROOT volume: %s" % volume.name)
        snapshot = Snapshot.create(self.apiclient, volumes[0].id)
        self.debug("Snapshot created: ID - %s" % snapshot.id)

        snapshots = list_snapshots(
            self.apiclient,
            id=snapshot.id,
            listall=True
        )
        self.assertEqual(
            isinstance(snapshots, list),
            True,
            "Check list response returns a valid list"
        )
        self.assertNotEqual(
            snapshots,
            None,
            "Check if result exists in list snapshots call"
        )
        self.assertEqual(
            snapshots[0].id,
            snapshot.id,
            "Check snapshot id in list resources call"
        )

        # Generate template from the snapshot
        self.debug("Generating template from snapshot: %s" % snapshot.name)
        template = Template.create_from_snapshot(
            self.apiclient,
            snapshot,
            self.services["templates"]
        )
        self.debug("Created template from snapshot: %s" % template.id)

        templates = list_templates(
            self.apiclient,
            templatefilter=self.services["templates"]["templatefilter"],
            id=template.id
        )

        self.assertEqual(
            isinstance(templates, list),
            True,
            "List template call should return the newly created template"
        )

        self.assertEqual(
            templates[0].isready,
            True,
            "The newly created template should be in ready state"
        )

        self.debug("Enabling maintenance mode for host %s" % second_host)
        cmd = prepareHostForMaintenance.prepareHostForMaintenanceCmd()
        cmd.id = second_host
        self.apiclient.prepareHostForMaintenance(cmd)
        self.debug("Maintenance mode enabled for host: %s" % second_host)

        self.debug("Waiting for SSVMs to come up")
        wait_for_ssvms(
            self.apiclient,
            zoneid=self.zone.id,
            podid=self.pod.id,
        )

        # Poll and check the status of VMs
        timeout = self.services["timeout"]
        while True:
            vms = VirtualMachine.list(
                self.apiclient,
                account=self.account.name,
                domainid=self.account.domainid,
                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(
                "VM state after enabling maintenance on first host: %s" %
                vm.state)
            if vm.state in ["Stopping",
                            "Stopped",
                            "Running",
                            "Starting",
                            "Migrating"]:
                if vm.state == "Running":
                    break
                else:
                    time.sleep(self.services["sleep"])
                    timeout = timeout - 1
            else:
                self.fail(
                    "VM migration from one-host-to-other failed\
                            while enabling maintenance"
                )

        # Poll and check the status of VMs
        timeout = self.services["timeout"]
        while True:
            vms = VirtualMachine.list(
                self.apiclient,
                account=self.account.name,
                domainid=self.account.domainid,
                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[1]
            self.debug(
                "VM state after enabling maintenance on first host: %s" %
                vm.state)
            if vm.state in ["Stopping",
                            "Stopped",
                            "Running",
                            "Starting",
                            "Migrating"]:
                if vm.state == "Running":
                    break
                else:
                    time.sleep(self.services["sleep"])
                    timeout = timeout - 1
            else:
                self.fail(
                    "VM migration from one-host-to-other failed\
                            while enabling maintenance"
                )

        for vm in vms:
            self.debug(
                "VM states after enabling maintenance mode on host: %s - %s" %
                (first_host, vm.state))
            self.assertEqual(
                vm.state,
                "Running",
                "Deployed VM should be in Running state"
            )

        # Spawn an instance on other host
        virtual_machine_3 = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id
        )
        vms = VirtualMachine.list(
            self.apiclient,
            id=virtual_machine_3.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)
        self.debug("VM 3 state: %s" % vm.state)
        self.assertEqual(
            vm.state,
            "Running",
            "Deployed VM should be in Running state"
        )

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

        self.debug("Waiting for SSVMs to come up")
        wait_for_ssvms(
            self.apiclient,
            zoneid=self.zone.id,
            podid=self.pod.id,
        )
        return
Exemple #35
0
    def test_04_copy_template(self):
        """
        @Desc: Test to copy Template from one zone to another
        @steps:
        Step1: Listing Zones available for a user
        Step2: Verifying if the zones listed are greater than 1.
               If Yes continuing.
               If not halting the test.
        Step3: Listing all the templates for a user in zone1
        Step4: Verifying that no templates are listed
        Step5: Listing all the templates for a user in zone2
        Step6: Verifying that no templates are listed
        Step7: Creating a Template in zone 1
        Step8: Listing all the Templates again for a user in zone1
        Step9: Verifying that list size is 1
        Step10: Listing all the templates for a user in zone2
        Step11: Verifying that no templates are listed
        Step12: Copying the template created in step7 from zone1 to zone2
        Step13: Listing all the templates for a user in zone2
        Step14: Verifying that list size is 1
        Step15: Listing all the Templates for a user in zone1
        Step16: Verifying that list size is 1
        """
        # Listing Zones available for a user
        zones_list = Zone.list(
            self.userapiclient,
            available=True
        )
        status = validateList(zones_list)
        self.assertEquals(
            PASS,
            status[0],
            "Failed to list Zones"
        )
        if not len(zones_list) > 1:
            raise unittest.SkipTest("Not enough zones exist to copy template")
        else:
            # Listing all the Templates for a User in Zone 1
            list_templates_zone1 = Template.list(
                self.userapiclient,
                listall=self.services["listall"],
                templatefilter=self.services["templatefilter"],
                zoneid=zones_list[0].id
            )
            # Verifying that no Templates are listed
            self.assertIsNone(
                list_templates_zone1,
                "Templates listed for newly created User in Zone1"
            )
            # Listing all the Templates for a User in Zone 2
            list_templates_zone2 = Template.list(
                self.userapiclient,
                listall=self.services["listall"],
                templatefilter=self.services["templatefilter"],
                zoneid=zones_list[1].id
            )
            # Verifying that no Templates are listed
            self.assertIsNone(
                list_templates_zone2,
                "Templates listed for newly created User in Zone2"
            )
            self.services["privatetemplate"][
                "ostype"] = self.services["ostype"]
            # Listing Hypervisors in Zone 1
            hypervisor_list = Hypervisor.list(
                self.apiClient,
                zoneid=zones_list[0].id
            )
            status = validateList(zones_list)
            self.assertEquals(
                PASS,
                status[0],
                "Failed to list Hypervisors in Zone 1"
            )
            # Creating aTemplate in Zone 1
            template_created = Template.register(
                self.userapiclient,
                self.services["privatetemplate"],
                zones_list[0].id,
                hypervisor=hypervisor_list[0].name
            )
            self.assertIsNotNone(
                template_created,
                "Template creation failed"
            )
            # Listing all the Templates for a User in Zone 1
            list_templates_zone1 = Template.list(
                self.userapiclient,
                listall=self.services["listall"],
                templatefilter=self.services["templatefilter"],
                zoneid=zones_list[0].id
            )
            status = validateList(list_templates_zone1)
            self.assertEquals(
                PASS,
                status[0],
                "Templates creation failed in Zone1"
            )
            # Verifying that list size is 1
            self.assertEquals(
                1,
                len(list_templates_zone1),
                "Failed to create a Template"
            )
            # Listing all the Templates for a User in Zone 2
            list_templates_zone2 = Template.list(
                self.userapiclient,
                listall=self.services["listall"],
                templatefilter=self.services["templatefilter"],
                zoneid=zones_list[1].id
            )
            # Verifying that no Templates are listed
            self.assertIsNone(
                list_templates_zone2,
                "Templates listed for newly created User in Zone2"
            )
            # Verifying the state of the template to be ready. If not waiting
            # for state to become ready till time out
            template_ready = False
            count = 0
            while template_ready is False:
                list_template = Template.list(
                    self.userapiclient,
                    id=template_created.id,
                    listall=self.services["listall"],
                    templatefilter=self.services["templatefilter"],
                )
                status = validateList(list_template)
                self.assertEquals(
                    PASS,
                    status[0],
                    "Failed to list Templates by Id"
                )
                if list_template[0].isready is True:
                    template_ready = True
                elif (str(list_template[0].status) == "Error"):
                    self.fail("Created Template is in Errored state")
                    break
                elif count > 10:
                    self.fail(
                        "Timed out before Template came into ready state")
                    break
                else:
                    time.sleep(self.services["sleep"])
                    count = count + 1

            # Copying the Template from Zone1 to Zone2
            copied_template = template_created.copy(
                self.userapiclient,
                sourcezoneid=template_created.zoneid,
                destzoneid=zones_list[1].id
            )
            self.assertIsNotNone(
                copied_template,
                "Copying Template from Zone1 to Zone2 failed"
            )
            # Listing all the Templates for a User in Zone 1
            list_templates_zone1 = Template.list(
                self.userapiclient,
                listall=self.services["listall"],
                templatefilter=self.services["templatefilter"],
                zoneid=zones_list[0].id
            )
            status = validateList(list_templates_zone1)
            self.assertEquals(
                PASS,
                status[0],
                "Templates creation failed in Zone1"
            )
            # Verifying that list size is 1
            self.assertEquals(
                1,
                len(list_templates_zone1),
                "Failed to create a Template"
            )
            # Listing all the Templates for a User in Zone 2
            list_templates_zone2 = Template.list(
                self.userapiclient,
                listall=self.services["listall"],
                templatefilter=self.services["templatefilter"],
                zoneid=zones_list[1].id
            )
            status = validateList(list_templates_zone2)
            self.assertEquals(
                PASS,
                status[0],
                "Template failed to copy into Zone2"
            )
            # Verifying that list size is 1
            self.assertEquals(
                1,
                len(list_templates_zone2),
                "Template failed to copy into Zone2"
            )
            self.assertNotEquals(
                "Connection refused",
                list_templates_zone2[0].status,
                "Failed to copy Template"
            )
            self.assertEquals(
                True,
                list_templates_zone2[0].isready,
                "Failed to copy Template"
            )
        del self.services["privatetemplate"]["ostype"]
        return
Exemple #36
0
    def test_02_download_template(self):
        """
        @Desc: Test to Download Template
        @steps:
        Step1: Listing all the Templates for a user
        Step2: Verifying that no Templates are listed
        Step3: Creating a Templates
        Step4: Listing all the Templates again for a user
        Step5: Verifying that list size is 1
        Step6: Verifying if the template is in ready state.
                If yes the continuing
                If not waiting and checking for template to be ready till timeout
        Step7: Downloading the template (Extract)
        Step8: Verifying that Template is downloaded
        """
        # Listing all the Templates for a User
        list_templates_before = Template.list(
            self.userapiclient,
            listall=self.services["listall"],
            templatefilter=self.services["templatefilter"]
        )
        # Verifying that no Templates are listed
        self.assertIsNone(
            list_templates_before,
            "Templates listed for newly created User"
        )
        self.services["privatetemplate"]["ostype"] = self.services["ostype"]
        self.services["privatetemplate"]["isextractable"] = True
        # Creating aTemplate
        template_created = Template.register(
            self.userapiclient,
            self.services["privatetemplate"],
            self.zone.id,
            hypervisor=self.hypervisor
        )
        self.assertIsNotNone(
            template_created,
            "Template creation failed"
        )
        # Listing all the Templates for a User
        list_templates_after = Template.list(
            self.userapiclient,
            listall=self.services["listall"],
            templatefilter=self.services["templatefilter"]
        )
        status = validateList(list_templates_after)
        self.assertEquals(
            PASS,
            status[0],
            "Templates creation failed"
        )
        # Verifying that list size is 1
        self.assertEquals(
            1,
            len(list_templates_after),
            "Failed to create a Template"
        )
        # Verifying the state of the template to be ready. If not waiting for
        # state to become ready till time out
        template_ready = False
        count = 0
        while template_ready is False:
            list_template = Template.list(
                self.userapiclient,
                id=template_created.id,
                listall=self.services["listall"],
                templatefilter=self.services["templatefilter"],
            )
            status = validateList(list_template)
            self.assertEquals(
                PASS,
                status[0],
                "Failed to list Templates by Id"
            )
            if list_template[0].isready is True:
                template_ready = True
            elif (str(list_template[0].status) == "Error"):
                self.fail("Created Template is in Errored state")
                break
            elif count > 10:
                self.fail("Timed out before Template came into ready state")
                break
            else:
                time.sleep(self.services["sleep"])
                count = count + 1

        # Downloading the Template name
        download_template = Template.extract(
            self.userapiclient,
            template_created.id,
            mode="HTTP_DOWNLOAD",
            zoneid=self.zone.id
        )
        self.assertIsNotNone(
            download_template,
            "Download Template failed"
        )
        # Verifying the details of downloaded template
        self.assertEquals(
            "DOWNLOAD_URL_CREATED",
            download_template.state,
            "Download URL not created for Template"
        )
        self.assertIsNotNone(
            download_template.url,
            "Download URL not created for Template"
        )
        self.assertEquals(
            template_created.id,
            download_template.id,
            "Download Template details are not same as Template created"
        )
        del self.services["privatetemplate"]["ostype"]
        del self.services["privatetemplate"]["isextractable"]
        return
Exemple #37
0
    def setUpClass(cls):

        cls.testClient = super(TestTemplates, cls).getClsTestClient()
        cls.api_client = cls.testClient.getApiClient()
        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
        cls._cleanup = []
        cls.unsupportedHypervisor = False
        cls.hypervisor = cls.testClient.getHypervisorInfo()
        if cls.hypervisor.lower() in ['lxc']:
            cls.unsupportedHypervisor = True
            return
        # 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
        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)
Exemple #38
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
Exemple #39
0
    def test_07_templates_per_project(self):
        """Test Templates limit per project
        """
        # 1. set max no of templates per project to 1.
        # 2. Create a template in this project. Both template should be in
        #    ready state
        # 3. Try create 2nd template in the project. It should give the user
        #    appropriate error and an alert should be generated.

        # Reset the volume limits
        update_resource_limit(
            self.apiclient,
            2,  # Volume
            max=5,
            projectid=self.project.id)
        self.debug("Updating template resource limits for domain: %s" %
                   self.account.domainid)
        # Set usage_vm=1 for Account 1
        update_resource_limit(
            self.apiclient,
            4,  # Template
            max=1,
            projectid=self.project.id)

        # Register the First Template in the project
        self.debug("Register the First Template in the project")
        builtin_info = get_builtin_template_info(self.apiclient, self.zone.id)
        self.services["template"]["url"] = builtin_info[0]
        self.services["template"]["hypervisor"] = builtin_info[1]
        self.services["template"]["format"] = builtin_info[2]

        # Register new template
        template = Template.register(self.userapiclient,
                                     self.services["template"],
                                     zoneid=self.zone.id,
                                     projectid=self.project.id)
        self.debug("Registered a template of format: %s with ID: %s" %
                   (self.services["template"]["format"], template.id))
        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,
                projectid=self.project.id,
            )
            if list_template_response[0].isready is True:
                break
            elif timeout == 0:
                raise Exception("Template state is not ready, it is %s" %
                                list_template_response[0].isready)

            time.sleep(self.services["sleep"])
            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)

        # Exception should be raised for second template
        with self.assertRaises(Exception):
            Template.register(self.userapiclient,
                              self.services["template"],
                              zoneid=self.zone.id,
                              projectid=self.project.id)
        return
 def test_01_attach_volume_ide(self):
     """
     @desc: Exception when attaching data disk to RHEL VM on vSphere
     Step1: Confirm that vmware.root.disk.controller = "ide" in Global Settings.
     Step2: Register RHEl 6.0 template and deploy a VM.
     Step3: Note that the root disk is attached to IDE.
     Step4: Create new DATA disk and attempt to attach it to the VM.
     Verify that step4 succeeds without any exception
     """
     self.hypervisor = str(get_hypervisor_type(self.api_client)).lower()
     if self.hypervisor != "vmware":
         self.skipTest("This test can be run only on vmware")
     cmd = listConfigurations.listConfigurationsCmd()
     cmd.name = "vmware.root.disk.controller"
     cmd.listAll = True
     try:
         config_descs = self.api_client.listConfigurations(cmd)
     except Exception as e:
         raise Exception("Failed to fetch configurations: %s" % e)
     if not isinstance(config_descs, list):
         raise Exception("List configs didn't returned a valid data")
     config_desc = config_descs[0]
     if str(config_desc.value).lower() != "ide":
         self.skipTest(
             "This test is invalid if {} is not set to ide".format(
                 config_desc.name))
     """
     Register RHEL 6.0 template and deploy vm
     """
     template = Template.register(self.userapiclient,
                                  self.services["rhel60template"],
                                  zoneid=self.zone.id,
                                  account=self.account.name,
                                  domainid=self.account.domainid,
                                  hypervisor=self.hypervisor)
     self.assertIsNotNone(template, "Failed to register Rhel6 template")
     self.debug("Registered a template with format {} and id {}".format(
         self.services["rhel60template"]["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")
     """
     list root disk of the vm created above and make sure that device type is ide
     """
     volume_res = Volume.list(self.userapiclient,
                              virtualmachineid=vm.id,
                              type="root",
                              listAll="true")
     self.assertEqual(
         validateList(volume_res)[0], PASS,
         "list vm response returned invalid list")
     chaininfo = volume_res[0].chaininfo
     device_Bus = literal_eval(chaininfo)["diskDeviceBusName"]
     if "ide" not in device_Bus:
         self.fail("Root disk is not created with device type IDE")
     disk = Volume.create(self.userapiclient,
                          self.services["volume"],
                          zoneid=self.zone.id,
                          diskofferingid=self.disk_offering.id)
     self.assertIsNotNone(disk, "Failed to create custom volume")
     self.cleanup.append(disk)
     try:
         vm.attach_volume(self.userapiclient, disk)
         list_volumes = Volume.list(self.userapiclient,
                                    listall=self.services["listall"],
                                    id=disk.id)
         attached_volume = list_volumes[0]
         self.assertEqual(
             disk.id, attached_volume.id,
             "list volume response does not match with the volume created and attached to vm"
         )
     except Exception as e:
         self.fail(
             "Failed to attach data disk to RHEL vm whose root disk type is IDE"
         )
     return
 def test01_template_download_URL_expire(self):
     """
     @Desc:Template files are deleted from secondary storage after download URL expires
     Step1:Deploy vm with default cent os template
     Step2:Stop the vm
     Step3:Create template from the vm's root volume
     Step4:Extract Template and wait for the download url to expire
     Step5:Deploy another vm with the template created at Step3
     Step6:Verify that vm deployment succeeds
     """
     params = [
         'extract.url.expiration.interval', 'extract.url.cleanup.interval'
     ]
     wait_time = 0
     for param in params:
         config = Configurations.list(
             self.apiClient,
             name=param,
         )
         self.assertEqual(
             validateList(config)[0], PASS,
             "Config list returned invalid response")
         wait_time = wait_time + int(config[0].value)
     self.debug("Total wait time for url expiry: %s" % wait_time)
     # Creating Virtual Machine
     self.virtual_machine = VirtualMachine.create(
         self.userapiclient,
         self.services["virtual_machine"],
         accountid=self.account.name,
         domainid=self.account.domainid,
         serviceofferingid=self.service_offering.id,
     )
     self.assertIsNotNone(self.virtual_machine,
                          "Virtual Machine creation failed")
     self.cleanup.append(self.virtual_machine)
     #Stop virtual machine
     self.virtual_machine.stop(self.userapiclient)
     list_volume = Volume.list(self.userapiclient,
                               virtualmachineid=self.virtual_machine.id,
                               type='ROOT',
                               listall=True)
     self.assertEqual(
         validateList(list_volume)[0], PASS,
         "list volumes with type ROOT returned invalid list")
     self.volume = list_volume[0]
     self.create_template = Template.create(self.userapiclient,
                                            self.services["template"],
                                            volumeid=self.volume.id,
                                            account=self.account.name,
                                            domainid=self.account.domainid)
     self.assertIsNotNone(self.create_template,
                          "Failed to create template from root volume")
     self.cleanup.append(self.create_template)
     """
     Extract template
     """
     try:
         Template.extract(self.userapiclient, self.create_template.id,
                          'HTTP_DOWNLOAD', self.zone.id)
     except Exception as e:
         self.fail("Extract template failed with error %s" % e)
     self.debug("Waiting for %s seconds for url to expire" %
                repr(wait_time + 20))
     time.sleep(wait_time + 20)
     self.debug("Waited for %s seconds for url to expire" %
                repr(wait_time + 20))
     """
     Deploy vm with the template created from the volume. After url expiration interval only
     url should be deleted not the template. To validate this deploy vm with the template
     """
     try:
         self.vm = VirtualMachine.create(
             self.userapiclient,
             self.services["virtual_machine"],
             accountid=self.account.name,
             domainid=self.account.domainid,
             serviceofferingid=self.service_offering.id,
             templateid=self.create_template.id)
         self.cleanup.append(self.vm)
     except Exception as e:
         self.fail("Template is automatically deleted after URL expired.\
                   So vm deployment failed with error: %s" % e)
     return
    def setUpClass(cls):

        cls.logger = logging.getLogger('TestRedundantIsolateNetworks')
        cls.stream_handler = logging.StreamHandler()
        cls.logger.setLevel(logging.DEBUG)
        cls.logger.addHandler(cls.stream_handler)

        cls.testClient = super(TestRedundantIsolateNetworks, 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

        macchinina = Templates().templates["macchinina"]
        cls.hypervisor = cls.testClient.getHypervisorInfo()
        cls.logger.debug("Downloading Template: %s from: %s" % (macchinina[cls.hypervisor.lower()],
                         macchinina[cls.hypervisor.lower()]["url"]))
        cls.template = Template.register(cls.api_client, macchinina[cls.hypervisor.lower()],
                       cls.zone.id, hypervisor=cls.hypervisor.lower(), domainid=cls.domain.id)
        cls.template.download(cls.api_client)

        if cls.template == FAILED:
            assert False, "get_template() failed to return template"

        cls.services["virtual_machine"]["zoneid"] = cls.zone.id
        cls.services["virtual_machine"]["template"] = cls.template.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.services["nw_off_persistent_RVR_egress_true"] = cls.services["nw_off_persistent_RVR"].copy()
        cls.services["nw_off_persistent_RVR_egress_true"]["egress_policy"] = "true"

        cls.services["nw_off_persistent_RVR_egress_false"] = cls.services["nw_off_persistent_RVR"].copy()
        cls.services["nw_off_persistent_RVR_egress_false"]["egress_policy"] = "false"

        cls.services["egress_80"] = {
                                    "startport": 80,
                                    "endport": 80,
                                    "protocol": "TCP",
                                    "cidrlist": ["0.0.0.0/0"]
                                    }

        cls.services["egress_53"] = {
                                    "startport": 53,
                                    "endport": 53,
                                    "protocol": "UDP",
                                    "cidrlist": ["0.0.0.0/0"]
                                    }

        cls._cleanup = [
                        cls.service_offering,
                        cls.account,
                        cls.template
                        ]

        return
    def test_01_volume_snapshot(self):
        """ Test Volume (root) Snapshot
        # 1. Deploy a VM on primary storage and .
        # 2. Take snapshot on root disk
        # 3. Verify the snapshot's entry in the "snapshots" table 
                and presence of the corresponding 
                snapshot on the Secondary Storage
        # 4. Create Template from the Snapshot and Deploy a 
                VM using the Template
        # 5. Log in to the VM from template and make verify 
                the contents of the ROOT disk matches with the snapshot.
        # 6. Delete Snapshot and Deploy a Linux VM from the 
             Template and verify the successful deployment of the VM.
        # 7. Create multiple snapshots on the same volume and 
                Check the integrity of all the snapshots by creating 
                a template from the snapshot and deploying a Vm from it 
                and delete one of the snapshots
        # 8. Verify that the original checksum matches with the checksum 
                of VM's created from remaning snapshots
        # 9. Make verify the contents of the ROOT disk 
                matches with the snapshot
        # 10.Verify that Snapshot of both DATA and ROOT volume should 
                succeed when snapshot of Data disk of a VM is taken 
                when snapshot of ROOT volume of VM is in progress
        # 11.Create snapshot of data disk and verify the original checksum 
                matches with the volume created from snapshot
        # 12.Verify that volume's state should not change when snapshot of 
                a DATA volume is taken that is attached to a VM
        # 13.Verify that volume's state should not change when snapshot of 
                a DATA volume is taken that is not attached to a VM
        # 14.Verify that create Snapshot with quiescevm=True should succeed
        # 15.revertSnapshot() to revert VM to a specified 
                Volume snapshot for root volume
        """

        # Step 1
        # Get ROOT Volume Id
        root_volumes_cluster_list = list_volumes(self.apiclient,
                                                 virtualmachineid=self.vm_1.id,
                                                 type='ROOT',
                                                 listall=True)

        root_volume_cluster = root_volumes_cluster_list[0]

        disk_volumes_cluster_list = list_volumes(self.apiclient,
                                                 virtualmachineid=self.vm_1.id,
                                                 type='DATADISK',
                                                 listall=True)

        data_disk = disk_volumes_cluster_list[0]

        root_vol_state = root_volume_cluster.state

        ckecksum_random_root_cluster = createChecksum(
            service=self.testdata,
            virtual_machine=self.vm_1,
            disk=root_volume_cluster,
            disk_type="rootdiskdevice")

        self.vm_1.stop(self.apiclient)
        root_vol_snap = Snapshot.create(self.apiclient, root_volume_cluster.id)

        self.assertEqual(root_vol_snap.state, "BackedUp",
                         "Check if the snapshot state is correct ")

        self.assertEqual(root_vol_state, root_volume_cluster.state,
                         "Check if volume state has changed")

        self.vm_1.start(self.apiclient)
        # Step 2
        snapshot_list = list_snapshots(self.apiclient, id=root_vol_snap.id)

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

        self.assertTrue(
            is_snapshot_on_nfs(self.apiclient, self.dbclient, self.config,
                               self.zone.id, root_vol_snap.id))

        events = list_events(self.apiclient,
                             account=self.account.name,
                             domainid=self.account.domainid,
                             type='SNAPSHOT.CREATE')

        event_list_validation_result = validateList(events)

        self.assertEqual(
            event_list_validation_result[0], PASS,
            "event list validation failed due to %s" %
            event_list_validation_result[2])
        self.debug("Events list contains event SNAPSHOT.CREATE")

        qresultset = self.dbclient.execute(
            "select * from event where type='SNAPSHOT.CREATE' AND \
                    description like '%%%s%%' AND state='Completed';" %
            root_volume_cluster.id)

        event_validation_result = validateList(qresultset)

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

        self.assertNotEqual(len(qresultset), 0, "Check DB Query result set")

        qresult = str(qresultset)
        self.assertEqual(
            qresult.count('SNAPSHOT.CREATE') > 0, True,
            "Check SNAPSHOT.CREATE event in events table")

        #Usage_Event
        qresultset = self.dbclient.execute(
            "select * from usage_event where type='SNAPSHOT.CREATE' AND \
                        resource_name='%s'" % root_vol_snap.name)

        usage_event_validation_result = validateList(qresultset)

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

        self.assertNotEqual(len(qresultset), 0, "Check DB Query result set")

        self.assertEqual(
            self.dbclient.execute(
                "select size from usage_event where type='SNAPSHOT.CREATE' AND \
            resource_name='%s'" % root_vol_snap.name)[0][0],
            root_vol_snap.physicalsize)

        # Step 3
        # create template from snapshot root_vol_snap
        templateFromSnapshot = Template.create_from_snapshot(
            self.apiclient, root_vol_snap, self.testdata["template_2"])

        self.assertNotEqual(templateFromSnapshot, None,
                            "Check if result exists in list item call")

        vm_from_temp = VirtualMachine.create(
            self.apiclient,
            self.testdata["small"],
            templateid=templateFromSnapshot.id,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            zoneid=self.zone.id,
            mode=self.zone.networktype)

        self.assertNotEqual(vm_from_temp, None,
                            "Check if result exists in list item call")

        compareChecksum(self.apiclient,
                        service=self.testdata,
                        original_checksum=ckecksum_random_root_cluster,
                        disk_type="rootdiskdevice",
                        virt_machine=vm_from_temp)
        vm_from_temp.delete(self.apiclient)
        # Step 4
        root_vol_snap.delete(self.userapiclient)

        self.assertEqual(
            list_snapshots(
                self.apiclient,
                volumeid=root_volume_cluster.id,
            ), None, "Snapshot list should be empty")

        events = list_events(self.apiclient,
                             account=self.account.name,
                             domainid=self.account.domainid,
                             type='SNAPSHOT.DELETE')

        event_list_validation_result = validateList(events)

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

        self.debug("Events list contains event SNAPSHOT.DELETE")

        self.debug("select id from account where uuid = '%s';" %
                   self.account.id)

        qresultset = self.dbclient.execute(
            "select id from account where uuid = '%s';" % self.account.id)

        account_validation_result = validateList(qresultset)

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

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

        account_id = qresult[0]

        qresultset = self.dbclient.execute(
            "select * from event where type='SNAPSHOT.DELETE' AND \
                    account_id='%s' AND state='Completed';" % account_id)

        delete_snap_validation_result = validateList(qresultset)

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

        self.assertNotEqual(len(qresultset), 0, "Check DB Query result set")

        qresult = str(qresultset)
        self.assertEqual(
            qresult.count('SNAPSHOT.DELETE') > 0, True,
            "Check SNAPSHOT.DELETE event in events table")

        # Step 5
        # delete snapshot and deploy vm from snapshot
        vm_from_temp_2 = VirtualMachine.create(
            self.userapiclient,
            self.testdata["small"],
            templateid=templateFromSnapshot.id,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            zoneid=self.zone.id,
            mode=self.zone.networktype)

        self.assertNotEqual(vm_from_temp_2, None,
                            "Check if result exists in list item call")

        # Step 6:
        compareChecksum(self.apiclient,
                        service=self.testdata,
                        original_checksum=ckecksum_random_root_cluster,
                        disk_type="rootdiskdevice",
                        virt_machine=vm_from_temp_2)

        vm_from_temp_2.delete(self.apiclient)
        # Step 7
        # Multiple Snapshots
        self.vm_1.stop(self.apiclient)
        snaps = []
        for i in range(2):

            root_vol_snap = Snapshot.create(self.apiclient,
                                            root_volume_cluster.id)

            self.assertEqual(
                root_vol_snap.state, "BackedUp",
                "Check if the data vol snapshot state is correct ")

            snaps.append(root_vol_snap)

            templateFromSnapshot = Template.create_from_snapshot(
                self.apiclient, root_vol_snap, self.testdata["template_2"])

            self.assertNotEqual(templateFromSnapshot, None,
                                "Check if result exists in list item call")

            vm_from_temp = VirtualMachine.create(
                self.userapiclient,
                self.testdata["small"],
                templateid=templateFromSnapshot.id,
                accountid=self.account.name,
                domainid=self.account.domainid,
                serviceofferingid=self.service_offering.id,
                zoneid=self.zone.id,
                mode=self.zone.networktype)

            self.assertNotEqual(vm_from_temp, None,
                                "Check if result exists in list item call")

            compareChecksum(self.apiclient,
                            service=self.testdata,
                            original_checksum=ckecksum_random_root_cluster,
                            disk_type="rootdiskdevice",
                            virt_machine=vm_from_temp)
            vm_from_temp.delete(self.apiclient)
            templateFromSnapshot.delete(self.apiclient)

        self.vm_1.start(self.apiclient)

        delete_snap = snaps.pop(1)
        delete_snap.delete(self.apiclient)

        self.assertEqual(Snapshot.list(self.apiclient, id=delete_snap.id),
                         None, "Snapshot list should be empty")

        # Step 8
        for snap in snaps:

            templateFromSnapshot = Template.create_from_snapshot(
                self.apiclient, snap, self.testdata["template_2"])

            self.assertNotEqual(templateFromSnapshot, None,
                                "Check if result exists in list item call")

            vm_from_temp = VirtualMachine.create(
                self.userapiclient,
                self.testdata["small"],
                templateid=templateFromSnapshot.id,
                accountid=self.account.name,
                domainid=self.account.domainid,
                serviceofferingid=self.service_offering.id,
                zoneid=self.zone.id,
                mode=self.zone.networktype)

            self.assertNotEqual(vm_from_temp, None,
                                "Check if result exists in list item call")

            compareChecksum(self.apiclient,
                            service=self.testdata,
                            original_checksum=ckecksum_random_root_cluster,
                            disk_type="rootdiskdevice",
                            virt_machine=vm_from_temp)

            templateFromSnapshot.delete(self.apiclient)
            vm_from_temp.delete(self.apiclient)

        for snap in snaps:
            snap.delete(self.apiclient)

        # Step 9
        ckecksum_root_cluster = createChecksum(service=self.testdata,
                                               virtual_machine=self.vm_1,
                                               disk=root_volume_cluster,
                                               disk_type="rootdiskdevice")

        self.vm_1.stop(self.apiclient)

        root_vol_snap_2 = Snapshot.create(self.apiclient,
                                          root_volume_cluster.id)

        self.assertEqual(root_vol_snap_2.state, "BackedUp",
                         "Check if the data vol snapshot state is correct ")
        snap_list_validation_result = validateList(events)

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

        self.assertNotEqual(snapshot_list, None,
                            "Check if result exists in list item call")

        templateFromSnapshot = Template.create_from_snapshot(
            self.apiclient, root_vol_snap_2, self.testdata["template_2"])

        self.debug("create template event comlites with template %s name" %
                   templateFromSnapshot.name)

        self.assertNotEqual(templateFromSnapshot, None,
                            "Check if result exists in list item call")

        vm_from_temp_2 = VirtualMachine.create(
            self.userapiclient,
            self.testdata["small"],
            templateid=templateFromSnapshot.id,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            zoneid=self.zone.id,
            mode=self.zone.networktype)

        self.assertNotEqual(vm_from_temp_2, None,
                            "Check if result exists in list item call")

        compareChecksum(self.apiclient,
                        service=self.testdata,
                        original_checksum=ckecksum_root_cluster,
                        disk_type="rootdiskdevice",
                        virt_machine=vm_from_temp_2)

        vm_from_temp_2.delete(self.apiclient)

        # Step 10
        # Take snapshot of Data disk of a VM , when snapshot of ROOT volume of
        # VM is in progress
        try:
            self.vm_1.stop(self.apiclient)

            t1 = Thread(target=Snapshot.create,
                        args=(self.apiclient, root_volume_cluster.id))

            t2 = Thread(target=Snapshot.create,
                        args=(self.apiclient, data_disk.id))

            t1.start()
            t2.start()
            t1.join()
            t2.join()

        except:
            self.debug("Error: unable to start thread")

        # Step 11
        # Data Disk
        self.vm_1.start(self.apiclient)
        ckecksum_data_disk = createChecksum(service=self.testdata,
                                            virtual_machine=self.vm_1,
                                            disk=data_disk,
                                            disk_type="datadiskdevice_1")

        data_vol_state = data_disk.state

        self.vm_1.stop(self.apiclient)

        data_vol_snap = Snapshot.create(self.apiclient, data_disk.id)

        self.assertEqual(data_vol_snap.state, "BackedUp",
                         "Check if the data vol snapshot state is correct ")

        self.assertEqual(data_vol_state, data_disk.state,
                         "Check if volume state has changed")

        data_snapshot_list = list_snapshots(self.apiclient,
                                            id=data_vol_snap.id)

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

        self.assertTrue(
            is_snapshot_on_nfs(self.apiclient, self.dbclient, self.config,
                               self.zone.id, data_vol_snap.id))

        events = list_events(self.apiclient,
                             account=self.account.name,
                             domainid=self.account.domainid,
                             type='SNAPSHOT.CREATE')

        event_list_validation_result = validateList(events)

        self.assertEqual(
            event_list_validation_result[0], PASS,
            "event list validation failed due to %s" %
            event_list_validation_result[2])
        self.debug("Events list contains event SNAPSHOT.CREATE")

        self.testdata["volume"]["zoneid"] = self.zone.id
        volumeFromSnap = Volume.create_from_snapshot(
            self.apiclient,
            data_vol_snap.id,
            self.testdata["volume"],
            account=self.account.name,
            domainid=self.account.domainid,
        )

        self.assertTrue(
            is_snapshot_on_nfs(self.apiclient, self.dbclient, self.config,
                               self.zone.id, data_vol_snap.id))

        new_vm = VirtualMachine.create(
            self.userapiclient,
            self.testdata["small"],
            templateid=self.template.id,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            zoneid=self.zone.id,
            mode=self.zone.networktype)

        new_vm.attach_volume(self.apiclient, volumeFromSnap)

        new_vm.reboot(self.apiclient)

        compareChecksum(self.apiclient,
                        service=self.testdata,
                        original_checksum=ckecksum_data_disk,
                        disk_type="datadiskdevice_1",
                        virt_machine=new_vm)

        # Step 12
        data_volume_2 = Volume.create(self.apiclient,
                                      self.testdata["volume"],
                                      zoneid=self.zone.id,
                                      account=self.account.name,
                                      domainid=self.account.domainid,
                                      diskofferingid=self.disk_offering.id)

        self.vm_1.start(self.apiclient)
        self.vm_1.attach_volume(self.userapiclient, data_volume_2)

        self.vm_1.reboot(self.apiclient)
        self.vm_1.stop(self.apiclient)

        data_vol_snap_1 = Snapshot.create(self.apiclient, data_volume_2.id)

        self.assertEqual(data_vol_snap_1.state, "BackedUp",
                         "Check if the snapshot state is correct ")

        data_disk_2_list = Volume.list(self.userapiclient,
                                       listall=self.testdata["listall"],
                                       id=data_volume_2.id)

        self.vm_1.start(self.apiclient)

        checksum_data_2 = createChecksum(service=self.testdata,
                                         virtual_machine=self.vm_1,
                                         disk=data_disk_2_list[0],
                                         disk_type="datadiskdevice_2")

        # Step 13
        self.vm_1.detach_volume(self.apiclient, data_volume_2)

        self.vm_1.reboot(self.apiclient)

        prev_state = data_volume_2.state

        data_vol_snap_2 = Snapshot.create(self.apiclient, data_volume_2.id)

        self.assertEqual(data_vol_snap_2.state, prev_state,
                         "Check if the volume state is correct ")

        data_snapshot_list_2 = list_snapshots(self.apiclient,
                                              id=data_vol_snap_2.id)

        self.assertNotEqual(data_snapshot_list_2, None,
                            "Check if result exists in list item call")

        self.assertEqual(data_snapshot_list_2[0].id, data_vol_snap_2.id,
                         "Check resource id in list resources call")

        self.testdata["volume"]["zoneid"] = self.zone.id
        volumeFromSnap_2 = Volume.create_from_snapshot(
            self.apiclient,
            data_vol_snap_2.id,
            self.testdata["volume"],
            account=self.account.name,
            domainid=self.account.domainid,
        )

        self.vm_2.attach_volume(self.userapiclient, volumeFromSnap_2)

        self.vm_2.reboot(self.apiclient)

        data_disk_2_list = Volume.list(self.userapiclient,
                                       listall=self.testdata["listall"],
                                       id=volumeFromSnap_2.id)

        compareChecksum(self.apiclient,
                        service=self.testdata,
                        original_checksum=checksum_data_2,
                        disk_type="datadiskdevice_2",
                        virt_machine=self.vm_2)

        # Step 14
        self.vm_1.stop(self.apiclient)
        with self.assertRaises(Exception):
            root_vol_snap.revertVolToSnapshot(self.apiclient)

        # Step 15
        root_snap = Snapshot.create(self.apiclient, root_volume_cluster.id)

        with self.assertRaises(Exception):
            root_snap.revertVolToSnapshot(self.apiclient)

        return
Exemple #44
0
    def test_05_create_template_from_non_native_snapshot(self):

        old_supports_resign = self.supports_resign
        self._set_supports_resign(False)

        primary_storage_db_id = self._get_cs_storage_pool_db_id(
            self.primary_storage)

        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)

        self.assertEqual(virtual_machine.state.lower(), "running",
                         TestSnapshots._vm_not_in_running_state_err_msg)

        list_volumes_response = list_volumes(
            self.apiClient, virtualmachineid=virtual_machine.id, listall=True)

        self._check_list(
            list_volumes_response, 1,
            TestSnapshots._should_only_be_one_volume_in_list_err_msg)

        vm_1_root_volume = list_volumes_response[0]

        dt_volume = self._get_dt_volume_for_cs_volume(vm_1_root_volume)

        self.assertNotEqual(dt_volume, None,
                            TestSnapshots._should_be_a_valid_volume_err)

        vol_snap_1 = self._create_and_test_non_native_snapshot(
            vm_1_root_volume.id, primary_storage_db_id, 1,
            TestSnapshots._should_only_be_one_snapshot_in_list_err_msg)

        vol_snap_2 = self._create_and_test_non_native_snapshot(
            vm_1_root_volume.id, primary_storage_db_id, 2,
            TestSnapshots._should_be_two_snapshots_in_list_err_msg)

        vol_snap_3 = self._create_and_test_non_native_snapshot(
            vm_1_root_volume.id, primary_storage_db_id, 3,
            TestSnapshots._should_be_three_snapshots_in_list_err_msg)

        services = {
            "displaytext": "Template-1",
            "name": "Template-1-name",
            "ostype": "CentOS 5.6 (64-bit)",
            "ispublic": "true"
        }

        template = Template.create_from_snapshot(self.apiClient, vol_snap_2,
                                                 services)

        self.cleanup.append(template)

        virtual_machine_dict = {"name": "TestVM2", "displayname": "Test VM 2"}

        virtual_machine_2 = VirtualMachine.create(
            self.apiClient,
            virtual_machine_dict,
            accountid=self.account.name,
            zoneid=self.zone.id,
            serviceofferingid=self.compute_offering.id,
            templateid=template.id,
            domainid=self.domain.id,
            startvm=True)

        list_volumes_response = list_volumes(
            self.apiClient,
            virtualmachineid=virtual_machine_2.id,
            listall=True)

        self.assertEqual(virtual_machine_2.state.lower(), "running",
                         TestSnapshots._vm_not_in_running_state_err_msg)

        self._check_list(
            list_volumes_response, 1,
            TestSnapshots._should_only_be_one_volume_in_list_err_msg)

        vm_2_root_volume = list_volumes_response[0]

        dt_volume_2 = self._get_dt_volume_for_cs_volume(vm_2_root_volume)

        self.assertNotEqual(dt_volume_2, None,
                            TestSnapshots._should_be_a_valid_volume_err)

        virtual_machine.delete(self.apiClient, True)
        virtual_machine_2.delete(self.apiClient, True)

        self._delete_and_test_non_native_snapshot(vol_snap_1)

        self._delete_and_test_non_native_snapshot(vol_snap_2)

        self._delete_and_test_non_native_snapshot(vol_snap_3)

        self._set_supports_resign(old_supports_resign)
Exemple #45
0
    def test_01_list_templates_pagination(self):
        """
        @Desc: Test to List Templates pagination
        @steps:
        Step1: Listing all the Templates for a user
        Step2: Verifying that no Templates are listed
        Step3: Creating (page size + 1) number of Templates
        Step4: Listing all the Templates again for a user
        Step5: Verifying that list size is (page size + 1)
        Step6: Listing all the Templates in page1
        Step7: Verifying that list size is (page size)
        Step8: Listing all the Templates in page2
        Step9: Verifying that list size is 1
        Step10: Listing the template by Id
        Step11: Verifying if the template is downloaded and ready.
                If yes the continuing
                If not waiting and checking for template to be ready till timeout
        Step12: Deleting the Template present in page 2
        Step13: Listing all the Templates in page2
        Step14: Verifying that no Templates are listed
        """
        # Listing all the Templates for a User
        list_templates_before = Template.list(
            self.userapiclient,
            listall=self.services["listall"],
            templatefilter=self.services["templatefilter"]
        )
        # Verifying that no Templates are listed
        self.assertIsNone(
            list_templates_before,
            "Templates listed for newly created User"
        )
        self.services["privatetemplate"]["ostype"] = self.services["ostype"]
        # Creating pagesize + 1 number of Templates
        for i in range(0, (self.services["pagesize"] + 1)):
            template_created = Template.register(
                self.userapiclient,
                self.services["privatetemplate"],
                self.zone.id,
                hypervisor=self.hypervisor
            )
            self.assertIsNotNone(
                template_created,
                "Template creation failed"
            )

        # Listing all the Templates for a User
        list_templates_after = Template.list(
            self.userapiclient,
            listall=self.services["listall"],
            templatefilter=self.services["templatefilter"]
        )
        status = validateList(list_templates_after)
        self.assertEquals(
            PASS,
            status[0],
            "Templates creation failed"
        )
        # Verifying that list size is pagesize + 1
        self.assertEquals(
            self.services["pagesize"] + 1,
            len(list_templates_after),
            "Failed to create pagesize + 1 number of Templates"
        )
        # Listing all the Templates in page 1
        list_templates_page1 = Template.list(
            self.userapiclient,
            listall=self.services["listall"],
            templatefilter=self.services["templatefilter"],
            page=1,
            pagesize=self.services["pagesize"]
        )
        status = validateList(list_templates_page1)
        self.assertEquals(
            PASS,
            status[0],
            "Failed to list Templates in page 1"
        )
        # Verifying the list size to be equal to pagesize
        self.assertEquals(
            self.services["pagesize"],
            len(list_templates_page1),
            "Size of Templates in page 1 is not matching"
        )
        # Listing all the Templates in page 2
        list_templates_page2 = Template.list(
            self.userapiclient,
            listall=self.services["listall"],
            templatefilter=self.services["templatefilter"],
            page=2,
            pagesize=self.services["pagesize"]
        )
        status = validateList(list_templates_page2)
        self.assertEquals(
            PASS,
            status[0],
            "Failed to list Templates in page 2"
        )
        # Verifying the list size to be equal to 1
        self.assertEquals(
            1,
            len(list_templates_page2),
            "Size of Templates in page 2 is not matching"
        )
        # Verifying the state of the template to be ready. If not waiting for
        # state to become ready
        template_ready = False
        count = 0
        while template_ready is False:
            list_template = Template.list(
                self.userapiclient,
                id=template_created.id,
                listall=self.services["listall"],
                templatefilter=self.services["templatefilter"],
            )
            status = validateList(list_template)
            self.assertEquals(
                PASS,
                status[0],
                "Failed to list Templates by Id"
            )
            if list_template[0].isready is True:
                template_ready = True
            elif (str(list_template[0].status) == "Error"):
                self.fail("Created Template is in Errored state")
                break
            elif count > 10:
                self.fail("Timed out before Template came into ready state")
                break
            else:
                time.sleep(self.services["sleep"])
                count = count + 1

        # Deleting the Template present in page 2
        Template.delete(
            template_created,
            self.userapiclient
        )
        # Listing all the Templates in page 2 again
        list_templates_page2 = Template.list(
            self.userapiclient,
            listall=self.services["listall"],
            templatefilter=self.services["templatefilter"],
            page=2,
            pagesize=self.services["pagesize"]
        )
        # Verifying that there are no Templates listed
        self.assertIsNone(
            list_templates_page2,
            "Templates not deleted from page 2"
        )
        del self.services["privatetemplate"]["ostype"]
        return
Exemple #46
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', 'lxc']:
            self.skipTest("Snapshots feature is not supported on %s" %
                          self.hypervisor.lower())

        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
Exemple #47
0
    def test_03_edit_template_details(self):
        """
        @Desc: Test to Edit Template name, displaytext, OSType
        @steps:
        Step1: Listing all the Templates for a user
        Step2: Verifying that no Templates are listed
        Step3: Creating a Templates
        Step4: Listing all the Templates again for a user
        Step5: Verifying that list size is 1
        Step6: Verifying if the template is in ready state.
                If yes the continuing
                If not waiting and checking for template to be ready till timeout
        Step7: Editing the template name
        Step8: Verifying that Template name is edited
        Step9: Editing the template displaytext
        Step10: Verifying that Template displaytext is edited
        Step11: Editing the template ostypeid
        Step12: Verifying that Template ostypeid is edited
        Step13: Editing the template name, displaytext
        Step14: Verifying that Template name, displaytext are edited
        Step15: Editing the template name, displaytext, ostypeid
        Step16: Verifying that Template name, displaytext and ostypeid are edited
        """
        # Listing all the Templates for a User
        list_templates_before = Template.list(
            self.userapiclient,
            listall=self.services["listall"],
            templatefilter=self.services["templatefilter"]
        )
        # Verifying that no Templates are listed
        self.assertIsNone(
            list_templates_before,
            "Templates listed for newly created User"
        )
        self.services["privatetemplate"]["ostype"] = self.services["ostype"]
        # Creating aTemplate
        template_created = Template.register(
            self.userapiclient,
            self.services["privatetemplate"],
            self.zone.id,
            hypervisor=self.hypervisor
        )
        self.assertIsNotNone(
            template_created,
            "Template creation failed"
        )
        # Listing all the Templates for a User
        list_templates_after = Template.list(
            self.userapiclient,
            listall=self.services["listall"],
            templatefilter=self.services["templatefilter"]
        )
        status = validateList(list_templates_after)
        self.assertEquals(
            PASS,
            status[0],
            "Templates creation failed"
        )
        # Verifying that list size is 1
        self.assertEquals(
            1,
            len(list_templates_after),
            "Failed to create a Template"
        )
        # Verifying the state of the template to be ready. If not waiting for
        # state to become ready till time out
        template_ready = False
        count = 0
        while template_ready is False:
            list_template = Template.list(
                self.userapiclient,
                id=template_created.id,
                listall=self.services["listall"],
                templatefilter=self.services["templatefilter"],
            )
            status = validateList(list_template)
            self.assertEquals(
                PASS,
                status[0],
                "Failed to list Templates by Id"
            )
            if list_template[0].isready is True:
                template_ready = True
            elif (str(list_template[0].status) == "Error"):
                self.fail("Created Template is in Errored state")
                break
            elif count > 10:
                self.fail("Timed out before Template came into ready state")
                break
            else:
                time.sleep(self.services["sleep"])
                count = count + 1

        # Editing the Template name
        edited_template = Template.update(
            template_created,
            self.userapiclient,
            name="NewTemplateName"
        )
        self.assertIsNotNone(
            edited_template,
            "Editing Template failed"
        )
        # Verifying the details of edited template
        expected_dict = {
            "id": template_created.id,
            "name": "NewTemplateName",
            "displaytest": template_created.displaytext,
            "account": template_created.account,
            "domainid": template_created.domainid,
            "format": template_created.format,
            "ostypeid": template_created.ostypeid,
            "templatetype": template_created.templatetype,
        }
        actual_dict = {
            "id": edited_template.id,
            "name": edited_template.name,
            "displaytest": edited_template.displaytext,
            "account": edited_template.account,
            "domainid": edited_template.domainid,
            "format": edited_template.format,
            "ostypeid": edited_template.ostypeid,
            "templatetype": edited_template.templatetype,
        }
        edit_template_status = self.__verify_values(
            expected_dict,
            actual_dict
        )
        self.assertEqual(
            True,
            edit_template_status,
            "Edited Template details are not as expected"
        )
        # Editing the Template displaytext
        edited_template = Template.update(
            template_created,
            self.userapiclient,
            displaytext="TemplateDisplaytext"
        )
        self.assertIsNotNone(
            edited_template,
            "Editing Template failed"
        )
        # Verifying the details of edited template
        expected_dict = {
            "id": template_created.id,
            "name": "NewTemplateName",
            "displaytest": "TemplateDisplaytext",
            "account": template_created.account,
            "domainid": template_created.domainid,
            "format": template_created.format,
            "ostypeid": template_created.ostypeid,
            "templatetype": template_created.templatetype,
        }
        actual_dict = {
            "id": edited_template.id,
            "name": edited_template.name,
            "displaytest": edited_template.displaytext,
            "account": edited_template.account,
            "domainid": edited_template.domainid,
            "format": edited_template.format,
            "ostypeid": edited_template.ostypeid,
            "templatetype": edited_template.templatetype,
        }
        edit_template_status = self.__verify_values(
            expected_dict,
            actual_dict
        )
        self.assertEqual(
            True,
            edit_template_status,
            "Edited Template details are not as expected"
        )
        # Editing the Template ostypeid
        ostype_list = list_os_types(self.userapiclient)
        status = validateList(ostype_list)
        self.assertEquals(
            PASS,
            status[0],
            "Failed to list OS Types"
        )
        for i in range(0, len(ostype_list)):
            if ostype_list[i].id != template_created.ostypeid:
                newostypeid = ostype_list[i].id
                break

        edited_template = Template.update(
            template_created,
            self.userapiclient,
            ostypeid=newostypeid
        )
        self.assertIsNotNone(
            edited_template,
            "Editing Template failed"
        )
        # Verifying the details of edited template
        expected_dict = {
            "id": template_created.id,
            "name": "NewTemplateName",
            "displaytest": "TemplateDisplaytext",
            "account": template_created.account,
            "domainid": template_created.domainid,
            "format": template_created.format,
            "ostypeid": newostypeid,
            "templatetype": template_created.templatetype,
        }
        actual_dict = {
            "id": edited_template.id,
            "name": edited_template.name,
            "displaytest": edited_template.displaytext,
            "account": edited_template.account,
            "domainid": edited_template.domainid,
            "format": edited_template.format,
            "ostypeid": edited_template.ostypeid,
            "templatetype": edited_template.templatetype,
        }
        edit_template_status = self.__verify_values(
            expected_dict,
            actual_dict
        )
        self.assertEqual(
            True,
            edit_template_status,
            "Edited Template details are not as expected"
        )
        # Editing the Template name, displaytext
        edited_template = Template.update(
            template_created,
            self.userapiclient,
            name=template_created.name,
            displaytext=template_created.displaytext
        )
        self.assertIsNotNone(
            edited_template,
            "Editing Template failed"
        )
        # Verifying the details of edited template
        expected_dict = {
            "id": template_created.id,
            "name": template_created.name,
            "displaytest": template_created.displaytext,
            "account": template_created.account,
            "domainid": template_created.domainid,
            "format": template_created.format,
            "ostypeid": newostypeid,
            "templatetype": template_created.templatetype,
        }
        actual_dict = {
            "id": edited_template.id,
            "name": edited_template.name,
            "displaytest": edited_template.displaytext,
            "account": edited_template.account,
            "domainid": edited_template.domainid,
            "format": edited_template.format,
            "ostypeid": edited_template.ostypeid,
            "templatetype": edited_template.templatetype,
        }
        edit_template_status = self.__verify_values(
            expected_dict,
            actual_dict
        )
        self.assertEqual(
            True,
            edit_template_status,
            "Edited Template details are not as expected"
        )
        # Editing the Template name, displaytext, ostypeid
        edited_template = Template.update(
            template_created,
            self.userapiclient,
            name="NewTemplateName",
            displaytext="TemplateDisplaytext",
            ostypeid=template_created.ostypeid
        )
        self.assertIsNotNone(
            edited_template,
            "Editing Template failed"
        )
        # Verifying the details of edited template
        expected_dict = {
            "id": template_created.id,
            "name": "NewTemplateName",
            "displaytest": "TemplateDisplaytext",
            "account": template_created.account,
            "domainid": template_created.domainid,
            "format": template_created.format,
            "ostypeid": template_created.ostypeid,
            "templatetype": template_created.templatetype,
        }
        actual_dict = {
            "id": edited_template.id,
            "name": edited_template.name,
            "displaytest": edited_template.displaytext,
            "account": edited_template.account,
            "domainid": edited_template.domainid,
            "format": edited_template.format,
            "ostypeid": edited_template.ostypeid,
            "templatetype": edited_template.templatetype,
        }
        edit_template_status = self.__verify_values(
            expected_dict,
            actual_dict
        )
        self.assertEqual(
            True,
            edit_template_status,
            "Edited Template details are not as expected"
        )
        del self.services["privatetemplate"]["ostype"]
        return
Exemple #48
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 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
    def test_vm_nic_adapter_vmxnet3(self):
        """

        # 1. Register a template for VMware with nicAdapter vmxnet3
        # 2. Deploy a VM using this template
        # 3. Create an isolated network
        # 4. Add network to VM
        # 5. Verify that the NIC adapter for VM for both the nics
        #    is vmxnet3
        """

        if self.hypervisor.lower() not in ["vmware"]:
            self.skipTest("This test case is written specifically\
                    for Vmware hypervisor")

        # Register a private template in the account with nic adapter vmxnet3
        template = Template.register(
            self.userapiclient,
            self.testdata["configurableData"]["vmxnet3template"],
            zoneid=self.zone.id,
            account=self.account.name,
            domainid=self.account.domainid,
            details=[{
                "nicAdapter":
                self.testdata["configurableData"]["vmxnet3template"]
                ["nicadapter"]
            }])
        self.cleanup.append(template)
        template.download(self.apiclient)

        templates = Template.list(self.userapiclient,
                                  listall=True,
                                  id=template.id,
                                  templatefilter="self")

        self.assertEqual(
            validateList(templates)[0], PASS,
            "Templates list validation failed")

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

        virtual_machine = VirtualMachine.create(
            self.apiclient,
            self.testdata["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id)

        isolated_network = Network.create(
            self.apiclient,
            self.testdata["isolated_network"],
            self.account.name,
            self.account.domainid,
            networkofferingid=self.isolated_network_offering.id)

        virtual_machine.add_nic(self.apiclient, isolated_network.id)

        # TODO: Add steps to check the Nic Adapter type in VCenter
        # using VCenter APIs
        return
    def test_01_create_template(self):
        """TS_BUG_002-Test to create and deploy VM using password enabled template
        """

        # Validate the following:
        #1. Create a password enabled template
        #2. Deploy VM using this template
        #3. Deploy VM should return password set in template.

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

        self.debug("Registering a new template")

        # Register new template
        template = Template.register(self.apiclient,
                                     self.services["template"],
                                     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["template"]["format"], template.id))
        try:
            # Wait for template to download
            template.download(self.apiclient)
        except Exception as e:
            self.fail("Exception while downloading template %s: %s"\
                      % (template.id, e))

        self.cleanup.append(template)

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

        list_template_response = Template.list(
                                            self.apiclient,
                                            templatefilter=\
                                            self.services["template"]["templatefilter"],
                                            id=template.id,
                                            zoneid=self.zone.id
                                            )

        self.assertEqual(isinstance(list_template_response, list), True,
                         "Check list response returns a valid list")
        #Verify template response to check whether template added successfully
        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,
        )
        self.debug("Deployed VM with ID: %s " % virtual_machine.id)
        self.assertEqual(hasattr(virtual_machine, "password"), True,
                         "Check if the deployed VM returned a password")
        return
    def setUpClass(cls):
        cls.testClient = super(TestDirectDownloadTemplates, cls).getClsTestClient()
        cls.apiclient = cls.testClient.getApiClient()
        cls.hypervisor = cls.testClient.getHypervisorInfo()
        cls.dbclient = cls.testClient.getDbConnection()
        cls.zone = get_zone(cls.apiclient, cls.testClient.getZoneForTests())
        cls.pod = get_pod(cls.apiclient, cls.zone.id)
        cls.services = cls.testClient.getParsedTestDataConfig()

        cls._cleanup = []
        cls.hypervisorSupported = False
        cls.nfsStorageFound = False
        cls.localStorageFound = False
        cls.sharedMountPointFound = False

        if cls.hypervisor.lower() in ['kvm', 'lxc']:
            cls.hypervisorSupported = True

        if cls.hypervisorSupported:
            cls.services["test_templates"]["kvm"]["directdownload"] = "true"
            cls.template = Template.register(cls.apiclient, cls.services["test_templates"]["kvm"],
                              zoneid=cls.zone.id, hypervisor=cls.hypervisor)
            cls._cleanup.append(cls.template)

            cls.services["virtual_machine"]["zoneid"] = cls.zone.id
            cls.services["virtual_machine"]["template"] = cls.template.id
            cls.services["virtual_machine"]["hypervisor"] = cls.hypervisor
            cls.service_offering = ServiceOffering.create(
                cls.apiclient,
                cls.services["service_offerings"]["tiny"]
            )
            cls._cleanup.append(cls.service_offering)
            cls.network_offering = NetworkOffering.create(
                cls.apiclient,
                cls.services["l2-network_offering"],
            )
            cls.network_offering.update(cls.apiclient, state='Enabled')
            cls.services["network"]["networkoffering"] = cls.network_offering.id
            cls.l2_network = Network.create(
                cls.apiclient,
                cls.services["l2-network"],
                zoneid=cls.zone.id,
                networkofferingid=cls.network_offering.id
            )
            cls._cleanup.append(cls.l2_network)
            cls._cleanup.append(cls.network_offering)

            storage_pools = StoragePool.list(
                cls.apiclient,
                zoneid=cls.zone.id
            )
            for pool in storage_pools:
                if not cls.nfsStorageFound and pool.type == "NetworkFilesystem":
                    cls.nfsStorageFound = True
                    cls.nfsPoolId = pool.id
                elif not cls.localStorageFound and pool.type == "Filesystem":
                    cls.localStorageFound = True
                    cls.localPoolId = pool.id
                elif not cls.sharedMountPointFound and pool.type == "SharedMountPoint":
                    cls.sharedMountPointFound = True
                    cls.sharedPoolId = pool.id

        cls.nfsKvmNotAvailable = not cls.hypervisorSupported or not cls.nfsStorageFound
        cls.localStorageKvmNotAvailable = not cls.hypervisorSupported or not cls.localStorageFound
        cls.sharedMountPointKvmNotAvailable = not cls.hypervisorSupported or not cls.sharedMountPointFound
        return
    def test_03_reuse_template_name(self):
        """TS_BUG_011-Test Reusing deleted template name
        """

        # Validate the following
        # 1. Deploy VM using default template, small service offering
        #    and small data disk offering.
        # 2. Perform snapshot on the root disk of this VM.
        # 3. Create a template from snapshot.
        # 4. Delete the template and create a new template with same name
        # 5. Template should be created succesfully

        # Create a snapshot from the ROOTDISK
        snapshot = Snapshot.create(self.apiclient,
                                   self.volume.id,
                                   account=self.account.name,
                                   domainid=self.account.domainid)
        self.debug("Created snapshot with ID: %s" % snapshot.id)
        snapshots = Snapshot.list(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 snapshots call")
        self.assertEqual(snapshots[0].id, snapshot.id,
                         "Check snapshot id in list resources call")

        # Generate template from the snapshot
        template = Template.create_from_snapshot(self.apiclient,
                                                 snapshot,
                                                 self.services["template"],
                                                 random_name=False)
        self.debug("Created template from snapshot: %s" % template.id)
        templates = Template.list(
                                self.apiclient,
                                templatefilter=\
                                self.services["template"]["templatefilter"],
                                id=template.id
                                )
        self.assertEqual(isinstance(templates, list), True,
                         "Check list response returns a valid list")
        self.assertNotEqual(templates, None,
                            "Check if result exists in list item call")

        self.assertEqual(templates[0].isready, True,
                         "Check new template state in list templates call")

        self.debug("Deleting template: %s" % template.id)
        template.delete(self.apiclient)

        # Wait for some time to ensure template state is reflected in other calls
        time.sleep(self.services["sleep"])

        # Generate template from the snapshot
        self.debug("Creating template from snapshot: %s with same name" %
                   template.id)
        template = Template.create_from_snapshot(self.apiclient,
                                                 snapshot,
                                                 self.services["template"],
                                                 random_name=False)

        templates = Template.list(
                                self.apiclient,
                                templatefilter=\
                                self.services["template"]["templatefilter"],
                                id=template.id
                                )
        self.assertEqual(isinstance(templates, list), True,
                         "Check list response returns a valid list")
        self.assertNotEqual(templates, None,
                            "Check if result exists in list item call")

        self.assertEqual(templates[0].name, self.services["template"]["name"],
                         "Check the name of the template")
        return
    def test_16_create_template_volume(self):
        """Test Create template from volume
        """

        noffering = NetworkOffering.list(
            self.user_api_client,
            name="DefaultIsolatedNetworkOfferingWithSourceNatService")
        vm2network = Network.create(self.user_api_client,
                                    self.services["network"],
                                    accountid=self.account.name,
                                    domainid=self.account.domainid,
                                    networkofferingid=noffering[0].id,
                                    zoneid=self.zone.id)

        list_nw_response = Network.list(self.user_api_client, id=vm2network.id)
        self.assertEqual(isinstance(list_nw_response, list), True,
                         "Check list response returns a valid networks list")

        templatevm = VirtualMachine.create(
            self.user_api_client,
            self.services["small"],
            templateid=self.template.id,
            accountid=self.account.name,
            domainid=self.account.domainid,
            networkids=vm2network.id,
            serviceofferingid=self.service_offering.id,
            mode=self.services['mode'],
            startvm="true")
        time.sleep(600)
        vm_response = VirtualMachine.list(self.user_api_client,
                                          id=templatevm.id)

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

        templatevm.stop(self.user_api_client, forced="false")

        vm_response = VirtualMachine.list(self.user_api_client,
                                          id=templatevm.id)

        vm = vm_response[0]
        self.assertEqual(
            vm.state, 'Stopped',
            "Check the state of VM is in Stopped state before creating the Template"
        )

        list_volume_response = Volume.list(self.user_api_client,
                                           virtualmachineid=vm.id,
                                           type="ROOT",
                                           listall=True)

        #Create template from Virtual machine and Volume ID
        roottemplate = Template.create(
            self.user_api_client,
            self.services["interop"]["template"],
            volumeid=list_volume_response[0].id,
            account=self.account.name,
            domainid=self.domain.id,
        )

        time.sleep(600)

        list_template_response = Template.list(
                                    self.user_api_client,
                                    templatefilter=\
                                    self.services["templatefilter"],
                                    id=roottemplate.id
                                    )

        self.assertEqual(isinstance(list_template_response, list), True,
                         "Check list response returns a valid list")
        #Verify template response to check whether template added successfully
        self.assertNotEqual(len(list_template_response), 0,
                            "Check template available in List Templates")
        template_response = list_template_response[0]

        self.assertEqual(template_response.displaytext,
                         self.services["interop"]["template"]["displaytext"],
                         "Check display text of newly created template")
        name = template_response.name
        self.assertEqual(
            name.count(self.services["interop"]["template"]["name"]), 1,
            "Check name of newly created template")

        templatevm.delete(self.apiclient)
        vm2network.delete(self.user_api_client)

        vm3network = Network.create(self.user_api_client,
                                    self.services["network"],
                                    accountid=self.account.name,
                                    domainid=self.account.domainid,
                                    networkofferingid=noffering[0].id,
                                    zoneid=self.zone.id)

        list_nw_response = Network.list(self.user_api_client, id=vm3network.id)
        self.assertEqual(isinstance(list_nw_response, list), True,
                         "Check list response returns a valid networks list")

        templatevm = VirtualMachine.create(
            self.user_api_client,
            self.services["small"],
            templateid=roottemplate.id,
            networkids=vm3network.id,
            serviceofferingid=self.service_offering.id,
            accountid=self.account.name,
            domainid=self.account.domainid,
            mode=self.services['mode'],
            startvm="true")
        time.sleep(600)
        vm_response = VirtualMachine.list(self.user_api_client,
                                          id=templatevm.id)

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

        # Delete the template
        roottemplate.delete(self.user_api_client)

        list_template_response = Template.list(
                                    self.user_api_client,
                                    templatefilter=\
                                    self.services["template"]["templatefilter"],
                                    id=roottemplate.id,
                                    zoneid=self.zone.id
                                    )
        self.assertEqual(list_template_response, None,
                         "Check template available in List Templates")

        templatevm.delete(self.apiclient)

        vm3network.delete(self.user_api_client)
        return
Exemple #54
0
    def setUpClass(cls):

        testClient = super(TestTemplates, cls).getClsTestClient()
        cls.apiclient = testClient.getApiClient()
        cls._cleanup = []
        cls.services = testClient.getParsedTestDataConfig()
        cls.unsupportedHypervisor = False
        cls.hypervisor = testClient.getHypervisorInfo()
        if cls.hypervisor.lower() in ['lxc']:
            # Template creation from root volume is not supported in LXC
            cls.unsupportedHypervisor = True
            return

        # 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
        cls.zones = Zone.list(cls.apiclient)
        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)
        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
        ]
Exemple #55
0
    def test_02_edit_template(self):
        """Test Edit template
        """

        # Validate the following:
        # 1. UI should show the edited values for template
        # 2. database (vm_template table) should have updated values

        new_displayText = random_gen()
        new_name = random_gen()

        self.template_1.update(
            self.apiclient,
            displaytext=new_displayText,
            name=new_name,
            bootable=self.services["bootable"],
            passwordenabled=self.services["passwordenabled"])

        self.debug("Edited template with new name: %s" % new_name)

        # Sleep to ensure update reflected across all the calls
        time.sleep(self.services["sleep"])

        timeout = self.services["timeout"]
        while True:
            # Verify template response for updated attributes
            list_template_response = Template.list(
                                    self.apiclient,
                                    templatefilter=\
                                    self.services["templatefilter"],
                                    id=self.template_1.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(10)
            timeout = timeout - 1

        self.assertEqual(isinstance(list_template_response, list), True,
                         "Check list response returns a valid list")
        self.assertNotEqual(len(list_template_response), 0,
                            "Check template available in List Templates")
        template_response = list_template_response[0]

        self.debug("New Name: %s" % new_displayText)
        self.debug("Name in Template response: %s" %
                   template_response.displaytext)
        self.assertEqual(template_response.displaytext, new_displayText,
                         "Check display text of updated template")
        self.assertEqual(template_response.name, new_name,
                         "Check name of updated template")
        self.assertEqual(
            str(template_response.passwordenabled).lower(),
            str(self.services["passwordenabled"]).lower(),
            "Check passwordenabled field of updated template")
        self.assertEqual(template_response.ostypeid, self.services["ostypeid"],
                         "Check OSTypeID of updated template")
        return
Exemple #56
0
    def test_06_copy_template(self):
        """Test for copy template from one zone to another"""

        # Validate the following
        # 1. copy template should be successful and
        #    secondary storage should contain new copied template.

        if len(self.zones) <= 1:
            self.skipTest(
                "Not enough zones available to perform copy template")

        self.services["destzoneid"] = filter(
            lambda z: z.id != self.services["sourcezoneid"], self.zones)[0].id

        self.debug(
            "Copy template from Zone: %s to %s" %
            (self.services["sourcezoneid"], self.services["destzoneid"]))

        self.template_2.copy(self.apiclient,
                             sourcezoneid=self.services["sourcezoneid"],
                             destzoneid=self.services["destzoneid"])

        # Verify template is copied to another zone using ListTemplates
        list_template_response = Template.list(
                                    self.apiclient,
                                    templatefilter=\
                                    self.services["templatefilter"],
                                    id=self.template_2.id,
                                    zoneid=self.services["destzoneid"]
                                    )
        self.assertEqual(isinstance(list_template_response, list), True,
                         "Check list response returns a valid list")
        self.assertNotEqual(len(list_template_response), 0,
                            "Check template extracted in List Templates")

        template_response = list_template_response[0]
        self.assertEqual(template_response.id, self.template_2.id,
                         "Check ID of the downloaded template")
        self.assertEqual(template_response.zoneid, self.services["destzoneid"],
                         "Check zone ID of the copied template")

        # Cleanup- Delete the copied template
        timeout = self.services["timeout"]
        while True:
            time.sleep(self.services["sleep"])
            list_template_response = Template.list(
                                        self.apiclient,
                                        templatefilter=\
                                        self.services["templatefilter"],
                                        id=self.template_2.id,
                                        zoneid=self.services["destzoneid"]
                                        )
            self.assertEqual(isinstance(list_template_response, list), True,
                             "Check list response returns a valid list")
            self.assertNotEqual(len(list_template_response), 0,
                                "Check template extracted in List Templates")

            template_response = list_template_response[0]
            if template_response.isready == True:
                break

            if timeout == 0:
                raise Exception("Failed to download copied template(ID: %s)" %
                                template_response.id)

            timeout = timeout - 1
        self.template_2.delete(self.apiclient,
                               zoneid=self.services["destzoneid"])
        return
Exemple #57
0
    def test_07_template_from_snapshot(self):
        """Create Template from snapshot
        """

        # 1. Login to machine; create temp/test directories on data volume
        # 2. Snapshot the Volume
        # 3. Create Template from snapshot
        # 4. Deploy Virtual machine using this template
        # 5. Login to newly created virtual machine
        # 6. Compare data in the root disk with the one that was written on the
        # volume, it should match

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

        random_data_0 = random_gen(size=100)
        random_data_1 = random_gen(size=100)

        try:
            # Login to virtual machine
            ssh_client = self.virtual_machine.get_ssh_client()

            cmds = [
                "mkdir -p %s" % self.services["paths"]["mount_dir"],
                "mount %s1 %s" %
                (self.services["volume"][self.hypervisor]["rootdiskdevice"],
                 self.services["paths"]["mount_dir"]),
                "mkdir -p %s/%s/{%s,%s} " %
                (self.services["paths"]["mount_dir"],
                 self.services["paths"]["sub_dir"],
                 self.services["paths"]["sub_lvl_dir1"],
                 self.services["paths"]["sub_lvl_dir2"]),
                "echo %s > %s/%s/%s/%s" %
                (random_data_0, self.services["paths"]["mount_dir"],
                 self.services["paths"]["sub_dir"],
                 self.services["paths"]["sub_lvl_dir1"],
                 self.services["paths"]["random_data"]),
                "echo %s > %s/%s/%s/%s" %
                (random_data_1, self.services["paths"]["mount_dir"],
                 self.services["paths"]["sub_dir"],
                 self.services["paths"]["sub_lvl_dir2"],
                 self.services["paths"]["random_data"]),
                "sync",
            ]

            for c in cmds:
                self.debug(c)
                result = ssh_client.execute(c)
                self.debug(result)

        except Exception as e:
            self.fail("SSH failed for VM with IP address: %s" %
                      self.virtual_machine.ipaddress)

        # Unmount the Volume
        cmds = [
            "umount %s" % (self.services["paths"]["mount_dir"]),
        ]
        for c in cmds:
            self.debug(c)
            ssh_client.execute(c)

        volumes = list_volumes(userapiclient,
                               virtualmachineid=self.virtual_machine.id,
                               type='ROOT',
                               listall=True)
        self.assertEqual(isinstance(volumes, list), True,
                         "Check list response returns a valid list")

        volume = volumes[0]

        # Create a snapshot of volume
        snapshot = Snapshot.create(userapiclient,
                                   volume.id,
                                   account=self.account.name,
                                   domainid=self.account.domainid)

        self.debug("Snapshot created from volume ID: %s" % volume.id)
        # Generate template from the snapshot
        template = Template.create_from_snapshot(userapiclient, snapshot,
                                                 self.services["templates"])
        self.cleanup.append(template)
        self.debug("Template created from snapshot ID: %s" % snapshot.id)

        # Verify created template
        templates = list_templates(
            userapiclient,
            templatefilter=self.services["templates"]["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 new VM from template: %s" % template.id)

        # Deploy new virtual machine using template
        new_virtual_machine = VirtualMachine.create(
            userapiclient,
            self.services["server_without_disk"],
            templateid=template.id,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            mode=self.services["mode"])
        try:
            # Login to VM & mount directory
            ssh = new_virtual_machine.get_ssh_client()

            cmds = [
                "mkdir -p %s" % self.services["paths"]["mount_dir"],
                "mount %s1 %s" %
                (self.services["volume"][self.hypervisor]["rootdiskdevice"],
                 self.services["paths"]["mount_dir"])
            ]

            for c in cmds:
                ssh.execute(c)

            returned_data_0 = ssh.execute(
                "cat %s/%s/%s/%s" % (self.services["paths"]["mount_dir"],
                                     self.services["paths"]["sub_dir"],
                                     self.services["paths"]["sub_lvl_dir1"],
                                     self.services["paths"]["random_data"]))
            self.debug(returned_data_0)
            returned_data_1 = ssh.execute(
                "cat %s/%s/%s/%s" % (self.services["paths"]["mount_dir"],
                                     self.services["paths"]["sub_dir"],
                                     self.services["paths"]["sub_lvl_dir2"],
                                     self.services["paths"]["random_data"]))
            self.debug(returned_data_1)
        except Exception as e:
            self.fail("SSH failed for VM with IP address: %s" %
                      new_virtual_machine.ipaddress)
        # Verify returned data
        self.assertEqual(
            random_data_0, returned_data_0[0],
            "Verify newly attached volume contents with existing one")
        self.assertEqual(
            random_data_1, returned_data_1[0],
            "Verify newly attached volume contents with existing one")
        # Unmount the volume
        cmds = [
            "umount %s" % (self.services["paths"]["mount_dir"]),
        ]
        try:
            for c in cmds:
                self.debug(c)
                ssh_client.execute(c)

        except Exception as e:
            self.fail("SSH failed for VM with IP address: %s, Exception: %s" %
                      (new_virtual_machine.ipaddress, e))
        return
    def test_01_data_persistency_root_disk(self):
        """
        Test the timing issue of root disk data sync

        # 1. Write data to root disk of a VM
        # 2. Create a template from the root disk of VM
        # 3. Create a new VM from this template
        # 4. Check that the data is present in the new VM

        This is to test that data is persisted on root disk of VM or not
        when template is created immediately from it
        """

        ssh = self.virtual_machine.get_ssh_client()

        sampleText = "This is sample data"

        cmds = [
                "cd /root/",
                "touch testFile.txt",
                "chmod 600 testFile.txt",
                "echo %s >> testFile.txt" % sampleText
                ]
        for c in cmds:
            ssh.execute(c)

        #Stop virtual machine
        self.virtual_machine.stop(self.api_client)

        list_volume = Volume.list(
                            self.api_client,
                            virtualmachineid=self.virtual_machine.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" %
                self.virtual_machine.id)

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

        virtual_machine = VirtualMachine.create(
                                    self.apiclient,
                                    self.services["virtual_machine"],
                                    templateid=customTemplate.id,
                                    accountid=self.account.name,
                                    domainid=self.account.domainid,
                                    serviceofferingid=self.service_offering.id,
                                    mode=self.services["mode"]
                                    )

        ssh = virtual_machine.get_ssh_client()

        response = ssh.execute("cat /root/testFile.txt")
        res = str(response[0])

        self.assertEqual(res, sampleText, "The data %s does not match\
                with sample test %s" %
                (res, sampleText))
        return
    def test_01_positive_test_1(self):
        """
        positive test for volume life cycle
        # 1. Deploy a vm [vm1] with shared storage and data disk
        # 2. Deploy a vm [vm2]with shared storage without data disk
        # 3.
        # 4. Create a new volume and attache to vm2
        # 5. Detach data disk from vm1 and download it
        #  Variance(1-9)
        # 6. Upload volume by providing url of downloaded volume in step 5
        # 7. Attach the volume to a different vm - vm2
        # 8. Try to delete an attached volume
        # 9. Create template from root volume of VM1
        # 10. Create new VM using the template created in step 9
        # 11. Delete the template
        # 12. Detach the disk from VM2 and re-attach the disk to VM1
        # 13.
        # 14.
        # 15.Migrate volume(detached) and then attach to a vm and live-migrate
        # 16.Upload volume of size smaller  than storage.max.volume.upload.size(leaving the negative case)
        # 17.NA
        # 18.
        # 19.NA
        # 20.Detach data disks from VM2 and delete volume

        """
        # 1. Deploy a vm [vm1] with shared storage and data disk
        self.virtual_machine_1 = VirtualMachine.create(self.userapiclient,
                                                       self.testdata["small"],
                                                       templateid=self.template.id,
                                                       accountid=self.account.name,
                                                       domainid=self.account.domainid,
                                                       serviceofferingid=self.service_offering_1.id,
                                                       zoneid=self.zone.id,
                                                       diskofferingid=self.disk_offering_1.id,
                                                       mode=self.testdata["mode"]
                                                       )
        verify_vm(self, self.virtual_machine_1.id)
        # List data volume for vm1
        list_volume = Volume.list(self.userapiclient,
                                  virtualmachineid=self.virtual_machine_1.id,
                                  type='DATADISK'
                                  )
        self.assertEqual(validateList(list_volume)[0], PASS, "Check List volume response for vm id  %s" % self.virtual_machine_1.id)
        list_data_volume_for_vm1 = list_volume[0]
        self.assertEqual(len(list_volume), 1, "There is no data disk attached to vm id:%s" % self.virtual_machine_1.id)
        self.assertEqual(list_data_volume_for_vm1.virtualmachineid, str(self.virtual_machine_1.id), "Check if volume state (attached) is reflected")
        # 2. Deploy a vm [vm2]with shared storage without data disk
        self.virtual_machine_2 = VirtualMachine.create(self.userapiclient,
                                                       self.testdata["small"],
                                                       templateid=self.template.id,
                                                       accountid=self.account.name,
                                                       domainid=self.account.domainid,
                                                       serviceofferingid=self.service_offering_1.id,
                                                       zoneid=self.zone.id,
                                                       mode=self.testdata["mode"]
                                                       )
        verify_vm(self, self.virtual_machine_2.id)

        #4. Create a new volume and attache to vm2
        self.volume = Volume.create(self.userapiclient,
                                    services=self.testdata["volume"],
                                    diskofferingid=self.disk_offering_1.id,
                                    zoneid=self.zone.id
                                    )

        list_data_volume = Volume.list(self.userapiclient,
                                       id=self.volume.id
                                       )
        self.assertEqual(validateList(list_data_volume)[0], PASS, "Check List volume response for volume %s" % self.volume.id)
        self.assertEqual(list_data_volume[0].id, self.volume.id, "check list volume response for volume id:  %s" % self.volume.id)
        self.debug("volume id %s got created successfully" % list_data_volume[0].id)
        # Attach volume to vm2
        self.virtual_machine_2.attach_volume(self.userapiclient,
                                             self.volume
                                             )
        verify_attach_volume(self, self.virtual_machine_2.id, self.volume.id)

        #Variance
        if self.zone.localstorageenabled:
            # V1.Create vm3 with local storage offering
            self.virtual_machine_local_3=VirtualMachine.create(self.userapiclient,
                                                               self.testdata["small"],
                                                               templateid=self.template.id,
                                                               accountid=self.account.name,
                                                               domainid=self.account.domainid,
                                                               serviceofferingid=self.service_offering_2.id,
                                                               zoneid=self.zone.id,
                                                               mode=self.testdata["mode"]
                                                               )
            verify_vm(self, self.virtual_machine_local_3.id)

            # V2.create two data disk on local storage
            self.local_volumes = []
            for i in range(2):

                    local_volume = Volume.create(self.userapiclient,
                                                 services=self.testdata["volume"],
                                                 diskofferingid=self.disk_offering_local.id,
                                                 zoneid=self.zone.id
                                                 )

                    list_local_data_volume = Volume.list(self.userapiclient,
                                                         id=local_volume.id
                                                         )
                    self.assertEqual(validateList(list_local_data_volume)[0], PASS, "Check List volume response for volume %s" % local_volume.id)
                    self.assertEqual(list_local_data_volume[0].id, local_volume.id, "check list volume response for volume id:  %s" % local_volume.id)
                    self.debug("volume id %s got created successfully" % list_local_data_volume[0].id)
                    self.local_volumes.append(local_volume)
            # V3.Attach local disk to vm1
            self.virtual_machine_1.attach_volume(self.userapiclient,
                                                 self.local_volumes[0]
                                                 )
            verify_attach_volume(self, self.virtual_machine_1.id, self.local_volumes[0].id)
        if self.list_storage:
            # V4.create vm4 with zone wide storage
            self.virtual_machine_zone_4 = VirtualMachine.create(self.userapiclient,
                                                                self.testdata["small"],
                                                                templateid=self.template.id,
                                                                accountid=self.account.name,
                                                                domainid=self.account.domainid,
                                                                serviceofferingid=self.tagged_so.id,
                                                                zoneid=self.zone.id,
                                                                mode=self.testdata["mode"]
                                                                )
            verify_vm(self, self.virtual_machine_zone_4.id)

            # V5.Create two data disk on zone  wide storage
            self.zone_volumes = []
            for i in range(2):

                    zone_volume = Volume.create(self.userapiclient,
                                                services=self.testdata["volume"],
                                                diskofferingid=self.disk_offering_tagged.id,
                                                zoneid=self.zone.id
                                                )

                    list_zone_data_volume = Volume.list(self.userapiclient,
                                                        id=zone_volume.id
                                                        )
                    self.assertEqual(validateList(list_zone_data_volume)[0], PASS, "Check List volume response for volume %s" % zone_volume.id)
                    self.assertEqual(list_zone_data_volume[0].id, zone_volume.id, "check list volume response for volume id:  %s" % zone_volume.id)
                    self.debug("volume id:%s got created successfully" % list_zone_data_volume[0].id)
                    self.zone_volumes.append(zone_volume)

            # V6.Attach data disk running on ZWPS to VM1 (root disk on shared)
            self.virtual_machine_1.attach_volume(self.userapiclient,
                                                 self.zone_volumes[0]
                                                 )
            verify_attach_volume(self, self.virtual_machine_1.id, self.zone_volumes[0].id)
            # V7. Create a cluster wide volume and attach to vm running on zone wide storage
            self.cluster_volume = Volume.create(self.userapiclient,
                                                services=self.testdata["volume"],
                                                diskofferingid=self.disk_offering_1.id,
                                                zoneid=self.zone.id
                                                )
            list_cluster_volume = Volume.list(self.userapiclient,
                                              id=self.cluster_volume.id
                                              )
            self.assertEqual(validateList(list_cluster_volume)[0], PASS, "Check List volume response for volume %s" % self.cluster_volume.id)
            self.assertEqual(list_cluster_volume[0].id, str(self.cluster_volume.id), "volume does not exist %s" % self.cluster_volume.id)
            self.debug("volume id %s got created successfuly" % list_cluster_volume[0].id)
            self.virtual_machine_zone_4.attach_volume(self.userapiclient,
                                                      self.cluster_volume
                                                      )
            verify_attach_volume(self, self.virtual_machine_zone_4.id, self.cluster_volume.id)
        if self.list_storage and self.zone.localstorageenabled:
            #V8.Attach zone wide volume to vm running on local storage
            self.virtual_machine_local_3.attach_volume(self.userapiclient,
                                                       self.zone_volumes[1]
                                                       )
            verify_attach_volume(self, self.virtual_machine_local_3.id, self.zone_volumes[1].id)
            # V9.Attach local volume to a vm running on zone wide storage
            self.virtual_machine_zone_4.attach_volume(self.userapiclient,
                                                      self.local_volumes[1]
                                                      )
            verify_attach_volume(self, self.virtual_machine_zone_4.id, self.local_volumes[1].id)
        # 5. Detach data disk from vm1 and download it
        self.virtual_machine_1.detach_volume(self.userapiclient,
                                             volume=list_data_volume_for_vm1
                                             )
        verify_detach_volume(self, self.virtual_machine_1.id, list_data_volume_for_vm1.id)
        # download detached volume
        self.extract_volume = Volume.extract(self.userapiclient,
                                             volume_id=list_data_volume_for_vm1.id,
                                             zoneid=self.zone.id,
                                             mode='HTTP_DOWNLOAD'
                                             )

        self.debug("extracted url is%s  :" % self.extract_volume.url)
        try:

            formatted_url = urllib.unquote_plus(self.extract_volume.url)
            self.debug("Attempting to download volume at url %s" % formatted_url)
            response = urllib.urlopen(formatted_url)
            self.debug("response from volume url %s" % response.getcode())
            fd, path = tempfile.mkstemp()
            self.debug("Saving volume %s to path %s" % (list_data_volume_for_vm1.id, path))
            os.close(fd)
            with open(path, 'wb') as fd:
                fd.write(response.read())
            self.debug("Saved volume successfully")
        except Exception:
            self.fail("Extract Volume Failed with invalid URL %s (vol id: %s)" % (self.extract_volume, list_data_volume_for_vm1.id))
        #Need to get format for downloaded volume ,for now using default format VHD
        if "OVA" in self.extract_volume.url.upper():
            self.testdata["upload_volume"]["format"] = "OVA"
        if "QCOW2" in self.extract_volume.url.upper():
            self.testdata["upload_volume"]["format"] = "QCOW2"
        # 6. Upload volume by providing url of downloaded volume in step 5
        self.upload_response = Volume.upload(self.userapiclient,
                                             zoneid=self.zone.id,
                                             url=self.extract_volume.url,
                                             services=self.testdata["upload_volume"]
                                             )
        self.upload_response.wait_for_upload(self.userapiclient
                                             )
        self.debug("uploaded volume id is %s" % self.upload_response.id)
        # 7. Attach the volume to a different vm - vm2
        self.virtual_machine_2.attach_volume(self.userapiclient,
                                             volume=self.upload_response
                                             )
        verify_attach_volume(self, self.virtual_machine_2.id, self.upload_response.id)
        # 8. Try to delete an attached volume
        try:
            self.volume.delete(self.userapiclient
                               )
            self.fail("Volume got deleted in attached state %s " % self.volume.id)
        except Exception as e:
            self.debug("Attached volume deletion failed because  %s" % e)
        #9. Create template from root volume of VM1(stop VM->create template -> start vm)

        self.virtual_machine_1.stop(self.userapiclient
                                    )

        self.list_root_disk_for_vm1 = Volume.list(self.userapiclient,
                                                  virtualmachineid=self.virtual_machine_1.id,
                                                  type='ROOT'
                                                  )
        self.assertEqual(validateList(self.list_root_disk_for_vm1)[0], PASS, "Check List volume response for vm %s" % self.virtual_machine_1.id)
        self.assertEqual(len(self.list_root_disk_for_vm1), 1, "list root disk for vm1 is empty : %s" % self.virtual_machine_1.id)
        self.template_from_vm1_root_disk = Template.create(self.userapiclient,
                                                           self.testdata["template"],
                                                           self.list_root_disk_for_vm1[0].id,
                                                           account=self.account.name,
                                                           domainid=self.account.domainid
                                                           )
        list_template = Template.list(self.userapiclient,
                                      templatefilter=self.testdata["templatefilter"],
                                      id=self.template_from_vm1_root_disk.id
                                      )
        self.assertEqual(validateList(list_template)[0], PASS, "Check List template response for template id %s" % self.template_from_vm1_root_disk.id)
        self.assertEqual(len(list_template), 1, "list template response is empty for template id  : %s" % list_template[0].id)
        self.assertEqual(list_template[0].id, self.template_from_vm1_root_disk.id, "list template id is not same as created template")
        self.debug("Template id:%s got created successfully" % self.template_from_vm1_root_disk.id)
        self.virtual_machine_1.start(self.userapiclient
                                     )
        # 10. Deploy a vm using template ,created  from vm1's root disk

        self.virtual_machine_3 = VirtualMachine.create(self.userapiclient,
                                                       self.testdata["small"],
                                                       templateid=self.template_from_vm1_root_disk.id,
                                                       accountid=self.account.name,
                                                       domainid=self.account.domainid,
                                                       serviceofferingid=self.service_offering_1.id,
                                                       zoneid=self.zone.id,
                                                       mode=self.testdata["mode"]
                                                       )
        verify_vm(self, self.virtual_machine_3.id)

        # 11.delete the template created from root disk of vm1
        try:
            self.template_from_vm1_root_disk.delete(self.userapiclient
                                                    )
            self.debug("Template id: %s got deleted successfuly" % self.template_from_vm1_root_disk.id)
        except Exception as e:
            raise Exception("Template deletion failed with error %s" % e)
        list_template = Template.list(self.userapiclient,
                                      templatefilter=self.testdata["templatefilter"],
                                      id=self.template_from_vm1_root_disk.id
                                      )
        self.assertEqual(list_template, None, "Template is not deleted, id %s:" % self.template_from_vm1_root_disk.id)
        self.debug("Template id%s got deleted successfully" % self.template_from_vm1_root_disk.id)

        # List vm and check the state of vm
        verify_vm(self, self.virtual_machine_3.id)

        #12.Detach the disk from VM2 and re-attach the disk to VM1
        self.virtual_machine_2.detach_volume(self.userapiclient,
                                             volume=self.upload_response
                                             )
        verify_detach_volume(self, self.virtual_machine_2.id, self.upload_response.id)

        self.virtual_machine_1.attach_volume(self.userapiclient,
                                             volume=self.upload_response
                                             )

        verify_attach_volume(self, self.virtual_machine_1.id, self.upload_response.id)

        # 15.Migrate volume(detached) and then attach to a vm and live-migrate
        self.migrate_volume = Volume.create(self.userapiclient,
                                            services=self.testdata["volume"],
                                            diskofferingid=self.disk_offering_1.id,
                                            zoneid=self.zone.id
                                            )
        list_volume = Volume.list(self.apiclient,
                                  id=self.migrate_volume.id
                                  )
        self.assertEqual(validateList(list_volume)[0], PASS, "Check List volume response for volume %s" % self.migrate_volume.id)
        self.assertEqual(list_volume[0].id, str(self.migrate_volume.id), "volume does not exist %s" % self.migrate_volume.id)
        self.debug("volume id %s got created successfuly" % list_volume[0].id)

        self.virtual_machine_1.attach_volume(self.userapiclient,
                                             self.migrate_volume
                                             )
        verify_attach_volume(self, self.virtual_machine_1.id, self.migrate_volume.id)

        self.virtual_machine_1.detach_volume(self.userapiclient,
                                             volume=self.migrate_volume
                                             )
        verify_detach_volume(self, self.virtual_machine_1.id, self.migrate_volume.id)

        list_volume = Volume.list(self.apiclient,
                                  id=self.migrate_volume.id
                                  )
        self.assertEqual(validateList(list_volume)[0], PASS, "Check List volume response for volume %s" % self.migrate_volume.id)
        self.assertEqual(list_volume[0].id, str(self.migrate_volume.id), "volume does not exist %s" % self.migrate_volume.id)
        self.debug("volume id %s got created successfuly" % list_volume[0].id)
        list_pool = StoragePool.list(self.apiclient,
                                     id=list_volume[0].storageid
                                     )
        self.assertEqual(validateList(list_pool)[0], PASS, "Check List pool response for storage id %s" % list_volume[0].storageid)
        self.assertGreater(len(list_pool), 0, "Check the list list storagepoolresponse for vm id:  %s" % list_volume[0].storageid)
        list_pools = StoragePool.list(self.apiclient,
                                      scope=list_pool[0].scope
                                      )
        self.assertEqual(validateList(list_pools)[0], PASS, "Check List pool response for scope %s" % list_pool[0].scope)
        self.assertGreater(len(list_pools), 0, "Check the list vm response for scope :%s" % list_volume[0].scope)
        storagepoolid = None
        for i in range(len(list_pools)):
            if list_volume[0].storageid != list_pools[i].id:
                storagepoolid = list_pools[i].id
                break
            else:
                self.debug("No pool available for volume migration ")

        if storagepoolid is not None:
            try:
                volume_migrate = Volume.migrate(self.apiclient,
                                                storageid=storagepoolid,
                                                volumeid=self.migrate_volume.id
                                                )
            except Exception as e:
                raise Exception("Volume migration failed with error %s" % e)

            self.virtual_machine_2.attach_volume(self.userapiclient,
                                                 self.migrate_volume
                                                 )
            verify_attach_volume(self, self.virtual_machine_2.id, self.migrate_volume.id)

            pool_for_migration = StoragePool.listForMigration(self.apiclient,
                                                              id=self.migrate_volume.id
                                                              )
            self.assertEqual(validateList(pool_for_migration)[0], PASS, "Check list pool For Migration response for volume %s" % self.migrate_volume.id)
            self.assertGreater(len(pool_for_migration), 0, "Check the listForMigration response for volume :%s" % self.migrate_volume.id)
            try:
                volume_migrate = Volume.migrate(self.apiclient,
                                                storageid=pool_for_migration[0].id,
                                                volumeid=self.migrate_volume.id,
                                                livemigrate=True
                                                )
            except Exception as e:
                raise Exception("Volume migration failed with error %s" % e)
        else:
            try:
                self.migrate_volume.delete(self.userapiclient
                                           )
                self.debug("volume id:%s got deleted successfully " % self.migrate_volume.id)
            except Exception as e:
                raise Exception("Volume deletion failed with error %s" % e)
        # 16.Upload volume of size smaller  than storage.max.volume.upload.size(leaving the negative case)
        self.testdata["upload_volume"]["format"] = "VHD"
        volume_upload = Volume.upload(self.userapiclient,
                                      self.testdata["upload_volume"],
                                      zoneid=self.zone.id
                                      )
        volume_upload.wait_for_upload(self.userapiclient
                                      )
        self.debug("volume id :%s got uploaded successfully is " % volume_upload.id)

        # 20.Detach data disk from vm 2 and delete the volume
        self.virtual_machine_2.detach_volume(self.userapiclient,
                                             volume=self.volume
                                             )
        verify_detach_volume(self, self.virtual_machine_2.id, self.volume.id)

        try:
            self.volume.delete(self.userapiclient
                               )
            self.debug("volume id:%s got deleted successfully " % self.volume.id)
        except Exception as e:
            raise Exception("Volume deletion failed with error %s" % e)
Exemple #60
0
    def test_01_createVM_snapshotTemplate(self):
        """Test create VM, Snapshot and Template
        """
        # Validate the following
        # 1. Deploy VM using default template, small service offering
        #    and small data disk offering.
        # 2. Perform snapshot on the root disk of this VM.
        # 3. Create a template from snapshot.
        # 4. Create a instance from above created template.
        # 5. listSnapshots should list the snapshot that was created.
        # 6. verify that secondary storage NFS share contains the reqd
        #    volume under /secondary/snapshots/$accountid/
        #    $volumeid/$snapshot_uuid
        # 7. verify backup_snap_id was non null in the `snapshots` table
        # 8. listTemplates() should return the newly created Template,
        #    and check for template state as READY"
        # 9. listVirtualMachines() command should return the deployed VM.
        #    State of this VM should be Running.

        # Create Virtual Machine

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

        self.virtual_machine = VirtualMachine.create(
            userapiclient,
            self.services["server"],
            templateid=self.template.id,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id)
        self.debug("Created VM with ID: %s" % self.virtual_machine.id)
        # Get the Root disk of VM
        volumes = list_volumes(userapiclient,
                               virtualmachineid=self.virtual_machine.id,
                               type='ROOT',
                               listall=True)
        volume = volumes[0]

        # Create a snapshot from the ROOTDISK
        snapshot = Snapshot.create(userapiclient, volume.id)
        self.debug("Snapshot created: ID - %s" % snapshot.id)
        self.cleanup.append(snapshot)

        snapshots = list_snapshots(userapiclient, 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 snapshots call")
        self.assertEqual(snapshots[0].id, snapshot.id,
                         "Check snapshot id in list resources call")
        self.debug(
            "select backup_snap_id, account_id, volume_id from snapshots where uuid = '%s';"
            % snapshot.id)
        snapshot_uuid = snapshot.id

        # Generate template from the snapshot
        template = Template.create_from_snapshot(userapiclient, snapshot,
                                                 self.services["templates"])
        self.debug("Created template from snapshot: %s" % template.id)
        self.cleanup.append(template)

        templates = list_templates(
            userapiclient,
            templatefilter=self.services["templates"]["templatefilter"],
            id=template.id)

        self.assertNotEqual(templates, None,
                            "Check if result exists in list item call")

        self.assertEqual(templates[0].isready, True,
                         "Check new template state in list templates call")

        # Deploy new virtual machine using template
        new_virtual_machine = VirtualMachine.create(
            userapiclient,
            self.services["server"],
            templateid=template.id,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id)
        self.debug("Created VM with ID: %s from template: %s" %
                   (new_virtual_machine.id, template.id))
        self.cleanup.append(new_virtual_machine)

        # Newly deployed VM should be 'Running'
        virtual_machines = list_virtual_machines(
            userapiclient,
            id=new_virtual_machine.id,
            account=self.account.name,
            domainid=self.account.domainid)
        self.assertEqual(isinstance(virtual_machines, list), True,
                         "Check list response returns a valid list")
        self.assertNotEqual(len(virtual_machines), 0,
                            "Check list virtual machines response")
        for virtual_machine in virtual_machines:
            self.assertEqual(virtual_machine.state, 'Running',
                             "Check list VM response for Running state")
        self.assertTrue(
            is_snapshot_on_nfs(self.apiclient, self.dbclient, self.config,
                               self.zone.id, snapshot_uuid))
        return