Esempio n. 1
0
    def test_01_cluster_settings(self):
        """change cpu/mem.overprovisioning.factor at cluster level and
         verify the change """
        listHost = Host.list(self.apiclient,
                             id=self.deployVmResponse.hostid
                             )
        self.assertEqual(
            validateList(listHost)[0],
            PASS,
            "check list host response for host id %s" %
            self.deployVmResponse.hostid)
        Configurations.update(self.apiclient,
                              clusterid=listHost[0].clusterid,
                              name="mem.overprovisioning.factor",
                              value=2)

        Configurations.update(self.apiclient,
                              clusterid=listHost[0].clusterid,
                              name="cpu.overprovisioning.factor",
                              value=3)

        list_cluster = Cluster.list(self.apiclient,
                                    id=listHost[0].clusterid)
        self.assertEqual(
            validateList(list_cluster)[0],
            PASS,
            "check list cluster response for cluster id %s" %
            listHost[0].clusterid)
        self.assertEqual(int(list_cluster[0].cpuovercommitratio),
                         3,
                         "check the cpu overcommit value at cluster level ")

        self.assertEqual(int(list_cluster[0].memoryovercommitratio),
                         2,
                         "check memory overcommit value at cluster level")

        Configurations.update(self.apiclient,
                              clusterid=listHost[0].clusterid,
                              name="mem.overprovisioning.factor",
                              value=1)

        Configurations.update(self.apiclient,
                              clusterid=listHost[0].clusterid,
                              name="cpu.overprovisioning.factor",
                              value=1)
        list_cluster1 = Cluster.list(self.apiclient,
                                     id=listHost[0].clusterid)
        self.assertEqual(
            validateList(list_cluster1)[0],
            PASS,
            "check the list cluster response for id %s" %
            listHost[0].clusterid)
        self.assertEqual(int(list_cluster1[0].cpuovercommitratio),
                         1,
                         "check the cpu overcommit value at cluster level ")

        self.assertEqual(int(list_cluster1[0].memoryovercommitratio),
                         1,
                         "check memory overcommit value at cluster level")
    def test_Scale_VM(self):
        """
        @desc:
        1. Enable dynamic scaling in Global settings
        2. Register an CentOS 7 tempplate(with tools) and tick dynamic scaling
        3. Deploy VM with this template
        4.Start the VM and try to change service offering

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

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


        return
Esempio n. 3
0
    def test_01_verify_events_table(self):
        """ Test events table

        # 1. Deploy a VM.
        # 2. Take VM snapshot.
        # 3. Verify that events table records UUID of the volume in descrption
            instead of volume ID
        """
        # Step 1
        # Create VM
        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,
        )
        volumes_list = list_volumes(self.apiclient,
                                    virtualmachineid=vm.id,
                                    type='ROOT',
                                    listall=True)

        volume_list_validation = validateList(volumes_list)
        self.assertEqual(
            volume_list_validation[0], PASS,
            "volume list validation failed due to %s" %
            volume_list_validation[2])
        root_volume = volumes_list[0]

        # Step 2
        # Create snapshot of root volume
        snapshot = Snapshot.create(self.apiclient, root_volume.id)

        self.assertNotEqual(len(snapshot), 0,
                            "Check if snapshot gets created properly")

        # Step 3
        qresultset = self.dbclient.execute(
            "select  description from event where type='SNAPSHOT.CREATE' AND \
                        description like '%%%s%%'" % root_volume.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 if events table records UUID of the volume")

        return
 def test_03_attach_ISO_in_RHEL7OSVM(self):
     """
     @desc:Incorrect guest os mapping in vmware for Rhel7. Add a valid RHEL7 URL to execute this test case
     Step1 :Register an RHEL 7 template
     Step2 :Launch a VM
     Step3: Try to attach VMware Tools ISO
     Step4: Verify VMware tools ISO attached correctly
     """
     self.hypervisor = str(get_hypervisor_type(self.api_client)).lower()
     if self.hypervisor != "vmware":
         self.skipTest("This test can be run only on vmware")
     self.services["Rhel7template"][
         "url"] = "http://10.147.28.7/templates/rhel71.ova",
     template = Template.register(self.userapiclient,
                                  self.services["Rhel7template"],
                                  zoneid=self.zone.id,
                                  account=self.account.name,
                                  domainid=self.account.domainid,
                                  hypervisor=self.hypervisor)
     self.debug("Registered a template with format {} and id {}".format(
         self.services["Rhel7template"]["format"], template.id))
     template.download(self.userapiclient)
     self.cleanup.append(template)
     vm = VirtualMachine.create(self.userapiclient,
                                self.services["virtual_machine"],
                                accountid=self.account.name,
                                domainid=self.account.domainid,
                                serviceofferingid=self.service_offering.id,
                                templateid=template.id,
                                zoneid=self.zone.id)
     self.cleanup.append(vm)
     response = VirtualMachine.list(self.userapiclient, id=vm.id)
     status = validateList(response)
     self.assertEqual(status[0], PASS,
                      "list vm response returned invalid list")
     list_default_iso_response = list_isos(self.api_client,
                                           name="vmware-tools.iso",
                                           account="system",
                                           isready="true")
     status = validateList(list_default_iso_response)
     self.assertEqual(PASS, status[0], "ISO list is empty")
     self.debug("Registered a ISO with name {}".format(
         list_default_iso_response[0].name))
     try:
         vm.attach_iso(self.userapiclient, list_default_iso_response[0])
     except CloudstackAPIException as e:
         self.fail("Attached ISO failed : %s" % e)
     response = VirtualMachine.list(self.userapiclient, id=vm.id)
     status = validateList(response)
     self.assertEqual(status[0], PASS,
                      "list vm response returned invalid list")
     attachedIsoName = response[0].isoname
     self.assertEqual(attachedIsoName, "vmware-tools.iso",
                      "vmware-tools.iso not attached")
     return
    def test_01_test_vm_volume_snapshot(self):
        """
        @Desc: Test that Volume snapshot for root volume is allowed
        when VM snapshot is present for the VM
        @Steps:
        1: Deploy a VM and create a VM snapshot for VM
        2: Try to create snapshot for the root volume of the VM,
        It should not fail
        """

        # Creating Virtual Machine
        virtual_machine = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
        )

        VmSnapshot.create(
            self.apiclient,
            virtual_machine.id,
        )

        volumes = Volume.list(self.apiclient,
                              virtualmachineid=virtual_machine.id,
                              type="ROOT",
                              listall=True)

        self.assertEqual(validateList(volumes)[0], PASS,
                "Failed to get root volume of the VM")

        snapshot = Snapshot.create(
            self.apiclient,
            volumes[0].id,
            account=self.account.name,
            domainid=self.account.domainid
        )
        self.debug("Snapshot created: ID - %s" % snapshot.id)
        snapshots = list_snapshots(
            self.apiclient,
            id=snapshot.id
        )
        self.assertEqual(
            validateList(snapshots)[0],
            PASS,
            "Invalid snapshot list"
        )
        self.assertEqual(
            snapshots[0].id,
            snapshot.id,
            "Check resource id in list resources call"
        )
        return
Esempio n. 6
0
 def test_01_migrateVolume(self):
     """
     @Desc:Volume is not retaining same uuid when migrating from one
           storage to another.
     Step1:Create a volume/data disk
     Step2:Verify UUID of the volume
     Step3:Migrate the volume to another primary storage within
           the cluster
     Step4:Migrating volume to new primary storage should succeed
     Step5:volume UUID should not change even after migration
     """
     vol = Volume.create(
         self.apiclient,
         self.services["volume"],
         diskofferingid=self.disk_offering.id,
         zoneid=self.zone.id,
         account=self.account.name,
         domainid=self.account.domainid,
     )
     self.assertIsNotNone(vol, "Failed to create volume")
     vol_res = Volume.list(self.apiclient, id=vol.id)
     self.assertEqual(validateList(vol_res)[0], PASS, "Invalid response returned for list volumes")
     vol_uuid = vol_res[0].id
     try:
         self.virtual_machine.attach_volume(self.apiclient, vol)
     except Exception as e:
         self.fail("Attaching data disk to vm failed with error %s" % e)
     pools = StoragePool.listForMigration(self.apiclient, id=vol.id)
     if not pools:
         self.skipTest(
             "No suitable storage pools found for volume migration.\
                     Skipping"
         )
     self.assertEqual(validateList(pools)[0], PASS, "invalid pool response from findStoragePoolsForMigration")
     pool = pools[0]
     self.debug("Migrating Volume-ID: %s to Pool: %s" % (vol.id, pool.id))
     try:
         Volume.migrate(self.apiclient, volumeid=vol.id, storageid=pool.id, livemigrate="true")
     except Exception as e:
         self.fail("Volume migration failed with error %s" % e)
     migrated_vols = Volume.list(
         self.apiclient, virtualmachineid=self.virtual_machine.id, listall="true", type="DATADISK"
     )
     self.assertEqual(validateList(migrated_vols)[0], PASS, "invalid volumes response after migration")
     migrated_vol_uuid = migrated_vols[0].id
     self.assertEqual(
         vol_uuid,
         migrated_vol_uuid,
         "Volume is not retaining same uuid when migrating from one\
                 storage to another",
     )
     self.virtual_machine.detach_volume(self.apiclient, vol)
     self.cleanup.append(vol)
     return
    def test_01_test_vm_volume_snapshot(self):
        """
        @Desc: Test that Volume snapshot for root volume is allowed
        when VM snapshot is present for the VM
        @Steps:
        1: Deploy a VM and create a VM snapshot for VM
        2: Try to create snapshot for the root volume of the VM,
        It should not fail
        """

        # Creating Virtual Machine
        virtual_machine = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
        )

        VmSnapshot.create(
            self.apiclient,
            virtual_machine.id,
        )

        volumes = Volume.list(self.apiclient,
                              virtualmachineid=virtual_machine.id,
                              type="ROOT",
                              listall=True)

        self.assertEqual(validateList(volumes)[0], PASS,
                "Failed to get root volume of the VM")

        snapshot = Snapshot.create(
            self.apiclient,
            volumes[0].id,
            account=self.account.name,
            domainid=self.account.domainid
        )
        self.debug("Snapshot created: ID - %s" % snapshot.id)
        snapshots = list_snapshots(
            self.apiclient,
            id=snapshot.id
        )
        self.assertEqual(
            validateList(snapshots)[0],
            PASS,
            "Invalid snapshot list"
        )
        self.assertEqual(
            snapshots[0].id,
            snapshot.id,
            "Check resource id in list resources call"
        )
        return
Esempio n. 8
0
    def test_03_cluste_capacity_check(self):
        """change cpu/mem.overprovisioning.factor at cluster level and
           verify cluster capacity """

        listHost = Host.list(self.apiclient, id=self.deployVmResponse.hostid)
        self.assertEqual(
            validateList(listHost)[0], PASS,
            "check list host for host id %s" % self.deployVmResponse.hostid)

        Configurations.update(self.apiclient,
                              clusterid=listHost[0].clusterid,
                              name="mem.overprovisioning.factor",
                              value=1)
        Configurations.update(self.apiclient,
                              clusterid=listHost[0].clusterid,
                              name="cpu.overprovisioning.factor",
                              value=1)

        time.sleep(self.wait_time)

        capacity = Capacities.list(self.apiclient,
                                   clusterid=listHost[0].clusterid)
        self.assertEqual(
            validateList(capacity)[0], PASS,
            "check list capacity response for cluster id %s" %
            listHost[0].clusterid)
        cpu, mem = capacity_parser(capacity)

        Configurations.update(self.apiclient,
                              clusterid=listHost[0].clusterid,
                              name="mem.overprovisioning.factor",
                              value=2)
        Configurations.update(self.apiclient,
                              clusterid=listHost[0].clusterid,
                              name="cpu.overprovisioning.factor",
                              value=2)

        time.sleep(self.wait_time)

        capacity1 = Capacities.list(self.apiclient,
                                    clusterid=listHost[0].clusterid)
        self.assertEqual(
            validateList(capacity1)[0], PASS,
            "check list capacity response for cluster id %s" %
            listHost[0].clusterid)
        cpu1, mem1 = capacity_parser(capacity1)
        self.assertEqual(2 * cpu[0], cpu1[0], "check total capacity ")
        self.assertEqual(2 * cpu[1], cpu1[1], "check capacity used")
        self.assertEqual(cpu[2], cpu1[2], "check capacity % used")

        self.assertEqual(2 * mem[0], mem1[0], "check mem total capacity ")
        self.assertEqual(2 * mem[1], mem1[1], "check mem capacity used")
        self.assertEqual(mem[2], mem1[2], "check mem capacity % used")
    def test_Scale_VM(self):
        """
        @desc:
        1. Enable dynamic scaling in Global settings
        2. Register an CentOS 7 tempplate(with tools) and tick dynamic scaling
        3. Deploy VM with this template
        4.Start the VM and try to change service offering

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

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

        return
    def test_08_add_TCP_PF_Rule_In_VPN(self):
        """
        Test to add TCP Port Forwarding rule for specific ports(500,1701 and 4500) in VPN
        """
        # Steps for verification
        # 1. Enable vpn on SourceNAT IP address
        # 2. Configure PF with TCP ports 500,1701 and 4500. It should be allowed
        # Should not conflict with UPD ports used for VPN

        vm_res = VirtualMachine.list(self.apiclient,
                                     id=self.virtual_machine.id,
                                     listall=True)
        self.assertEqual(
            validateList(vm_res)[0], PASS, "Failed to list virtual machine")
        network_id = vm_res[0].nic[0].networkid
        src_nat_list = PublicIPAddress.list(self.apiclient,
                                            account=self.account.name,
                                            domainid=self.account.domainid,
                                            listall=True,
                                            issourcenat=True,
                                            associatednetworkid=network_id)
        self.assertEqual(
            validateList(src_nat_list)[0], PASS,
            "Failed to list source nat ip address")
        ip = src_nat_list[0]
        try:
            vpn = Vpn.create(
                self.apiclient,
                publicipid=ip.id,
                account=self.account.name,
                domainid=self.account.domainid,
            )
            self.assertIsNotNone(vpn, "Failed to create remote access vpn")
        except Exception as e:
            self.fail("Failed to enable vpn on SourceNAT IP with error: %s" %
                      e)

        #Create PF rule with TCP ports 500,4500 and 1701
        self.services['natrule']['protocol'] = "TCP"
        for port in [500, 4500, 1701]:
            self.services['natrule']['privateport'] = port
            self.services['natrule']['publicport'] = port
            try:
                nat = NATRule.create(self.apiclient, self.virtual_machine,
                                     self.services["natrule"], ip.id)
                self.assertIsNotNone(
                    nat, "Failed to add PF rule with tcp parts matching vpn")
            except Exception as e:
                self.fail(
                    "Creating PF rule for TCP port %s in VPN failed : %s" %
                    (port, e))
        return
