def test_04_change_service_offerring_vpc(self):
        """ Tests to change service offering of the Router after
            creating a vpc
        """

        # Validate the following
        # 1. Create a VPC with cidr - 10.1.1.1/16
        # 2. Change the service offerings of the VPC Virtual Router which is
        # created as a result of VPC creation.

        self.validate_vpc_offering(self.vpc_off)
        self.validate_vpc_network(self.vpc)

        routers = Router.list(
            self.api_client,
            account=self.account.name,
            domainid=self.account.domainid,
            listall=True
        )
        self.assertEqual(
            isinstance(routers, list),
            True,
            "List Routers should return a valid list"
        )

        # Stop the router
        router = routers[0]
        self.debug("Stopping the router with ID: %s" % router.id)
        cmd = stopRouter.stopRouterCmd()
        cmd.id = router.id
        self.api_client.stopRouter(cmd)

        service_offering = ServiceOffering.create(
            self.api_client,
            self.services["service_offering_new"]
        )
        self.debug("Changing service offering for the Router %s" % router.id)
        try:
            router = Router.change_service_offering(self.api_client,
                                                    router.id,
                                                    service_offering.id
                                                    )
        except:
            self.fail("Changing service offering failed")

        self.debug("Router %s" % router)
        routers = Router.list(
            self.api_client,
            account=self.account.name,
            domainid=self.account.domainid,
            listall=True
        )
        router = routers[0]
        self.assertEqual(
            router.serviceofferingid,
            service_offering.id,
            "Changing service offering failed as id is %s and expected"
            "is %s" % (router.serviceofferingid, service_offering.id)
        )
        return
    def _disable_zone_and_delete_system_vms(self, virtual_router, verify_managed_system_vm_deleted=True):
        self.zone.update(self.apiClient, id=self.zone.id, allocationstate="Disabled")

        if virtual_router is not None:
            Router.destroy(self.apiClient, virtual_router.id)

            if verify_managed_system_vm_deleted:
                cs_root_volume = self._get_root_volume_for_system_vm(virtual_router.id, 'Expunged')

                self._verify_managed_system_vm_deleted(cs_root_volume.name)

        # list_ssvms lists the secondary storage VM and the console proxy VM
        system_vms = list_ssvms(self.apiClient)

        for system_vm in system_vms:
            destroy_ssvm_cmd = destroySystemVm.destroySystemVmCmd()

            destroy_ssvm_cmd.id = system_vm.id

            self.apiClient.destroySystemVm(destroy_ssvm_cmd)

            if verify_managed_system_vm_deleted:
                cs_root_volume = self._get_root_volume_for_system_vm(system_vm.id, 'Expunged')

                self._verify_managed_system_vm_deleted(cs_root_volume.name)
    def test_05_destroy_router_after_creating_vpc(self):
        """ Test to destroy the router after creating a VPC
            """
        # Validate the following
        # 1. Create a VPC with cidr - 10.1.1.1/16
        # 2. Destroy the VPC Virtual Router which is created as a result of VPC
        # creation.
        self.validate_vpc_offering(self.vpc_off)
        self.validate_vpc_network(self.vpc)
        routers = Router.list(self.api_client,
                              account=self.account.name,
                              domainid=self.account.domainid,
                              listall=True)
        self.assertEqual(isinstance(routers, list), True,
                         "List Routers should return a valid list")

        Router.destroy(self.api_client, id=routers[0].id)

        routers = Router.list(self.api_client,
                              account=self.account.name,
                              domainid=self.account.domainid,
                              listall=True)
        self.assertEqual(isinstance(routers, list), False,
                         "List Routers should be empty")
        return
Beispiel #4
0
    def test_09_create_policy_router_destroy(self):
        """Test check the stickiness policy rules after destroying router"""

        # Validate the following
        # 1. create an account
        # 2. using that account,create an instances
        # 3. select the Source NAT IP  and configure the stikiness policy
        # 4. destroy the router.

        self.debug("Creating LB rule for account: %s" % self.account.name)
        lb_rule = self.create_LB_Rule(
            self.public_ip,
            network=self.get_Network(self.account),
            vmarray=[self.virtual_machine, self.virtual_machine_2],
        )

        self.debug("Fetching routers for the account: %s" % self.account.name)
        router = self.get_router(self.account)

        policies = self.configure_Stickiness_Policy(lb_rule, method="LbCookie")
        policy = policies.stickinesspolicy[0]

        self.debug("Policy: %s" % str(policy))
        self.debug("Validating the stickiness policy")
        self.validate_Stickiness_Policy(lb_rule, "LbCookie", self.public_ip.ipaddress.ipaddress)

        self.debug("Destroying the router: %s" % router.name)
        Router.destroy(self.apiclient, id=router.id)

        return
Beispiel #5
0
    def test_08_create_policy_router_stopped(self):
        """Test verify create stickiness policy when router is stopped state"""

        # Validate the following
        # 1. stop the router
        # 2. create stikiness policy from UI
        # 3. start the router. listLBStickinessPolicies Api should show created
        #    stikiness policy

        self.debug("Creating LB rule for account: %s" % self.account.name)
        lb_rule = self.create_LB_Rule(
            self.public_ip,
            network=self.get_Network(self.account),
            vmarray=[self.virtual_machine, self.virtual_machine_2],
        )

        self.debug("Fetching routers for the account: %s" % self.account.name)
        router = self.get_router(self.account)

        self.debug("Stopping the router: %s" % router.name)
        Router.stop(self.apiclient, id=router.id)

        policies = self.configure_Stickiness_Policy(lb_rule, method="LbCookie")
        policy = policies.stickinesspolicy[0]

        self.debug("Starting the router: %s" % router.name)
        Router.start(self.apiclient, id=router.id)

        self.debug("Policy: %s" % str(policy))
        self.debug("Validating the stickiness policy")
        self.validate_Stickiness_Policy(lb_rule, "LbCookie", self.public_ip.ipaddress.ipaddress)
        return
Beispiel #6
0
    def test_08_create_policy_router_stopped(self):
        """Test verify create stickiness policy when router is stopped state"""

        # Validate the following
        # 1. stop the router
        # 2. create stikiness policy from UI
        # 3. start the router. listLBStickinessPolicies Api should show created
        #    stikiness policy

        self.debug("Creating LB rule for account: %s" % self.account.name)
        lb_rule = self.create_LB_Rule(self.public_ip,
                                      network=self.get_Network(self.account),
                                      vmarray=[self.virtual_machine, self.virtual_machine_2])

        self.debug("Fetching routers for the account: %s" %
                                                    self.account.name)
        router = self.get_router(self.account)

        self.debug("Stopping the router: %s" % router.name)
        Router.stop(self.apiclient, id=router.id)

        policies = self.configure_Stickiness_Policy(lb_rule, method="LbCookie")
        policy = policies.stickinesspolicy[0]

        self.debug("Starting the router: %s" % router.name)
        Router.start(self.apiclient, id=router.id)

        self.debug("Policy: %s" % str(policy))
        self.debug("Validating the stickiness policy")
        self.validate_Stickiness_Policy(lb_rule, "LbCookie", self.public_ip.ipaddress.ipaddress)
        return
