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
Exemplo n.º 2
0
    def test_01_deploy_instance_with_is_volatile_offering(self):
        """ Test deploy an instance with service offerings with IsVolatile set.
        """

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

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

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

        for vm in vms:
            self.debug("VM name: %s, VM state: %s" % (vm.name, vm.state))
            self.debug("%s" %vm)
            self.assertEqual(
                             vm.state,
                             "Running",
                             "Vm state should be running for each VM deployed"
                             )
        return
Exemplo n.º 3
0
    def VerifyStaticNatForPublicIp(self, ipaddressid, natrulestatus):
        """ List public IP and verify that NAT rule status for the IP is as desired """

        publiciplist = PublicIPAddress.list(self.apiclient, id=ipaddressid, listall=True)
        self.assertEqual(validateList(publiciplist)[0], PASS, "Public IP list validation failed")
        self.assertEqual(publiciplist[0].isstaticnat, natrulestatus, "isstaticnat should be %s, it is %s" %
                (natrulestatus, publiciplist[0].isstaticnat))

        return
Exemplo n.º 4
0
def verifyNetworkState(apiclient, networkid, state):
    """List networks and check if the network state matches the given state"""
    try:
        networks = Network.list(apiclient, id=networkid)
    except Exception as e:
        raise Exception("Failed while fetching network list with error: %s" % e)
    assert validateList(networks)[0] == PASS, "Networks list validation failed, list is %s" % networks
    assert str(networks[0].state).lower() == state, "network state should be %s, it is %s" % (state, networks[0].state)
    return
Exemplo n.º 5
0
def verifyNetworkState(apiclient, networkid, state):
    """List networks and check if the network state matches the given state"""
    try:
        networks = Network.list(apiclient, id=networkid)
    except Exception as e:
        raise Exception("Failed while fetching network list with error: %s" %
                        e)
    assert validateList(networks)[
        0] == PASS, "Networks list validation failed, list is %s" % networks
    assert str(networks[0].state).lower(
    ) == state, "network state should be %s, it is %s" % (state,
                                                          networks[0].state)
    return
Exemplo n.º 6
0
def is_public_ip_in_correct_state(apiclient, ipaddressid, state):
    """ Check if the given IP is in the correct state (given)
    and return True/False accordingly"""
    retriesCount = 10
    while True:
        portableips = PublicIPAddress.list(apiclient, id=ipaddressid)
        assert validateList(portableips)[0] == PASS, "IPs list validation failed"
        if str(portableips[0].state).lower() == state:
            break
        elif retriesCount == 0:
           return False
        else:
            retriesCount -= 1
            time.sleep(60)
            continue
    return True
Exemplo n.º 7
0
def createNetwork(self, networkType):
    """Create a network of given type (isolated/shared/isolated in VPC)"""

    network = None

    if networkType == ISOLATED_NETWORK:
        try:
            network = Network.create(self.apiclient,self.services["isolated_network"],
                                     networkofferingid=self.isolated_network_offering.id,
                                     accountid=self.account.name,domainid=self.account.domainid,
                                     zoneid=self.zone.id)
        except Exception as e:
            self.fail("Isolated network creation failed because: %s" % e)

    elif networkType == SHARED_NETWORK:
        physical_network, vlan = get_free_vlan(self.api_client, self.zone.id)

        #create network using the shared network offering created
        self.services["shared_network"]["acltype"] = "domain"
        self.services["shared_network"]["vlan"] = vlan
        self.services["shared_network"]["networkofferingid"] = self.shared_network_offering.id
        self.services["shared_network"]["physicalnetworkid"] = physical_network.id

        self.services["shared_network"] = setSharedNetworkParams(self.services["shared_network"])

        try:
            network = Network.create(self.api_client, self.services["shared_network"],
                                     networkofferingid=self.shared_network_offering.id, zoneid=self.zone.id)
            self.cleanup.append(network)
        except Exception as e:
            self.fail("Shared Network creation failed because: %s" % e)

    elif networkType == VPC_NETWORK:
        self.services["vpc"]["cidr"] = "10.1.1.1/16"
        self.debug("creating a VPC network in the account: %s" %
                                                    self.account.name)
        vpc = VPC.create(self.apiclient, self.services["vpc"],
                         vpcofferingid=self.vpc_off.id, zoneid=self.zone.id,
                         account=self.account.name, domainid=self.account.domainid)
        vpcs = VPC.list(self.apiclient, id=vpc.id)
        self.assertEqual(validateList(vpcs)[0], PASS, "VPC list validation failed, vpc list is %s" % vpcs)

        network = Network.create(self.api_client,self.services["isolated_network"],
                                 networkofferingid=self.isolated_network_offering_vpc.id,
                                 accountid=self.account.name,domainid=self.account.domainid,
                                 zoneid=self.zone.id, vpcid=vpc.id, gateway="10.1.1.1", netmask="255.255.255.0")
    return network