Esempio n. 11
0
    def test_01_positive_tests_vm_deploy_shared_nw(self):
        """ Positive tests for VMLC test path - Advanced Zone in Shared Network

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

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

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

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

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

        network = CreateNetwork(self, SHARED_NETWORK)

        # Create VM in account
        self.virtual_machine = VirtualMachine.create(
            self.userapiclient,
            self.testdata["small"],
            templateid=self.template.id,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering_1.id,
            networkids=[
                network.id,
            ],
            zoneid=self.zone.id)
        self.cleanup.append(self.virtual_machine)
        return
Esempio n. 12
0
    def test_01_positive_tests_vm_deploy_shared_nw(self):
        """ Positive tests for VMLC test path - Advanced Zone in Shared Network

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

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

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

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

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

        network = CreateNetwork(self, SHARED_NETWORK)

        # Create VM in account
        self.virtual_machine = VirtualMachine.create(
            self.userapiclient,
            self.testdata["small"],
            templateid=self.template.id,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering_1.id,
            networkids=[network.id, ],
            zoneid=self.zone.id
        )
        self.cleanup.append(self.virtual_machine)
        return
Esempio n. 13
0
def createSnapshotFromVirtualMachineVolume(apiclient, account, vmid):
    """Create snapshot from volume"""

    try:
        volumes = Volume.list(apiclient, account=account.name, domainid=account.domainid, virtualmachineid=vmid)
        validationresult = validateList(volumes)
        assert validateList(volumes)[0] == PASS, "List volumes should return a valid response"
        snapshot = Snapshot.create(apiclient, volume_id=volumes[0].id, account=account.name, domainid=account.domainid)
        snapshots = Snapshot.list(apiclient, id=snapshot.id, listall=True)
        validationresult = validateList(snapshots)
        assert validationresult[0] == PASS, "List snapshot should return a valid list"
    except Exception as e:
        return [FAIL, e]
    return [PASS, snapshot]
    def test_01_check_revert_snapshot(self):
        """ Test revert snapshot on XenServer

        # 1. Deploy a VM.
        # 2. Take VM snapshot.
        # 3. Verify that volume snapshot fails with error 
                can not create volume snapshot for VM with VM-snapshot

        """
        # Step 1
        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,
        )
        volumes_cluster_list = list_volumes(
                self.apiclient,
                virtualmachineid=vm.id,
                type='ROOT',
                listall=True
                )

        volume_list_validation = validateList(volumes_cluster_list)

	self.assertEqual(
                volume_list_validation[0],
                PASS,
                "Event list validation failed due to %s" %
		volume_list_validation[2]
            )
 
        root_volume = volumes_cluster_list[0]
        
        #Step 2
        vm_snap = VmSnapshot.create(self.apiclient,
                vm.id)

        volume_list_validation = validateList(vm_snap)

        #Step 3
        with self.assertRaises(Exception):
            Snapshot.create(
                    self.apiclient,
                    root_volume.id)

        return
