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
    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
    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
示例#4
0
    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
        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"])
        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 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
    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
    def test_01_disable_enable_pod(self):
        """disable enable Pod
            1. Disable pod and verify following things:
                For admin user:
                    -- Should be able to create new vm, snapshot,
                            volume,template,iso in the same pod
                For Non-admin user:
                    -- Should not be able to create new vm, snapshot,
                            volume,template,iso in the same pod
            2. Enable the above disabled pod and verify that:
                -All users should be able to create new vm, snapshot,
                volume,template,iso in the same pod
            3. Try to delete the pod and it should fail with error message:
                - "The pod is not deletable because there are servers
                running in this pod"

        """
        # Step 1
        vm_user = 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,
        )

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

        cmd = updatePod.updatePodCmd()
        cmd.id = self.pod.id
        cmd.allocationstate = DISABLED
        self.apiclient.updatePod(cmd)
        podList = Pod.list(self.apiclient, id=self.pod.id)

        self.assertEqual(podList[0].allocationstate, DISABLED, "Check if the pod is in disabled state")
        self.assertEqual(vm_user.state.lower(), "running", "Verify that the user vm is running")

        self.assertEqual(vm_root.state.lower(), "running", "Verify that the admin vm is running")

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

        root_volume = list_volumes(self.apiclient, virtualmachineid=vm_root.id, type="ROOT", listall=True)
        self.assertEqual(validateList(root_volume)[0], PASS, "list snapshot  is empty for volume id %s" % vm_root.id)

        if self.snapshotSupported:
            Snapshot.create(self.apiclient, root_volume[0].id)

            snapshots = list_snapshots(self.apiclient, volumeid=root_volume[0].id, listall=True)
            self.assertEqual(
                validateList(snapshots)[0], PASS, "list snapshot  is empty for volume id %s" % root_volume[0].id
            )

            Template.create_from_snapshot(self.apiclient, snapshots[0], self.testdata["privatetemplate"])

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

        Template.register(self.apiclient, self.testdata["privatetemplate"], zoneid=self.zone.id)

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

        Iso.create(
            self.apiclient,
            self.testdata["iso2"],
            zoneid=self.zone.id,
            account=self.admin_account.name,
            domainid=self.admin_account.domainid,
        )

        with self.assertRaises(Exception):
            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,
            )

        root_volume = list_volumes(self.userapiclient, virtualmachineid=vm_user.id, type="ROOT", listall=True)

        self.assertEqual(validateList(root_volume)[0], PASS, "list volume  is empty for volume id %s" % vm_user.id)
        if self.snapshotSupported:
            Snapshot.create(self.userapiclient, root_volume[0].id)

        Template.register(self.userapiclient, self.testdata["privatetemplate"], zoneid=self.zone.id)

        Volume.create(
            self.userapiclient,
            self.testdata["volume"],
            zoneid=self.zone.id,
            account=self.account.name,
            domainid=self.account.domainid,
            diskofferingid=self.disk_offering.id,
        )

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

        # Step 2
        cmd.allocationstate = ENABLED
        self.apiclient.updatePod(cmd)
        podList = Pod.list(self.apiclient, id=self.pod.id)

        self.assertEqual(podList[0].allocationstate, ENABLED, "Check if the pod is in enabled state")

        root_vm_new = VirtualMachine.create(
            self.apiclient,
            self.testdata["small"],
            templateid=self.template.id,
            accountid=self.admin_account.name,
            domainid=self.admin_account.domainid,
            serviceofferingid=self.service_offering.id,
            zoneid=self.zone.id,
        )
        self.assertEqual(
            root_vm_new.state.lower(),
            "running",
            "Verify that admin should be able \
                                    to create new VM",
        )

        if self.snapshotSupported:
            Snapshot.create(self.apiclient, root_volume[0].id)

            snapshots = list_snapshots(self.apiclient, volumeid=root_volume[0].id, listall=True)

            self.assertEqual(
                validateList(snapshots)[0], PASS, "list snapshot  is empty for volume id %s" % root_volume[0].id
            )

            Template.create_from_snapshot(self.apiclient, snapshots[0], self.testdata["privatetemplate"])

        Template.register(self.apiclient, self.testdata["privatetemplate"], zoneid=self.zone.id)

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

        Iso.create(
            self.apiclient,
            self.testdata["iso2"],
            zoneid=self.zone.id,
            account=self.admin_account.name,
            domainid=self.admin_account.domainid,
        )

        # Non root user
        user_vm_new = 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,
        )
        self.assertEqual(user_vm_new.state.lower(), "running", "Verify that admin should create new VM")

        if self.snapshotSupported:
            Snapshot.create(self.userapiclient, root_volume[0].id)

            snapshots = list_snapshots(self.userapiclient, volumeid=root_volume[0].id, listall=True)
            self.assertEqual(
                validateList(snapshots)[0], PASS, "list snapshot  is empty for volume id %s" % root_volume[0].id
            )

        Template.register(self.userapiclient, self.testdata["privatetemplate"], zoneid=self.zone.id)

        Volume.create(
            self.userapiclient,
            self.testdata["volume"],
            zoneid=self.zone.id,
            account=self.account.name,
            domainid=self.account.domainid,
            diskofferingid=self.disk_offering.id,
        )

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

        user_vm_new.delete(self.apiclient)
        # Step 3
        # Deletion of zone should fail if resources are running on the zone
        with self.assertRaises(Exception):
            self.pod.delete(self.apiclient)

        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