Beispiel #7
0
    def test_09_create_policy_router_destroy(self):
        """Test check the stickiness policy rules after destroying router"""

        # Validate the following
        # 1. create an account
        # 2. using that account,create an instances
        # 3. select the Source NAT IP  and configure the stikiness policy
        # 4. destroy the router.

        self.debug("Creating LB rule for account: %s" % self.account.name)
        lb_rule = self.create_LB_Rule(
            self.public_ip,
            network=self.get_Network(self.account),
            vmarray=[self.virtual_machine, self.virtual_machine_2])

        self.debug("Fetching routers for the account: %s" % self.account.name)
        router = self.get_router(self.account)

        policies = self.configure_Stickiness_Policy(lb_rule,
                                                    method="SourceBased")
        policy = policies.stickinesspolicy[0]

        self.debug("Policy: %s" % str(policy))
        self.debug("Validating the stickiness policy")
        self.validate_Stickiness_Policy(lb_rule, "SourceBased",
                                        self.public_ip.ipaddress.ipaddress)

        self.debug("Destroying the router: %s" % router.name)
        Router.destroy(self.apiclient, id=router.id)

        return
    def test_04_chg_srv_off_router_after_addition_of_one_guest_network(self):
        """ Test to change service offering of router after addition of one guest network
            """
        # Validations
        # 1. Create a VPC with cidr - 10.1.1.1/16
        # 2. Add network1(10.1.1.1/24) to this VPC.
        # 3. Deploy vm1,vm2 and vm3 such that they are part of network1.
        # 4. Create a PF /Static Nat/LB rule for vms in network1.
        # 5. Create ingress network ACL for allowing all the above rules from a public ip range on network1.
        # 6. Create egress network ACL for network1 to access google.com.
        # 7. Create a private gateway for this VPC and add a static route to this gateway.
        # 8. Create a VPN gateway for this VPC and add a static route to this gateway.
        # 9. Make sure that all the PF,LB and Static NAT rules work as expected.
        # 10. Make sure that we are able to access google.com from all the user Vms.
        # 11. Make sure that the newly added private gateway's and VPN
        # gateway's static routes work as expected

        self.validate_vpc_offering(self.vpc_off)
        self.validate_vpc_network(self.vpc)
        self.assertEqual(
            isinstance(self.gateways, list), True,
            "List private gateways should return a valid response")
        self.assertEqual(isinstance(self.static_routes, list), True,
                         "List static route should return a valid response")

        routers = Router.list(self.api_client,
                              account=self.account.name,
                              domainid=self.account.domainid,
                              listall=True)
        self.assertEqual(isinstance(routers, list), True,
                         "List Routers should return a valid list")

        # Stop the router
        router = routers[0]
        self.debug("Stopping the router with ID: %s" % router.id)
        cmd = stopRouter.stopRouterCmd()
        cmd.id = router.id
        self.api_client.stopRouter(cmd)

        service_offering = ServiceOffering.create(
            self.api_client, self.services["service_offering_new"])
        self.debug("Changing service offering for the Router %s" % router.id)
        try:
            router = Router.change_service_offering(self.api_client, router.id,
                                                    service_offering.id)
        except:
            self.fail("Changing service offering failed")

        self.debug("Router %s" % router)
        routers = Router.list(self.api_client,
                              account=self.account.name,
                              domainid=self.account.domainid,
                              listall=True)
        router = routers[0]
        self.assertEqual(
            router.serviceofferingid, service_offering.id,
            "Changing service offering failed as id is %s and expected"
            "is %s" % (router.serviceofferingid, service_offering.id))
        return
    def test_05_destroy_router_after_addition_of_one_guest_network(self):
        """ Test destroy of router after addition of one guest network
        """
        # Validations
        # 1. Create a VPC with cidr - 10.1.1.1/16
        # 2. Add network1(10.1.1.1/24) to this VPC.
        # 3. Deploy vm1,vm2 and vm3 such that they are part of network1.
        # 4. Create a PF /Static Nat/LB rule for vms in network1.
        # 5. Create ingress network ACL for allowing all the above rules from a public ip range on network1.
        # 6. Create egress network ACL for network1 to access google.com.
        # 7. Create a private gateway for this VPC and add a static route to this gateway.
        # 8. Create a VPN gateway for this VPC and add a static route to this gateway.
        # 9. Make sure that all the PF,LB and Static NAT rules work as expected.
        # 10. Make sure that we are able to access google.com from all the user Vms.
        # 11. Make sure that the newly added private gateway's and VPN
        # gateway's static routes work as expected

        self.validate_vpc_offering(self.vpc_off)
        self.validate_vpc_network(self.vpc)
        self.assertEqual(
            isinstance(self.gateways, list),
            True,
            "List private gateways should return a valid response"
        )
        self.assertEqual(
            isinstance(self.static_routes, list),
            True,
            "List static route should return a valid response"
        )

        routers = Router.list(
            self.api_client,
            account=self.account.name,
            domainid=self.account.domainid,
            listall=True
        )
        self.assertEqual(
            isinstance(routers, list),
            True,
            "List Routers should return a valid list"
        )

        Router.destroy(self.api_client,
                       id=routers[0].id
                       )

        routers = Router.list(
            self.api_client,
            account=self.account.name,
            domainid=self.account.domainid,
            listall=True
        )
        self.assertEqual(
            isinstance(routers, list),
            False,
            "List Routers should be empty"
        )
        return
Beispiel #10
0
    def test_13_1_egress_fr13(self):
        """Test Redundant Router : Master failover
        """
        # Validate the following:
        # 1. deploy VM using network offering with egress policy false.
        # 2. create egress rule valid cidr valid port range.
        # 3. redundant router
        # 3. All should work fine.
        #TODO: setup network with RR
        self.create_vm(RR=True, egress_policy=False)
        self.createEgressRule(cidr=TestEgressFWRules.zone.guestcidraddress)
        vm_network_id = self.virtual_machine.nic[0].networkid
        self.debug("Listing routers for network: %s" % vm_network_id)
        routers = Router.list(self.apiclient,
                              networkid=vm_network_id,
                              listall=True)
        self.assertEqual(
            isinstance(routers, list), True,
            "list router should return Master and backup routers")
        self.assertEqual(
            len(routers), 2,
            "Length of the list router should be 2 (Backup & master)")

        if routers[0].redundantstate == 'MASTER':
            master_router = routers[0]
            backup_router = routers[1]
        else:
            master_router = routers[1]
            backup_router = routers[0]

        self.debug(
            "Redundant states: %s, %s" %
            (master_router.redundantstate, backup_router.redundantstate))
        self.debug("Stopping the Master router")
        try:
            Router.stop(self.apiclient, id=master_router.id)
        except Exception as e:
            self.fail("Failed to stop master router: %s" % e)

        # wait for VR update state
        time.sleep(60)

        self.debug("Checking state of the master router in %s" %
                   self.network.name)
        routers = Router.list(self.apiclient,
                              id=master_router.id,
                              listall=True)
        self.assertEqual(
            isinstance(routers, list), True,
            "list router should return Master and backup routers")

        self.exec_script_on_user_vm('ping -c 1 www.google.com',
                                    "| grep -oP \'\d+(?=% packet loss)\'",
                                    "['0']",
                                    negative_test=False)
Beispiel #11
0
 def checkNetworkVRRedundancy(self):
     primary_router = self.getNetworkRouter(self.network)
     Router.stop(
         self.apiclient,
         id=primary_router.id
     )
     time.sleep(self.services["sleep"]/2)
     new_primary_router = self.getNetworkRouter(self.network)
     self.assertNotEqual(new_primary_router.id, primary_router.id,
         "Original primary router ID: %s of network is still the primary router after stopping" % (primary_router.id))
     print(new_primary_router)
     self.checkIpv6NetworkPrimaryRouter(new_primary_router)
    def test_13_1_egress_fr13(self):
        """Test Redundant Router : Master failover
        """
        # Validate the following:
        # 1. deploy VM using network offering with egress policy false.
        # 2. create egress rule valid cidr valid port range.
        # 3. redundant router
        # 3. All should work fine.
        #TODO: setup network with RR
        self.create_vm(RR=True, egress_policy=False)
        self.createEgressRule()
        vm_network_id = self.virtual_machine.nic[0].networkid
        self.debug("Listing routers for network: %s" % vm_network_id)
        routers = Router.list(self.apiclient,
                              networkid=vm_network_id,
                              listall=True)
        self.assertEqual(isinstance(routers, list),
                         True,
                         "list router should return Master and backup routers")
        self.assertEqual(len(routers),
                         2,
                         "Length of the list router should be 2 (Backup & master)")

        if routers[0].redundantstate == 'MASTER':
            master_router = routers[0]
            backup_router = routers[1]
        else:
            master_router = routers[1]
            backup_router = routers[0]

        self.debug("Redundant states: %s, %s" % (master_router.redundantstate,
                                                backup_router.redundantstate))
        self.debug("Stopping the Master router")
        try:
            Router.stop(self.apiclient, id=master_router.id)
        except Exception as e:
            self.fail("Failed to stop master router: %s" % e)

        # wait for VR update state
        time.sleep(60)

        self.debug("Checking state of the master router in %s" % self.network.name)
        routers = Router.list(self.apiclient,
                              id=master_router.id,
                              listall=True)
        self.assertEqual(isinstance(routers, list),
                         True,
                         "list router should return Master and backup routers")

        self.exec_script_on_user_vm('ping -c 1 www.google.com',
                                    "| grep -oP \'\d+(?=% packet loss)\'",
                                    "['0']",
                                    negative_test=False)
    def test_01_deploy_vm_no_startvm(self):
        """Test Deploy Virtual Machine with no startVM parameter
        """

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

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

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

        response = self.virtual_machine_2.getState(self.apiclient, VirtualMachine.RUNNING)
        self.assertEqual(response[0], PASS, response[1])
        self.debug("Checking the router state after VM deployment")
        routers = Router.list(self.apiclient, account=self.account.name, domainid=self.account.domainid, listall=True)
        self.assertEqual(isinstance(routers, list), True, "List routers should not return empty response")
        for router in routers:
            self.debug("Router state: %s" % router.state)
            self.assertEqual(
                router.state, "Running", "Router should be in running state when instance is running in the account"
            )
        self.debug("Destroying the running VM:%s" % self.virtual_machine_2.name)
        self.virtual_machine_2.delete(self.apiclient, expunge=True)
        routers = Router.list(self.apiclient, account=self.account.name, domainid=self.account.domainid, listall=True)
        self.assertNotEqual(routers, None, "Router should get deleted after expunge delay+wait")
        return
    def test_01_isolated_persistent_network(self):
        network = Network.create(
            self.apiclient,
            self.services["isolated_network"],
            networkofferingid=self.isolated_persistent_network_offering.id,
            zoneid=self.zone.id)
        self.cleanup.append(network)
        networkVlan = network.vlan
        response = verifyNetworkState(self.apiclient, network.id,
                                      "implemented")
        exceptionOccurred = response[0]
        isNetworkInDesiredState = response[1]
        exceptionMessage = response[2]

        if (exceptionOccurred or (not isNetworkInDesiredState)):
            self.fail(exceptionMessage)
        self.assertIsNotNone(networkVlan,
                             "vlan must not be null for persistent network")

        router = Router.list(self.apiclient, networkid=network.id)[0]
        router_host_id = router.hostid
        host = Host.list(self.apiclient, id=router_host_id)[0]
        if host.hypervisor.lower() in "kvm":
            result = self.verify_bridge_creation(host, networkVlan)
            self.assertEqual(
                int(result), 0,
                "Failed to find bridge on the breth1$-{networkVlan}")
        elif host.hypervisor.lower() in ["xenserver", "vmware"]:
            self.verify_network_setup_on_host_per_cluster(
                host.hypervisor.lower(), networkVlan)
    def test_03_migrate_router_after_addition_of_one_guest_network(self):
        """ Test migrate of router after addition of one guest network
            """
        # Validations
        # 1. Create a VPC with cidr - 10.1.1.1/16
        # 2. Add network1(10.1.1.1/24) to this VPC.
        # 3. Deploy vm1,vm2 and vm3 such that they are part of network1.
        # 4. Create a PF /Static Nat/LB rule for vms in network1.
        # 5. Create ingress network ACL for allowing all the above rules from a public ip range on network1.
        # 6. Create egress network ACL for network1 to access google.com.
        # 7. Create a private gateway for this VPC and add a static route to this gateway.
        # 8. Create a VPN gateway for this VPC and add a static route to this gateway.
        # 9. Make sure that all the PF,LB and Static NAT rules work as expected.
        # 10. Make sure that we are able to access google.com from all the user Vms.
        # 11. Make sure that the newly added private gateway's and VPN
        # gateway's static routes work as expected

        self.hypervisor = self.testClient.getHypervisorInfo()
        self.validate_vpc_offering(self.vpc_off)
        self.validate_vpc_network(self.vpc)
        self.assertEqual(
            isinstance(self.gateways, list), True,
            "List private gateways should return a valid response")
        self.assertEqual(isinstance(self.static_routes, list), True,
                         "List static route should return a valid response")
        routers = Router.list(self.api_client,
                              account=self.account.name,
                              domainid=self.account.domainid,
                              listall=True)
        self.assertEqual(isinstance(routers, list), True,
                         "List Routers should return a valid list")
        self.migrate_router(routers[0])
        return