Esempio n. 15
0
    def test_01_cluster_settings(self):
        """change cpu/mem.overprovisioning.factor at cluster level and
         verify the change """
        listHost = Host.list(self.apiclient, id=self.deployVmResponse.hostid)
        self.assertEqual(
            validateList(listHost)[0], PASS,
            "check list host response for host id %s" %
            self.deployVmResponse.hostid)
        Configurations.update(self.apiclient,
                              clusterid=listHost[0].clusterid,
                              name="mem.overprovisioning.factor",
                              value=2)

        Configurations.update(self.apiclient,
                              clusterid=listHost[0].clusterid,
                              name="cpu.overprovisioning.factor",
                              value=3)

        list_cluster = Cluster.list(self.apiclient, id=listHost[0].clusterid)
        self.assertEqual(
            validateList(list_cluster)[0], PASS,
            "check list cluster response for cluster id %s" %
            listHost[0].clusterid)
        self.assertEqual(int(list_cluster[0].cpuovercommitratio), 3,
                         "check the cpu overcommit value at cluster level ")

        self.assertEqual(int(list_cluster[0].memoryovercommitratio), 2,
                         "check memory overcommit value at cluster level")

        Configurations.update(self.apiclient,
                              clusterid=listHost[0].clusterid,
                              name="mem.overprovisioning.factor",
                              value=1)

        Configurations.update(self.apiclient,
                              clusterid=listHost[0].clusterid,
                              name="cpu.overprovisioning.factor",
                              value=1)
        list_cluster1 = Cluster.list(self.apiclient, id=listHost[0].clusterid)
        self.assertEqual(
            validateList(list_cluster1)[0], PASS,
            "check the list cluster response for id %s" %
            listHost[0].clusterid)
        self.assertEqual(int(list_cluster1[0].cpuovercommitratio), 1,
                         "check the cpu overcommit value at cluster level ")

        self.assertEqual(int(list_cluster1[0].memoryovercommitratio), 1,
                         "check memory overcommit value at cluster level")
    def setUp(self):
        self.apiclient = self.testClient.getApiClient()
        self.dbclient = self.testClient.getDbConnection()

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

        try:
            self.vm = VirtualMachine.create(
                self.apiclient,
                self.services["virtual_machine"],
                templateid=self.template.id,
                projectid=self.project.id,
                serviceofferingid=self.service_offering.id)
            projects = Project.list(self.apiclient,
                                    id=self.project.id,
                                    listall=True)
            self.assertEqual(validateList(projects)[0], PASS,\
                    "projects list validation failed")
            self.initialResourceCount = projects[0].primarystoragetotal
        except Exception as e:
            self.tearDown()
            self.skipTest("Exception occured in setup: %s" % e)
        return
Esempio n. 17
0
    def getKubernetesTemplate(cls, cks_templates=None):

        if cks_templates is None:
            cks_templates = cls.services["cks_templates"]

        hypervisor = cls.hypervisor.lower()

        if hypervisor not in cks_templates.keys():
            cls.debug("Provided hypervisor has no CKS template")
            return FAILED, False

        cks_template = cks_templates[hypervisor]

        cmd = listTemplates.listTemplatesCmd()
        cmd.name = cks_template['name']
        cmd.templatefilter = 'all'
        cmd.zoneid = cls.zone.id
        cmd.hypervisor = hypervisor
        templates = cls.apiclient.listTemplates(cmd)

        if validateList(templates)[0] != PASS:
            details = None
            if hypervisor in ["vmware"]:
                details = [{"keyboard": "us"}]
            template = Template.register(cls.apiclient, cks_template, zoneid=cls.zone.id, hypervisor=hypervisor.lower(), randomize_name=False, details=details)
            template.download(cls.apiclient)
            return template, False

        for template in templates:
            if template.isready and template.ispublic:
                return Template(template.__dict__), True

        return FAILED, False