Exemplo n.º 8
0
def is_public_ip_in_correct_state(apiclient, ipaddressid, state):
    """ Check if the given IP is in the correct state (given)
    and return True/False accordingly"""
    retriesCount = 10
    while True:
        portableips = PublicIPAddress.list(apiclient, id=ipaddressid)
        assert validateList(
            portableips)[0] == PASS, "IPs list validation failed"
        if str(portableips[0].state).lower() == state:
            break
        elif retriesCount == 0:
            return False
        else:
            retriesCount -= 1
            time.sleep(60)
            continue
    return True
Exemplo n.º 9
0
    def verify_template_listing(self, template):

        retriesCount = int(self.services["retriesCount"])

        template_list_validation_result = None

        while True:
            list_template_response = list_templates(
                                self.apiclient,
                                templatefilter=\
                                self.services["template"]["templatefilter"],
                                id=template.id,
                                zoneid=self.zone.id,
                                account=self.account.name,
                                domainid=self.account.domainid
                                )

            template_list_validation_result = validateList(list_template_response)

            if template_list_validation_result[0] == PASS:
                break

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

	        # Sleep for 5 seconds and again continue the loop if retriesCount has not reached zero
            time.sleep(5)

	        #Reduce the retriesCount until it becomes zero, when it reaches zero, exception is raised
            retriesCount = retriesCount - 1

        template_response = template_list_validation_result[1]

        self.assertEqual(
                        template_response.isready,
                        True,
                        "Check isready of newly created template Expected :True Got:%s" %template_response.isready
                    )

        return
    def verify_template_listing(self, template):

        retriesCount = int(self.services["retriesCount"])

        template_list_validation_result = None

        while True:
            list_template_response = list_templates(
                                self.apiclient,
                                templatefilter=\
                                self.services["template"]["templatefilter"],
                                id=template.id,
                                zoneid=self.zone.id,
                                account=self.account.name,
                                domainid=self.account.domainid
                                )

            template_list_validation_result = validateList(
                list_template_response)

            if template_list_validation_result[0] == PASS:
                break

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

# Sleep for 5 seconds and again continue the loop if retriesCount has not reached zero
            time.sleep(5)

            #Reduce the retriesCount until it becomes zero, when it reaches zero, exception is raised
            retriesCount = retriesCount - 1

        template_response = template_list_validation_result[1]

        self.assertEqual(
            template_response.isready, True,
            "Check isready of newly created template Expected :True Got:%s" %
            template_response.isready)

        return
    def test_02_reboot_instance_with_is_volatile_offering(self):
        """ Test rebooting instances created with isVolatile service offerings
        """

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

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

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

        vm_list_validation_result = validateList(vms)

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

        vm_with_reset = vm_list_validation_result[1]
        vm_with_reset_root_disk_id = self.get_root_device_uuid_for_vm(vm_with_reset.id, vm_with_reset.rootdeviceid)

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

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

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

        vm_without_reset = vm_list_validation_result[1]

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

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

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

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

        project = None
        try:
            self.virtual_machine = VirtualMachine.create(self.apiclient,
                                                         self.services["virtual_machine"],
                                                         accountid=self.account.name,
                                                         domainid=self.domain.id,
                                                         serviceofferingid=self.service_offering.id,
                                                         mode=self.zone.networktype if pfrule else 'basic',
                                                         networkids=[str(self.network.id)],
                                                         projectid=project.id if project else None)
            self.cleanup_vms.append(self.virtual_machine)
        except Exception as e:
            self.fail("Virtual machine deployment failed with exception: %s" % e)
        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