示例#9
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)
    def test_01_disable_enable_zone(self):
        """disable enable zone
            1. Disable zone and verify following things:
                For admin user:
                    1. Should be create to start/stop exsiting vms
                    2. Should be create to deploy new vm, snapshot,volume,
                       template,iso in the same zone
                For Non-admin user:
                    1. Should be create to start/stop exsiting vms
                    2. Should not be create to deploy new vm, snapshot,volume,
                       template,iso in the same zone
            2. Enable the above disabled zone and verify that:
                -All users should be create to deploy new vm,
                    snapshot,volume,template,iso in the same zone
            3. Try to delete the zone and it should fail with error message:
                -"The zone is not deletable because there are
                    servers running in this zone"
        """
        # Step 1
        vm_user = 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
        )

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

        cmd = updateZone.updateZoneCmd()
        cmd.id = self.zone.id
        cmd.allocationstate = DISABLED
        self.apiclient.updateZone(cmd)
        zoneList = Zone.list(self.apiclient, id=self.zone.id)

        self.assertEqual(zoneList[0].allocationstate,
                         DISABLED,
                         "Check if the zone is in disabled state"
                         )

        # Both user and admin vms shoul be running
        self.assertEqual(vm_user.state,
                         RUNNING,
                         "Verify that the user vm is running")

        self.assertEqual(vm_root.state,
                         RUNNING,
                         "Verify that the admin vm is running")

        vm_root.stop(self.apiclient)
        vm_user.stop(self.apiclient)

        root_state = self.dbclient.execute(
            "select state from vm_instance where name='%s'" %
            vm_root.name)[0][0]

        user_state = self.dbclient.execute(
            "select state from vm_instance where name='%s'" %
            vm_user.name)[0][0]

        self.assertEqual(root_state,
                         STOPPED,
                         "verify that vm is Stopped")

        self.assertEqual(user_state,
                         STOPPED,
                         "verify that vm is stopped")

        root_volume = list_volumes(
            self.userapiclient,
            virtualmachineid=vm_root.id,
            type='ROOT',
            listall=True
        )

        snap = Snapshot.create(
            self.apiclient,
            root_volume[0].id)

        self.assertNotEqual(snap,
                            None,
                            "Verify that admin should be \
                                    able to create snapshot")

        snapshots = list_snapshots(
            self.apiclient,
            volumeid=root_volume[0].id,
            listall=True)

        template_from_snapshot = Template.create_from_snapshot(
            self.apiclient,
            snapshots[0],
            self.testdata["privatetemplate"])

        self.assertNotEqual(
            template_from_snapshot,
            None,
            "Verify that admin should be able to create template"
        )

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

        template_regis = Template.register(
            self.apiclient,
            self.testdata["privatetemplate"],
            zoneid=self.zone.id)

        self.assertNotEqual(
            template_regis,
            None,
            "Check if template gets created"
        )
        self.assertNotEqual(
            template_from_snapshot,
            None,
            "Check if template gets created"
        )

        data_volume = 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.assertNotEqual(
            data_volume,
            None,
            "Check if volume gets created"
        )

        ISO = Iso.create(
            self.apiclient,
            self.testdata["iso2"],
            zoneid=self.zone.id,
            account=self.account.name,
            domainid=self.account.domainid,
        )

        self.assertNotEqual(
            ISO,
            None,
            "Check if volume gets created"
        )
        # non-admin user should fail to create vm, snap, temp etc
        with self.assertRaises(Exception):
            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
                                  )

        root_volume = list_volumes(
            self.userapiclient,
            virtualmachineid=vm_user.id,
            type='ROOT',
            listall=True
        )

        with self.assertRaises(Exception):
            snap = Snapshot.create(
                self.userapiclient,
                root_volume[0].id)

        with self.assertRaises(Exception):
            Template.register(
                self.userapiclient,
                self.testdata["privatetemplate"],
                zoneid=self.zone.id)

        with self.assertRaises(Exception):
            Volume.create(
                self.userapiclient,
                self.testdata["volume"],
                zoneid=self.zone.id,
                account=self.account.name,
                domainid=self.account.domainid,
                diskofferingid=self.disk_offering.id
            )

        with self.assertRaises(Exception):
            ISO = Iso.create(
                self.userapiclient,
                self.testdata["iso2"],
                zoneid=self.zone.id,
                account=self.account.name,
                domainid=self.account.domainid,
            )

        # Step 2
        cmd.allocationstate = ENABLED
        self.apiclient.updateZone(cmd)

        # After enabling the zone all users should be able to add new VM,
        # volume, template and iso

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

        self.assertNotEqual(root_vm_new,
                            None,
                            "Verify that admin should create new VM")

        snap = Snapshot.create(
            self.apiclient,
            root_volume[0].id)

        self.assertNotEqual(snap,
                            None,
                            "Verify that admin should snashot")

        snapshots = list_snapshots(
            self.apiclient,
            volumeid=root_volume[0].id,
            listall=True)

        template_from_snapshot = Template.create_from_snapshot(
            self.apiclient,
            snapshots[0],
            self.testdata["privatetemplate"])

        self.assertNotEqual(
            template_from_snapshot,
            None,
            "Check if template gets created"
        )

        template_regis = Template.register(
            self.apiclient,
            self.testdata["privatetemplate"],
            zoneid=self.zone.id)

        self.assertNotEqual(
            template_regis,
            None,
            "Check if template gets created"
        )
        self.assertNotEqual(
            template_from_snapshot,
            None,
            "Check if template gets created"
        )

        data_volume = 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.assertNotEqual(
            data_volume,
            None,
            "Check if volume gets created"
        )

        ISO = Iso.create(
            self.apiclient,
            self.testdata["iso2"],
            zoneid=self.zone.id,
            account=self.account.name,
            domainid=self.account.domainid,
        )

        self.assertNotEqual(
            ISO,
            None,
            "Check if volume gets created"
        )
        root_vm_new.delete(self.apiclient)
        # Non root user
        user_vm_new = 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
        )

        self.assertNotEqual(user_vm_new,
                            None,
                            "Verify that admin should create new VM")

        snap = Snapshot.create(
            self.userapiclient,
            root_volume[0].id)

        self.assertNotEqual(snap,
                            None,
                            "Verify that admin should snashot")

        snapshots = list_snapshots(
            self.userapiclient,
            volumeid=root_volume[0].id,
            listall=True)

        template_regis = Template.register(
            self.userapiclient,
            self.testdata["privatetemplate"],
            zoneid=self.zone.id)

        self.assertNotEqual(
            template_regis,
            None,
            "Check if template gets created"
        )
        self.assertNotEqual(
            template_from_snapshot,
            None,
            "Check if template gets created"
        )

        data_volume = Volume.create(
            self.userapiclient,
            self.testdata["volume"],
            zoneid=self.zone.id,
            account=self.account.name,
            domainid=self.account.domainid,
            diskofferingid=self.disk_offering.id
        )
        self.assertNotEqual(
            data_volume,
            None,
            "Check if volume gets created"
        )

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

        self.assertNotEqual(
            ISO,
            None,
            "Check if volume gets created"
        )
        user_vm_new.delete(self.apiclient)

        # Step 3
        # Deletion of zone should fail if vm,volume is present on the zone
        with self.assertRaises(Exception):
            self.zone.delete(self.apiclient)

        return
    def test_01_create_template_snampshot(self):

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

        return
    def test_01_create_template_snampshot(self):

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

        return