def VerifyRouterState(apiclient, account, domainid, desiredState, retries=0):
    """List the router associated with the account and
       verify that router state matches with the desired state
       Return PASS/FAIL depending upon whether router state matches
       or not"""

    isRouterStateDesired = False
    failureMessage = ""
    while retries >= 0:
        routers = Router.list(apiclient,
                              account=account,
                              domainid=domainid,
                              listall=True)
        if str(routers[0].state).lower() == str(desiredState).lower():
            isRouterStateDesired = True
            break
        time.sleep(60)
        retries -= 1
    # whileEnd

    if not isRouterStateDesired:
        failureMessage = "Router state should be %s,\
                but it is %s"                              % \
                         (desiredState, routers[0].state)
    return [isRouterStateDesired, failureMessage]
Beispiel #17
0
    def test_03_reconnect_host(self):
        """ Test reconnect Host which has VPC elements
        """

        # Steps:
        # 1.Reconnect one of the host on which VPC Virtual Router is present.
        # Validate the following
        # 1. Host should successfully reconnect.
        # 2. Network connectivity to all the VMs on the host should not be
        #    effected due to reconnection.

        self.debug("Reconnecting the host where VPC VR is running")
        try:
            Host.reconnect(self.apiclient, id=self.vpcvr.hostid)
        except Exception as e:
            self.fail("Failed to reconnect to host: %s" % e)

        self.debug("Check the status of router after migration")
        routers = Router.list(
                              self.apiclient,
                              id=self.vpcvr.id,
                              listall=True
                              )
        self.assertEqual(
                         isinstance(routers, list),
                         True,
                         "List routers shall return the valid response"
                         )
        self.assertEqual(
                         routers[0].state,
                         "Running",
                         "Router state should be running"
                         )
        #  TODO: Check for the network connectivity
        return
    def test_02_reboot_router_after_creating_vpc(self):
        """ Test to reboot the router after creating a VPC
        """
        # Validate the following
        # 1. Create a VPC with cidr - 10.1.1.1/16
        # 2. Reboot the VPC Virtual Router which is created as a result of VPC creation.
        # Stop the VPC Router

        self.validate_vpc_offering(self.vpc_off)
        self.validate_vpc_network(self.vpc)
        routers = Router.list(self.api_client,
                              account=self.account.name,
                              domainid=self.account.domainid,
                              listall=True)
        self.assertEqual(isinstance(routers, list), True,
                         "List Routers should return a valid list")
        router = routers[0]

        self.debug("Rebooting the router ...")
        # Reboot the router
        cmd = rebootRouter.rebootRouterCmd()
        cmd.id = router.id
        self.api_client.rebootRouter(cmd)

        # List routers to check state of router
        router_response = list_routers(self.api_client, id=router.id)
        self.assertEqual(isinstance(router_response, list), True,
                         "Check list response returns a valid list")
        # List router should have router in running state and same public IP
        self.assertEqual(router_response[0].state, 'Running',
                         "Check list router response for router state")
        return
    def test_03_deploy_vm_startvm_false(self):
        """Test Deploy Virtual Machine with startVM=false parameter
        """

        # Validate the following:
        # 1. deploy Vm  with the startvm=false
        # 2. Should not be able to login to the VM.
        # 3. listVM command should return the deployed VM.State of this VM
        #    should be "Stopped".
        # 4. Check listRouters call for that account. List routers should
        #    return empty response

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

        response = self.virtual_machine.getState(self.apiclient, VirtualMachine.STOPPED)
        self.assertEqual(response[0], PASS, response[1])
        routers = Router.list(self.apiclient, account=self.account.name, domainid=self.account.domainid, listall=True)
        self.assertEqual(routers, None, "List routers should return empty response")
        self.debug("Destroying instance: %s" % self.virtual_machine.name)
        self.virtual_machine.delete(self.apiclient, expunge=True)
        return
    def test_advZoneVirtualRouter(self):
        #TODO: SIMENH: duplicate test, remove it
        """
        Test advanced zone virtual router
        1. Is Running
        2. is in the account the VM was deployed in
        3. Has a linklocalip, publicip and a guestip
        @return:
        """
        routers = Router.list(self.apiclient, account=self.account.name)
        self.assertTrue(len(routers) > 0, msg="No virtual router found")
        router = routers[0]

        self.assertEqual(router.state,
                         'Running',
                         msg="Router is not in running state")
        self.assertEqual(router.account,
                         self.account.name,
                         msg="Router does not belong to the account")

        #Has linklocal, public and guest ips
        self.assertIsNotNone(router.linklocalip,
                             msg="Router has no linklocal ip")
        self.assertIsNotNone(router.publicip, msg="Router has no public ip")
        self.assertIsNotNone(router.guestipaddress,
                             msg="Router has no guest ip")
Beispiel #21
0
 def checkIpv6NetworkRoutersBasic(self):
     self.debug("Listing routers for network: %s" % self.network.name)
     self.routers = Router.list(
         self.apiclient,
         networkid=self.network.id,
         listall=True
     )
     self.assertTrue(
         isinstance(self.routers, list),
         "Check listRouters response returns a valid list"
     )
     self.assertTrue(
         len(self.routers) > 0,
         "Router for the network isn't found"
     )
     for router in self.routers:
         self.assertFalse(
             router.isredundantrouter == True and router.redundantstate == "FAULT",
             "Router for the network is in FAULT state"
         )
         nics = router.nic
         for nic in nics:
             if (nic.traffictype == 'Guest' and router.isredundantrouter == False) or nic.traffictype == 'Public':
                 self.assertNotEqual(nic.ip6address,
                             None,
                             "IPv6 address for router %s NIC is empty" % nic.traffictype)
                 self.assertNotEqual(nic.ip6cidr,
                             None,
                             "IPv6 CIDR for router %s NIC is empty" % nic.traffictype)
                 self.assertNotEqual(nic.ip6gateway,
                             None,
                             "IPv6 gateway for router %s NIC is empty" % nic.traffictype)