Esempio n. 18
0
    def test_01_attach_datadisk_to_vm_on_zwps(self):
        """ Attach Data Disk To VM on ZWPS
            1.  Check if zwps storage pool exists.
            2.  Adding tag to zone wide primary storage
            3.  Launch a VM on ZWPS
            4.  Attach data disk to vm which is on zwps.
            5.  Verify disk is attached.
        """

        # Step 1
        if len(
                list(storagePool for storagePool in self.pools
                     if storagePool.scope == "ZONE")) < 1:
            self.skipTest("There must be at least one zone wide \
                storage pools available in the setup")

        # Adding tags to Storage Pools
        zone_no = 1
        for storagePool in self.pools:
            if storagePool.scope == "ZONE":
                StoragePool.update(self.apiclient,
                                   id=storagePool.id,
                                   tags=[ZONETAG1[:-1] + repr(zone_no)])
                zone_no += 1

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

        self.data_volume_created = 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.cleanup.append(self.data_volume_created)

        # Step 2
        self.vm.attach_volume(self.userapiclient, self.data_volume_created)

        data_volumes_list = Volume.list(self.userapiclient,
                                        id=self.data_volume_created.id,
                                        virtualmachineid=self.vm.id)

        data_volume = data_volumes_list[0]

        status = validateList(data_volume)

        # Step 3
        self.assertEqual(status[0], PASS,
                         "Check: Data if Disk is attached to VM")

        return
    def test_02_migrate_vm(self):
        """Test migrate VM in project

        # Validate the following
        # 1. Create VM with custom disk offering in a project and check
        #    initial primary storage count
        # 2. List the hosts suitable for migrating the VM
        # 3. Migrate the VM and verify that primary storage count of project remains same"""
        self.hypervisor = self.testClient.getHypervisorInfo()
        if self.hypervisor.lower() in ['lxc']:
            self.skipTest("vm migrate feature is not supported on %s" % self.hypervisor.lower())
        try:
            hosts = Host.list(self.apiclient,virtualmachineid=self.vm.id,
                              listall=True)
            self.assertEqual(validateList(hosts)[0], PASS, "hosts list validation failed")
            host = hosts[0]
            self.vm.migrate(self.apiclient, host.id)
        except Exception as e:
            self.fail("Exception occured: %s" % e)

        expectedCount = self.initialResourceCount
        response = matchResourceCount(
                        self.apiclient, expectedCount,
                        RESOURCE_PRIMARY_STORAGE,
                        projectid=self.project.id)
        self.assertEqual(response[0], PASS, response[1])
        return
    def test_attach_multiple_volumes(self):
        """Attach multiple Volumes simultaneously to a Running VM
        """
        # Validate the following
        # 1. All data disks attached successfully without any exception

        self.debug(
                "Attaching volume (ID: %s) to VM (ID: %s)" % (
                                                    self.volume1.id,
                                                    self.virtual_machine.id
                                                    ))
        vol1_jobId = self.attach_volume(self.apiClient, self.virtual_machine.id,self.volume1)

        self.debug(
                "Attaching volume (ID: %s) to VM (ID: %s)" % (
                                                    self.volume2.id,
                                                    self.virtual_machine.id
                                                    ))
        vol2_jobId = self.attach_volume(self.apiClient,self.virtual_machine.id, self.volume2)

        self.debug(
                "Attaching volume (ID: %s) to VM (ID: %s)" % (
                                                    self.volume3.id,
                                                    self.virtual_machine.id
                                                    ))
        vol3_jobId = self.attach_volume(self.apiClient,self.virtual_machine.id, self.volume3)

        self.debug(
                "Attaching volume (ID: %s) to VM (ID: %s)" % (
                                                    self.volume4.id,
                                                    self.virtual_machine.id
                                                    ))
        vol4_jobId = self.attach_volume(self.apiClient,self.virtual_machine.id, self.volume4)

        self.query_async_job(self.apiClient,vol1_jobId.jobid)
        self.query_async_job(self.apiClient,vol2_jobId.jobid)
        self.query_async_job(self.apiClient,vol3_jobId.jobid)
        self.query_async_job(self.apiClient,vol4_jobId.jobid)

        # List all the volumes attached to the instance. Includes even the Root disk.
        list_volume_response = Volume.list(
                                            self.apiClient,
                                            virtualmachineid=self.virtual_machine.id,
                                            type="DATADISK",
                                            account=self.account.name,
                                            domainid=self.account.domainid
                                          )
        self.assertEqual(
            validateList(list_volume_response)[0],
            PASS,
            "Check list response returns a valid list"
        )

        self.assertEqual(
                            len(list_volume_response),
                            4,
                            "All 4 data disks are not attached to VM Successfully"
                            )

        return
    def test_08_removeNic_in_sharedNetwork_scope_all_as_domain_parentAdmin(
            self):
        """Validate that Parent domain admin is able to remove a NIC  which is
        added by child domain user
        """

        self.api_client.connection.apiKey = self.user_d1_apikey
        self.api_client.connection.securityKey = self.user_d1_secretkey
        self.debug("Removing NIC od shared Network as user d1")

        vm_list = list_virtual_machines(self.api_client, id=self.vmvpc1.id)
        vm_list_validation_result = validateList(vm_list)
        self.assertEqual(vm_list_validation_result[0], PASS,
                         "vm list validation failed due to %s" %
                         vm_list_validation_result[2])
        self.debug("virtual machine nics: %s" % vm_list[0].nic)
        for nic in vm_list[0].nic:
            if nic.networkid == self.shared_network_all.id:
                reqNic = nic

        self.vmvpc1.remove_nic(self.api_client, reqNic.id)

        if not self.verify_nic(self.shared_network_all, self.vmvpc1):
            self.debug(
                "virtual machine has mot NIC is SharedNetwork: %s" %
                self.shared_network_all.name)
        else:
            self.fail("network %s NIC is present in the virtual Machine %s" %
                      (self.shared_network_all.name, self.vmvpc1.id))
    def test_attach_volume_exceeding_primary_limits(self):
        """
        # do
        # 1. create a normal user account and update primary store limits to the current resource count
        # 2. Upload a volume of any size
        # 3. Verify that upload volume succeeds
        # 4. Verify that primary storage count doesnt change
        # 6. Try attaching volume to VM and verify that the attach fails (as the resource limits exceed)
        # 7. Verify that primary storage count doesnt change
        # done
        """
        # create an account, launch a vm with default template and custom disk offering, update the primary store limits to the current primary store resource count
        response = self.setupNormalAccount()
        self.assertEqual(response[0], PASS, response[1])

        # upload volume and verify that the volume is uploaded
        volume = Volume.upload(
            self.apiclient,
            self.services["configurableData"]["upload_volume"],
            zoneid=self.zone.id,
            account=self.account.name,
            domainid=self.account.domainid,
            url="http://people.apache.org/~sanjeev/rajani-thin-volume.vhd",
        )

        volume.wait_for_upload(self.apiclient)
        volumes = Volume.list(self.apiclient, id=volume.id, zoneid=self.zone.id, listall=True)
        validationresult = validateList(volumes)
        assert validationresult[0] == PASS, "volumes list validation failed: %s" % validationresult[2]
        assert str(volumes[0].state).lower() == "uploaded", (
            "Volume state should be 'uploaded' but it is %s" % volumes[0].state
        )

        # verify that the resource count didnt change due to upload volume
        response = matchResourceCount(
            self.apiclient, self.initialResourceCount, RESOURCE_PRIMARY_STORAGE, accountid=self.account.id
        )
        self.assertEqual(response[0], PASS, response[1])

        # attach the above volume to the vm
        try:
            self.virtualMachine.attach_volume(self.apiclient, volume=volume)
        except Exception as e:
            if (
                "Maximum number of resources of type 'primary_storage' for account name=" + self.account.name
                in e.message
            ):
                self.assertTrue(True, "there should be primary store resource limit reached exception")
            else:
                self.fail(
                    "only resource limit reached exception is expected. some other exception occurred. Failing the test case."
                )

        # resource count should match as the attach should fail due to reaching resource limits
        response = matchResourceCount(
            self.apiclient, self.initialResourceCount, RESOURCE_PRIMARY_STORAGE, accountid=self.account.id
        )
        self.assertEqual(response[0], PASS, response[1])

        return
    def create_vm(self, pfrule=False, egress_policy=True, RR=False):
        self.create_network_offering(egress_policy, RR)
        # Creating network using the network offering created
        self.debug("Creating network with network offering: %s" % self.network_offering.id)
        self.network = Network.create(
            self.apiclient,
            self.services["network"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            networkofferingid=self.network_offering.id,
            zoneid=self.zone.id,
        )
        self.debug("Created network with ID: %s" % self.network.id)
        self.debug("Deploying instance in the account: %s" % self.account.name)

        project = None
        self.virtual_machine = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.domain.id,
            serviceofferingid=self.service_offering.id,
            mode=self.zone.networktype if pfrule else "basic",
            networkids=[str(self.network.id)],
            projectid=project.id if project else None,
        )
        self.debug("Deployed instance %s in account: %s" % (self.virtual_machine.id, self.account.name))

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

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

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

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

        self.debug("Creating NAT rule for VM ID: %s" % self.virtual_machine.id)
        # Create NAT rule
        NATRule.create(self.apiclient, self.virtual_machine, self.services["natrule"], self.public_ip.ipaddress.id)
        return
    def setupNormalAccount(self):
        """Setup the account required for the test"""

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

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

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

            accounts = Account.list(self.apiclient, id=self.account.id)

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

            self.initialResourceCount = int(accounts[0].primarystoragetotal)

            primarystoragelimit = self.initialResourceCount
            update_resource_limit(self.api_client, RESOURCE_PRIMARY_STORAGE, account=self.account.name, domainid=self.account.domainid, max=primarystoragelimit)

        except Exception as e:
            return [FAIL, e]
        return [PASS, None]