示例#13
0
    def test_02_template_permissions(self):
        """
        @Desc: Test to create Public Template by registering or by snapshot and volume when
        Global parameter 'allow.public.user.template' is set to  False
        @steps:
        1.Set Global parameter 'allow.public.user.template' as False. Restart Management server
        2. Create a domain
        3. Create a domain admin and a domain user
        4. Create a vm as domain user
        5. take snapshot of root disk as user vm
        6. try to create public template from snapshot . It should fail
        7. stop the VM
        8. take the public template from volume. it should fail
        9. register a public template as a domain user . it should fail
        10. create a VM  as domain admin
        11. create a snapshot of root disk as domain admin
        12 create a public template of the snapshot .it should fail
        13. Register a public template as domain admin. it should fail
        14 Stop the vm as domain admin
        15. Create a template from volume as domain admin . it should fail

        """
        self.updateConfigurAndRestart("allow.public.user.templates", "false")

        user_account = Account.create(self.apiclient,
                                      self.testdata["account2"],
                                      admin=False,
                                      domainid=self.domain.id)
        admin_user = self.account.user[0]
        self.admin_api_client = self.testClient.getUserApiClient(
            admin_user.username, self.domain.name)
        user = user_account.user[0]
        self.user_api_client = self.testClient.getUserApiClient(
            user.username, self.domain.name)

        self.testdata["templates"]["ispublic"] = True
        # Register new public template as domain user
        # Exception should be raised for registering public template
        try:
            template = Template.register(self.user_api_client,
                                         self.testdata["templates"],
                                         zoneid=self.zone.id,
                                         account=user_account.name,
                                         domainid=user_account.domainid,
                                         hypervisor=self.hypervisor)
            self.updateConfigurAndRestart("allow.public.user.templates",
                                          "true")
            self.fail("Template creation passed for user")
        except CloudstackAPIException as e:
            self.assertRaises("Exception Raised : %s" % e)
        # Register new public template as domain admin
        # Exception should be raised for registering public template
        try:
            template = Template.register(self.admin_api_client,
                                         self.testdata["templates"],
                                         zoneid=self.zone.id,
                                         account=self.account.name,
                                         domainid=self.account.domainid,
                                         hypervisor=self.hypervisor)
            self.updateConfigurAndRestart("allow.public.user.templates",
                                          "true")
            self.fail("Template creation passed for domain admin")
        except CloudstackAPIException as e:
            self.assertRaises("Exception Raised : %s" % e)

        if self.hypervisor.lower() in ['hyperv', 'lxc']:
            self.updateConfigurAndRestart("allow.public.user.templates",
                                          "true")
            return
        else:
            user_vm_created = VirtualMachine.create(
                self.user_api_client,
                self.testdata["virtual_machine"],
                accountid=user_account.name,
                domainid=user_account.domainid,
                serviceofferingid=self.service_offering.id,
            )
            self.assertIsNotNone(user_vm_created, "VM creation failed")
            # Get the Root disk of VM
            volume = list_volumes(self.user_api_client,
                                  virtualmachineid=user_vm_created.id,
                                  type='ROOT',
                                  listall=True)
            snapshot_created = Snapshot.create(self.user_api_client,
                                               volume[0].id,
                                               account=user_account.name,
                                               domainid=user_account.domainid)
            self.assertIsNotNone(snapshot_created, "Snapshot creation failed")
            self.debug("Creating a template from snapshot: %s" %
                       snapshot_created.id)
            #
            # Generate public template from the snapshot
            self.testdata["template"]["ispublic"] = True
            try:
                user_template = Template.create_from_snapshot(
                    self.user_api_client, snapshot_created,
                    self.testdata["template"])
                self.updateConfigurAndRestart("allow.public.user.templates",
                                              "true")
                self.fail(
                    "Template creation passed from snapshot for domain user")
            except CloudstackAPIException as e:
                self.assertRaises("Exception Raised : %s" % e)

            VirtualMachine.stop(user_vm_created, self.user_api_client)
            list_stopped_vms_after = VirtualMachine.list(
                self.user_api_client,
                listall=self.testdata["listall"],
                domainid=user_account.domainid,
                state="Stopped")
            status = validateList(list_stopped_vms_after)
            self.assertEqual(PASS, status[0],
                             "Stopped VM is not in Stopped state")
            try:
                user_template = Template.create(self.user_api_client,
                                                self.testdata["template"],
                                                volume[0].id)
                self.updateConfigurAndRestart("allow.public.user.templates",
                                              "true")
                self.fail(
                    "Template creation passed from volume for domain user")
            except CloudstackAPIException as e:
                self.assertRaises("Exception Raised : %s" % e)

            admin_vm_created = VirtualMachine.create(
                self.admin_api_client,
                self.testdata["virtual_machine"],
                accountid=self.account.name,
                domainid=self.account.domainid,
                serviceofferingid=self.service_offering.id,
            )
            self.assertIsNotNone(admin_vm_created, "VM creation failed")
            # Get the Root disk of VM
            volume = list_volumes(self.admin_api_client,
                                  virtualmachineid=admin_vm_created.id,
                                  type='ROOT',
                                  listall=True)
            snapshot_created = Snapshot.create(self.admin_api_client,
                                               volume[0].id,
                                               account=self.account.name,
                                               domainid=self.account.domainid)
            self.assertIsNotNone(snapshot_created, "Snapshot creation failed")
            self.debug("Creating a template from snapshot: %s" %
                       snapshot_created.id)
            #
            #    Generate public template from the snapshot
            try:
                admin_template = Template.create_from_snapshot(
                    self.admin_api_client, snapshot_created,
                    self.testdata["template"])
                self.updateConfigurAndRestart("allow.public.user.templates",
                                              "true")
                self.fail(
                    "Template creation passed from snapshot for domain admin")
            except CloudstackAPIException as e:
                self.assertRaises("Exception Raised : %s" % e)

            VirtualMachine.stop(admin_vm_created, self.admin_api_client)
            list_stopped_vms_after = VirtualMachine.list(
                self.admin_api_client,
                listall=self.testdata["listall"],
                domainid=self.account.domainid,
                state="Stopped")
            status = validateList(list_stopped_vms_after)
            self.assertEqual(PASS, status[0],
                             "Stopped VM is not in Stopped state")
            try:
                admin_template = Template.create(self.admin_api_client,
                                                 self.testdata["template"],
                                                 volume[0].id)
                self.updateConfigurAndRestart("allow.public.user.templates",
                                              "true")
                self.fail(
                    "Template creation passed from volume for domain admin")
            except CloudstackAPIException as e:
                self.assertRaises("Exception Raised : %s" % e)

            self.updateConfigurAndRestart("allow.public.user.templates",
                                          "true")
        return
    def test_04_try_delete_primary_with_template(self):
        virtual_machine = VirtualMachine.create(
            self.apiclient, {"name": "StorPool-%s" % uuid.uuid4()},
            zoneid=self.zone.id,
            templateid=self.template.id,
            serviceofferingid=self.serviceOfferings.id,
            hypervisor=self.hypervisor,
            rootdisksize=10)

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

        volume = volume[0]

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

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

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

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

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

        Template.delete(template, self.apiclient)