Beispiel #22
0
def VerifyRouterState(apiclient, account, domainid, desiredState,
                      retries=0):
    """List the router associated with the account and
       verify that router state matches with the desired state
       Return PASS/FAIL depending upon whether router state matches
       or not"""

    isRouterStateDesired = False
    failureMessage = ""
    while retries >= 0:
        routers = Router.list(
            apiclient,
            account=account,
            domainid=domainid,
            listall=True
        )
        if str(routers[0].state).lower() == str(desiredState).lower():
            isRouterStateDesired = True
            break
        time.sleep(60)
        retries -= 1
    # whileEnd

    if not isRouterStateDesired:
        failureMessage = "Router state should be %s,\
                but it is %s" %\
            (desiredState, routers[0].state)
    return [isRouterStateDesired, failureMessage]
    def test_04_change_service_offerring_vpc(self):
        """ Tests to change service offering of the Router after
            creating a vpc
        """

        # Validate the following
        # 1. Create a VPC with cidr - 10.1.1.1/16
        # 2. Change the service offerings of the VPC Virtual Router which is
        # created as a result of VPC creation.

        self.validate_vpc_offering(self.vpc_off)
        self.validate_vpc_network(self.vpc)

        routers = Router.list(self.api_client,
                              account=self.account.name,
                              domainid=self.account.domainid,
                              listall=True)
        self.assertEqual(isinstance(routers, list), True,
                         "List Routers should return a valid list")

        # Stop the router
        router = routers[0]
        self.debug("Stopping the router with ID: %s" % router.id)
        cmd = stopRouter.stopRouterCmd()
        cmd.id = router.id
        self.api_client.stopRouter(cmd)

        service_offering = ServiceOffering.create(
            self.api_client, self.services["service_offering_new"])
        self.debug("Changing service offering for the Router %s" % router.id)
        try:
            router = Router.change_service_offering(self.api_client, router.id,
                                                    service_offering.id)
        except:
            self.fail("Changing service offering failed")

        self.debug("Router %s" % router)
        routers = Router.list(self.api_client,
                              account=self.account.name,
                              domainid=self.account.domainid,
                              listall=True)
        router = routers[0]
        self.assertEqual(
            router.serviceofferingid, service_offering.id,
            "Changing service offering failed as id is %s and expected"
            "is %s" % (router.serviceofferingid, service_offering.id))
        return
Beispiel #24
0
 def check_router_state(self, router, state=None):
     self.debug("Check if the virtual router is in state - %s" % state)
     routers = Router.list(self.api_client, id=router.id, listall=True)
     self.assertEqual(isinstance(routers, list), True,
                      "List router should return a valid list")
     if state:
         self.assertEqual(routers[0].state, state,
                          "Virtual router is not in the expected state")
     self.debug("Virtual router is in the expected state - %s" % state)
Beispiel #25
0
 def get_network_router(self, network):
     self.debug("Finding the virtual router for network: %s" % network.name)
     routers = Router.list(self.api_client,
                           networkid=network.id,
                           listall=True)
     self.assertEqual(
         isinstance(routers, list), True,
         "List routers should return a valid virtual router for network")
     return routers[0]
    def test_03_reconnect_host(self):
        """ Test reconnect Host which has VPC elements
        """

        # Steps:
        # 1.Reconnect one of the host on which VPC Virtual Router is present.
        # Validate the following
        # 1. Host should successfully reconnect.
        # 2. Network connectivity to all the VMs on the host should not be
        #    effected due to reconnection.

        try:
            timeout = self.services["timeout"]        
            while True:
                list_host_response = Host.list(
                    self.apiclient,
                    id=self.vpcvr.hostid,
                    resourcestate="Enabled")
                
                if list_host_response is not None:
                    break
                elif timeout == 0:
                    raise Exception("Failed to list the Host in Up State")

                time.sleep(self.services["sleep"])
                timeout = timeout - 1
            
            self.debug("Verified that the Host is in Up State")
            
        except:
            self.fail("Failed to find the Host in Up State")

        self.debug("Reconnecting the host where VPC VR is running")
        try:
            Host.reconnect(self.apiclient, id=self.vpcvr.hostid)
        except Exception as e:
            self.fail("Failed to reconnect to host: %s" % e)

        self.debug("Check the status of router after migration")
        routers = Router.list(
                              self.apiclient,
                              id=self.vpcvr.id,
                              listall=True
                              )
        self.assertEqual(
                         isinstance(routers, list),
                         True,
                         "List routers shall return the valid response"
                         )
        self.assertEqual(
                         routers[0].state,
                         "Running",
                         "Router state should be running"
                         )
        #  TODO: Check for the network connectivity
        return
    def test_03_reconnect_host(self):
        """ Test reconnect Host which has VPC elements
        """

        # Steps:
        # 1.Reconnect one of the host on which VPC Virtual Router is present.
        # Validate the following
        # 1. Host should successfully reconnect.
        # 2. Network connectivity to all the VMs on the host should not be
        #    effected due to reconnection.

        try:
            timeout = self.services["timeout"]        
            while True:
                list_host_response = Host.list(
                    self.apiclient,
                    id=self.vpcvr.hostid,
                    resourcestate="Enabled")
                
                if list_host_response is not None:
                    break
                elif timeout == 0:
                    raise Exception("Failed to list the Host in Up State")

                time.sleep(self.services["sleep"])
                timeout = timeout - 1
            
            self.debug("Verified that the Host is in Up State")
            
        except:
            self.fail("Failed to find the Host in Up State")

        self.debug("Reconnecting the host where VPC VR is running")
        try:
            Host.reconnect(self.apiclient, id=self.vpcvr.hostid)
        except Exception as e:
            self.fail("Failed to reconnect to host: %s" % e)

        self.debug("Check the status of router after migration")
        routers = Router.list(
                              self.apiclient,
                              id=self.vpcvr.id,
                              listall=True
                              )
        self.assertEqual(
                         isinstance(routers, list),
                         True,
                         "List routers shall return the valid response"
                         )
        self.assertEqual(
                         routers[0].state,
                         "Running",
                         "Router state should be running"
                         )
        #  TODO: Check for the network connectivity
        return
    def test_06_reboot_VR_verify_ip_alias(self):
        """Reboot VR and verify ip alias
            1.Deploy guest vm in new cidr
            2.Verify ip alias creation
            3.Reboot VR
            4.Verify ip alias on VR
        """
        list_router_response = list_routers(self.apiclient,
                                            zoneid=self.zone.id,
                                            listall=True)
        self.assertEqual(isinstance(list_router_response, list), True,
                         "Check list response returns a valid list")
        router = list_router_response[0]
        hosts = list_hosts(self.apiclient,
                           zoneid=router.zoneid,
                           type='Routing',
                           state='Up',
                           id=router.hostid)
        self.assertEqual(isinstance(hosts, list), True,
                         "Check list host returns a valid list")
        host = hosts[0]
        self.debug("Router ID: %s, state: %s" % (router.id, router.state))
        self.assertEqual(router.state, 'Running',
                         "Check list router response for router state")

        port = self.testdata['configurableData']['host']["publicport"]
        username = self.testdata['configurableData']['host']["username"]
        password = self.testdata['configurableData']['host']["password"]

        # SSH to host so that host key is saved in first
        # attempt
        SshClient(host.ipaddress, port, username, password)

        proc = "ip addr show eth0"
        result = get_process_status(host.ipaddress, port, username, password,
                                    router.linklocalip, proc)
        res = str(result)
        self.debug("ip alias configuration on VR: %s" % res)
        self.assertNotEqual(
            res.find(self.alias_ip) - 1, "ip alias is not created on VR eth0")
        resp = Router.reboot(self.apiclient, router.id)
        self.debug("Reboot router api response: %s" % resp)
        list_router_response = list_routers(self.apiclient,
                                            zoneid=self.zone.id,
                                            listall=True)
        self.assertEqual(isinstance(list_router_response, list), True,
                         "Check list response returns a valid list")
        router = list_router_response[0]
        self.assertEqual(router.state, 'Running',
                         "Router is not in running state after reboot")
        result = get_process_status(host.ipaddress, port, username, password,
                                    router.linklocalip, proc)
        res = str(result)
        self.assertNotEqual(res.find(self.alias_ip), -1,
                            "IP alias not present on VR after VR reboot")
        return
Beispiel #29
0
    def setUp(self):

        self.apiclient = self.testClient.getApiClient()
        self.dbclient = self.testClient.getDbConnection()
        self.debug("Check the status of VPC virtual router")
        routers = Router.list(
                              self.apiclient,
                              networkid=self.network_1.id,
                              listall=True
                              )
        if not isinstance(routers, list):
            raise Exception("No response from list routers API")

        self.router = routers[0]
        if self.router.state == "Running":
            Router.stop(self.apiclient, id=self.router.id)

        self.cleanup = []
        return
 def get_Router(self, network):
     self.debug("Finding the virtual router for network with ID - %s" % network.id)
     routers = Router.list(self.api_client,
                           networkid=network.id,
                           listall=True
                           )
     self.assertEqual(isinstance(routers, list), True,
                      "List routers should return a valid virtual router for network"
                      )
     return routers[0]
Beispiel #31
0
    def get_router(self, account):
        """Returns a default router for account"""

        routers = Router.list(self.apiclient,
                              account=self.account.name,
                              domainid=self.account.domainid,
                              listall=True)
        self.assertIsInstance(routers, list,
                              "List routers should return a valid repsonse")
        return routers[0]