Esempio n. 25
0
def uploadVolume(apiclient, zoneid, account, services):
    try:
        # Upload the volume
        volume = Volume.upload(apiclient,
                               services["volume"],
                               zoneid=zoneid,
                               account=account.name,
                               domainid=account.domainid,
                               url=services["url"])

        volume.wait_for_upload(apiclient)

        # Check List Volume response for newly created volume
        volumes = Volume.list(apiclient,
                              id=volume.id,
                              zoneid=zoneid,
                              listall=True)
        validationresult = validateList(volumes)
        assert validationresult[0] == PASS,\
                            "volumes list validation failed: %s" % validationresult[2]
        assert str(volumes[0].state).lower() == "uploaded",\
                    "Volume state should be 'uploaded' but it is %s" % volumes[0].state
    except Exception as e:
        return [FAIL, e]
    return [PASS, volume]
Esempio n. 26
0
    def test_listtemplate(self):

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

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

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

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

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

        self.assertEqual(listtemplate, None, "Check templates are not listed")
        return
Esempio n. 27
0
    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
Esempio n. 28
0
def isIpInDesiredState(apiclient, ipaddressid, state):
    """ Check if the given IP is in the correct state (given)
    and return True/False accordingly"""
    retriesCount = 10
    ipInDesiredState = False
    exceptionOccured = False
    exceptionMessage = ""
    try:
        while retriesCount >= 0:
            portableips = PublicIPAddress.list(apiclient, id=ipaddressid)
            assert validateList(
                portableips)[0] == PASS, "IPs list validation failed"
            if str(portableips[0].state).lower() == state:
                ipInDesiredState = True
                break
            retriesCount -= 1
            time.sleep(60)
    except Exception as e:
        exceptionOccured = True
        exceptionMessage = e
        return [exceptionOccured, ipInDesiredState, e]
    if not ipInDesiredState:
        exceptionMessage = "Ip should be in %s state, it is in %s" %\
                            (state, portableips[0].state)
    return [False, ipInDesiredState, exceptionMessage]
Esempio n. 29
0
def matchResourceCount(apiclient, expectedCount, resourceType,
                              accountid=None, projectid=None):
    """Match the resource count of account/project with the expected
    resource count"""
    try:
        resourceholderlist = None
        if accountid:
            resourceholderlist = Account.list(apiclient, id=accountid)
        elif projectid:
            resourceholderlist = Project.list(apiclient, id=projectid, listall=True)
        validationresult = validateList(resourceholderlist)
        assert validationresult[0] == PASS,\
               "accounts list validation failed"
        if resourceType == RESOURCE_PRIMARY_STORAGE:
            resourceCount = resourceholderlist[0].primarystoragetotal
        elif resourceType == RESOURCE_SECONDARY_STORAGE:
            resourceCount = resourceholderlist[0].secondarystoragetotal
        elif resourceType == RESOURCE_CPU:
            resourceCount = resourceholderlist[0].cputotal
        elif resourceType == RESOURCE_MEMORY:
            resourceCount = resourceholderlist[0].memorytotal
        assert str(resourceCount) == str(expectedCount),\
                "Resource count %s should match with the expected resource count %s" %\
                (resourceCount, expectedCount)
    except Exception as e:
        return [FAIL, e]
    return [PASS, None]
    def test_02_migrate_vm(self):
        """Test migrate VM in project

        # Validate the following
        # 1. Create VM with custom disk offering in a project and check
        #    initial primary storage count
        # 2. List the hosts suitable for migrating the VM
        # 3. Migrate the VM and verify that primary storage count of project remains same"""

        try:
            hosts = Host.list(self.apiclient,virtualmachineid=self.vm.id,
                              listall=True)
            self.assertEqual(validateList(hosts)[0], PASS, "hosts list validation failed")
            host = hosts[0]
            self.vm.migrate(self.apiclient, host.id)
        except Exception as e:
            self.fail("Exception occured" % e)

        expectedCount = self.initialResourceCount
        response = matchResourceCount(
                        self.apiclient, expectedCount,
                        RESOURCE_PRIMARY_STORAGE,
                        projectid=self.project.id)
        self.assertEqual(response[0], PASS, response[1])
        return
    def test_01_deploy_instance_with_is_volatile_offering(self):
        """ Test deploy an instance with service offerings with IsVolatile set.
        """

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

        self.debug("Checking if deployed VMs are in running state...")
        vms = VirtualMachine.list(
                                  self.apiclient,
                                  account=self.account.name,
                                  domainid=self.account.domainid,
                                  listall=True
                                  )
        vm_list_validation_result = validateList(vms)

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

        for vm in vms:
            self.debug("VM name: %s, VM state: %s" % (vm.name, vm.state))
            self.debug("%s" %vm)
            self.assertEqual(
                             vm.state,
                             "Running",
                             "Vm state should be running for each VM deployed"
                             )
        return
    def test_vm_nic_adapter_vmxnet3(self):
        """

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

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

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

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

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

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

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

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

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

        # TODO: Add steps to check the Nic Adapter type in VCenter
        # using VCenter APIs
        return
Esempio n. 33
0
def VerifyChangeInServiceOffering(self, virtualmachine, serviceoffering):
    """List the VM and verify that the new values for cpuspeed,
       cpunumber and memory match with the new service offering"""

    vmlist = VirtualMachine.list(self.userapiclient, id=virtualmachine.id)
    self.assertEqual(
        validateList(vmlist)[0],
        PASS,
        "vm list validation failed")
    vm = vmlist[0]

    # Verify the custom values
    self.assertEqual(str(vm.cpunumber), str(serviceoffering.cpunumber),
                     "vm cpu number %s not matching with cpu number in\
                      service offering %s" %
                     (vm.cpunumber, serviceoffering.cpunumber))

    self.assertEqual(str(vm.cpuspeed), str(serviceoffering.cpuspeed),
                     "vm cpu speed %s not matching with cpu speed in\
                     service offering %s" %
                     (vm.cpuspeed, serviceoffering.cpuspeed))

    self.assertEqual(str(vm.memory), str(serviceoffering.memory),
                     "vm memory %s not matching with memory in\
                     service offering %s" %
                     (vm.memory, serviceoffering.memory))
    return
Esempio n. 34
0
    def setupAccount(self, accountType):
        """Setup the account required for the test"""

        try:
            if accountType == CHILD_DOMAIN_ADMIN:
                self.domain = Domain.create(self.apiclient,
                                        services=self.services["domain"],
                                        parentdomainid=self.domain.id)

            self.account = Account.create(self.apiclient, self.services["account"],
                                      domainid=self.domain.id, admin=True)
            self.cleanup.append(self.account)
            if accountType == CHILD_DOMAIN_ADMIN:
                self.cleanup.append(self.domain)

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

            accounts = Account.list(self.apiclient, id=self.account.id)

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

            self.initialResourceCount = int(accounts[0].primarystoragetotal)
        except Exception as e:
            return [FAIL, e]
        return [PASS, None]
Esempio n. 35
0
    def tearDown(self):
        try:
            for storagePool in self.pools:
                StoragePool.update(self.apiclient, id=storagePool.id, tags="")

            if hasattr(self, "data_volume_created"):
                data_volumes_list = Volume.list(
                    self.userapiclient,
                    id=self.data_volume_created.id,
                    virtualmachineid=self.vm.id
                )
                if data_volumes_list:
                    self.vm.detach_volume(
                        self.userapiclient,
                        data_volumes_list[0]
                    )

                status = validateList(data_volumes_list)
                self.assertEqual(
                    status[0],
                    PASS,
                    "DATA Volume List Validation Failed")

            cleanup_resources(self.apiclient, self.cleanup)
        except Exception as e:
            raise Exception("Warning: Exception during cleanup : %s" % e)
        return
Esempio n. 36
0
    def registerTemplate(self, inProject=False):
        """Register and download template by default in the account/domain,
        in project if stated so"""

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

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

            template.download(self.apiclient)

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

            self.templateSize = (templates[0].size / (1024**3))
        except Exception as e:
            return [FAIL, e]
        return [PASS, None]
Esempio n. 37
0
    def setupAccount(self, accountType):
        """Setup the account required for the test"""

        try:
            if accountType == CHILD_DOMAIN_ADMIN:
                self.domain = Domain.create(self.apiclient,
                                            services=self.services["domain"],
                                            parentdomainid=self.domain.id)

            self.account = Account.create(self.apiclient,
                                          self.services["account"],
                                          domainid=self.domain.id,
                                          admin=True)
            self.cleanup.append(self.account)
            if accountType == CHILD_DOMAIN_ADMIN:
                self.cleanup.append(self.domain)

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

            accounts = Account.list(self.apiclient, id=self.account.id)

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

            self.initialResourceCount = int(accounts[0].primarystoragetotal)
        except Exception as e:
            return [FAIL, e]
        return [PASS, None]
    def test_02_create_template_snapshot(self, value):
        """Test create snapshot and templates from volume

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

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

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

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

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

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

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

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

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

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

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

        expectedSecondaryStorageCount = int(templateSize + snapshotSize)
        response = matchResourceCount(
            self.apiclient,
            expectedSecondaryStorageCount,
            resourceType=RESOURCE_SECONDARY_STORAGE,
            accountid=self.account.id,
        )
        self.assertEqual(response[0], PASS, response[1])
        return