Exemplo n.º 13
0
    def test_08_migrate_vm(self):
        """Test migrate VM
        """
        # Validate the following
        # 1. Environment has enough hosts for migration
        # 2. DeployVM on suitable host (with another host in the cluster)
        # 3. Migrate the VM and assert migration successful

        suitable_hosts = None

        hosts = Host.list(self.apiclient, zoneid=self.zone.id, type='Routing')
        self.assertEqual(
            validateList(hosts)[0], PASS, "hosts list validation failed")

        if len(hosts) < 2:
            self.skipTest(
                "At least two hosts should be present in the zone for migration"
            )

        hypervisor = str(get_hypervisor_type(self.apiclient)).lower()

        # For KVM, two hosts used for migration should  be present in same cluster
        # For XenServer and VMware, migration is possible between hosts belonging to different clusters
        # with the help of XenMotion and Vmotion respectively.

        if hypervisor == "kvm":
            #identify suitable host
            clusters = [h.clusterid for h in hosts]
            #find hosts withe same clusterid
            clusters = [
                cluster for index, cluster in enumerate(clusters)
                if clusters.count(cluster) > 1
            ]

            if len(clusters) <= 1:
                self.skipTest(
                    "In KVM, Live Migration needs two hosts within same cluster"
                )

            suitable_hosts = [
                host for host in hosts if host.clusterid == clusters[0]
            ]
        else:
            suitable_hosts = hosts

        target_host = suitable_hosts[0]
        migrate_host = suitable_hosts[1]

        #deploy VM on target host
        self.vm_to_migrate = VirtualMachine.create(
            self.api_client,
            self.services["small"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.small_offering.id,
            mode=self.services["mode"],
            hostid=target_host.id)
        self.debug("Migrating VM-ID: %s to Host: %s" %
                   (self.vm_to_migrate.id, migrate_host.id))

        self.vm_to_migrate.migrate(self.api_client, migrate_host.id)

        list_vm_response = list_virtual_machines(self.apiclient,
                                                 id=self.vm_to_migrate.id)
        self.assertNotEqual(list_vm_response, None,
                            "Check virtual machine is listed")

        vm_response = list_vm_response[0]

        self.assertEqual(vm_response.id, self.vm_to_migrate.id,
                         "Check virtual machine ID of migrated VM")

        self.assertEqual(vm_response.hostid, migrate_host.id,
                         "Check destination hostID of migrated VM")
        return
Exemplo n.º 14
0
    def test_08_migrate_vm(self):
        """Test migrate VM
        """
        # Validate the following
        # 1. Environment has enough hosts for migration
        # 2. DeployVM on suitable host (with another host in the cluster)
        # 3. Migrate the VM and assert migration successful

        suitable_hosts = None

        hosts = Host.list(
            self.apiclient,
            zoneid=self.zone.id,
            type='Routing'
        )
        self.assertEqual(validateList(hosts)[0], PASS, "hosts list validation failed")

        if len(hosts) < 2:
            self.skipTest("At least two hosts should be present in the zone for migration")

        hypervisor = str(get_hypervisor_type(self.apiclient)).lower()

        # For KVM, two hosts used for migration should  be present in same cluster
        # For XenServer and VMware, migration is possible between hosts belonging to different clusters
        # with the help of XenMotion and Vmotion respectively.

        if hypervisor == "kvm":
            #identify suitable host
            clusters = [h.clusterid for h in hosts]
            #find hosts withe same clusterid
            clusters = [cluster for index, cluster in enumerate(clusters) if clusters.count(cluster) > 1]

            if len(clusters) <= 1:
                self.skipTest("In KVM, Live Migration needs two hosts within same cluster")

            suitable_hosts = [host for host in hosts if host.clusterid == clusters[0]]
        else:
            suitable_hosts = hosts

        target_host = suitable_hosts[0]
        migrate_host = suitable_hosts[1]

        #deploy VM on target host
        self.vm_to_migrate = VirtualMachine.create(
            self.api_client,
            self.services["small"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.small_offering.id,
            mode=self.services["mode"],
            hostid=target_host.id
        )
        self.debug("Migrating VM-ID: %s to Host: %s" % (
                                        self.vm_to_migrate.id,
                                        migrate_host.id
                                        ))

        self.vm_to_migrate.migrate(self.api_client, migrate_host.id)

        list_vm_response = list_virtual_machines(
                                            self.apiclient,
                                            id=self.vm_to_migrate.id
                                            )
        self.assertNotEqual(
                            list_vm_response,
                            None,
                            "Check virtual machine is listed"
                        )

        vm_response = list_vm_response[0]

        self.assertEqual(
                            vm_response.id,
                            self.vm_to_migrate.id,
                            "Check virtual machine ID of migrated VM"
                        )

        self.assertEqual(
                            vm_response.hostid,
                            migrate_host.id,
                            "Check destination hostID of migrated VM"
                        )
        return
Exemplo n.º 15
0
    def test_vmware_anti_affinity(self):
        """ Test Set up anti-affinity rules

            The test requires following pre-requisites
            - VMWare cluster configured in fully automated mode
        """

        # Validate the following
        # 1. Deploy VMs on host 1 and 2
        # 2. Enable maintenance mode for host 1
        # 3. VM should be migrated to 3rd host

        hosts = Host.list(
                          self.apiclient,
                          zoneid=self.zone.id,
                          resourcestate='Enabled',
                          type='Routing'
                          )
        self.assertEqual(
                         isinstance(hosts, list),
                         True,
                         "List hosts should return valid host response"
                         )

        self.debug(len(hosts))

        self.assertGreaterEqual(
                         len(hosts),
                         3,
                         "There must be at least 3 hosts present in a cluster"
                        )

        aff_grp = self.create_aff_grp(aff_grp=self.services["host_anti_affinity"], acc=self.account.name, domainid=self.domain.id)

        vm_1 = VirtualMachine.create(
                              self.apiclient,
                              self.services["virtual_machine"],
                              accountid=self.account.name,
                              domainid=self.domain.id,
                              serviceofferingid=self.service_offering.id,
                              affinitygroupnames=[aff_grp.name]
                             )

        vm_2 = VirtualMachine.create(
                              self.apiclient,
                              self.services["virtual_machine"],
                              accountid=self.account.name,
                              domainid=self.domain.id,
                              serviceofferingid=self.service_offering.id,
                              affinitygroupnames=[aff_grp.name]
                             )

        host_1 = vm_1.hostid

        host_2 = vm_2.hostid

        vms = VirtualMachine.list(
                                  self.apiclient,
                                  id=vm_1.id,
                                  listall=True
                                  )
        vm_list_validation_result = validateList(vms)

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

        virtual_machine_1 = vm_list_validation_result[1]

        self.debug("VM State: %s" % virtual_machine_1.state)
        self.assertEqual(
                         virtual_machine_1.state,
                         "Running",
                         "Deployed VM should be in RUnning state"
                         )

        vms = VirtualMachine.list(
                                  self.apiclient,
                                  id=vm_2.id,
                                  listall=True
                                  )
        vm_list_validation_result = validateList(vms)

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

        virtual_machine_2 = vm_list_validation_result[1]

        self.debug("VM %s  State: %s" % (
                                         virtual_machine_2.name,
                                         virtual_machine_2.state
                                         ))
        self.assertEqual(
                         virtual_machine_2.state,
                         "Running",
                         "Deployed VM should be in RUnning state"
                         )
        self.debug("Enabling maintenance mode on host_1: %s" % host_1)

        cmd = prepareHostForMaintenance.prepareHostForMaintenanceCmd()
        cmd.id = host_1
        self.apiclient.prepareHostForMaintenance(cmd)

        timeout = self.services["timeout"]
        while True:
            hosts = Host.list(
                          self.apiclient,
                          zoneid=self.zone.id,
                          type='Routing',
                          id=host_1
                          )
            host_list_validation_result = validateList(hosts)

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

            host = host_list_validation_result[1]

            if host.resourcestate == 'Maintenance':
                break
            elif timeout == 0:
                self.fail("Failed to put host: %s in maintenance mode" % host.name)

            time.sleep(self.services["sleep"])
            timeout = timeout - 1

        vms = VirtualMachine.list(
                                  self.apiclient,
                                  id=virtual_machine_1.id,
                                  listall=True
                                  )
        vm_list_validation_result = validateList(vms)

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

        vm = vm_list_validation_result[0]

        self.assertEqual(
                         vm.state,
                         "Running",
                         "Deployed VM should be in RUnning state"
                         )
        self.assertNotEqual(
                         vm.hostid,
                         host_2,
                         "The host name should not match with second host name"
                         )

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

        return
Exemplo n.º 16
0
    def test_vmware_affinity(self):
        """ Test Set up affinity rules

            The test requires following pre-requisites
            - VMWare cluster configured in fully automated mode
        """

        # Validate the following
        # 1. Deploy 2 VMs on same hosts
        # 2. Migrate one VM from one host to another
        # 3. The second VM should also get migrated

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

        host_1 = hosts[0].id

        host_2 = hosts[1].id

        aff_grp = self.create_aff_grp(aff_grp=self.services["host_affinity"], acc=self.account.name, domainid=self.domain.id)

        vm_1 = VirtualMachine.create(
                              self.apiclient,
                              self.services["virtual_machine"],
                              accountid=self.account.name,
                              domainid=self.domain.id,
                              serviceofferingid=self.service_offering.id,
                              affinitygroupnames=[aff_grp.name],
                              hostid = host_1
                             )

        vm_2 = VirtualMachine.create(
                              self.apiclient,
                              self.services["virtual_machine"],
                              accountid=self.account.name,
                              domainid=self.domain.id,
                              serviceofferingid=self.service_offering.id,
                              affinitygroupnames=[aff_grp.name]
                             )

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

        vm_list_validation_result = validateList(vms)

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

        virtual_machine_1 = vm_list_validation_result[1]

        self.assertEqual(
                         virtual_machine_1.state,
                         "Running",
                         "Deployed VM should be in RUnning state"
                         )

        self.debug("Deploying VM on account: %s" % self.account.name)

        vms = VirtualMachine.list(
                                  self.apiclient,
                                  id=vm_2.id,
                                  listall=True
                                  )
        vm_list_validation_result = validateList(vms)

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

        virtual_machine_2 = vm_list_validation_result[1]

        self.assertEqual(
                         virtual_machine_2.state,
                         "Running",
                         "Deployed VM should be in RUnning state"
                         )

        self.debug("Migrate VM from host_1 to host_2")
        cmd = migrateVirtualMachine.migrateVirtualMachineCmd()
        cmd.virtualmachineid = virtual_machine_2.id
        cmd.hostid = host_2
        self.apiclient.migrateVirtualMachine(cmd)
        self.debug("Migrated VM from host_1 to host_2")

        vms = VirtualMachine.list(
                                  self.apiclient,
                                  hostid=host_2,
                                  listall=True
                                  )
        vm_list_validation_result = validateList(vms)

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

        vmids = [vm.id for vm in vms]

        self.assertIn(
                      virtual_machine_1.id,
                      vmids,
                      "VM 1 should be successfully migrated to host 2"
                      )
        self.assertIn(
                      virtual_machine_2.id,
                      vmids,
                      "VM 2 should be automatically migrated to host 2"
                      )
        return
    def test_vmware_anti_affinity(self):
        """ Test Set up anti-affinity rules

            The test requires following pre-requisites
            - VMWare cluster configured in fully automated mode
        """

        # Validate the following
        # 1. Deploy VMs on host 1 and 2
        # 2. Enable maintenance mode for host 1
        # 3. VM should be migrated to 3rd host

        hosts = Host.list(self.apiclient,
                          zoneid=self.zone.id,
                          resourcestate='Enabled',
                          type='Routing')
        self.assertEqual(isinstance(hosts, list), True,
                         "List hosts should return valid host response")

        self.debug(len(hosts))

        self.assertGreaterEqual(
            len(hosts), 3,
            "There must be at least 3 hosts present in a cluster")

        aff_grp = self.create_aff_grp(
            aff_grp=self.services["host_anti_affinity"],
            acc=self.account.name,
            domainid=self.domain.id)

        vm_1 = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.domain.id,
            serviceofferingid=self.service_offering.id,
            affinitygroupnames=[aff_grp.name])

        vm_2 = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.domain.id,
            serviceofferingid=self.service_offering.id,
            affinitygroupnames=[aff_grp.name])

        host_1 = vm_1.hostid

        host_2 = vm_2.hostid

        vms = VirtualMachine.list(self.apiclient, id=vm_1.id, listall=True)
        vm_list_validation_result = validateList(vms)

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

        virtual_machine_1 = vm_list_validation_result[1]

        self.debug("VM State: %s" % virtual_machine_1.state)
        self.assertEqual(virtual_machine_1.state, "Running",
                         "Deployed VM should be in RUnning state")

        vms = VirtualMachine.list(self.apiclient, id=vm_2.id, listall=True)
        vm_list_validation_result = validateList(vms)

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

        virtual_machine_2 = vm_list_validation_result[1]

        self.debug("VM %s  State: %s" %
                   (virtual_machine_2.name, virtual_machine_2.state))
        self.assertEqual(virtual_machine_2.state, "Running",
                         "Deployed VM should be in RUnning state")
        self.debug("Enabling maintenance mode on host_1: %s" % host_1)

        cmd = prepareHostForMaintenance.prepareHostForMaintenanceCmd()
        cmd.id = host_1
        self.apiclient.prepareHostForMaintenance(cmd)

        timeout = self.services["timeout"]
        while True:
            hosts = Host.list(self.apiclient,
                              zoneid=self.zone.id,
                              type='Routing',
                              id=host_1)
            host_list_validation_result = validateList(hosts)

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

            host = host_list_validation_result[1]

            if host.resourcestate == 'Maintenance':
                break
            elif timeout == 0:
                self.fail("Failed to put host: %s in maintenance mode" %
                          host.name)

            time.sleep(self.services["sleep"])
            timeout = timeout - 1

        vms = VirtualMachine.list(self.apiclient,
                                  id=virtual_machine_1.id,
                                  listall=True)
        vm_list_validation_result = validateList(vms)

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

        vm = vm_list_validation_result[0]

        self.assertEqual(vm.state, "Running",
                         "Deployed VM should be in RUnning state")
        self.assertNotEqual(
            vm.hostid, host_2,
            "The host name should not match with second host name")

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

        return
    def test_03_restore_vm_with_new_template(self):
        """ Test restoring a vm with different template than the one it was created with
        """

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

        host_list_validation_result = validateList(hosts)

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

        hypervisor = host_list_validation_result[1].hypervisor

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

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

                self.verify_template_listing(template)

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

                # Make sure the VMs now have the new template ID
                # Make sure the Ip address of the VMs haven't changed
                self.debug("Checking template id of VM with isVolatile=True")
                vms = VirtualMachine.list(self.apiclient,
                                          id=self.vm_with_reset.id,
                                          listall=True)

                vm_list_validation_result = validateList(vms)

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

                vm_with_reset = vm_list_validation_result[1]

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

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

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

                vm_list_validation_result = validateList(vms)

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

                vm_without_reset = vm_list_validation_result[1]

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

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

            return
    def test_02_reboot_instance_with_is_volatile_offering(self):
        """ Test rebooting instances created with isVolatile service offerings
        """

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

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

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

        vm_list_validation_result = validateList(vms)

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

        vm_with_reset = vm_list_validation_result[1]
        vm_with_reset_root_disk_id = self.get_root_device_uuid_for_vm(
            vm_with_reset.id, vm_with_reset.rootdeviceid)

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

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

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

        vm_without_reset = vm_list_validation_result[1]

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

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

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

        return
    def test_03_restore_vm_with_new_template(self):
        """ Test restoring a vm with different template than the one it was created with
        """

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

        host_list_validation_result = validateList(hosts)

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

        hypervisor = host_list_validation_result[1].hypervisor

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

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

                self.verify_template_listing(template)

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

                # Make sure the VMs now have the new template ID
                # Make sure the Ip address of the VMs haven't changed
                self.debug("Checking template id of VM with isVolatile=True")
                vms = VirtualMachine.list(self.apiclient, id=self.vm_with_reset.id, listall=True)

                vm_list_validation_result = validateList(vms)

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

                vm_with_reset = vm_list_validation_result[1]

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

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

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

                vm_list_validation_result = validateList(vms)

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

                vm_without_reset = vm_list_validation_result[1]

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

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

            return
    def test_04_reoccuring_snapshot_rules(self):
        """
        1) Create a VM using the Service offering IsVolatile enabled
        2) Apply a recurring snapshot rule on the  Volume.
        3) After a couple of snapshots are taken reboot the VM.

        Verify the following conditions
        1) New root disk should be formed
        2) The recurring snapshot rule should be deleted
        """
        vms = VirtualMachine.list(self.apiclient,
                                  id=self.vm_with_reset.id,
                                  listall=True)

        vm_list_validation_result = validateList(vms)

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

        vm_with_reset = vm_list_validation_result[1]
        vm_with_reset_root_disk_id = self.get_root_device_uuid_for_vm(
            vm_with_reset.id, vm_with_reset.rootdeviceid)

        now = datetime.now()
        delta = timedelta(minutes=15)
        scheduled_time = now + delta

        self.services["recurring_snapshot"]["schedule"] = scheduled_time.minute

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

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

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

        snapshot_list_validation_result = validateList(list_snapshots_policy)

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

        snapshots_policy = snapshot_list_validation_result[1]

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

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

            snapshot_list_validation_result = validateList(snapshots)

            if snapshot_list_validation_result[0] == PASS:
                break

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

            time.sleep(60)
            retriesCount = retriesCount - 1

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

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

        vm_list_validation_result = validateList(vms)

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

        vm_with_reset_after_reboot = vm_list_validation_result[1]

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

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

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

        with self.assertRaises(Exception):
            list_snapshots_policy = SnapshotPolicy.list(
                self.apiclient, volumeid=vm_with_reset_root_disk_id)
        return
    def test_04_reoccuring_snapshot_rules(self):
        """
        1) Create a VM using the Service offering IsVolatile enabled
        2) Apply a recurring snapshot rule on the  Volume.
        3) After a couple of snapshots are taken reboot the VM.

        Verify the following conditions
        1) New root disk should be formed
        2) The recurring snapshot rule should be deleted
        """
        vms = VirtualMachine.list(self.apiclient, id=self.vm_with_reset.id, listall=True)

        vm_list_validation_result = validateList(vms)

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

        vm_with_reset = vm_list_validation_result[1]
        vm_with_reset_root_disk_id = self.get_root_device_uuid_for_vm(vm_with_reset.id, vm_with_reset.rootdeviceid)

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

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

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

        snapshot_list_validation_result = validateList(list_snapshots_policy)

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

        snapshots_policy = snapshot_list_validation_result[1]

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

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

            snapshot_list_validation_result = validateList(snapshots)

            if snapshot_list_validation_result[0] == PASS:
                break

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

            time.sleep(60)
            retriesCount = retriesCount - 1

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

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

        vm_list_validation_result = validateList(vms)

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

        vm_with_reset_after_reboot = vm_list_validation_result[1]

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

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

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

        with self.assertRaises(Exception):
            list_snapshots_policy = SnapshotPolicy.list(self.apiclient, volumeid=vm_with_reset_root_disk_id)
        return
    def test_vmware_affinity(self):
        """ Test Set up affinity rules

            The test requires following pre-requisites
            - VMWare cluster configured in fully automated mode
        """

        # Validate the following
        # 1. Deploy 2 VMs on same hosts
        # 2. Migrate one VM from one host to another
        # 3. The second VM should also get migrated

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

        host_1 = hosts[0].id

        host_2 = hosts[1].id

        aff_grp = self.create_aff_grp(aff_grp=self.services["host_affinity"],
                                      acc=self.account.name,
                                      domainid=self.domain.id)

        vm_1 = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.domain.id,
            serviceofferingid=self.service_offering.id,
            affinitygroupnames=[aff_grp.name],
            hostid=host_1)

        vm_2 = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.domain.id,
            serviceofferingid=self.service_offering.id,
            affinitygroupnames=[aff_grp.name])

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

        vm_list_validation_result = validateList(vms)

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

        virtual_machine_1 = vm_list_validation_result[1]

        self.assertEqual(virtual_machine_1.state, "Running",
                         "Deployed VM should be in RUnning state")

        self.debug("Deploying VM on account: %s" % self.account.name)

        vms = VirtualMachine.list(self.apiclient, id=vm_2.id, listall=True)
        vm_list_validation_result = validateList(vms)

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

        virtual_machine_2 = vm_list_validation_result[1]

        self.assertEqual(virtual_machine_2.state, "Running",
                         "Deployed VM should be in RUnning state")

        self.debug("Migrate VM from host_1 to host_2")
        cmd = migrateVirtualMachine.migrateVirtualMachineCmd()
        cmd.virtualmachineid = virtual_machine_2.id
        cmd.hostid = host_2
        self.apiclient.migrateVirtualMachine(cmd)
        self.debug("Migrated VM from host_1 to host_2")

        vms = VirtualMachine.list(self.apiclient, hostid=host_2, listall=True)
        vm_list_validation_result = validateList(vms)

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

        vmids = [vm.id for vm in vms]

        self.assertIn(virtual_machine_1.id, vmids,
                      "VM 1 should be successfully migrated to host 2")
        self.assertIn(virtual_machine_2.id, vmids,
                      "VM 2 should be automatically migrated to host 2")
        return
    def test_check_vm_stats(self, value):
        """Deploy VM with dynamic service offering and check VM stats"""

        # Steps:
        # 1. Create admin/user account and create its user api client
        # 2. Create a dynamic service offering
        # 3. Deploy a VM with account api client and dynamic service offering
        #    providing custom values for cpu number, cpu speed and memory
        # 4. List the VM and verify the dynamic parameters are same as passed

        isadmin=True
        if value == USER_ACCOUNT:
            isadmin=False

        # Create Account and api client
        self.account = Account.create(self.apiclient,self.services["account"],domainid=self.domain.id, admin=isadmin)
        apiclient = self.testClient.createUserApiClient(
                                    UserName=self.account.name,
                                    DomainName=self.account.domain)
        self.cleanup.append(self.account)

        # Create dynamic compute offering
        self.services["service_offering"]["cpunumber"] = ""
        self.services["service_offering"]["cpuspeed"] = ""
        self.services["service_offering"]["memory"] = ""

        serviceOffering = ServiceOffering.create(self.apiclient,
                                                 self.services["service_offering"])

        self.cleanup_co.append(serviceOffering)

        # Custom values
        customcpunumber = 2
        customcpuspeed = 256
        custommemory = 128

        # Deploy VM with dynamic service offering and the custom values
        try:
            virtualMachine = VirtualMachine.create(apiclient,self.services["virtual_machine"],
                serviceofferingid=serviceOffering.id,
                customcpunumber=customcpunumber,
                customcpuspeed=customcpuspeed,
                custommemory=custommemory,
                accountid=self.account.name,domainid=self.account.domainid)
        except Exception as e:
            self.fail("vm creation failed: %s" % e)

        vmlist = VirtualMachine.list(self.apiclient, 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(customcpunumber), "vm cpu number %s\
                 not matching with provided custom cpu number %s" % \
                 (vm.cpunumber, customcpunumber))

        self.assertEqual(str(vm.cpuspeed), str(customcpuspeed), "vm cpu speed %s\
                 not matching with provided custom cpu speed %s" % \
                 (vm.cpuspeed, customcpuspeed))

        self.assertEqual(str(vm.memory), str(custommemory), "vm memory %s\
                 not matching with provided custom memory %s" % \
                 (vm.memory, custommemory))
        return