Beispiel #32
0
    def get_router(self, account):
        """Returns a default router for account"""

        routers = Router.list(self.apiclient,
                              account=self.account.name,
                              domainid=self.account.domainid,
                              listall=True)
        self.assertIsInstance(routers, list,
                              "List routers should return a valid repsonse")
        return routers[0]
    def test_01_stop_start_router_after_creating_vpc(self):
        """ Test to stop and start router after creation of VPC
        """

        # Validate following:
        # 1. Create a VPC with cidr - 10.1.1.1/16
        # 2. Stop the VPC Virtual Router which is created as a result of VPC creation.
        # 3. Start the Stopped VPC Virtual Router

        self.validate_vpc_offering(self.vpc_off)
        self.validate_vpc_network(self.vpc)

        # Stop the VPC Router
        routers = Router.list(self.api_client,
                              account=self.account.name,
                              domainid=self.account.domainid,
                              listall=True)
        self.assertEqual(isinstance(routers, list), True,
                         "List Routers should return a valid list")
        router = routers[0]
        self.debug("Stopping the router with ID: %s" % router.id)

        # Stop the router
        cmd = stopRouter.stopRouterCmd()
        cmd.id = router.id
        self.api_client.stopRouter(cmd)

        # List routers to check state of router
        router_response = list_routers(self.api_client, id=router.id)
        self.assertEqual(isinstance(router_response, list), True,
                         "Check list response returns a valid list")
        # List router should have router in stopped state
        self.assertEqual(router_response[0].state, 'Stopped',
                         "Check list router response for router state")

        self.debug("Stopped the router with ID: %s" % router.id)

        # Start The Router
        self.debug("Starting the router with ID: %s" % router.id)
        cmd = startRouter.startRouterCmd()
        cmd.id = router.id
        self.api_client.startRouter(cmd)

        # List routers to check state of router
        router_response = list_routers(self.api_client, id=router.id)
        self.assertEqual(isinstance(router_response, list), True,
                         "Check list response returns a valid list")
        # List router should have router in running state
        self.assertEqual(router_response[0].state, 'Running',
                         "Check list router response for router state")
        self.debug("Started the router with ID: %s" % router.id)

        return
 def check_Router_state(self, router, state=None):
     """Validates the Router state"""
     self.debug("Validating the deployment and state of Router - %s" %
                router.name)
     routers = Router.list(self.api_client, id=router.id, listall=True)
     self.assertEqual(isinstance(routers, list), True,
                      "List router should return a valid list")
     if state:
         self.assertEqual(routers[0].state, state,
                          "Virtual router is not in the expected state")
     self.debug(
         "Successfully validated the deployment and state of Router - %s" %
         router.name)
    def test_basicZoneVirtualRouter(self):
        # TODO: SIMENH: duplicate test, remove it
        """
        Tests for basic zone virtual router
        1. Is Running
        2. is in the account the VM was deployed in
        @return:
        """
        routers = Router.list(self.apiclient, account=self.account.name)
        self.assertTrue(len(routers) > 0, msg="No virtual router found")
        router = routers[0]

        self.assertEqual(router.state, 'Running', msg="Router is not in running state")
        self.assertEqual(router.account, self.account.name, msg="Router does not belong to the account")
    def test_basicZoneVirtualRouter(self):
        #TODO: SIMENH: duplicate test, remove it
        """
        Tests for basic zone virtual router
        1. Is Running
        2. is in the account the VM was deployed in
        @return:
        """
        routers = Router.list(self.apiclient, account=self.account.name)
        self.assertTrue(len(routers) > 0, msg = "No virtual router found")
        router = routers[0]

        self.assertEqual(router.state, 'Running', msg="Router is not in running state")
        self.assertEqual(router.account, self.account.name, msg="Router does not belong to the account")
Beispiel #37
0
 def check_router_state(self, router, state=None):
     self.debug("Check if the virtual router is in state - %s" % state)
     routers = Router.list(self.api_client,
                           id=router.id,
                           listall=True
                           )
     self.assertEqual(isinstance(routers, list), True,
                      "List router should return a valid list"
                      )
     if state:
         self.assertEqual(routers[0].state, state,
                          "Virtual router is not in the expected state"
                          )
     self.debug("Virtual router is in the expected state - %s" % state)
    def test_05_destroy_router_after_creating_vpc(self):
        """ Test to destroy the router after creating a VPC
            """
        # Validate the following
        # 1. Create a VPC with cidr - 10.1.1.1/16
        # 2. Destroy the VPC Virtual Router which is created as a result of VPC
        # creation.
        self.validate_vpc_offering(self.vpc_off)
        self.validate_vpc_network(self.vpc)
        routers = Router.list(
            self.api_client,
            account=self.account.name,
            domainid=self.account.domainid,
            listall=True
        )
        self.assertEqual(
            isinstance(routers, list),
            True,
            "List Routers should return a valid list"
        )

        Router.destroy(self.api_client,
                       id=routers[0].id
                       )

        routers = Router.list(
            self.api_client,
            account=self.account.name,
            domainid=self.account.domainid,
            listall=True
        )
        self.assertEqual(
            isinstance(routers, list),
            False,
            "List Routers should be empty"
        )
        return
    def test_03_migrate_router_after_creating_vpc(self):
        """ Test migration of router to another host after creating VPC """
        self.hypervisor = self.testClient.getHypervisorInfo()

        self.validate_vpc_offering(self.vpc_off)
        self.validate_vpc_network(self.vpc)

        routers = Router.list(self.api_client,
                              account=self.account.name,
                              domainid=self.account.domainid,
                              listall=True)
        self.assertEqual(isinstance(routers, list), True,
                         "List Routers should return a valid list")
        self.migrate_router(routers[0])
        return
Beispiel #40
0
 def check_Router_state(self, router, state=None):
     """Validates the Router state"""
     self.debug("Validating the deployment and state of Router - %s" % router.name)
     routers = Router.list(self.api_client,
                           id=router.id,
                           listall=True
                           )
     self.assertEqual(isinstance(routers, list), True,
                      "List router should return a valid list"
                      )
     if state:
         self.assertEqual(routers[0].state, state,
                          "Virtual router is not in the expected state"
                          )
     self.debug("Successfully validated the deployment and state of Router - %s" % router.name)
Beispiel #41
0
 def getNetworkRouter(self, network, red_state="PRIMARY"):
     routers = Router.list(
         self.apiclient,
         networkid=network.id,
         listall=True
     )
     self.assertTrue(
         isinstance(routers, list) and len(routers) > 0,
         "No routers found for network %s" % network.id
     )
     if len(routers) == 1:
         return routers[0]
     for router in routers:
         if router.redundantstate == red_state:
             return router