def VerifyChangeInServiceOffering(self, virtualmachine, serviceoffering):
    """List the VM and verify that the new values for cpuspeed,
       cpunumber and memory match with the new service offering"""

    exceptionOccured = False
    exceptionMessage = ""
    try:
        vmlist = VirtualMachine.list(self.userapiclient, id=virtualmachine.id)
        self.assertEqual(
            validateList(vmlist)[0], PASS, "vm list validation failed")
        vm = vmlist[0]

        # Verify the custom values
        self.assertEqual(
            str(vm.cpunumber), str(serviceoffering.cpunumber),
            "vm cpu number %s not matching with cpu number in\
                      service offering %s" %
            (vm.cpunumber, serviceoffering.cpunumber))

        self.assertEqual(
            str(vm.cpuspeed), str(serviceoffering.cpuspeed),
            "vm cpu speed %s not matching with cpu speed in\
                     service offering %s" %
            (vm.cpuspeed, serviceoffering.cpuspeed))

        self.assertEqual(
            str(vm.memory), str(serviceoffering.memory),
            "vm memory %s not matching with memory in\
                     service offering %s" %
            (vm.memory, serviceoffering.memory))
    except Exception as e:
        exceptionOccured = True
        exceptionMessage = e
    return [exceptionOccured, exceptionMessage]
Esempio n. 40
0
    def test_08_removeNic_in_sharedNetwork_scope_all_as_domain_parentAdmin(
            self):
        """Validate that Parent domain admin is able to remove a NIC  which is
        added by child domain user
        """

        self.api_client.connection.apiKey = self.user_d1_apikey
        self.api_client.connection.securityKey = self.user_d1_secretkey
        self.debug("Removing NIC od shared Network as user d1")

        vm_list = list_virtual_machines(self.api_client, id=self.vmvpc1.id)
        vm_list_validation_result = validateList(vm_list)
        self.assertEqual(
            vm_list_validation_result[0], PASS,
            "vm list validation failed due to %s" %
            vm_list_validation_result[2])
        self.debug("virtual machine nics: %s" % vm_list[0].nic)
        for nic in vm_list[0].nic:
            if nic.networkid == self.shared_network_all.id:
                reqNic = nic

        self.vmvpc1.remove_nic(self.api_client, reqNic.id)

        if not self.verify_nic(self.shared_network_all, self.vmvpc1):
            self.debug("virtual machine has mot NIC is SharedNetwork: %s" %
                       self.shared_network_all.name)
        else:
            self.fail("network %s NIC is present in the virtual Machine %s" %
                      (self.shared_network_all.name, self.vmvpc1.id))
Esempio n. 41
0
def matchResourceCount(apiclient, expectedCount, resourceType, accountid=None, projectid=None):
    """Match the resource count of account/project with the expected
    resource count"""
    try:
        resourceholderlist = None
        if accountid:
            resourceholderlist = Account.list(apiclient, id=accountid)
        elif projectid:
            resourceholderlist = Project.list(apiclient, id=projectid, listall=True)
        validationresult = validateList(resourceholderlist)
        assert validationresult[0] == PASS, "accounts list validation failed"
        if resourceType == RESOURCE_PRIMARY_STORAGE:
            resourceCount = resourceholderlist[0].primarystoragetotal
        elif resourceType == RESOURCE_SECONDARY_STORAGE:
            resourceCount = resourceholderlist[0].secondarystoragetotal
        elif resourceType == RESOURCE_CPU:
            resourceCount = resourceholderlist[0].cputotal
        elif resourceType == RESOURCE_MEMORY:
            resourceCount = resourceholderlist[0].memorytotal
        assert str(resourceCount) == str(
            expectedCount
        ), "Resource count %s should match with the expected resource count %s" % (resourceCount, expectedCount)
    except Exception as e:
        return [FAIL, e]
    return [PASS, None]
    def test_01_deploy_instance_with_is_volatile_offering(self):
        """ Test deploy an instance with service offerings with IsVolatile set.
        """

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

        self.debug("Checking if deployed VMs are in running state...")
        vms = VirtualMachine.list(self.apiclient,
                                  account=self.account.name,
                                  domainid=self.account.domainid,
                                  listall=True)
        vm_list_validation_result = validateList(vms)

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

        for vm in vms:
            self.debug("VM name: %s, VM state: %s" % (vm.name, vm.state))
            self.debug("%s" % vm)
            self.assertEqual(
                vm.state, "Running",
                "Vm state should be running for each VM deployed")
        return