def checkIntegrityOfSnapshot(
        self, snapshotsToRestore, checksumToCompare, disk_type=ROOT):
    """
    Check integrity of snapshot created of ROOT or DATA Disk:

    If ROOT Disk: Deploy a Vm from a template created from the snapshot
                  and checking the contents of the ROOT disk.
    If DATA Disk: Users can create a volume from the snapshot.
                  The volume can then be mounted to a VM and files
                  recovered as needed.

    Inputs:
    1. snapshotsToRestore: Snapshots whose integrity is
                           to be checked.

    2. checksumToCompare:  The contents of ROOT Disk to be compared.

    3. disk_type:          The type of disk - ROOT or DATA Disk
                           of which snapshot was created.

    """
    if disk_type == ROOT:
        # Create template from snapshot
        template_from_snapshot = Template.create_from_snapshot(
            self.apiclient,
            snapshotsToRestore,
            self.testdata["template_2"])

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

        # Deploy VM
        vm_from_temp = VirtualMachine.create(
            self.apiclient,
            self.testdata["small"],
            templateid=template_from_snapshot.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"
        )

        # Verify contents of ROOT disk match with snapshot

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

        vm_from_temp.delete(self.apiclient)
        template_from_snapshot.delete(self.apiclient)
    else:
        volumeFormSnap = Volume.create_from_snapshot(
            self.apiclient,
            snapshotsToRestore.id,
            self.testdata["volume"],
            account=self.account.name,
            domainid=self.account.domainid,
            zoneid=self.zone.id
        )

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

        temp_vm.reboot(self.apiclient)

        compareChecksum(
            self.apiclient,
            self.testdata,
            checksumToCompare,
            "datadiskdevice_1",
            temp_vm
        )

        temp_vm.delete(self.apiclient)
        volumeFormSnap.delete(self.apiclient)

    return
    def test_01_disable_enable_cluster(self):
        """disable enable cluster
            1. Disable cluster and verify following things:
                For admin user:
                     --Should be able to create new vm, snapshot,
                     volume,template,iso in the same cluster
                For Non-admin user:
                     --Should not be able create new vm, snapshot,
                     volume,template,iso in the same cluster
            2. Enable the above disabled cluster and verify that:
                -All users should be create to deploy new vm, snapshot,
                volume,template,iso in the same cluster
            3. Disable the managestate of the cluster and verify that:
                --Host in the cluster should get disconnected
                --VM's in the cluster are ping-able and ssh to
                --Creation of new VM in the cluster should fail
            4. Enable the managestate of the cluster and verify that:
                --Hosts in the cluster get connected
                --VM's in the cluster are accessible
            5. Try to delete the cluster and it should fail with error message:
                -"The cluster is not deletable because there are
                servers running in this cluster"

        """
        # Step 1
        vm_user = 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,
        )

        self.vm_list.append(vm_user)

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

        self.vm_list.append(vm_root)

        cmd = updateCluster.updateClusterCmd()
        cmd.id = self.cluster.id
        cmd.allocationstate = DISABLED
        self.apiclient.updateCluster(cmd)
        clusterList = Cluster.list(self.apiclient, id=self.cluster.id)

        self.assertEqual(clusterList[0].allocationstate, DISABLED, "Check if the cluster is in disabled state")

        # Verify the existing vms should be running
        self.assertEqual(vm_user.state.lower(), "running", "Verify that the user vm is running")

        self.assertEqual(vm_root.state.lower(), "running", "Verify that the root vm is running")

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

        root_volume = list_volumes(self.apiclient, virtualmachineid=vm_root.id, type="ROOT", listall=True)

        self.assertEqual(
            validateList(root_volume)[0], PASS, "list root volume response is empty for volume id %s" % vm_root.id
        )

        if self.snapshotSupported:
            Snapshot.create(self.apiclient, root_volume[0].id)

            snapshots = list_snapshots(self.apiclient, volumeid=root_volume[0].id, listall=True)
            self.assertEqual(
                validateList(snapshots)[0], PASS, "list snapshot  is empty for volume id %s" % root_volume[0].id
            )

            Template.create_from_snapshot(self.apiclient, snapshots[0], self.testdata["privatetemplate"])

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

        Template.register(self.apiclient, self.testdata["privatetemplate"], zoneid=self.zone.id)

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

        Iso.create(
            self.apiclient,
            self.testdata["iso2"],
            zoneid=self.zone.id,
            account=self.admin_account.name,
            domainid=self.admin_account.domainid,
        )

        # non-admin user should fail to create vm, snap, temp etc
        with self.assertRaises(Exception):
            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,
            )

        root_volume = list_volumes(self.userapiclient, virtualmachineid=vm_user.id, type="ROOT", listall=True)

        self.assertEqual(
            validateList(root_volume)[0], PASS, "list root volume response is empty for volume id %s" % vm_user.id
        )

        if self.snapshotSupported:
            Snapshot.create(self.userapiclient, root_volume[0].id)

        Template.register(self.userapiclient, self.testdata["privatetemplate"], zoneid=self.zone.id)

        Volume.create(
            self.userapiclient,
            self.testdata["volume"],
            zoneid=self.zone.id,
            account=self.account.name,
            domainid=self.account.domainid,
            diskofferingid=self.disk_offering.id,
        )

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

        # Step 2
        cmd.allocationstate = ENABLED
        self.apiclient.updateCluster(cmd)
        clusterList = Cluster.list(self.apiclient, id=self.cluster.id)
        self.assertEqual(clusterList[0].allocationstate, ENABLED, "Check if the cluster is in disabled state")

        # After enabling the zone all users should be able to add new VM,
        # volume, templatee and iso

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

        self.assertEqual(root_vm_new.state.lower(), "running", "Verify that admin should create new VM")

        if self.snapshotSupported:
            Snapshot.create(self.apiclient, root_volume[0].id)

        # Non root user
        user_vm_new = 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,
        )

        self.assertEqual(user_vm_new.state.lower(), "running", "Verify that admin should create new VM")

        if self.snapshotSupported:
            Snapshot.create(self.userapiclient, root_volume[0].id)

        # Step 3

        cmd = updateCluster.updateClusterCmd()
        cmd.id = self.cluster.id
        cmd.managedstate = "Unmanaged"
        self.apiclient.updateCluster(cmd)
        clusterList = Cluster.list(self.apiclient, id=self.cluster.id)

        self.assertEqual(
            clusterList[0].managedstate.lower(), "unmanaged", "Check if the cluster is in unmanaged  state"
        )
        # Hosts in the cluster takes some time to go into disconnected state
        time.sleep(60)
        hostList = Host.list(self.apiclient, clusterid=self.cluster.id)

        for host in hostList:
            self.assertEqual(host.state.lower(), "disconnected", "Check if host in the cluster gets disconnected")
        exception_list = []
        for vm in self.vm_list:
            try:
                SshClient(vm.ssh_ip, vm.ssh_port, vm.username, vm.password)

            except Exception as e:
                exception_list.append(e)

        self.assertEqual(len(exception_list), 0, "Check if vm's are accesible")

        # non-admin user should fail to create vm, snap, temp etc
        with self.assertRaises(Exception):
            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,
            )

        root_volume = list_volumes(self.userapiclient, virtualmachineid=vm_user.id, type="ROOT", listall=True)

        if self.snapshotSupported:
            with self.assertRaises(Exception):
                Snapshot.create(self.userapiclient, root_volume[0].id)

        Template.register(self.userapiclient, self.testdata["privatetemplate"], zoneid=self.zone.id)

        # Step 4
        cmd.managedstate = "Managed"
        self.apiclient.updateCluster(cmd)
        # After changing the cluster's managestate to Managed hosts in the
        # cluster takes some time to come back to Up state
        time.sleep(120)
        hostList = Host.list(self.apiclient, clusterid=self.cluster.id)
        for host in hostList:
            self.assertEqual(host.state.lower(), "up", "Check if host in the cluster gets up")

        vm_root.stop(self.apiclient)
        vm_user.stop(self.apiclient)
        root_state = self.dbclient.execute("select state from vm_instance where name='%s'" % vm_root.name)[0][0]

        user_state = self.dbclient.execute("select state from vm_instance where name='%s'" % vm_user.name)[0][0]

        self.assertEqual(root_state, "Stopped", "verify that vm should stop")

        self.assertEqual(user_state, "Stopped", "verify that vm should stop")

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

        self.assertEqual(root_vm_new.state.lower(), "running", "Verify that admin should create new VM")

        # Step 5
        # Deletion of zone should fail if resources are running on the zone
        with self.assertRaises(Exception):
            self.pod.delete(self.apiclient)

        return