Beispiel #42
0
    def test_02_cancel_maintenance(self):
        """ Test cancel Maintenance Mode on the above Hosts + Migrate VMs Back
        """

        # Steps
        # 1. Cancel Maintenance Mode on the host.
        # 2. Migrate the VMs back onto the host on which Maintenance mode is
        #    cancelled.
        # Validate the following
        # 1. Successfully cancel the Maintenance mode on the host.
        # 2. Migrate the VMs back successfully onto the host.
        # 3. Check that the network connectivity exists with the migrated VMs.

        self.debug("Cancel host maintenence on which the VPCVR is running")
        try:
            Host.cancelMaintenance(self.apiclient, id=self.vpcvr.hostid)
        except Exception as e:
            self.fail("Failed to enable maintenance mode on host: %s" % e)

        self.debug(
            "Migrating the instances back to the host: %s" %
                                                        self.vpcvr.hostid)
        try:
            cmd = migrateSystemVm.migrateSystemVmCmd()
            cmd.hostid = self.vpcvr.hostid
            cmd.virtualmachineid = self.vpcvr.id
            self.apiclient.migrateSystemVm(cmd)
        except Exception as e:
            self.fail("Failed to migrate VPCVR back: %s" % e)

        self.debug("Check the status of router after migration")
        routers = Router.list(
                              self.apiclient,
                              id=self.vpcvr.id,
                              listall=True
                              )
        self.assertEqual(
                         isinstance(routers, list),
                         True,
                         "List routers shall return the valid response"
                         )
        self.assertEqual(
                         routers[0].state,
                         "Running",
                         "Router state should be running"
                         )
        #  TODO: Check for the network connectivity
        return
    def test_02_reboot_router_after_addition_of_one_guest_network(self):
        """ Test reboot of router after addition of one guest network
            """
        # Validations
        # 1. Create a VPC with cidr - 10.1.1.1/16
        # 2. Add network1(10.1.1.1/24) to this VPC.
        # 3. Deploy vm1,vm2 and vm3 such that they are part of network1.
        # 4. Create a PF /Static Nat/LB rule for vms in network1.
        # 5. Create ingress network ACL for allowing all the above rules from a public ip range on network1.
        # 6. Create egress network ACL for network1 to access google.com.
        # 7. Create a private gateway for this VPC and add a static route to this gateway.
        # 8. Create a VPN gateway for this VPC and add a static route to this gateway.
        # 9. Make sure that all the PF,LB and Static NAT rules work as expected.
        # 10. Make sure that we are able to access google.com from all the user Vms.
        # 11. Make sure that the newly added private gateway's and VPN
        # gateway's static routes work as expected

        self.validate_vpc_offering(self.vpc_off)
        self.validate_vpc_network(self.vpc)
        self.assertEqual(
            isinstance(self.gateways, list), True,
            "List private gateways should return a valid response")
        self.assertEqual(isinstance(self.static_routes, list), True,
                         "List static route should return a valid response")

        routers = Router.list(self.api_client,
                              account=self.account.name,
                              domainid=self.account.domainid,
                              listall=True)
        self.assertEqual(isinstance(routers, list), True,
                         "List Routers should return a valid list")
        router = routers[0]

        self.debug("Rebooting the router ...")
        # Reboot the router
        cmd = rebootRouter.rebootRouterCmd()
        cmd.id = router.id
        self.api_client.rebootRouter(cmd)

        # List routers to check state of router
        router_response = list_routers(self.api_client, id=router.id)
        self.assertEqual(isinstance(router_response, list), True,
                         "Check list response returns a valid list")
        # List router should have router in running state and same public IP
        self.assertEqual(router_response[0].state, 'Running',
                         "Check list router response for router state")
        return
    def test_02_reboot_router_after_creating_vpc(self):
        """ Test to reboot the router after creating a VPC
        """
        # Validate the following
        # 1. Create a VPC with cidr - 10.1.1.1/16
        # 2. Reboot the VPC Virtual Router which is created as a result of VPC creation.
        # Stop the VPC Router

        self.validate_vpc_offering(self.vpc_off)
        self.validate_vpc_network(self.vpc)
        routers = Router.list(
            self.api_client,
            account=self.account.name,
            domainid=self.account.domainid,
            listall=True
        )
        self.assertEqual(
            isinstance(routers, list),
            True,
            "List Routers should return a valid list"
        )
        router = routers[0]

        self.debug("Rebooting the router ...")
        # Reboot the router
        cmd = rebootRouter.rebootRouterCmd()
        cmd.id = router.id
        self.api_client.rebootRouter(cmd)

        # List routers to check state of router
        router_response = list_routers(
            self.api_client,
            id=router.id
        )
        self.assertEqual(
            isinstance(router_response, list),
            True,
            "Check list response returns a valid list"
        )
        # List router should have router in running state and same public IP
        self.assertEqual(
            router_response[0].state,
            'Running',
            "Check list router response for router state"
        )
        return
    def test_advZoneVirtualRouter(self):
        #TODO: SIMENH: duplicate test, remove it
        """
        Test advanced zone virtual router
        1. Is Running
        2. is in the account the VM was deployed in
        3. Has a linklocalip, publicip and a guestip
        @return:
        """
        routers = Router.list(self.apiclient, account=self.account.name)
        self.assertTrue(len(routers) > 0, msg = "No virtual router found")
        router = routers[0]

        self.assertEqual(router.state, 'Running', msg="Router is not in running state")
        self.assertEqual(router.account, self.account.name, msg="Router does not belong to the account")

        #Has linklocal, public and guest ips
        self.assertIsNotNone(router.linklocalip, msg="Router has no linklocal ip")
        self.assertIsNotNone(router.publicip, msg="Router has no public ip")
        self.assertIsNotNone(router.guestipaddress, msg="Router has no guest ip")
    def test_03_migrate_router_after_creating_vpc(self):
        """ Test migration of router to another host after creating VPC """
        self.hypervisor = self.testClient.getHypervisorInfo()

        self.validate_vpc_offering(self.vpc_off)
        self.validate_vpc_network(self.vpc)

        routers = Router.list(
            self.api_client,
            account=self.account.name,
            domainid=self.account.domainid,
            listall=True
        )
        self.assertEqual(
            isinstance(routers, list),
            True,
            "List Routers should return a valid list"
        )
        self.migrate_router(routers[0])
        return
Beispiel #47
0
def verifyRouterState(apiclient, routerid, state, listall=True):
    """List router and check if the router state matches the given state"""
    retriesCount = 10
    isRouterInDesiredState = False
    exceptionOccured = False
    exceptionMessage = ""
    try:
        while retriesCount >= 0:
            routers = Router.list(apiclient, id=routerid, listall=listall)
            assert validateList(
                routers)[0] == PASS, "Routers list validation failed"
            if str(routers[0].state).lower() == state:
                isRouterInDesiredState = True
                break
            retriesCount -= 1
            time.sleep(60)
        if not isRouterInDesiredState:
            exceptionMessage = "Router state should be %s, it is %s" %\
                                (state, routers[0].state)
    except Exception as e:
        exceptionOccured = True
        exceptionMessage = e
        return [exceptionOccured, isRouterInDesiredState, exceptionMessage]
    return [exceptionOccured, isRouterInDesiredState, exceptionMessage]
    def test_restart_network_with_destroyed_masterVR(self):
        """Test restarting RvR network without cleanup after destroying master VR
        """

        # Steps to validate
        # 1. createNetwork using network offering for redundant virtual router
        # 2. listRouters in above network
        # 3. deployVM in above user account in the created network
        # 4. Destroy master VR
        # 5. restartNetwork cleanup=false
        # 6. Verify RVR status after network restart

        # Creating network using the network offering created
        self.debug("Creating network with network offering: %s" %
                   self.network_offering.id)
        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" % network.id)
        networks = Network.list(
            self.apiclient,
            id=network.id,
            listall=True
        )
        self.assertEqual(
            validateList(networks)[0],
            PASS,
            "List networks should return a valid response for created network"
        )

        self.debug("Deploying VM in account: %s" % self.account.name)
        # Spawn an instance in that network
        virtual_machine = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            networkids=[str(network.id)]
        )
        self.debug("Deployed VM in network: %s" % network.id)
        vms = VirtualMachine.list(
            self.apiclient,
            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.state,
            "Running",
            "Vm should be in running state after deployment"
        )

        self.debug("Listing routers for network: %s" % network.name)
        routers = Router.list(
            self.apiclient,
            networkid=network.id,
            listall=True
        )
        self.assertEqual(
            validateList(routers)[0],
            PASS,
            "list router should return Master and backup routers"
        )
        self.assertEqual(
            len(routers),
            2,
            "Length of the list router should be 2 (Backup & master)"
        )
        if routers[0].redundantstate == 'MASTER' and\
                routers[1].redundantstate == 'BACKUP':
            master_router = routers[0]
            backup_router = routers[1]
        elif routers[1].redundantstate == 'MASTER' and \
                routers[0].redundantstate == 'BACKUP':
            master_router = routers[1]
            backup_router = routers[0]
        else:
            self.fail("Both the routers in RVR are in BackupState")

        Router.stop(
            self.apiclient,
            id=master_router.id
        )
        Router.destroy(
            self.apiclient,
            id=master_router.id
        )
        masterVR = Router.list(
            self.apiclient,
            id=master_router.id
        )
        self.assertIsNone(masterVR, "Router is not destroyed")
        new_master = Router.list(
            self.apiclient,
            id=backup_router.id
        )
        self.assertEqual(validateList(new_master)[0], PASS, "Invalid response after vr destroy")
        self.assertEqual(
            new_master[0].redundantstate,
            "MASTER",
            "Backup didn't switch to Master after destroying Master VR"
        )

        self.debug("restarting network with cleanup=False")
        try:
            network.restart(self.apiclient, cleanup=False)
        except Exception as e:
            self.fail("Failed to cleanup network - %s" % e)

        self.debug("Listing routers for network: %s" % network.name)
        routers = Router.list(
            self.apiclient,
            networkid=network.id,
            listall=True
        )
        self.assertEqual(
            validateList(routers)[0],
            PASS,
            "list router should return Master and backup routers afrer network restart"
        )
        self.assertEqual(
            len(routers),
            2,
            "Length of the list router should be 2 (Backup & master)"
        )
        for router in routers:
            self.assertEqual(
                router.state,
                "Running",
                "Router state should be running"
            )
        if routers[0].redundantstate == 'MASTER' and\
                routers[1].redundantstate == 'BACKUP':
            self.debug("Found master and backup VRs after network restart")
        elif routers[0].redundantstate == 'BACKUP' and \
                routers[1].redundantstate == 'MASTER':
            self.debug("Found master and backup routers")
        else:
            self.fail("RVR is not in proper start after network restart")
        return