Esempio n. 43
0
    def create_another_vm(self):
        self.debug("Deploying instance in the account: %s and network: %s" %
                   (self.account.name, self.network.id))

        project = None
        self.virtual_machine1 = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.domain.id,
            serviceofferingid=self.service_offering.id,
            mode=self.zone.networktype,
            networkids=[str(self.network.id)],
            projectid=project.id if project else None)
        self.debug("Deployed instance %s in account: %s" %
                   (self.virtual_machine.id, self.account.name))

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

        self.assertEqual(
            validateList(self.vm_list)[0], PASS,
            "vm list validation failed, vm list is %s" % self.vm_list)
        self.assertEqual(
            str(self.vm_list[0].state).lower(), 'running',
            "VM state should be running, it is %s" % self.vm_list[0].state)
Esempio n. 44
0
    def __createApiClient(self):
        try:
            '''
            Step1 : Create a CS Connection Object
            '''
            mgmt_details = self.__mgmtDetails
            self.__csConnection = CSConnection(mgmt_details,
                                               self.__asyncTimeOut,
                                               self.__logger)

            '''
            Step2 : Create API Client with earlier created connection object
            '''
            self.__apiClient = CloudStackAPIClient(self.__csConnection)

            '''
            Step3:  If API Key is not provided as part of Management Details,
                    then verify and register
            '''
            if mgmt_details.apiKey is None:
                list_user = listUsers.listUsersCmd()
                list_user.account = "admin"
                list_user_res = self.__apiClient.listUsers(list_user)
                if list_user_res is None or\
                        (validateList(list_user_res)[0] != PASS):
                    self.__logger.error("__createApiClient: API "
                                        "Client Creation Failed")
                    return FAILED
                user_id = list_user_res[0].id
                api_key = list_user_res[0].apikey
                security_key = list_user_res[0].secretkey
                if api_key is None:
                    ret = self.__getKeys(user_id)
                    if ret != FAILED:
                        mgmt_details.apiKey = ret[0]
                        mgmt_details.securityKey = ret[1]
                    else:
                        self.__logger.error("__createApiClient: API Client "
                                            "Creation Failed while "
                                            "Registering User")
                        return FAILED
                else:
                    mgmt_details.port = 8080
                    mgmt_details.apiKey = api_key
                    mgmt_details.securityKey = security_key
                '''
                Now Create the Connection objects and Api Client using
                new details
                '''
                self.__csConnection = CSConnection(mgmt_details,
                                                   self.__asyncTimeOut,
                                                   self.__logger)
                self.__apiClient = CloudStackAPIClient(self.__csConnection)
            return SUCCESS
        except Exception as e:
            self.__logger.exception(" Exception Occurred Under "
                                    "__createApiClient: %s" %
                                    GetDetailExceptionInfo(e))
            return FAILED
    def test_02_Overcommit_factor(self):
        """change mem.overprovisioning.factor and verify vm memory """

        listHost = Host.list(self.apiclient, id=self.deployVmResponse.hostid)
        self.assertEqual(
            validateList(listHost)[0], PASS,
            "check list host for host id %s" % self.deployVmResponse.hostid)
        if listHost[0].hypervisor.lower() not in ['kvm', 'xenserver']:
            self.skipTest(
                "Skiping test because of not supported hypervisor type %s" %
                listHost[0].hypervisor)

        Configurations.update(self.apiclient,
                              clusterid=listHost[0].clusterid,
                              name="mem.overprovisioning.factor",
                              value=1)

        self.deployVmResponse.stop(self.apiclient)
        self.deployVmResponse.start(self.apiclient)

        if listHost[0].hypervisor.lower() == 'xenserver':

            k = ssh_xen_host(self.hostConfig["password"],
                             self.hostConfig["username"],
                             listHost[0].ipaddress,
                             self.deployVmResponse.instancename)

        elif listHost[0].hypervisor.lower() == 'kvm':

            k = ssh_kvm_host(self.hostConfig["password"],
                             self.hostConfig["username"],
                             listHost[0].ipaddress,
                             self.deployVmResponse.instancename)

        self.assertEqual(k[0], k[1],
                         "Check static max ,min on host for overcommit 1 ")

        Configurations.update(self.apiclient,
                              clusterid=listHost[0].clusterid,
                              name="mem.overprovisioning.factor",
                              value=2)

        self.deployVmResponse.stop(self.apiclient)
        self.deployVmResponse.start(self.apiclient)

        if listHost[0].hypervisor.lower() == 'xenserver':
            k1 = ssh_xen_host(self.hostConfig["password"],
                              self.hostConfig["username"],
                              listHost[0].ipaddress,
                              self.deployVmResponse.instancename)

        elif listHost[0].hypervisor.lower() == 'kvm':
            time.sleep(200)
            k1 = ssh_kvm_host(self.hostConfig["password"],
                              self.hostConfig["username"],
                              listHost[0].ipaddress,
                              self.deployVmResponse.instancename)
        self.assertEqual(k1[0], 2 * k1[1],
                         "Check static max ,min on  host for overcommit 2")
    def __createApiClient(self):
        try:
            '''
            Step1 : Create a CS Connection Object
            '''
            self.__csConnection = CSConnection(self.__mgmtDetails,
                                               self.__asyncTimeOut,
                                               self.__logger)

            '''
            Step2 : Create API Client with earlier created connection object
            '''
            self.__apiClient = CloudStackAPIClient(self.__csConnection)

            '''
            Step3:  If API Key is not provided as part of Management Details,
                    then verify and register
            '''
            if self.__mgmtDetails.apiKey is None:
                list_user = listUsers.listUsersCmd()
                list_user.account = "admin"
                list_user_res = self.__apiClient.listUsers(list_user)
                if list_user_res is None or\
                        (validateList(list_user_res)[0] != PASS):
                    self.__logger.error("__createApiClient: API "
                                        "Client Creation Failed")
                    return FAILED
                user_id = list_user_res[0].id
                api_key = list_user_res[0].apikey
                security_key = list_user_res[0].secretkey
                if api_key is None:
                    ret = self.__getKeys(user_id)
                    if ret != FAILED:
                        self.__mgmtDetails.port = 8080
                        self.__mgmtDetails.apiKey = ret[0]
                        self.__mgmtDetails.securityKey = ret[1]
                    else:
                        self.__logger.error("__createApiClient: API Client "
                                            "Creation Failed while "
                                            "Registering User")
                        return FAILED
                else:
                    self.__mgmtDetails.port = 8080
                    self.__mgmtDetails.apiKey = api_key
                    self.__mgmtDetails.securityKey = security_key
                '''
                Now Create the Connection objects and Api Client using
                new details
                '''
                self.__csConnection = CSConnection(self.__mgmtDetails,
                                                   self.__asyncTimeOut,
                                                   self.__logger)
                self.__apiClient = CloudStackAPIClient(self.__csConnection)
            return SUCCESS
        except Exception as e:
            self.__logger.exception(" Exception Occurred Under "
                                    "__createApiClient: %s" %
                                    GetDetailExceptionInfo(e))
            return FAILED
    def test_03_register_iso(self, value):
        """Test register iso
        Steps and validations:
        1. Create a root domain/child domain admin account
        2. Register a test iso in the account
        3. Wait till the iso is downloaded and is in ready state
        3. Verify that secondary storage resource count of the account equals the
           iso size
        4. Delete the iso
        5. Verify that the secondary storage count of the account equals 0
        """
        response = self.setupAccount(value)
        self.assertEqual(response[0], PASS, response[1])

        self.services["iso"]["zoneid"] = self.zone.id
        try:
            iso = Iso.create(
                         self.apiclient,
                         self.services["iso"],
                         account=self.account.name,
                         domainid=self.account.domainid
                         )
        except Exception as e:
            self.fail("Failed to create Iso: %s" % e)

        timeout = 600
        isoList = None
        while timeout >= 0:
            isoList = Iso.list(self.apiclient,
                                      isofilter="self",
                                      id=iso.id)
            self.assertEqual(validateList(isoList)[0],PASS,\
                            "iso list validation failed")
            if isoList[0].isready:
                break
            time.sleep(60)
            timeout -= 60

        self.assertNotEqual(timeout, 0,\
                "template not downloaded completely")

        isoSize = (isoList[0].size / (1024**3))
        expectedCount = isoSize
        response = matchResourceCount(self.apiclient, expectedCount,
                                      resourceType=RESOURCE_SECONDARY_STORAGE,
                                      accountid=self.account.id)
        self.assertEqual(response[0], PASS, response[1])

        try:
            iso.delete(self.apiclient)
        except Exception as e:
            self.fail("Failed to delete Iso")

        expectedCount = 0
        response = matchResourceCount(self.apiclient, expectedCount,
                                      resourceType=RESOURCE_SECONDARY_STORAGE,
                                      accountid=self.account.id)
        self.assertEqual(response[0], PASS, response[1])
        return