示例#17
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
示例#18
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

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

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

        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
示例#19
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
示例#20
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

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

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

        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
示例#21
0
    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
示例#22
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

        volumes = Volume.list(self.apiclient,
                              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(self.apiclient,
                                   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(self.apiclient, snapshot,
                                                 self.services["template"])
        self.cleanup.append(template)
        # Verify created template
        templates = Template.list(
                                self.apiclient,
                                templatefilter=\
                                self.services["template"]["templatefilter"],
                                id=template.id
                                )
        self.assertNotEqual(templates, None,
                            "Check if result exists in list item call")

        self.assertEqual(templates[0].id, template.id,
                         "Check new template id in list resources call")
        self.debug("Deploying a VM from template: %s" % template.id)
        # 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.cleanup.append(virtual_machine)

        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 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
示例#23
0
    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
        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"]
                                    )
        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
示例#24
0
def checkIntegrityOfSnapshot(self,
                             snapshotsToRestore,
                             checksumToCompare,
                             disk_type=ROOT):
    """
    Check integrity of snapshot created of ROOT or DATA Disk:

    If ROOT Disk: Deploy a Vm from a template created from the snapshot
                  and checking the contents of the ROOT disk.
    If DATA Disk: Users can create a volume from the snapshot.
                  The volume can then be mounted to a VM and files
                  recovered as needed.

    Inputs:
    1. snapshotsToRestore: Snapshots whose integrity is
                           to be checked.

    2. checksumToCompare:  The contents of ROOT Disk to be compared.

    3. disk_type:          The type of disk - ROOT or DATA Disk
                           of which snapshot was created.

    """
    if disk_type == ROOT:
        # Create template from snapshot
        template_from_snapshot = Template.create_from_snapshot(
            self.apiclient, snapshotsToRestore, self.testdata["template_2"])

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

        # Deploy VM
        vm_from_temp = VirtualMachine.create(
            self.apiclient,
            self.testdata["small"],
            templateid=template_from_snapshot.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")

        # Verify contents of ROOT disk match with snapshot

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

        vm_from_temp.delete(self.apiclient)
        template_from_snapshot.delete(self.apiclient)
    else:
        volumeFormSnap = Volume.create_from_snapshot(
            self.apiclient,
            snapshotsToRestore.id,
            self.testdata["volume"],
            account=self.account.name,
            domainid=self.account.domainid,
            zoneid=self.zone.id)

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

        temp_vm.reboot(self.apiclient)

        compareChecksum(self.apiclient, self.testdata, checksumToCompare,
                        "datadiskdevice_1", temp_vm)

        temp_vm.delete(self.apiclient)
        volumeFormSnap.delete(self.apiclient)

    return
    def test_02_template_permissions(self):
        """
        @Desc: Test to create Public Template by registering or by snapshot and volume when
        Global parameter 'allow.public.user.template' is set to  False
        @steps:
        1.Set Global parameter 'allow.public.user.template' as False. Restart Management server
        2. Create a domain
        3. Create a domain admin and a domain user
        4. Create a vm as domain user
        5. take snapshot of root disk as user vm
        6. try to create public template from snapshot . It should fail
        7. stop the VM
        8. take the public template from volume. it should fail
        9. register a public template as a domain user . it should fail
        10. create a VM  as domain admin
        11. create a snapshot of root disk as domain admin
        12 create a public template of the snapshot .it should fail
        13. Register a public template as domain admin. it should fail
        14 Stop the vm as domain admin
        15. Create a template from volume as domain admin . it should fail

        """
        self.updateConfigurAndRestart("allow.public.user.templates", "false")
        
        user_account = Account.create(
            self.apiclient,
            self.testdata["account2"],
            admin=False,
            domainid=self.domain.id
        )
        admin_user = self.account.user[0]
        self.admin_api_client = self.testClient.getUserApiClient(
            admin_user.username,
            self.domain.name)
        user = user_account.user[0]
        self.user_api_client = self.testClient.getUserApiClient(
            user.username,
            self.domain.name)

        self.testdata["templates"]["ispublic"] = True
        # Register new public template as domain user
        # Exception should be raised for registering public template
        try:
            template = Template.register(
                self.user_api_client,
                self.testdata["templates"],
                zoneid=self.zone.id,
                account=user_account.name,
                domainid=user_account.domainid,
                hypervisor=self.hypervisor
            )
            self.updateConfigurAndRestart("allow.public.user.templates", "true")
            self.fail("Template creation passed for user")
        except CloudstackAPIException  as e:
            self.assertRaises("Exception Raised : %s" % e)
        # Register new public template as domain admin
        # Exception should be raised for registering public template
        try:
            template = Template.register(
                self.admin_api_client,
                self.testdata["templates"],
                zoneid=self.zone.id,
                account=self.account.name,
                domainid=self.account.domainid,
                hypervisor=self.hypervisor
            )
            self.updateConfigurAndRestart("allow.public.user.templates", "true")
            self.fail("Template creation passed for domain admin")
        except CloudstackAPIException  as e:
            self.assertRaises("Exception Raised : %s" % e)

        user_vm_created = VirtualMachine.create(
            self.user_api_client,
            self.testdata["virtual_machine"],
            accountid=user_account.name,
            domainid=user_account.domainid,
            serviceofferingid=self.service_offering.id,
        )
        self.assertIsNotNone(user_vm_created,
                             "VM creation failed"
        )
        # Get the Root disk of VM
        volume = list_volumes(
            self.user_api_client,
            virtualmachineid=user_vm_created.id,
            type='ROOT',
            listall=True
        )
        snapshot_created = Snapshot.create(
            self.user_api_client,
            volume[0].id,
            account=user_account.name,
            domainid=user_account.domainid
        )
        self.assertIsNotNone(
            snapshot_created,
            "Snapshot creation failed"
        )
        self.debug("Creating a template from snapshot: %s" % snapshot_created.id)
        #
        # Generate public template from the snapshot
        self.testdata["template"]["ispublic"] = True
        try:
            user_template = Template.create_from_snapshot(
                self.user_api_client,
                snapshot_created,
                self.testdata["template"]
            )
            self.updateConfigurAndRestart("allow.public.user.templates", "true")
            self.fail("Template creation passed from snapshot for domain user")
        except CloudstackAPIException  as e:
            self.assertRaises("Exception Raised : %s" % e)

        VirtualMachine.stop(user_vm_created, self.user_api_client)
        list_stopped_vms_after = VirtualMachine.list(
            self.user_api_client,
            listall=self.testdata["listall"],
            domainid=user_account.domainid,
            state="Stopped")
        status = validateList(list_stopped_vms_after)
        self.assertEquals(
            PASS,
            status[0],
            "Stopped VM is not in Stopped state"
        )
        try:
            user_template = Template.create(
                self.user_api_client, self.testdata["template"],
                volume[0].id
            )
            self.updateConfigurAndRestart("allow.public.user.templates", "true")
            self.fail("Template creation passed from volume for domain user")
        except CloudstackAPIException  as e:
            self.assertRaises("Exception Raised : %s" % e)

        admin_vm_created = VirtualMachine.create(
            self.admin_api_client,
            self.testdata["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
        )
        self.assertIsNotNone(
            admin_vm_created,
            "VM creation failed"
        )
        # Get the Root disk of VM
        volume = list_volumes(
            self.admin_api_client,
            virtualmachineid=admin_vm_created.id,
            type='ROOT',
            listall=True
        )
        snapshot_created = Snapshot.create(
            self.admin_api_client,
            volume[0].id,
            account=self.account.name,
            domainid=self.account.domainid
        )
        self.assertIsNotNone(
            snapshot_created,
            "Snapshot creation failed"
        )
        self.debug("Creating a template from snapshot: %s" % snapshot_created.id)
        #
        #    Generate public template from the snapshot
        try:
            admin_template = Template.create_from_snapshot(
                self.admin_api_client,
                snapshot_created,
                self.testdata["template"]
            )
            self.updateConfigurAndRestart("allow.public.user.templates", "true")
            self.fail("Template creation passed from snapshot for domain admin")
        except CloudstackAPIException  as e:
            self.assertRaises("Exception Raised : %s" % e)

        VirtualMachine.stop(admin_vm_created, self.admin_api_client)
        list_stopped_vms_after = VirtualMachine.list(
            self.admin_api_client,
            listall=self.testdata["listall"],
            domainid=self.account.domainid,
            state="Stopped")
        status = validateList(list_stopped_vms_after)
        self.assertEquals(
            PASS,
            status[0],
            "Stopped VM is not in Stopped state"
        )
        try:
            admin_template = Template.create(
                self.admin_api_client, self.testdata["template"],
                volume[0].id
            )
            self.updateConfigurAndRestart("allow.public.user.templates", "true")
            self.fail("Template creation passed from volume for domain admin")
        except CloudstackAPIException  as e:
            self.assertRaises("Exception Raised : %s" % e)

        self.updateConfigurAndRestart("allow.public.user.templates", "true")
        return
    def test_01_disable_enable_zone(self):
        """disable enable zone
            1. Disable zone and verify following things:
                For admin user:
                    1. Should be create to start/stop exsiting vms
                    2. Should be create to deploy new vm, snapshot,volume,
                       template,iso in the same zone
                For Non-admin user:
                    1. Should be create to start/stop exsiting vms
                    2. Should not be create to deploy new vm, snapshot,volume,
                       template,iso in the same zone
            2. Enable the above disabled zone and verify that:
                -All users should be create to deploy new vm,
                    snapshot,volume,template,iso in the same zone
            3. Try to delete the zone and it should fail with error message:
                -"The zone is not deletable because there are
                    servers running in this zone"
        """
        # Step 1
        vm_user = 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,
        )

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

        cmd = updateZone.updateZoneCmd()
        cmd.id = self.zone.id
        cmd.allocationstate = DISABLED
        self.apiclient.updateZone(cmd)
        zoneList = Zone.list(self.apiclient, id=self.zone.id)

        self.assertEqual(zoneList[0].allocationstate, DISABLED, "Check if the zone is in disabled state")

        # Both user and admin vms shoul be running
        self.assertEqual(vm_user.state.lower(), "running", "Verify that the user vm is running")

        self.assertEqual(vm_root.state.lower(), "running", "Verify that the admin vm is running")

        vm_root.stop(self.apiclient)
        vm_user.stop(self.apiclient)

        root_state = self.dbclient.execute("select state from vm_instance where name='%s'" % vm_root.name)[0][0]

        user_state = self.dbclient.execute("select state from vm_instance where name='%s'" % vm_user.name)[0][0]

        self.assertEqual(root_state.lower(), "stopped", "verify that vm is Stopped")

        self.assertEqual(user_state.lower(), "stopped", "verify that vm is stopped")

        root_volume = list_volumes(self.apiclient, virtualmachineid=vm_root.id, type="ROOT", listall=True)

        self.assertEqual(validateList(root_volume)[0], PASS, "list volume  is empty for vmid %s" % vm_root.id)
        root_vm_new = VirtualMachine.create(
            self.apiclient,
            self.testdata["small"],
            templateid=self.template.id,
            accountid=self.admin_account.name,
            domainid=self.admin_account.domainid,
            serviceofferingid=self.service_offering.id,
            zoneid=self.zone.id,
        )

        self.assertEqual(root_vm_new.state.lower(), "running", "Verify that admin should create new VM")

        if self.snapshotSupported:
            Snapshot.create(self.apiclient, root_volume[0].id)

            snapshots = list_snapshots(self.apiclient, volumeid=root_volume[0].id, listall=True)

            self.assertEqual(
                validateList(snapshots)[0], PASS, "list snapshot  is empty for volume id %s" % root_volume[0].id
            )

            Template.create_from_snapshot(self.apiclient, snapshots[0], self.testdata["privatetemplate"])

        builtin_info = get_builtin_template_info(self.apiclient, self.zone.id)
        self.testdata["privatetemplate"]["url"] = builtin_info[0]
        self.testdata["privatetemplate"]["hypervisor"] = builtin_info[1]
        self.testdata["privatetemplate"]["format"] = builtin_info[2]
        """
        //commenting it for now will uncomment  once expected behaviour is known
        Template.register(
            self.apiclient,
            self.testdata["privatetemplate"],
            zoneid=self.zone.id)
        """
        Volume.create(
            self.apiclient,
            self.testdata["volume"],
            zoneid=self.zone.id,
            account=self.admin_account.name,
            domainid=self.admin_account.domainid,
            diskofferingid=self.disk_offering.id,
        )
        """
        //commenting it for now will uncomment  once expected behaviour is known
        Iso.create(
            self.apiclient,
            self.testdata["iso2"],
            zoneid=self.zone.id,
            account=self.admin_account.name,
            domainid=self.admin_account.domainid,
        )
        """
        # non-admin user should fail to create vm, snap, temp etc
        with self.assertRaises(Exception):
            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,
            )

        root_volume = list_volumes(self.userapiclient, virtualmachineid=vm_user.id, type="ROOT", listall=True)
        self.assertEqual(validateList(root_volume)[0], PASS, "list volume  is empty for vmid id %s" % vm_user.id)

        if self.snapshotSupported:
            with self.assertRaises(Exception):
                Snapshot.create(self.userapiclient, root_volume[0].id)

        with self.assertRaises(Exception):
            Template.register(self.userapiclient, self.testdata["privatetemplate"], zoneid=self.zone.id)

        with self.assertRaises(Exception):
            Volume.create(
                self.userapiclient,
                self.testdata["volume"],
                zoneid=self.zone.id,
                account=self.account.name,
                domainid=self.account.domainid,
                diskofferingid=self.disk_offering.id,
            )

        with self.assertRaises(Exception):
            Iso.create(
                self.userapiclient,
                self.testdata["iso2"],
                zoneid=self.zone.id,
                account=self.account.name,
                domainid=self.account.domainid,
            )

        # Step 2
        cmd.allocationstate = ENABLED
        self.apiclient.updateZone(cmd)

        # After enabling the zone all users should be able to add new VM,
        # volume, template and iso

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

        self.assertEqual(root_vm_new.state.lower(), "running", "Verify that admin should create new VM")

        if self.snapshotSupported:
            Snapshot.create(self.apiclient, root_volume[0].id)

            snapshots = list_snapshots(self.apiclient, volumeid=root_volume[0].id, listall=True)

            self.assertEqual(
                validateList(snapshots)[0], PASS, "list snapshot  is empty for volume id %s" % root_volume[0].id
            )

            Template.create_from_snapshot(self.apiclient, snapshots[0], self.testdata["privatetemplate"])

        Template.register(self.apiclient, self.testdata["privatetemplate"], zoneid=self.zone.id)

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

        Iso.create(
            self.apiclient,
            self.testdata["iso2"],
            zoneid=self.zone.id,
            account=self.admin_account.name,
            domainid=self.admin_account.domainid,
        )

        # Non root user
        user_vm_new = 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,
        )

        self.assertEqual(user_vm_new.state.lower(), "running", "Verify that admin should create new VM")

        if self.snapshotSupported:
            Snapshot.create(self.userapiclient, root_volume[0].id)

            snapshots = list_snapshots(self.userapiclient, volumeid=root_volume[0].id, listall=True)

            self.assertEqual(
                validateList(snapshots)[0], PASS, "list snapshot  is empty for volume id %s" % root_volume[0].id
            )

        Template.register(self.userapiclient, self.testdata["privatetemplate"], zoneid=self.zone.id)

        Volume.create(
            self.userapiclient,
            self.testdata["volume"],
            zoneid=self.zone.id,
            account=self.account.name,
            domainid=self.account.domainid,
            diskofferingid=self.disk_offering.id,
        )
        Iso.create(
            self.userapiclient,
            self.testdata["iso2"],
            zoneid=self.zone.id,
            account=self.account.name,
            domainid=self.account.domainid,
        )

        # Step 3
        # Deletion of zone should fail if vm,volume is present on the zone
        with self.assertRaises(Exception):
            self.zone.delete(self.apiclient)

        return
示例#27
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
    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.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_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.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)
            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.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
            )

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

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

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

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

        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