Beispiel #49
0
    def test_01_RVR_Network_FW_PF_SSH_default_routes_egress_true(self):
        """ Test redundant router internals """
        self.logger.debug(
            "Starting test_01_RVR_Network_FW_PF_SSH_default_routes_egress_true..."
        )

        network_offering_egress_true = get_default_redundant_isolated_network_offering_with_egress(
            self.apiclient)

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

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

        self.logger.debug("Deploying VM in account: %s" % self.account.name)
        virtual_machine = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            templateid=self.template.id,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            networkids=[str(network.id)])

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

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

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

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

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

        public_ip = public_ips[0]

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

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

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

        # Test SSH after closing port 22
        expected = 1
        ssh_command = "ping -c 3 8.8.8.8"
        check_string = "3 packets received"
        result = self.check_router_command(virtual_machine, nat_rule.ipaddress,
                                           ssh_command, check_string, self)

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

        expected = 1
        ssh_command = self.HTTP_COMMAND
        check_string = self.HTTP_CHECK_STRING
        result = self.check_router_command(virtual_machine, nat_rule.ipaddress,
                                           ssh_command, check_string, self)

        self.assertEqual(result, expected, self.HTTP_ASSERT_SUCCESS_MESSAGE)

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

        expected = 0
        result = self.check_router_command(virtual_machine, nat_rule.ipaddress,
                                           ssh_command, check_string, self)

        self.assertEqual(result, expected, self.HTTP_ASSERT_FAILURE_MESSAGE)

        return
    def test_restart_ntwk_with_cleanup(self):
        """Test restart RvR network with cleanup
        """

        # Steps to validate
        # 1. createNetwork using network offering for redundant virtual router
        # 2. listRouters in above network
        # 3. deployVM in above user account in the created network
        # 4. restartNetwork cleanup=false
        # 5. listRouters in the account
        # 6. delete the account

        # Creating network using the network offering created
        self.debug("Creating network with network offering: %s" %
                                                    self.network_offering.id)
        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" % network.id)

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

        self.debug("Network state: %s" % nw_response.state)
        self.assertEqual(
                    nw_response.state,
                    "Allocated",
                    "The network should be in allocated state after creation"
                    )

        self.debug("Listing routers for network: %s" % network.name)
        routers = Router.list(
                              self.apiclient,
                              networkid=network.id,
                              listall=True
                              )
        self.assertEqual(
            routers,
            None,
            "Routers should not be spawned when network is in allocated state"
            )

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

        # Spawn an instance in that network
        virtual_machine = VirtualMachine.create(
                                  self.apiclient,
                                  self.services["virtual_machine"],
                                  accountid=self.account.name,
                                  domainid=self.account.domainid,
                                  serviceofferingid=self.service_offering.id,
                                  networkids=[str(network.id)]
                                  )
        self.debug("Deployed VM in network: %s" % network.id)

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

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

        self.debug("restarting network with cleanup=True")
        try:
            network.restart(self.apiclient, cleanup=True)
        except Exception as e:
                self.fail("Failed to cleanup network - %s" % e)

        self.debug("Listing routers for network: %s" % network.name)
        routers = Router.list(
                              self.apiclient,
                              networkid=network.id,
                              listall=True
                              )
        self.assertEqual(
                    isinstance(routers, list),
                    True,
                    "list router should return Master and backup routers"
                    )
        self.assertEqual(
                    len(routers),
                    2,
                    "Length of the list router should be 2 (Backup & master)"
                    )
        for router in routers:
            self.assertEqual(
                             router.state,
                             "Running",
                             "Router state should be running"
                             )
        return
    def test_network_gc(self):
        """Test network garbage collection with RVR
        """

        # Steps to validate
        # 1. createNetwork using network offering for redundant virtual router
        # 2. listRouters in above network
        # 3. deployVM in above user account in the created network
        # 4. stop the running user VM
        # 5. wait for network.gc time
        # 6. listRouters
        # 7. start the routers MASTER and BACK
        # 8. wait for network.gc time and listRouters
        # 9. delete the account

        # Creating network using the network offering created
        self.debug("Creating network with network offering: %s" %
                                                    self.network_offering.id)
        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" % network.id)

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

        self.debug("Network state: %s" % nw_response.state)
        self.assertEqual(
                    nw_response.state,
                    "Allocated",
                    "The network should be in allocated state after creation"
                    )

        self.debug("Listing routers for network: %s" % network.name)
        routers = Router.list(
                              self.apiclient,
                              networkid=network.id,
                              listall=True
                              )
        self.assertEqual(
            routers,
            None,
            "Routers should not be spawned when network is in allocated state"
            )

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

        # Spawn an instance in that network
        virtual_machine = VirtualMachine.create(
                                  self.apiclient,
                                  self.services["virtual_machine"],
                                  accountid=self.account.name,
                                  domainid=self.account.domainid,
                                  serviceofferingid=self.service_offering.id,
                                  networkids=[str(network.id)]
                                  )
        self.debug("Deployed VM in network: %s" % network.id)

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

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

        self.debug("Stopping the user VM: %s" % virtual_machine.name)

        try:
            virtual_machine.stop(self.apiclient)
        except Exception as e:
            self.fail("Failed to stop guest Vm: %s - %s" %
                                            (virtual_machine.name, e))

        interval = Configurations.list(
                                    self.apiclient,
                                    name='network.gc.interval'
                                    )
        delay = int(interval[0].value)
        interval = Configurations.list(
                                    self.apiclient,
                                    name='network.gc.wait'
                                    )
        exp = int(interval[0].value)

        self.debug("Sleeping for network gc wait + interval time")
        # Sleep to ensure that all resources are deleted
        time.sleep((delay + exp) * 2)

        routers = Router.list(
                              self.apiclient,
                              networkid=network.id,
                              listall=True
                              )
        self.assertEqual(
                    isinstance(routers, list),
                    True,
                    "list router should return Master and backup routers"
                    )
        for router in routers:
            self.assertEqual(
                             router.state,
                             "Stopped",
                             "Router should be in stopped state"
                             )
            self.debug("Starting the stopped router again")
            cmd = startRouter.startRouterCmd()
            cmd.id = router.id
            self.apiclient.startRouter(cmd)

        routers = Router.list(
                              self.apiclient,
                              networkid=network.id,
                              listall=True
                              )
        self.assertEqual(
                    isinstance(routers, list),
                    True,
                    "list router should return Master and backup routers"
                    )
        for router in routers:
            self.assertEqual(
                             router.state,
                             "Running",
                             "Router should be in running state"
                             )

        self.debug("Sleeping for network gc wait + interval time")
        # Sleep to ensure that all resources are deleted
        time.sleep((delay + exp) * 3)

        routers = Router.list(
                              self.apiclient,
                              networkid=network.id,
                              listall=True
                              )
        self.assertEqual(
                    isinstance(routers, list),
                    True,
                    "list router should return Master and backup routers"
                    )
        for router in routers:
            self.assertEqual(
                             router.state,
                             "Stopped",
                             "Router should be in stopped state"
                             )
        return