Esempio n. 48
0
    def setUpClass(cls):

        cls.testClient = super(TestTemplates, cls).getClsTestClient()
        cls.api_client = cls.testClient.getApiClient()
        cls.hypervisor = cls.testClient.getHypervisorInfo()
        cls.services = Services().services
        # Get Zone, Domain and templates
        cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
        cls.domain = get_domain(cls.api_client)

        cls.services['mode'] = cls.zone.networktype

        template = get_template(
                            cls.api_client,
                            cls.zone.id,
                            cls.services["ostype"]
                            )
        if cls.hypervisor.lower() in ['lxc']:
            raise unittest.SkipTest("Template creation from root volume is not supported in LXC")
        cls.services["virtual_machine"]["zoneid"] = cls.zone.id
        cls._cleanup = []
        try:
            cls.account = Account.create(
                            cls.api_client,
                            cls.services["account"],
                            domainid=cls.domain.id
                            )
            cls._cleanup.append(cls.account)

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

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

            listvolumes = Volume.list(
                                   cls.api_client,
                                   virtualmachineid=cls.virtual_machine.id,
                                   type='ROOT',
                                   listall=True
                                   )
            assert validateList(listvolumes)[0] == PASS, "volumes list is empty"
            cls.volume = listvolumes[0]
        except Exception as e:
            cls.tearDownClass()
            raise unittest.SkipTest("Exception in setUpClass: %s" % e)
def verify_detach_volume(self, vmid, volid):
        list_volumes = Volume.list(self.userapiclient,
                                   id=volid
                                   )
        self.assertEqual(validateList(list_volumes)[0], PASS, "Check List volume response for volume %s" % volid)
        self.assertEqual(len(list_volumes), 1, "Detach data disk id: %s  for vm id :%s was not successful" % (volid, vmid))
        self.assertEqual(list_volumes[0].virtualmachineid, None, "Check if volume state (attached) is reflected")
        self.debug("volume id: %s successfully detached from vm id:%s" % (volid, vmid))
Esempio n. 50
0
    def test_01_register_template(self, value):
        """Test register template
        # Validate the following:
        1. Create a root domain admin/ child domain admin account
        2. Register and download a template according to hypervisor type
        3. Verify that the template is listed
        4. Verify that the secondary storage count for the account equals the size
           of the template
        5. Delete the template
        6. Verify that the secondary storage resource count of the account equals 0
       """
        response = self.setupAccount(value)
        self.assertEqual(response[0], PASS, response[1])

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

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

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

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

        templateSize = (templates[0].size / (1024**3))
        expectedCount = templateSize
        response = matchResourceCount(
                        self.apiclient, expectedCount,
                        RESOURCE_SECONDARY_STORAGE,
                        accountid=self.account.id)
        self.assertEqual(response[0], PASS, response[1])

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

        expectedCount = 0
        response = matchResourceCount(
                        self.apiclient, expectedCount,
                        RESOURCE_SECONDARY_STORAGE,
                        accountid=self.account.id)
        self.assertEqual(response[0], PASS, response[1])
        return
Esempio n. 51
0
    def test_06_pt_startvm_false_attach_iso(self):
        """ Positive test for stopped VM test path - T5

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

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

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

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

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

        vms = VirtualMachine.list(
            self.userapiclient,
            id=virtual_machine.id,
            listall=True
        )
        self.assertEqual(
            validateList(vms)[0],
            PASS,
            "List vms should return a valid list"
        )
        vm = vms[0]
        self.assertEqual(
            vm.isoid,
            iso.id,
            "The ISO status should be reflected in list Vm call"
        )
        return
Esempio n. 52
0
    def test_01_positive_tests_usage(self):
        """ Check events in usage_events table when VM creation fails

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

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

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

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

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

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

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

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

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

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

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

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

        self.assertEqual(qresult.count("VOLUME.DELETE"), 1, "Check VM.DELETE in events table")
        return
def verify_attach_volume(self, vmid, volid):
        list_volumes = Volume.list(self.userapiclient,
                                   id=volid
                                   )
        self.assertEqual(validateList(list_volumes)[0], PASS, "Check List volume response for volume %s" % volid)
        self.assertEqual(len(list_volumes), 1, "There is no data disk attached to vm id:%s" % vmid)
        self.assertEqual(list_volumes[0].virtualmachineid, vmid, "Check if volume state (attached) is reflected")
        self.debug("volume id:%s successfully attached to vm id%s" % (volid, vmid))
        return
Esempio n. 54
0
def get_windows_template(
    apiclient,
    zone_id=None,
    ostype_desc=None,
    template_filter="featured",
    template_type="USER",
    template_id=None,
    template_name=None,
    account=None,
    domain_id=None,
    project_id=None,
    hypervisor=None,
):
    """
    @Name : get_template
    @Desc : Retrieves the template Information based upon inputs provided
            Template is retrieved based upon either of the inputs matched
            condition
    @Input : returns a template"
    @Output : FAILED in case of any failure
              template Information matching the inputs
    """
    cmd = listTemplates.listTemplatesCmd()
    cmd.templatefilter = template_filter
    if domain_id is not None:
        cmd.domainid = domain_id
    if zone_id is not None:
        cmd.zoneid = zone_id
    if template_id is not None:
        cmd.id = template_id
    if template_name is not None:
        cmd.name = template_name
    if hypervisor is not None:
        cmd.hypervisor = hypervisor
    if project_id is not None:
        cmd.projectid = project_id
    if account is not None:
        cmd.account = account

    """
    Get the Templates pertaining to the inputs provided
    """
    list_templatesout = apiclient.listTemplates(cmd)
    # print("template result is %s"%(list_templatesout))
    if list_templatesout is None:
        return FAILED
    if validateList(list_templatesout[0]) == FAIL:
        return FAILED

    for template in list_templatesout:
        if template.isready and template.templatetype == "USER" and template.ostypename == ostype_desc:
            return template
    """
    Return default first template, if no template matched
    """

    return FAILED