Beispiel #52
0
    def test_network_rules_acquired_public_ip(self, value):
        """Test for Router rules for network rules on acquired public IP"""

        # Validate the following:
        # 1. listPortForwardingRules should not return the deleted rule anymore
        # 2. attempt to do ssh should now fail

        self.ipaddress = PublicIPAddress.create(
            self.apiclient,
            accountid=self.account.name,
            zoneid=self.zone.id,
            domainid=self.account.domainid,
            networkid=self.defaultNetworkId
        )
        self.cleanup.append(self.ipaddress)

        self.createNetworkRules(rule=value,
                                ipaddressobj=self.ipaddress,
                                networkid=self.defaultNetworkId)

        router = Router.list(self.apiclient,
                             networkid=self.virtual_machine.nic[0].networkid,
                             listall=True)[0]

        response = self.getCommandResultFromRouter(router, "ip addr")
        self.debug(response)
        stringToMatch = "inet %s" % self.ipaddress.ipaddress.ipaddress
        self.assertTrue(stringToMatch in str(response), "IP address is\
                not removed from VR even after disabling statin NAT")

        try:
            self.debug("SSHing into VM with IP address %s with NAT IP %s" %
                       (
                           self.virtual_machine.ipaddress,
                           self.ipaddress.ipaddress.ipaddress
                       ))
            self.virtual_machine.get_ssh_client(
                self.ipaddress.ipaddress.ipaddress)
        except Exception as e:
            self.fail(
                "SSH Access failed for %s: %s" %
                (self.virtual_machine.ipaddress, e)
            )

        # Validate the following:
        # 1. listIpForwardingRules should not return the deleted rule anymore
        # 2. attempt to do ssh should now fail

        self.removeNetworkRules(rule=value, ipaddressobj=self.ipaddress)

        response = self.getCommandResultFromRouter(router, "ip addr")
        self.debug(response)
        stringToMatch = "inet %s" % self.ipaddress.ipaddress.ipaddress
        self.assertFalse(stringToMatch in str(response), "IP address is\
                not removed from VR even after disabling statin NAT")

        # Check if the Public SSH port is inaccessible
        with self.assertRaises(Exception):
            self.debug(
                "SSHing into VM with IP address %s after NAT rule deletion" %
                self.virtual_machine.ipaddress)

            SshClient(
                self.ipaddress.ipaddress.ipaddress,
                self.virtual_machine.ssh_port,
                self.virtual_machine.username,
                self.virtual_machine.password,
                retries=2,
                delay=0
            )
        return
    def test_03_RVR_Network_check_router_state(self):
        """ Test redundant router internals """
        self.logger.debug("Starting test_03_RVR_Network_check_router_state...")

        hypervisor = self.testClient.getHypervisorInfo()

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

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

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

        self.logger.debug("Deploying VM in account: %s" % self.account.name)
        virtual_machine = VirtualMachine.create(
                                  self.apiclient,
                                  self.services["virtual_machine"],
                                  templateid=self.template.id,
                                  accountid=self.account.name,
                                  domainid=self.account.domainid,
                                  serviceofferingid=self.service_offering.id,
                                  networkids=[str(network.id)]
                                  )

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

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

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

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

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

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

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

                    except KeyError:
                        self.skipTest(
                            "Marvin configuration has no host credentials to\
                                    check router services")
            
                if result.count(vals[0]) == 1:
                    cnts[vals.index(vals[0])] += 1

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

        return
    def test_02_cancel_maintenance(self):
        """ Test cancel Maintenance Mode on the above Hosts + Migrate VMs Back
        """

        # Steps
        # 1. Cancel Maintenance Mode on the host.
        # 2. Migrate the VMs back onto the host on which Maintenance mode is
        #    cancelled.
        # Validate the following
        # 1. Successfully cancel the Maintenance mode on the host.
        # 2. Migrate the VMs back successfully onto the host.
        # 3. Check that the network connectivity exists with the migrated VMs.

        try:
            timeout = self.services["timeout"]
            while True:
                list_host_response = Host.list(self.apiclient, id=self.vpcvr.hostid, resourcestate="Maintenance")

                if list_host_response is not None:
                    break
                elif timeout == 0:
                    raise Exception("Failed to list the Host in Maintenance State")

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

            self.debug("Verified that the Host is in Maintenance State")

        except:
            self.fail("Failed to find the Host in maintenance state")

        self.debug("Cancel host maintenence on which the VPCVR is running")
        try:
            Host.cancelMaintenance(self.apiclient, id=self.vpcvr.hostid)

            timeout = self.services["timeout"]
            while True:
                list_host_response = Host.list(self.apiclient, id=self.vpcvr.hostid, state="Up")

                if list_host_response is not None:
                    break
                elif timeout == 0:
                    raise Exception("Failed to list the Host in Up State after Canceling Maintenance Mode")

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

            self.debug("Verified that the Host is in Up State after Canceling Maintenance Mode")

        except Exception as e:
            self.fail("Failed to cancel maintenance mode on host: %s" % e)

        self.debug("Migrating the instances back to the host: %s" % self.vpcvr.hostid)
        try:
            cmd = migrateSystemVm.migrateSystemVmCmd()
            cmd.hostid = self.vpcvr.hostid
            cmd.virtualmachineid = self.vpcvr.id
            self.apiclient.migrateSystemVm(cmd)
        except Exception as e:
            self.fail("Failed to migrate VPCVR back: %s" % e)

        self.debug("Check the status of router after migration")
        routers = Router.list(self.apiclient, id=self.vpcvr.id, listall=True)
        self.assertEqual(isinstance(routers, list), True, "List routers shall return the valid response")
        self.assertEqual(routers[0].state, "Running", "Router state should be running")
        #  TODO: Check for the network connectivity
        return
    def test_01_enable_maintenance_with_vpc_nw(self):
        """ Test enable Maintenance Mode on Hosts which have VPC elements
        """

        # Validate the following
        # 1. Create a VPC with cidr - 10.1.1.1/16
        # 2. Add network1(10.1.1.1/24) and network2(10.1.2.1/24) to this VPC.
        # 3. Deploy vm1 and vm2 in network1 and vm3 and vm4 in network2. Make
        #    sure vm1 and vm3 are deployed on one host in the cluster while
        #    vm2 and vm4 are deployed on the other host in the cluster. This
        #    can be done using host's tags & service offerings with host tags
        # Steps:
        # 1.Enable Maintenance on one of host on which VPCVR is present
        # Validations:
        # 1. Successfully push the host into maintenance mode.
        # 2. VMs present on the above host should successfully migrate to the
        #    other host present in the cluster

        Host.update(self.apiclient, id=self.hosts[0].id, hosttags="hosttag1,hosttag2")
        Host.update(self.apiclient, id=self.hosts[1].id, hosttags="hosttag1,hosttag2")

        self.validate_vm_deployment()
        self.debug("Stop the host on which the VPC virtual router is running")
        try:
            Host.enableMaintenance(self.apiclient, id=self.vpcvr.hostid)
        except Exception as e:
            self.fail("Failed to enable maintenance mode on host: %s" % e)

        self.debug("Check if all instances belonging to the account are up again?")
        routers = Router.list(self.apiclient, account=self.account.name, domainid=self.account.domainid, listall=True)
        self.assertEqual(isinstance(routers, list), True, "List routers shall return a valid VPCVR for account")

        router = routers[0]

        try:

            timeout = self.services["timeout"]
            self.debug("Timeout Value %d : " % timeout)
            while True:
                list_router_response = Router.list(self.apiclient, id=router.id, state="Running")

                if list_router_response is not None:
                    break
                elif timeout == 0:
                    raise Exception("Router state should be running after migration")

                time.sleep(self.services["sleep"])
                timeout = timeout - 1
                self.debug("Waiting for %d seconds - %d tries left" % (self.services["sleep"], timeout))

            self.debug("Verified that the Router is in Running State")

        except Exception as e:
            self.fail("Failed to find the Router in Running state %s " % e)

        vms = VirtualMachine.list(
            self.apiclient, account=self.account.name, domainid=self.account.domainid, listall=True
        )
        self.assertEqual(isinstance(vms, list), True, "VM response should return instances running for account")
        for vm in vms:
            self.assertEqual(vm.state, "Running", "Vm state should be running after migration")
        return
    def setUpClass(cls):
        cls.testClient = super(TestVMLifeCycleHostmaintenance, cls).getClsTestClient()
        cls.api_client = cls.testClient.getApiClient()

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

        clusterWithSufficientHosts = None
        clusters = Cluster.list(cls.api_client, zoneid=cls.zone.id)
        for cluster in clusters:
            cls.hosts = Host.list(cls.api_client, clusterid=cluster.id)
            if len(cls.hosts) >= 2:
                clusterWithSufficientHosts = cluster

        if clusterWithSufficientHosts is None:
            raise unittest.SkipTest("No Cluster with 2 hosts found")

        Host.update(cls.api_client, id=cls.hosts[0].id, hosttags="hosttag1")
        Host.update(cls.api_client, id=cls.hosts[1].id, hosttags="hosttag2")

        cls.service_offering_1 = ServiceOffering.create(cls.api_client, cls.services["service_offering_1"])
        cls.service_offering_2 = ServiceOffering.create(cls.api_client, cls.services["service_offering_2"])
        cls.vpc_off = VpcOffering.create(cls.api_client, cls.services["vpc_offering"])
        cls.vpc_off.update(cls.api_client, state="Enabled")

        cls.account = Account.create(cls.api_client, cls.services["account"], admin=True, domainid=cls.domain.id)

        cls.vpc_off = VpcOffering.create(cls.api_client, cls.services["vpc_offering"])

        cls.vpc_off.update(cls.api_client, state="Enabled")

        cls.services["vpc"]["cidr"] = "10.1.1.1/16"
        cls.vpc = VPC.create(
            cls.api_client,
            cls.services["vpc"],
            vpcofferingid=cls.vpc_off.id,
            zoneid=cls.zone.id,
            account=cls.account.name,
            domainid=cls.account.domainid,
        )

        cls.nw_off = NetworkOffering.create(cls.api_client, cls.services["network_offering"], conservemode=False)
        # Enable Network offering
        cls.nw_off.update(cls.api_client, state="Enabled")

        # Creating network using the network offering created
        cls.network_1 = Network.create(
            cls.api_client,
            cls.services["network"],
            accountid=cls.account.name,
            domainid=cls.account.domainid,
            networkofferingid=cls.nw_off.id,
            zoneid=cls.zone.id,
            gateway="10.1.1.1",
            vpcid=cls.vpc.id,
        )
        cls.nw_off_no_lb = NetworkOffering.create(
            cls.api_client, cls.services["network_offering_no_lb"], conservemode=False
        )
        # Enable Network offering
        cls.nw_off_no_lb.update(cls.api_client, state="Enabled")

        # Creating network using the network offering created
        cls.network_2 = Network.create(
            cls.api_client,
            cls.services["network"],
            accountid=cls.account.name,
            domainid=cls.account.domainid,
            networkofferingid=cls.nw_off_no_lb.id,
            zoneid=cls.zone.id,
            gateway="10.1.2.1",
            vpcid=cls.vpc.id,
        )
        # Spawn an instance in that network
        cls.vm_1 = VirtualMachine.create(
            cls.api_client,
            cls.services["virtual_machine"],
            accountid=cls.account.name,
            domainid=cls.account.domainid,
            serviceofferingid=cls.service_offering_1.id,
            networkids=[str(cls.network_1.id)],
        )
        # Spawn an instance in that network
        cls.vm_2 = VirtualMachine.create(
            cls.api_client,
            cls.services["virtual_machine"],
            accountid=cls.account.name,
            domainid=cls.account.domainid,
            serviceofferingid=cls.service_offering_1.id,
            networkids=[str(cls.network_1.id)],
        )
        cls.vm_3 = VirtualMachine.create(
            cls.api_client,
            cls.services["virtual_machine"],
            accountid=cls.account.name,
            domainid=cls.account.domainid,
            serviceofferingid=cls.service_offering_2.id,
            networkids=[str(cls.network_2.id)],
        )
        routers = Router.list(cls.api_client, account=cls.account.name, domainid=cls.account.domainid, listall=True)
        if isinstance(routers, list):
            cls.vpcvr = routers[0]

        cls._cleanup = [cls.service_offering_1, cls.service_offering_2, cls.nw_off, cls.nw_off_no_lb]
        return