Esempio n. 1
0
 def checkIpv6NetworkBasic(self):
     self.debug("Listing network: %s" % (self.network.name))
     ipv6_network = Network.list(self.apiclient,listall="true",id=self.network.id)
     self.assertTrue(
         isinstance(ipv6_network, list),
         "Check listNetworks response returns a valid list"
     )
     self.assertEqual(
         len(ipv6_network),
         1,
         "Network not found"
     )
     ipv6_network = ipv6_network[0]
     self.assertNotEqual(ipv6_network,
                 None,
                 "User is not able to retrieve network details %s" % self.network.id)
     self.assertNotEqual(ipv6_network.ip6cidr,
                 None,
                 "IPv6 CIDR for network is empty")
     self.assertNotEqual(ipv6_network.ip6gateway,
                 None,
                 "IPv6 gateway for network is empty")
     self.assertNotEqual(ipv6_network.ip6routes,
                 None,
                 "IPv6 routes for network is empty")
     self.network_ipv6_routes = ipv6_network.ip6routes
Esempio n. 2
0
    def test_03_supported_policies_by_network(self):
        """Test listnetworks response to check supported stickiness policies"""

        # Validate the following
        # 1. List networks for the account in advance network mode
        # 2. List of supported sticky methods should be present under
        #    SupportedStickinessMethods tag

        self.debug("List networks for account: %s" % self.account.name)
        networks = Network.list(self.apiclient,
                                account=self.account.name,
                                domainid=self.account.domainid,
                                listall=True)

        self.assertIsInstance(networks, list,
                              "List network should return a valid response")
        network = networks[0]
        self.debug("Network: %s" % network)
        self.assertEqual(
            hasattr(network, "SupportedStickinessMethods"), True,
            "Network should have SupportedStickinessMethods param")

        self.assertEqual(hasattr(network, "LbCookie"), True,
                         "Network should have LbCookie LB method param")

        self.assertEqual(hasattr(network, "AppCookie"), True,
                         "Network should have AppCookie LB method param")

        self.assertEqual(hasattr(network, "SourceBased"), True,
                         "Network should have SourceBased LB method param")

        return
Esempio n. 3
0
    def test_03_supported_policies_by_network(self):
        """Test listnetworks response to check supported stickiness policies"""

        # Validate the following
        # 1. List networks for the account in advance network mode
        # 2. List of supported sticky methods should be present under
        #    SupportedStickinessMethods tag

        self.debug("List networks for account: %s" % self.account.name)
        networks = Network.list(self.apiclient, account=self.account.name, domainid=self.account.domainid, listall=True)

        self.assertIsInstance(networks, list, "List network should return a valid response")
        network = networks[0]
        self.debug("Network: %s" % network)
        self.assertEqual(
            hasattr(network, "SupportedStickinessMethods"), True, "Network should have SupportedStickinessMethods param"
        )

        self.assertEqual(hasattr(network, "LbCookie"), True, "Network should have LbCookie LB method param")

        self.assertEqual(hasattr(network, "AppCookie"), True, "Network should have AppCookie LB method param")

        self.assertEqual(hasattr(network, "SourceBased"), True, "Network should have SourceBased LB method param")

        return
Esempio n. 4
0
    def test_04_publicip_per_project(self):
        """Test Public IP limit per project
        """
        # Validate the following
        # 1. set max no of IPs per project to 2.
        # 2. Create an account in this domain
        # 3. Create 1 VM in this domain
        # 4. Acquire 1 IP in the domain. IP should be successfully acquired
        # 5. Try to acquire 3rd IP in this domain. It should give the user an
        #    appropriate error and an alert should be generated.

        self.debug("Updating public IP resource limits for project: %s" % self.project.id)
        # Set usage_vm=1 for Account 1
        update_resource_limit(self.apiclient, 1, max=2, projectid=self.project.id)  # Public Ip

        self.debug("Deploying VM for Project: %s" % self.project.id)
        virtual_machine_1 = VirtualMachine.create(
            self.apiclient,
            self.services["server"],
            templateid=self.template.id,
            serviceofferingid=self.service_offering.id,
            projectid=self.project.id,
        )
        self.cleanup.append(virtual_machine_1)
        # Verify VM state
        self.assertEqual(virtual_machine_1.state, "Running", "Check VM state is Running or not")
        networks = Network.list(self.apiclient, projectid=self.project.id, listall=True)
        self.assertEqual(isinstance(networks, list), True, "Check list networks response returns a valid response")
        self.assertNotEqual(len(networks), 0, "Check list networks response returns a valid network")
        network = networks[0]
        self.debug("Associating public IP for project: %s" % self.project.id)
        public_ip_1 = PublicIPAddress.create(
            self.apiclient,
            zoneid=virtual_machine_1.zoneid,
            services=self.services["server"],
            networkid=network.id,
            projectid=self.project.id,
        )
        self.cleanup.append(public_ip_1)
        # Verify Public IP state
        self.assertEqual(
            public_ip_1.ipaddress.state in ["Allocated", "Allocating"],
            True,
            "Check Public IP state is allocated or not",
        )

        # Exception should be raised for second Public IP
        with self.assertRaises(Exception):
            PublicIPAddress.create(
                self.apiclient,
                zoneid=virtual_machine_1.zoneid,
                services=self.services["server"],
                networkid=network.id,
                projectid=self.project.id,
            )
        return
Esempio n. 5
0
    def get_Network(self, account):
        """Returns a network for account"""

        networks = Network.list(self.apiclient,
                                account=account.name,
                                domainid=account.domainid,
                                listall=True)
        self.assertIsInstance(networks, list,
                              "List networks should return a valid response")
        return networks[0]
    def test_06_volumes_per_project(self):
        """Test Volumes limit per project
        """
        # Validate the following
        # 1. set max no of volume per project to 1.
        # 2. Create 1 VM in this project
        # 4. Try to Create another VM in the project. It should give the user
        #    an appropriate error that Volume limit is exhausted and an alert
        #    should be generated.

        if self.hypervisor.lower() == 'lxc':
            if not find_storage_pool_type(self.apiclient, storagetype='rbd'):
                self.skipTest(
                    "RBD storage type is required for data volumes for LXC")
        self.project_1 = Project.create(self.api_client,
                                        self.services["project"],
                                        account=self.account.name,
                                        domainid=self.account.domainid)
        self.cleanup.append(self.project_1)

        self.debug("Updating volume resource limits for project: %s" %
                   self.project_1.id)
        # Set usage_vm=1 for Account 1
        update_resource_limit(
            self.apiclient,
            2,  # Volume
            max=1,
            projectid=self.project_1.id)

        self.debug("Deploying VM for project: %s" % self.project_1.id)
        virtual_machine_1 = VirtualMachine.create(
            self.apiclient,
            self.services["server"],
            templateid=self.template.id,
            serviceofferingid=self.service_offering.id,
            projectid=self.project_1.id)
        # Verify VM state
        self.assertEqual(virtual_machine_1.state, 'Running',
                         "Check VM state is Running or not")
        self.cleanup.append(virtual_machine_1)
        networks = Network.list(self.apiclient,
                                projectid=self.project_1.id,
                                listall=True)
        for network in networks:
            self.cleanup.insert(1, Network(network.__dict__))

        # Exception should be raised for second volume
        with self.assertRaises(Exception):
            Volume.create(self.apiclient,
                          self.services["volume"],
                          zoneid=self.zone.id,
                          diskofferingid=self.disk_offering.id,
                          projectid=self.project_1.id)
        return
Esempio n. 7
0
def isNetworkDeleted(apiclient, networkid, timeout=600):
    """ List the network and check that the list is empty or not"""
    networkDeleted = False
    while timeout >= 0:
        networks = Network.list(apiclient, id=networkid)
        if networks is None:
            networkDeleted = True
            break
        timeout -= 60
        time.sleep(60)
    #end while
    return networkDeleted
    def test_04_publicip_per_project(self):
        """Test Public IP limit per project
        """
        # Validate the following
        # 1. set max no of IPs per project to 2.
        # 2. Create an account in this domain
        # 3. Create 1 VM in this domain
        # 4. Acquire 1 IP in the domain. IP should be successfully acquired
        # 5. Try to acquire 3rd IP in this domain. It should give the user an
        #    appropriate error and an alert should be generated.

        self.debug("Updating public IP resource limits for project: %s" %
                   self.project.id)
        # Set usage_vm=1 for Account 1
        update_resource_limit(
            self.apiclient,
            1,  # Public Ip
            max=2,
            projectid=self.project.id)

        self.debug("Deploying VM for Project: %s" % self.project.id)
        virtual_machine_1 = VirtualMachine.create(
            self.apiclient,
            self.services["server"],
            templateid=self.template.id,
            serviceofferingid=self.service_offering.id,
            projectid=self.project.id)
        self.cleanup.append(virtual_machine_1)
        # Verify VM state
        self.assertEqual(virtual_machine_1.state, 'Running',
                         "Check VM state is Running or not")
        networks = Network.list(self.apiclient,
                                projectid=self.project.id,
                                listall=True)
        self.assertEqual(
            isinstance(networks, list), True,
            "Check list networks response returns a valid response")
        self.assertNotEqual(
            len(networks), 0,
            "Check list networks response returns a valid network")
        network = networks[0]
        self.debug("Associating public IP for project: %s" % self.project.id)
        public_ip_1 = PublicIPAddress.create(self.apiclient,
                                             zoneid=virtual_machine_1.zoneid,
                                             services=self.services["server"],
                                             networkid=network.id,
                                             projectid=self.project.id)
        self.cleanup.append(public_ip_1)
        # Verify Public IP state
        self.assertEqual(
            public_ip_1.ipaddress.state in ['Allocated', 'Allocating'], True,
            "Check Public IP state is allocated or not")
        return
Esempio n. 9
0
def isNetworkDeleted(apiclient, networkid, timeout=600):
    """ List the network and check that the list is empty or not"""
    networkDeleted = False
    while timeout >= 0:
        networks = Network.list(apiclient, id=networkid)
        if networks is None:
            networkDeleted = True
            break
        timeout -= 60
        time.sleep(60)
    #end while
    return networkDeleted
Esempio n. 10
0
    def test_01_restart_network_cleanup(self):
        """TS_BUG_008-Test restart network
        """

        # Validate the following
        # 1. When cleanup = true, router is destroyed and a new one created
        # 2. New router will have new publicIp and linkLocalIp and
        #    all it's services should resume

        # Find router associated with user account
        list_router_response = list_routers(self.apiclient,
                                            account=self.account.name,
                                            domainid=self.account.domainid)
        self.assertEqual(isinstance(list_router_response, list), True,
                         "Check list response returns a valid list")
        router = list_router_response[0]

        #Store old values before restart
        old_linklocalip = router.linklocalip

        timeout = 10
        # Network should be in Implemented or Setup stage before restart
        while True:
            networks = Network.list(self.apiclient,
                                    account=self.account.name,
                                    domainid=self.account.domainid)
            network = networks[0]
            if network.state in ["Implemented", "Setup"]:
                break
            elif timeout == 0:
                break
            else:
                time.sleep(60)
                timeout = timeout - 1

        self.debug("Restarting network: %s" % network.id)
        cmd = restartNetwork.restartNetworkCmd()
        cmd.id = network.id
        cmd.cleanup = True
        self.apiclient.restartNetwork(cmd)

        # Get router details after restart
        list_router_response = list_routers(self.apiclient,
                                            account=self.account.name,
                                            domainid=self.account.domainid)
        self.assertEqual(isinstance(list_router_response, list), True,
                         "Check list response returns a valid list")
        router = list_router_response[0]

        self.assertNotEqual(router.linklocalip, old_linklocalip,
                            "Check link-local IP after restart")
        return
Esempio n. 11
0
    def get_Network(self, account):
        """Returns a network for account"""

        networks = Network.list(
                                self.apiclient,
                                account=account.name,
                                domainid=account.domainid,
                                listall=True
                                )
        self.assertIsInstance(networks,
                              list,
                              "List networks should return a valid response")
        return networks[0]
Esempio n. 12
0
 def validate_network(self, network, state=None):
     """Validates the network"""
     self.debug("Check if the network is created successfully ?")
     networks = Network.list(self.api_client, id=network.id)
     self.assertEqual(isinstance(networks, list), True,
                      "List network should return a valid list")
     self.assertEqual(
         network.name, networks[0].name,
         "Name of the network should match with with the returned list data"
     )
     if state:
         self.assertEqual(networks[0].state, state,
                          "Network state should be '%s'" % state)
     self.debug("Network creation successfully validated - %s" %
                network.name)
Esempio n. 13
0
 def getNetworkRoutes(self, network):
     ipv6_network = Network.list(self.apiclient,listall="true",id=network.id)
     self.assertTrue(
         isinstance(ipv6_network, list),
         "Check listNetworks response returns a valid list"
     )
     self.assertEqual(
         len(ipv6_network),
         1,
         "Network not found"
     )
     ipv6_network = ipv6_network[0]
     self.assertNotEqual(ipv6_network.ip6routes,
                 None,
                 "IPv6 routes for network is empty")
     return ipv6_network.ip6routes
 def check_network_state(self, apiclient, network, project, expected_state):
     project_id = None
     if project:
         project_id = project.id
     networks = Network.list(apiclient,
                             listall=True,
                             projectid=project_id,
                             id=network.id)
     if isinstance(networks, list) and len(networks) > 0:
         if expected_state == NETWORK_STATE_REMOVED:
             self.fail("Found the network, but expected to fail")
         if networks[0].state != expected_state:
             self.fail(
                 f"Expect network state is {expected_state}, but actual state is {networks[0].state}"
             )
     elif expected_state != NETWORK_STATE_REMOVED:
         self.fail("Failed to find the network, but expected to succeed")
Esempio n. 15
0
 def validate_Network(self, network, state=None):
     """Validates the Network"""
     self.debug("Check if the network is created successfully ?")
     networks = Network.list(self.api_client,
                             id=network.id
                             )
     self.assertEqual(isinstance(networks, list), True,
                      "List network should return a valid list"
                      )
     self.assertEqual(network.name, networks[0].name,
                      "Name of the network should match with with the returned list data"
                      )
     if state:
         self.assertEqual(networks[0].state, state,
                          "Network state should be in state - %s" % state
                          )
     self.debug("Network creation successfully validated for %s" % network.name)
Esempio n. 16
0
 def validate_Network(self, network, state=None):
     """Validates the network"""
     self.debug("Validating the creation and state of Network - %s" % network.name)
     networks = Network.list(self.api_client,
                             id=network.id
                             )
     self.assertEqual(isinstance(networks, list), True,
                      "List network should return a valid list"
                      )
     self.assertEqual(network.name, networks[0].name,
                      "Name of the network should match with with the returned list data"
                      )
     if state:
         self.assertEqual(networks[0].state, state,
                          "Network state should be '%s'" % state
                          )
     self.debug("Successfully validated the creation and state of Network - %s" % network.name)
Esempio n. 17
0
 def list_network(self,
                  apiclient,
                  account,
                  network,
                  project,
                  network_filter=None,
                  expected=True):
     # List networks by apiclient, account, network, project and network network_filter
     # If account is specified, list the networks which can be used by the domain (canusefordeploy=true,listall=false)
     # otherwise canusefordeploy is None and listall is True.
     domain_id = None
     account_name = None
     project_id = None
     canusefordeploy = None
     list_all = True
     if account:
         domain_id = account.domainid
         account_name = account.name
         canusefordeploy = True
         list_all = False
     if project:
         project_id = project.id
     networks = None
     try:
         networks = Network.list(apiclient,
                                 canusefordeploy=canusefordeploy,
                                 listall=list_all,
                                 networkfilter=network_filter,
                                 domainid=domain_id,
                                 account=account_name,
                                 projectid=project_id,
                                 id=network.id)
         if isinstance(networks, list) and len(networks) > 0:
             if not expected:
                 self.fail("Found the network, but expected to fail")
         elif expected:
             self.fail(
                 "Failed to find the network, but expected to succeed")
     except Exception as ex:
         networks = None
         if expected:
             self.fail(
                 f"Failed to list network, but expected to succeed : {ex}")
     if networks and not expected:
         self.fail("network is listed successfully, but expected to fail")
Esempio n. 18
0
def verifyNetworkState(apiclient, networkid, state):
    """List networks and check if the network state matches the given state"""
    retriesCount = 10
    isNetworkInDesiredState = False
    exceptionOccured = False
    exceptionMessage = ""
    try:
        while retriesCount >= 0:
            networks = Network.list(apiclient, id=networkid)
            assert validateList(
                networks)[0] == PASS, "Networks list validation failed"
            if str(networks[0].state).lower() == state:
                isNetworkInDesiredState = True
                break
            retriesCount -= 1
            time.sleep(60)
    except Exception as e:
        exceptionOccured = True
        exceptionMessage = e
        return [exceptionOccured, isNetworkInDesiredState, exceptionMessage]
    return [exceptionOccured, isNetworkInDesiredState, exceptionMessage]
    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_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
Esempio n. 21
0
    def test_16_create_template_volume(self):
        """Test Create template from volume
        """

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

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

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

        self.assertNotEqual(
                            len(vm_response),
                            0,
                            "Check VMs available in List VMs response"
                        )
        vm = vm_response[0]
        self.assertEqual(
                            vm.state,
                            'Running',
                            "Check the state of VM created from Template"
                        )

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

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

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

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

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

        time.sleep(600)

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

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

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


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

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

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


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

        self.assertNotEqual(
                            len(vm_response),
                            0,
                            "Check VMs available in List VMs response"
                        )
        vm = vm_response[0]
        self.assertEqual(
                            vm.state,
                            'Running',
                            "Check the state of VM created from Template"
                        )

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

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

        templatevm.delete(self.apiclient)

        vm3network.delete(self.user_api_client)
        return
Esempio n. 22
0
    def test_03_RVR_Network_check_router_state(self):
        """ Test redundant router internals """
        self.logger.debug("Starting test_03_RVR_Network_check_router_state...")

        network_offering_egress_false = get_default_redundant_isolated_network_offering(
            self.apiclient)

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

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

        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]

                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/cosmic/router/scripts/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
Esempio n. 23
0
    def test_01_restart_network_cleanup(self):
        """TS_BUG_008-Test restart network
        """


        # Validate the following
        # 1. When cleanup = true, router is destroyed and a new one created
        # 2. New router will have new publicIp and linkLocalIp and
        #    all it's services should resume

        # Find router associated with user account
        list_router_response = list_routers(
                                    self.apiclient,
                                    account=self.account.name,
                                    domainid=self.account.domainid
                                    )
        self.assertEqual(
                            isinstance(list_router_response, list),
                            True,
                            "Check list response returns a valid list"
                        )
        router = list_router_response[0]

        #Store old values before restart
        old_linklocalip = router.linklocalip

        timeout = 10
        # Network should be in Implemented or Setup stage before restart
        while True:
            networks = Network.list(
                                 self.apiclient,
                                 account=self.account.name,
                                 domainid=self.account.domainid
                                 )
            network = networks[0]
            if network.state in ["Implemented", "Setup"]:
                break
            elif timeout == 0:
                break
            else:
                time.sleep(60)
                timeout = timeout - 1

        self.debug("Restarting network: %s" % network.id)
        cmd = restartNetwork.restartNetworkCmd()
        cmd.id = network.id
        cmd.cleanup = True
        self.apiclient.restartNetwork(cmd)

        # Get router details after restart
        list_router_response = list_routers(
                                    self.apiclient,
                                    account=self.account.name,
                                    domainid=self.account.domainid
                                    )
        self.assertEqual(
                            isinstance(list_router_response, list),
                            True,
                            "Check list response returns a valid list"
                        )
        router = list_router_response[0]

        self.assertNotEqual(
                            router.linklocalip,
                            old_linklocalip,
                            "Check link-local IP after restart"
                        )
        return
Esempio n. 24
0
    def test_19_template_tag(self):
        """ Test creation, listing and deletion tag on templates
        """

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

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

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

        timeout = self.services["timeout"]
        while True:
            list_volume = Volume.list(
                self.user_api_client,
                virtualmachineid=vm_1.id,
                type='ROOT',
                listall=True
            )
            if isinstance(list_volume, list):
                break
            elif timeout == 0:
                raise Exception("List volumes failed.")

            time.sleep(5)
            timeout = timeout - 1

        self.volume = list_volume[0]

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

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

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

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

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

        self.debug("Verifying if tag is actually deleted!")
        tags = Tag.list(
            self.user_api_client,
            listall=True,
            resourceType='Template',
            key='OS',
            value='windows8'
        )
        self.assertEqual(
            tags,
            None,
            "List tags should return empty response"
        )
        return
Esempio n. 25
0
    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 Primary and backup routers"
                    )
        self.assertEqual(
                    len(routers),
                    2,
                    "Length of the list router should be 2 (Backup & Primary)"
                    )

        vals = ["PRIMARY", "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('PRIMARY')] != 1:
            self.fail("No Primary or too many primary routers found %s" % cnts[vals.index('PRIMARY')])

        return
Esempio n. 26
0
    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 - CLOUDSTACK-9015")

        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
Esempio n. 27
0
    def test_downgradeRvR_to_VR(self):
        """Test downgrade redundant virtual router to virtual router
        """

        # Steps to validate
        # 1. create a network Offering that has redundant router enabled and
        #    all VR based services
        # 2. create a network with above offering
        # 3. deploy a VM in the above network and listRouters
        # 4. create a network Offering that has redundant router disabled and
        #    all VR based services
        # 5. updateNetwork - downgrade - created above to the offfering in 4.
        # 6. listRouters in the network
        # 7. delete account in which resources are created
        # Validate the following
        # 1. listNetworkOfferings should show craeted offering for RvR
        # 2. listNetworks should show the created network in allocated state
        # 3. VM should be deployed and in Running state and there should be
        #    two routers (MASTER and BACKUP) for this network
        # 4. listNetworkOfferings should show craeted offering for VR
        # 5. listNetworks shows the network still successfully implemented
        # 6. listRouters shows only one router for this network in Running

        # 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("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 the account: %s" % self.account.name)

        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 account: %s" % self.account.name)
        routers = Router.list(self.apiclient,
                              account=self.account.name,
                              domainid=self.account.domainid,
                              listall=True)
        self.assertEqual(isinstance(routers, list), True,
                         "list router should return two routers")
        self.assertEqual(
            len(routers), 2,
            "Length of the list router should be 2 (MASTER & BACKUP)")

        network_offerings = NetworkOffering.list(
            self.apiclient,
            name='DefaultIsolatedNetworkOfferingWithSourceNatService',
            listall=True)
        self.assertEqual(
            isinstance(network_offerings, list), True,
            "List network offering should not return empty response")

        network_off_vr = network_offerings[0]

        self.debug("Upgrading the network to RVR network offering..")
        try:
            network.update(self.apiclient, networkofferingid=network_off_vr.id)
        except Exception as e:
            self.fail("Failed to upgrade the network from VR to RVR: %s" % e)

        self.debug("Listing routers for account: %s" % self.account.name)
        routers = Router.list(self.apiclient,
                              account=self.account.name,
                              domainid=self.account.domainid,
                              listall=True)
        self.assertEqual(isinstance(routers, list), True,
                         "list router should return only one router")
        self.assertEqual(len(routers), 1,
                         "Length of the list router should be 1")
        return
    def test_01_nuage_Domain_Template_selection_per_VPC(self):
        """Test Nuage VSP Domain Template selection per VPC
        """

        # 1. Associate an invalid/non-existing Nuage VSP domain template to a
        #    VPC; verify that the association fails.
        # 2. Associate a valid/existing pre-configured Nuage VSP domain
        #    template to a VPC; verify that the association is successful, VPC
        #    networks (domains) are instantiated from the associated domain
        #    template in VSD.
        # 3. Verify that the state of such VPC networks (domains) in VSD is not
        #    affected with their restarts in CloudStack with and without
        #    cleanup.
        # 4. Verify that multiple associations (update) of domain templates to
        #    a VPC goes through till the creation of its first VPC network
        #    (tier).
        # 5. Verify that the VPC networks (domains) creation fails in VSD when
        #    the associated domain templates to their corresponding VPCs have
        #    been deleted in VSD.
        # 6. Verify that the VPC networks (domains) creation fails in VSD when
        #    an acl list is associated with them after their corresponding VPCs
        #    have been associated with a pre-configured Nuage VSP domain
        #    template.
        # 7. Delete all the created objects (cleanup).

        # Creating VPC
        vpc_1 = self.create_vpc(self.vpc_offering, cidr='10.1.0.0/16')

        # Associating pre-configured Nuage VSP Domain Template to VPC
        with self.assertRaises(Exception):
            self.validate_NuageVspDomainTemplate("invalid_domain_template")
        self.debug("There is no domain template with name "
                   "invalid_domain_template in VSD")
        with self.assertRaises(Exception):
            self.associate_NuageVspDomainTemplate("invalid_domain_template",
                                                  vpc_1)
        self.debug("Association fails as there is no domain template with "
                   "name invalid_domain_template in VSD")
        self.associate_NuageVspDomainTemplate(self.domain_template_list[0],
                                              vpc_1)

        # Creating VPC networks (tiers)
        vpc_1_tier_1 = self.create_Network(self.network_offering,
                                           gateway='10.1.3.1',
                                           vpc=vpc_1)
        vpc_1_tier_2 = self.create_Network(self.network_offering,
                                           gateway='10.1.4.1',
                                           vpc=vpc_1)

        # VSD verification
        self.verify_vsd_network(
            self.account.domainid,
            vpc_1_tier_1,
            vpc_1,
            domain_template_name=self.domain_template_list[0])
        self.verify_vsd_network(
            self.account.domainid,
            vpc_1_tier_2,
            vpc_1,
            domain_template_name=self.domain_template_list[0])

        # Restart VPC networks (tiers) without cleanup
        Network.restart(vpc_1_tier_1, self.api_client, cleanup=False)
        Network.restart(vpc_1_tier_2, self.api_client, cleanup=False)

        # VSD verification
        self.verify_vsd_network(
            self.account.domainid,
            vpc_1_tier_1,
            vpc_1,
            domain_template_name=self.domain_template_list[0])
        self.verify_vsd_network(
            self.account.domainid,
            vpc_1_tier_2,
            vpc_1,
            domain_template_name=self.domain_template_list[0])

        # Restart VPC networks (tiers) with cleanup
        Network.restart(vpc_1_tier_1, self.api_client, cleanup=True)
        Network.restart(vpc_1_tier_2, self.api_client, cleanup=True)

        # VSD verification
        self.verify_vsd_network(
            self.account.domainid,
            vpc_1_tier_1,
            vpc_1,
            domain_template_name=self.domain_template_list[0])
        self.verify_vsd_network(
            self.account.domainid,
            vpc_1_tier_2,
            vpc_1,
            domain_template_name=self.domain_template_list[0])

        # Restart VPC without cleanup
        self.restart_Vpc(vpc_1, cleanup=False)

        # VSD verification
        self.verify_vsd_network(
            self.account.domainid,
            vpc_1_tier_1,
            vpc_1,
            domain_template_name=self.domain_template_list[0])
        self.verify_vsd_network(
            self.account.domainid,
            vpc_1_tier_2,
            vpc_1,
            domain_template_name=self.domain_template_list[0])

        # Restart VPC with cleanup
        self.restart_Vpc(vpc_1, cleanup=True)

        # VSD verification
        self.verify_vsd_network(
            self.account.domainid,
            vpc_1_tier_1,
            vpc_1,
            domain_template_name=self.domain_template_list[0])
        self.verify_vsd_network(
            self.account.domainid,
            vpc_1_tier_2,
            vpc_1,
            domain_template_name=self.domain_template_list[0])

        # Creating VPC
        vpc_2 = self.create_vpc(self.vpc_offering, cidr='10.1.0.0/16')

        # Associating pre-configured Nuage VSP Domain Template to VPC
        self.validate_NuageVspDomainTemplate(self.domain_template_list[0])
        self.associate_NuageVspDomainTemplate(self.domain_template_list[0],
                                              vpc_2)
        self.validate_NuageVspDomainTemplate(self.domain_template_list[1])
        self.associate_NuageVspDomainTemplate(self.domain_template_list[1],
                                              vpc_2)

        # Deleting the associated pre-configured Nuage VSP domain template
        enterprise = self._session.user.enterprises.get_first(
            filter="externalID BEGINSWITH '%s'" % self.account.domainid)
        domain_template = enterprise.domain_templates.get_first(
            filter="name is '%s'" % self.domain_template_list[1])
        domain_template.delete()

        # Creating VPC networks (tiers)
        with self.assertRaises(Exception):
            self.create_Network(self.network_offering,
                                gateway='10.1.1.1',
                                vpc=vpc_2)
        self.debug("Corresponding domain creation in VSD fails, but VPC "
                   "(tier) network gets created on CloudStack as the "
                   "associated pre-configured Nuage VSP domain template is no "
                   "longer existing in VSD")
        for vpc_2_tier in Network.list(self.api_client, vpcid=vpc_2.id):
            Network(vpc_2_tier.__dict__).delete(self.api_client)

        # Re-creating the associated pre-configured Nuage VSP domain template
        new_domain_template = self.vsdk.NUDomainTemplate(
            name=self.domain_template_list[1],
            description=self.domain_template_list[1])
        enterprise = self._session.user.enterprises.get_first(
            filter="externalID BEGINSWITH '%s'" % self.account.domainid)
        enterprise.create_child(new_domain_template)
        self.cleanup_domain_templates.append(
            enterprise.domain_templates.get_first(
                filter="name is '%s'" % self.domain_template_list[1]))

        vpc_2_tier_1 = self.create_Network(self.network_offering,
                                           gateway='10.1.2.1',
                                           vpc=vpc_2)
        vpc_2_tier_2 = self.create_Network(self.network_offering,
                                           gateway='10.1.3.1',
                                           vpc=vpc_2)

        # VSD verification
        self.verify_vsd_network(
            self.account.domainid,
            vpc_2_tier_1,
            vpc_2,
            domain_template_name=self.domain_template_list[1])
        self.verify_vsd_network(
            self.account.domainid,
            vpc_2_tier_2,
            vpc_2,
            domain_template_name=self.domain_template_list[1])

        # Creating VPC
        vpc_3 = self.create_vpc(self.vpc_offering, cidr='10.1.0.0/16')

        # Associating pre-configured Nuage VSP Domain Template to VPC
        self.validate_NuageVspDomainTemplate(self.domain_template_list[0])
        self.associate_NuageVspDomainTemplate(self.domain_template_list[0],
                                              vpc_3)

        # Creating an ACL list and an ACL item
        acl_list = self.create_NetworkAclList(name="acl",
                                              description="acl",
                                              vpc=vpc_3)
        self.create_NetworkAclRule(self.test_data["ingress_rule"],
                                   acl_list=acl_list)

        # Creating VPC networks (tiers)
        with self.assertRaises(Exception):
            self.create_Network(self.network_offering,
                                gateway='10.1.1.1',
                                vpc=vpc_3,
                                acl_list=acl_list)
        self.debug("Corresponding domain creation in VSD fails, but VPC "
                   "(tier) network gets created on CloudStack as creation of "
                   "Network ACLs from CloudStack is not supported when the "
                   "VPC is associated with a Nuage VSP pre-configured domain "
                   "template")
        for vpc_3_tier in Network.list(self.api_client, vpcid=vpc_3.id):
            Network(vpc_3_tier.__dict__).delete(self.api_client)

        vpc_3_tier_1 = self.create_Network(self.network_offering,
                                           gateway='10.1.2.1',
                                           vpc=vpc_3)
        vpc_3_tier_2 = self.create_Network(self.network_offering,
                                           gateway='10.1.3.1',
                                           vpc=vpc_3)

        # VSD verification
        self.verify_vsd_network(
            self.account.domainid,
            vpc_3_tier_1,
            vpc_3,
            domain_template_name=self.domain_template_list[0])
        self.verify_vsd_network(
            self.account.domainid,
            vpc_3_tier_2,
            vpc_3,
            domain_template_name=self.domain_template_list[0])

        # Creating VPC and VPC network (tier)
        vpc = self.create_vpc(self.vpc_offering, cidr='10.1.0.0/16')
        vpc_tier = self.create_Network(self.network_offering, vpc=vpc)

        # VSD verification
        self.verify_vsd_network(self.account.domainid, vpc_tier, vpc)

        # Associating pre-configured Nuage VSP Domain Template to VPC
        self.validate_NuageVspDomainTemplate(self.domain_template_list[0])
        with self.assertRaises(Exception):
            self.associate_NuageVspDomainTemplate(self.domain_template_list[0],
                                                  vpc)
        self.debug("Association fails as the corresponding domain and domain "
                   "templates are already created in VSD for the VPC vpc")
Esempio n. 29
0
 def isNetworkEgressDefaultPolicyAllow(self, network):
     ipv6_network = Network.list(self.apiclient,listall="true",id=network.id)
     if len(ipv6_network) == 1:
         ipv6_network = ipv6_network[0]
         return ipv6_network.egressdefaultpolicy
     return False
    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(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
    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_16_create_template_volume(self):
        """Test Create template from volume
        """

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

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

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

        self.assertNotEqual(len(vm_response), 0,
                            "Check VMs available in List VMs response")
        vm = vm_response[0]
        self.assertEqual(vm.state, 'Running',
                         "Check the state of VM created from Template")

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

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

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

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

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

        time.sleep(600)

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

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

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

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

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

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

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

        self.assertNotEqual(len(vm_response), 0,
                            "Check VMs available in List VMs response")
        vm = vm_response[0]
        self.assertEqual(vm.state, 'Running',
                         "Check the state of VM created from Template")

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

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

        templatevm.delete(self.apiclient)

        vm3network.delete(self.user_api_client)
        return
    def test_01_acquire_public_ip_in_isolated_network(self):
        # Validate the following
        # 1. create a vm . it will create a network as well.
        # 2. assign a specified IP from subnet which is dedicated to domain1, it should succeed
        # 3. assign a specified IP from subnet which is dedicated to domain1/account1, it should succeed
        # 4. assign a specified IP from subnet which is dedicated to domain2, it should fail
        # 5. assign a specified IP from subnet which is dedicated to domain2/account2, it should fail
        # 6. update account setting use.system.public.ips to false, assign a specified IP from subnet which is public, it should fail
        # 7. update account setting use.system.public.ips to true, assign a specified IP from subnet which is public, it should succeed

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

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

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

        # Associate IP in range dedicated to domain1
        ip_address_1 = self.get_free_ipaddress(self.public_ip_range1.vlan.id)
        ipaddress = PublicIPAddress.create(
            self.apiclient,
            zoneid=self.zone.id,
            networkid=network.id,
            ipaddress=ip_address_1
        )
        self.assertIsNotNone(
            ipaddress,
            "Failed to Associate IP Address"
        )
        self.cleanup.append(ipaddress)
        self.assertEqual(ipaddress.ipaddress.ipaddress, ip_address_1, "Associated IP is not same as specified")

        # Associate IP in range dedicated to domain1/account1
        ip_address_2 = self.get_free_ipaddress(self.public_ip_range2.vlan.id)
        ipaddress = PublicIPAddress.create(
            self.apiclient,
            zoneid=self.zone.id,
            networkid=network.id,
            ipaddress=ip_address_2
        )
        self.assertIsNotNone(
            ipaddress,
            "Failed to Associate IP Address"
        )
        self.cleanup.append(ipaddress)
        self.assertEqual(ipaddress.ipaddress.ipaddress, ip_address_2, "Associated IP is not same as specified")

        # Associate IP in range dedicated to domain2
        ip_address_3 = self.get_free_ipaddress(self.public_ip_range3.vlan.id)
        with self.assertRaises(Exception):
            ipaddress = PublicIPAddress.create(
                self.apiclient,
                zoneid=self.zone.id,
                networkid=network.id,
                ipaddress=ip_address_3
            )

        # Associate IP in range dedicated to domain2/account2
        ip_address_4 = self.get_free_ipaddress(self.public_ip_range4.vlan.id)
        with self.assertRaises(Exception):
            ipaddress = PublicIPAddress.create(
                self.apiclient,
                zoneid=self.zone.id,
                networkid=network.id,
                ipaddress=ip_address_4
            )

        # Associate IP in public IP pool
        Configurations.update(
            self.apiclient,
            name="use.system.public.ips",
            value="false",
            accountid=self.account1.id
        )

        ip_address_5 = self.get_free_ipaddress(self.public_ip_range5.vlan.id)
        with self.assertRaises(Exception):
            ipaddress = PublicIPAddress.create(
                self.apiclient,
                zoneid=self.zone.id,
                networkid=network.id,
                ipaddress=ip_address_5
            )

        Configurations.update(
            self.apiclient,
            name="use.system.public.ips",
            value="true",
            accountid=self.account1.id
        )
        ipaddress = PublicIPAddress.create(
            self.apiclient,
            zoneid=self.zone.id,
            networkid=network.id,
            ipaddress=ip_address_5
        )
        self.assertIsNotNone(
            ipaddress,
            "Failed to Associate IP Address"
        )
        self.cleanup.append(ipaddress)
        self.assertEqual(ipaddress.ipaddress.ipaddress, ip_address_5, "Associated IP is not same as specified")

        self.cleanup.append(self.virtual_machine)
        self.cleanup.append(self.service_offering)

        return
Esempio n. 34
0
    def test_01_host_maintenance_mode(self):
        """Test host maintenance mode
        """

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

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

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

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

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

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

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

        # Should be able to SSH VM
        try:
            self.debug("SSH into VM: %s" % virtual_machine.id)
            virtual_machine.get_ssh_client(
                ipaddress=public_ip.ipaddress.ipaddress)
        except Exception as e:
            self.fail("SSH Access failed for %s: %s" %
                      (virtual_machine.ipaddress, e))

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

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

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

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

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

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

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

        # Poll and check the status of VMs
        timeout = self.services["timeout"]
        while True:
            vms = VirtualMachine.list(self.apiclient,
                                      account=self.account.name,
                                      domainid=self.account.domainid,
                                      listall=True)
            self.assertEqual(
                isinstance(vms, list), True,
                "List VMs should return valid response for deployed VM")
            self.assertNotEqual(
                len(vms), 0,
                "List VMs should return valid response for deployed VM")
            vm = vms[0]
            self.debug(
                "VM state after enabling maintenance on first host: %s" %
                vm.state)
            if vm.state in [
                    "Stopping", "Stopped", "Running", "Starting", "Migrating"
            ]:
                if vm.state == "Running":
                    break
                else:
                    time.sleep(self.services["sleep"])
                    timeout = timeout - 1
            else:
                self.fail("VM migration from one-host-to-other failed\
                            while enabling maintenance")

                # Poll and check the status of VMs
        timeout = self.services["timeout"]
        while True:
            vms = VirtualMachine.list(self.apiclient,
                                      account=self.account.name,
                                      domainid=self.account.domainid,
                                      listall=True)
            self.assertEqual(
                isinstance(vms, list), True,
                "List VMs should return valid response for deployed VM")
            self.assertNotEqual(
                len(vms), 0,
                "List VMs should return valid response for deployed VM")
            vm = vms[1]
            self.debug(
                "VM state after enabling maintenance on first host: %s" %
                vm.state)
            if vm.state in [
                    "Stopping", "Stopped", "Running", "Starting", "Migrating"
            ]:
                if vm.state == "Running":
                    break
                else:
                    time.sleep(self.services["sleep"])
                    timeout = timeout - 1
            else:
                self.fail("VM migration from one-host-to-other\
                            failed while enabling maintenance")

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

        # Spawn an instance on other host
        virtual_machine_3 = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id)
        vms = VirtualMachine.list(self.apiclient,
                                  id=virtual_machine_3.id,
                                  listall=True)
        self.assertEqual(
            isinstance(vms, list), True,
            "List VMs should return valid response for deployed VM")
        self.assertNotEqual(
            len(vms), 0,
            "List VMs should return valid response for deployed VM")
        vm = vms[0]

        self.debug("Deployed VM on host: %s" % vm.hostid)
        self.debug("VM 3 state: %s" % vm.state)
        self.assertEqual(vm.state, "Running",
                         "Deployed VM should be in Running state")

        # Should be able to SSH VM
        try:
            self.debug("SSH into VM: %s" % virtual_machine.id)
            virtual_machine.get_ssh_client(
                ipaddress=public_ip.ipaddress.ipaddress)
        except Exception as e:
            self.fail("SSH Access failed for %s: %s" %
                      (virtual_machine.ipaddress, e))

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

        self.debug("Waiting for SSVMs to come up")
        wait_for_ssvms(
            self.apiclient,
            zoneid=self.zone.id,
            podid=self.pod.id,
        )
        return
    def test_01_host_maintenance_mode(self):
        """Test host maintenance mode
        """

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

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

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

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

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

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

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

        # Should be able to SSH VM
        try:
            self.debug("SSH into VM: %s" % virtual_machine.id)
            virtual_machine.get_ssh_client(
                ipaddress=public_ip.ipaddress.ipaddress)
        except Exception as e:
            self.fail("SSH Access failed for %s: %s" %
                      (virtual_machine.ipaddress, e)
                      )

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

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

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

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

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

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

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

        # Poll and check the status of VMs
        timeout = self.services["timeout"]
        while True:
            vms = VirtualMachine.list(
                self.apiclient,
                account=self.account.name,
                domainid=self.account.domainid,
                listall=True
            )
            self.assertEqual(
                isinstance(vms, list),
                True,
                "List VMs should return valid response for deployed VM"
            )
            self.assertNotEqual(
                len(vms),
                0,
                "List VMs should return valid response for deployed VM"
            )
            vm = vms[0]
            self.debug(
                "VM state after enabling maintenance on first host: %s" %
                vm.state)
            if vm.state in [
                "Stopping",
                "Stopped",
                "Running",
                "Starting",
                "Migrating"
            ]:
                if vm.state == "Running":
                    break
                else:
                    time.sleep(self.services["sleep"])
                    timeout = timeout - 1
            else:
                self.fail(
                    "VM migration from one-host-to-other failed\
                            while enabling maintenance"
                )

                # Poll and check the status of VMs
        timeout = self.services["timeout"]
        while True:
            vms = VirtualMachine.list(
                self.apiclient,
                account=self.account.name,
                domainid=self.account.domainid,
                listall=True
            )
            self.assertEqual(
                isinstance(vms, list),
                True,
                "List VMs should return valid response for deployed VM"
            )
            self.assertNotEqual(
                len(vms),
                0,
                "List VMs should return valid response for deployed VM"
            )
            vm = vms[1]
            self.debug(
                "VM state after enabling maintenance on first host: %s" %
                vm.state)
            if vm.state in [
                "Stopping",
                "Stopped",
                "Running",
                "Starting",
                "Migrating"
            ]:
                if vm.state == "Running":
                    break
                else:
                    time.sleep(self.services["sleep"])
                    timeout = timeout - 1
            else:
                self.fail(
                    "VM migration from one-host-to-other\
                            failed while enabling maintenance"
                )

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

        # Spawn an instance on other host
        virtual_machine_3 = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id
        )
        vms = VirtualMachine.list(
            self.apiclient,
            id=virtual_machine_3.id,
            listall=True
        )
        self.assertEqual(
            isinstance(vms, list),
            True,
            "List VMs should return valid response for deployed VM"
        )
        self.assertNotEqual(
            len(vms),
            0,
            "List VMs should return valid response for deployed VM"
        )
        vm = vms[0]

        self.debug("Deployed VM on host: %s" % vm.hostid)
        self.debug("VM 3 state: %s" % vm.state)
        self.assertEqual(
            vm.state,
            "Running",
            "Deployed VM should be in Running state"
        )

        # Should be able to SSH VM
        try:
            self.debug("SSH into VM: %s" % virtual_machine.id)
            virtual_machine.get_ssh_client(
                ipaddress=public_ip.ipaddress.ipaddress)
        except Exception as e:
            self.fail("SSH Access failed for %s: %s" %
                      (virtual_machine.ipaddress, e)
                      )

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

        self.debug("Waiting for SSVMs to come up")
        wait_for_ssvms(
            self.apiclient,
            zoneid=self.zone.id,
            podid=self.pod.id,
        )
        return
    def test_03_network_create(self):
        """ Test create network in project
        """
        # Validate the following
        # 1. Create a project.
        # 2. Add virtual/direct network resource to the project. User shared
        #    network resource for the project
        # 3. Verify any number of Project level Virtual/Direct networks can be
        #    created and used for vm deployment within the project.
        # 4. Verify shared networks (zone and domain wide) from outside the
        #    project can also be used in a project.

        # Create project as a domain admin
        project = Project.create(
            self.apiclient, self.services["project"], account=self.account.name, domainid=self.account.domainid
        )
        # Cleanup created project at end of test
        self.cleanup.append(project)
        self.debug("Created project with domain admin with ID: %s" % project.id)

        network_offerings = list_network_offerings(
            self.apiclient, projectid=project.id, supportedServices="SourceNat", type="isolated", state="Enabled"
        )
        self.assertEqual(isinstance(network_offerings, list), True, "Check for the valid network offerings")
        network_offering = network_offerings[0]

        self.debug("creating a network with network offering ID: %s" % network_offering.id)
        self.services["network"]["zoneid"] = self.zone.id
        network = Network.create(
            self.apiclient, self.services["network"], networkofferingid=network_offering.id, projectid=project.id
        )
        self.debug("Created network with ID: %s" % network.id)
        networks = Network.list(self.apiclient, projectid=project.id, listall=True)
        self.assertEqual(isinstance(networks, list), True, "Check for the valid network list response")

        self.debug("Deploying VM with network: %s" % network.id)

        virtual_machine = VirtualMachine.create(
            self.apiclient,
            self.services["server"],
            templateid=self.template.id,
            networkids=[str(network.id)],
            serviceofferingid=self.service_offering.id,
            projectid=project.id,
        )
        self.debug("Deployed VM with ID: %s" % virtual_machine.id)
        # Verify VM state
        self.assertEqual(virtual_machine.state, "Running", "Check VM state is Running or not")

        network_offerings = list_network_offerings(
            self.apiclient,
            state="Enabled",
            guestiptype="Shared",
            name="DefaultSharedNetworkOffering",
            displaytext="Offering for Shared networks",
        )
        self.assertEqual(isinstance(network_offerings, list), True, "Check for the valid network offerings")
        network_offering = network_offerings[0]

        self.debug("creating a shared network in domain: %s" % self.domain.id)

        # Getting physical network and free vlan in it
        physical_network, vlan = get_free_vlan(self.apiclient, self.zone.id)

        self.services["domain_network"]["vlan"] = vlan
        self.services["domain_network"]["physicalnetworkid"] = physical_network.id

        # Generating random subnet number for shared network creation
        shared_network_subnet_number = random.randrange(1, 254)

        self.services["domain_network"]["gateway"] = "172.16." + str(shared_network_subnet_number) + ".1"
        self.services["domain_network"]["startip"] = "172.16." + str(shared_network_subnet_number) + ".2"
        self.services["domain_network"]["endip"] = "172.16." + str(shared_network_subnet_number) + ".20"

        domain_network = Network.create(
            self.apiclient,
            self.services["domain_network"],
            domainid=self.domain.id,
            networkofferingid=network_offering.id,
            zoneid=self.zone.id,
        )
        self.cleanup.append(domain_network)
        self.debug("Created network with ID: %s" % domain_network.id)

        virtual_machine = VirtualMachine.create(
            self.apiclient,
            self.services["server"],
            templateid=self.template.id,
            networkids=[str(domain_network.id)],
            serviceofferingid=self.service_offering.id,
            projectid=project.id,
        )
        self.debug("Deployed VM with ID: %s" % virtual_machine.id)
        # Verify VM state
        self.assertEqual(virtual_machine.state, "Running", "Check VM state is Running or not")

        # Delete VM before network gets deleted in cleanup
        virtual_machine.delete(self.apiclient, expunge=True)
        return
    def test_02_host_maintenance_mode_with_activities(self):
        """Test host maintenance mode with activities
        """

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        # Poll and check the status of VMs
        timeout = self.services["timeout"]
        while True:
            vms = VirtualMachine.list(
                self.apiclient,
                account=self.account.name,
                domainid=self.account.domainid,
                listall=True
            )
            self.assertEqual(
                isinstance(vms, list),
                True,
                "List VMs should return valid response for deployed VM"
            )
            self.assertNotEqual(
                len(vms),
                0,
                "List VMs should return valid response for deployed VM"
            )
            vm = vms[0]
            self.debug(
                "VM state after enabling maintenance on first host: %s" %
                vm.state)
            if vm.state in ["Stopping",
                            "Stopped",
                            "Running",
                            "Starting",
                            "Migrating"]:
                if vm.state == "Running":
                    break
                else:
                    time.sleep(self.services["sleep"])
                    timeout = timeout - 1
            else:
                self.fail(
                    "VM migration from one-host-to-other failed\
                            while enabling maintenance"
                )

        # Poll and check the status of VMs
        timeout = self.services["timeout"]
        while True:
            vms = VirtualMachine.list(
                self.apiclient,
                account=self.account.name,
                domainid=self.account.domainid,
                listall=True
            )
            self.assertEqual(
                isinstance(vms, list),
                True,
                "List VMs should return valid response for deployed VM"
            )
            self.assertNotEqual(
                len(vms),
                0,
                "List VMs should return valid response for deployed VM"
            )
            vm = vms[1]
            self.debug(
                "VM state after enabling maintenance on first host: %s" %
                vm.state)
            if vm.state in ["Stopping",
                            "Stopped",
                            "Running",
                            "Starting",
                            "Migrating"]:
                if vm.state == "Running":
                    break
                else:
                    time.sleep(self.services["sleep"])
                    timeout = timeout - 1
            else:
                self.fail(
                    "VM migration from one-host-to-other failed\
                            while enabling maintenance"
                )

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

        # Spawn an instance on other host
        virtual_machine_3 = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id
        )
        vms = VirtualMachine.list(
            self.apiclient,
            id=virtual_machine_3.id,
            listall=True
        )
        self.assertEqual(
            isinstance(vms, list),
            True,
            "List VMs should return valid response for deployed VM"
        )
        self.assertNotEqual(
            len(vms),
            0,
            "List VMs should return valid response for deployed VM"
        )
        vm = vms[0]

        self.debug("Deployed VM on host: %s" % vm.hostid)
        self.debug("VM 3 state: %s" % vm.state)
        self.assertEqual(
            vm.state,
            "Running",
            "Deployed VM should be in Running state"
        )

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

        self.debug("Waiting for SSVMs to come up")
        wait_for_ssvms(
            self.apiclient,
            zoneid=self.zone.id,
            podid=self.pod.id,
        )
        return
    def test_01_nuage_Domain_Template_selection_per_VPC(self):
        """Test Nuage VSP Domain Template selection per VPC
        """

        # 1. Associate an invalid/non-existing Nuage VSP domain template to a
        #    VPC; verify that the association fails.
        # 2. Associate a valid/existing pre-configured Nuage VSP domain
        #    template to a VPC; verify that the association is successful, VPC
        #    networks (domains) are instantiated from the associated domain
        #    template in VSD.
        # 3. Verify that the state of such VPC networks (domains) in VSD is not
        #    affected with their restarts in CloudStack with and without
        #    cleanup.
        # 4. Verify that multiple associations (update) of domain templates to
        #    a VPC goes through till the creation of its first VPC network
        #    (tier).
        # 5. Verify that the VPC networks (domains) creation fails in VSD when
        #    the associated domain templates to their corresponding VPCs have
        #    been deleted in VSD.
        # 6. Verify that the VPC networks (domains) creation fails in VSD when
        #    an acl list is associated with them after their corresponding VPCs
        #    have been associated with a pre-configured Nuage VSP domain
        #    template.
        # 7. Delete all the created objects (cleanup).

        # Creating VPC
        vpc_1 = self.create_Vpc(self.vpc_offering, cidr='10.1.0.0/16')

        # Associating pre-configured Nuage VSP Domain Template to VPC
        with self.assertRaises(Exception):
            self.validate_NuageVspDomainTemplate("invalid_domain_template")
        self.debug("There is no domain template with name "
                   "invalid_domain_template in VSD")
        with self.assertRaises(Exception):
            self.associate_NuageVspDomainTemplate(
                "invalid_domain_template", vpc_1)
        self.debug("Association fails as there is no domain template with "
                   "name invalid_domain_template in VSD")
        self.associate_NuageVspDomainTemplate(
            self.domain_template_list[0], vpc_1)

        # Creating VPC networks (tiers)
        vpc_1_tier_1 = self.create_Network(
            self.network_offering, gateway='10.1.3.1', vpc=vpc_1)
        vpc_1_tier_2 = self.create_Network(
            self.network_offering, gateway='10.1.4.1', vpc=vpc_1)

        # VSD verification
        self.verify_vsd_network(
            self.account.domainid, vpc_1_tier_1, vpc_1,
            domain_template_name=self.domain_template_list[0])
        self.verify_vsd_network(
            self.account.domainid, vpc_1_tier_2, vpc_1,
            domain_template_name=self.domain_template_list[0])

        # Restart VPC networks (tiers) without cleanup
        Network.restart(vpc_1_tier_1, self.api_client, cleanup=False)
        Network.restart(vpc_1_tier_2, self.api_client, cleanup=False)

        # VSD verification
        self.verify_vsd_network(
            self.account.domainid, vpc_1_tier_1, vpc_1,
            domain_template_name=self.domain_template_list[0])
        self.verify_vsd_network(
            self.account.domainid, vpc_1_tier_2, vpc_1,
            domain_template_name=self.domain_template_list[0])

        # Restart VPC networks (tiers) with cleanup
        Network.restart(vpc_1_tier_1, self.api_client, cleanup=True)
        Network.restart(vpc_1_tier_2, self.api_client, cleanup=True)

        # VSD verification
        self.verify_vsd_network(
            self.account.domainid, vpc_1_tier_1, vpc_1,
            domain_template_name=self.domain_template_list[0])
        self.verify_vsd_network(
            self.account.domainid, vpc_1_tier_2, vpc_1,
            domain_template_name=self.domain_template_list[0])

        # Restart VPC without cleanup
        self.restart_Vpc(vpc_1, cleanup=False)

        # VSD verification
        self.verify_vsd_network(
            self.account.domainid, vpc_1_tier_1, vpc_1,
            domain_template_name=self.domain_template_list[0])
        self.verify_vsd_network(
            self.account.domainid, vpc_1_tier_2, vpc_1,
            domain_template_name=self.domain_template_list[0])

        # Restart VPC with cleanup
        self.restart_Vpc(vpc_1, cleanup=True)

        # VSD verification
        self.verify_vsd_network(
            self.account.domainid, vpc_1_tier_1, vpc_1,
            domain_template_name=self.domain_template_list[0])
        self.verify_vsd_network(
            self.account.domainid, vpc_1_tier_2, vpc_1,
            domain_template_name=self.domain_template_list[0])

        # Creating VPC
        vpc_2 = self.create_Vpc(self.vpc_offering, cidr='10.1.0.0/16')

        # Associating pre-configured Nuage VSP Domain Template to VPC
        self.validate_NuageVspDomainTemplate(self.domain_template_list[0])
        self.associate_NuageVspDomainTemplate(
            self.domain_template_list[0], vpc_2)
        self.validate_NuageVspDomainTemplate(self.domain_template_list[1])
        self.associate_NuageVspDomainTemplate(
            self.domain_template_list[1], vpc_2)

        # Deleting the associated pre-configured Nuage VSP domain template
        enterprise = self._session.user.enterprises.get_first(
            filter="externalID BEGINSWITH '%s'" % self.account.domainid)
        domain_template = enterprise.domain_templates.get_first(
            filter="name is '%s'" % self.domain_template_list[1])
        domain_template.delete()

        # Creating VPC networks (tiers)
        with self.assertRaises(Exception):
            self.create_Network(
                self.network_offering,
                gateway='10.1.1.1',
                vpc=vpc_2)
        self.debug("Corresponding domain creation in VSD fails, but VPC "
                   "(tier) network gets created on CloudStack as the "
                   "associated pre-configured Nuage VSP domain template is no "
                   "longer existing in VSD")
        for vpc_2_tier in Network.list(self.api_client, vpcid=vpc_2.id):
            Network(vpc_2_tier.__dict__).delete(self.api_client)

        # Re-creating the associated pre-configured Nuage VSP domain template
        new_domain_template = self.vsdk.NUDomainTemplate(
            name=self.domain_template_list[1],
            description=self.domain_template_list[1])
        enterprise = self._session.user.enterprises.get_first(
            filter="externalID BEGINSWITH '%s'" % self.account.domainid)
        enterprise.create_child(new_domain_template)
        self.cleanup_domain_templates.append(
            enterprise.domain_templates.get_first(
                filter="name is '%s'" % self.domain_template_list[1]))

        vpc_2_tier_1 = self.create_Network(
            self.network_offering, gateway='10.1.2.1', vpc=vpc_2)
        vpc_2_tier_2 = self.create_Network(
            self.network_offering, gateway='10.1.3.1', vpc=vpc_2)

        # VSD verification
        self.verify_vsd_network(
            self.account.domainid, vpc_2_tier_1, vpc_2,
            domain_template_name=self.domain_template_list[1])
        self.verify_vsd_network(
            self.account.domainid, vpc_2_tier_2, vpc_2,
            domain_template_name=self.domain_template_list[1])

        # Creating VPC
        vpc_3 = self.create_Vpc(self.vpc_offering, cidr='10.1.0.0/16')

        # Associating pre-configured Nuage VSP Domain Template to VPC
        self.validate_NuageVspDomainTemplate(self.domain_template_list[0])
        self.associate_NuageVspDomainTemplate(
            self.domain_template_list[0], vpc_3)

        # Creating an ACL list and an ACL item
        acl_list = self.create_NetworkAclList(
            name="acl", description="acl", vpc=vpc_3)
        self.create_NetworkAclRule(
            self.test_data["ingress_rule"], acl_list=acl_list)

        # Creating VPC networks (tiers)
        with self.assertRaises(Exception):
            self.create_Network(
                self.network_offering,
                gateway='10.1.1.1',
                vpc=vpc_3,
                acl_list=acl_list)
        self.debug("Corresponding domain creation in VSD fails, but VPC "
                   "(tier) network gets created on CloudStack as creation of "
                   "Network ACLs from CloudStack is not supported when the "
                   "VPC is associated with a Nuage VSP pre-configured domain "
                   "template")
        for vpc_3_tier in Network.list(self.api_client, vpcid=vpc_3.id):
            Network(vpc_3_tier.__dict__).delete(self.api_client)

        vpc_3_tier_1 = self.create_Network(
            self.network_offering, gateway='10.1.2.1', vpc=vpc_3)
        vpc_3_tier_2 = self.create_Network(
            self.network_offering, gateway='10.1.3.1', vpc=vpc_3)

        # VSD verification
        self.verify_vsd_network(
            self.account.domainid, vpc_3_tier_1, vpc_3,
            domain_template_name=self.domain_template_list[0])
        self.verify_vsd_network(
            self.account.domainid, vpc_3_tier_2, vpc_3,
            domain_template_name=self.domain_template_list[0])

        # Creating VPC and VPC network (tier)
        vpc = self.create_Vpc(self.vpc_offering, cidr='10.1.0.0/16')
        vpc_tier = self.create_Network(self.network_offering, vpc=vpc)

        # VSD verification
        self.verify_vsd_network(self.account.domainid, vpc_tier, vpc)

        # Associating pre-configured Nuage VSP Domain Template to VPC
        self.validate_NuageVspDomainTemplate(self.domain_template_list[0])
        with self.assertRaises(Exception):
            self.associate_NuageVspDomainTemplate(
                self.domain_template_list[0], vpc)
        self.debug("Association fails as the corresponding domain and domain "
                   "templates are already created in VSD for the VPC vpc")
    def test_01_create_delete_portforwarding_fornonvpc(self):
        """
        @summary: Test to list, create and delete Port Forwarding for
        IP Address associated to Non VPC network
        @Steps:
        Step1: Creating a Network for the user
        Step2: Associating an IP Addresses for Network
        Step3: Launching Virtual Machine in network created in step 2
        Step4: Listing Port Forwarding Rules for the IP Address associated
               in Step2
        Step5: Verifying that no Port Forwarding Rules are listed
        Step6: Creating a Port Forwarding Rule for IP Address associated in
               Step2
        Step7: Listing Port Forwarding Rules for the IP Address associated in
               Step2
        Step8: Verifying 1 Port Forwarding Rule is listed
        Step9: Deleting the Port Forwarding Rule created in Step6
        Step10: Listing Port Forwarding Rules for the IP Address associated in
               Step2
        Step11: Verifying that no Port Forwarding Rules are listed
        """
        # Listing all the Networks's for a user
        list_networks_before = Network.list(
            self.userapiclient,
            listall=self.services["listall"],
            type="Isolated"
        )
        # Verifying No Networks are listed
        self.assertIsNone(
            list_networks_before,
            "Networks listed for newly created User"
        )
        # Listing Network Offerings
        network_offerings_list = NetworkOffering.list(
            self.apiClient,
            forvpc="false",
            guestiptype="Isolated",
            state="Enabled",
            supportedservices="SourceNat,PortForwarding",
            zoneid=self.zone.id
        )
        status = validateList(network_offerings_list)
        self.assertEqual(
            PASS,
            status[0],
            "Isolated Network Offerings with sourceNat,\
                    PortForwarding enabled are not found"
        )
        # Creating a network
        network = Network.create(
            self.userapiclient,
            self.services["network"],
            accountid=self.account.name,
            domainid=self.domain.id,
            networkofferingid=network_offerings_list[0].id,
            zoneid=self.zone.id
        )

        self.assertIsNotNone(
            network,
            "Network creation failed"
        )
        # Listing all the IP Addresses for a user
        list_ipaddresses_before = PublicIPAddress.list(
            self.userapiclient,
            listall=self.services["listall"]
        )
        # Verifying no IP Addresses are listed
        self.assertIsNone(
            list_ipaddresses_before,
            "IP Addresses listed for newly created User"
        )

        service_offering = ServiceOffering.create(
            self.apiClient,
            self.services["service_offerings"]["tiny"],
        )

        self.services["virtual_machine"]["zoneid"] = self.zone.id

        vm = VirtualMachine.create(
            self.userapiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            networkids=network.id,
            serviceofferingid=service_offering.id
        )

        VirtualMachine.delete(vm, self.apiClient, expunge=True)

        # Associating an IP Addresses to Network created
        associated_ipaddress = PublicIPAddress.create(
            self.userapiclient,
            services=self.services["network"],
            networkid=network.id
        )
        self.assertIsNotNone(
            associated_ipaddress,
            "Failed to Associate IP Address"
        )
        # Listing all the IP Addresses for a user
        list_ipaddresses_after = PublicIPAddress.list(
            self.userapiclient,
            listall=self.services["listall"]
        )
        status = validateList(list_ipaddresses_after)
        self.assertEqual(
            PASS,
            status[0],
            "IP Addresses Association Failed"
        )
        # Verifying the length of the list is 2
        self.assertEqual(
            2,
            len(list_ipaddresses_after),
            "Number of IP Addresses associated are not matching expected"
        )
        # Launching a Virtual Machine with above created Network
        vm_created = VirtualMachine.create(
            self.userapiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            networkids=network.id,
            serviceofferingid=self.service_offering.id,
        )
        self.assertIsNotNone(
            vm_created,
            "Failed to launch a VM under network created"
        )
        self.cleanup.append(network)
        # Listing Virtual Machines in running state in above created network
        list_vms_running = VirtualMachine.list(
            self.userapiclient,
            listall=self.services["listall"],
            state="Running",
            networkid=network.id
        )
        status = validateList(list_vms_running)
        self.assertEqual(
            PASS,
            status[0],
            "VM Created is not in Running state"
        )
        # Verifying the length of the list is 2
        self.assertEqual(
            2,
            len(list_ipaddresses_after),
            "VM Created is not in Running state"
        )
        self.assertEqual(
            vm_created.id,
            list_vms_running[0].id,
            "VM Created is not in Running state"
        )
        # Listing Virtual Machines in stopped state in above created network
        list_vms_stopped = VirtualMachine.list(
            self.userapiclient,
            listall=self.services["listall"],
            state="Stopped",
            networkid=network.id
        )
        # Verifying no VMs are in stopped state
        self.assertIsNone(
            list_vms_stopped,
            "VM Created is in stopped state"
        )
        # Listing Port Forwarding Rules for the IP Address associated
        list_prtfwdrule_before = NATRule.list(
            self.userapiclient,
            listall=self.services["listall"],
            ipaddressid=associated_ipaddress.ipaddress.id
        )
        # Verifying no port forwarding rules are listed
        self.assertIsNone(
            list_prtfwdrule_before,
            "Port Forwarding Rules listed for newly associated IP Address"
        )
        # Creating a Port Forwarding rule
        portfwd_rule = NATRule.create(
            self.userapiclient,
            virtual_machine=vm_created,
            services=self.services["natrule"],
            ipaddressid=associated_ipaddress.ipaddress.id,
        )
        self.assertIsNotNone(
            portfwd_rule,
            "Failed to create Port Forwarding Rule"
        )
        # Verifying details of Sticky Policy created
        # Creating expected and actual values dictionaries
        expected_dict = {
            "ipaddressid": associated_ipaddress.ipaddress.id,
            "privateport": str(self.services["natrule"]["privateport"]),
            "publicport": str(self.services["natrule"]["publicport"]),
            "protocol": str(self.services["natrule"]["protocol"]).lower(),
        }
        actual_dict = {
            "ipaddressid": portfwd_rule.ipaddressid,
            "privateport": str(portfwd_rule.privateport),
            "publicport": str(portfwd_rule.publicport),
            "protocol": portfwd_rule.protocol,
        }
        portfwd_status = self.__verify_values(
            expected_dict,
            actual_dict
        )
        self.assertEqual(
            True,
            portfwd_status,
            "Created Port Forward Rule details are not as expected"
        )
        # Listing Port Forwarding Rules for the IP Address associated
        list_prtfwdrule_after = NATRule.list(
            self.userapiclient,
            listall=self.services["listall"],
            ipaddressid=associated_ipaddress.ipaddress.id
        )
        status = validateList(list_prtfwdrule_after)
        self.assertEqual(
            PASS,
            status[0],
            "Failed to create Port Forwarding Rule"
        )
        # Verifying the length of the list is 1
        self.assertEqual(
            1,
            len(list_prtfwdrule_after),
            "Failed to create Port Forwarding Rule"
        )
        # Deleting Port Forwarding Rule
        portfwd_rule.delete(self.userapiclient)

        # Creating a Port Forwarding rule with port range
        portfwd_rule = NATRule.create(
            self.userapiclient,
            virtual_machine=vm_created,
            services=self.services["natrulerange"],
            ipaddressid=associated_ipaddress.ipaddress.id,
        )
        self.assertIsNotNone(
            portfwd_rule,
            "Failed to create Port Forwarding Rule"
        )
        # update the private port for port forwarding rule
        updatefwd_rule = portfwd_rule.update(self.userapiclient,
                                             portfwd_rule.id,
                                             virtual_machine=vm_created,
                                             services=self.services["updatenatrulerange"],
                                             )

        # Verifying details of Sticky Policy created
        # Creating expected and actual values dictionaries
        expected_dict = {
            "privateport": str(self.services["updatenatrulerange"]["privateport"]),
            "privateendport": str(self.services["updatenatrulerange"]["privateendport"]),
        }
        actual_dict = {
            "privateport": str(updatefwd_rule.privateport),
            "privateendport": str(updatefwd_rule.privateendport),
        }
        portfwd_status = self.__verify_values(
            expected_dict,
            actual_dict
        )
        self.assertEqual(
            True,
            portfwd_status,
            "Updated Port Forward Rule details are not as expected"
        )
        # Deleting Port Forwarding Rule
        portfwd_rule.delete(self.userapiclient)
        # Listing Port Forwarding Rules for the IP Address associated
        list_prtfwdrule_after = NATRule.list(
            self.userapiclient,
            listall=self.services["listall"],
            ipaddressid=associated_ipaddress.ipaddress.id
        )
        # Verifying no port forwarding rules are listed
        self.assertIsNone(
            list_prtfwdrule_after,
            "Port Forwarding Rules listed after deletion"
        )
        # Destroying the VM Launched
        vm_created.delete(self.apiClient)
        self.cleanup.append(self.account)
        return
Esempio n. 40
0
    def test_15_restore_vm_with_template_id(self):

        """
        Test restoring Virtual Machine with template id
        """

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

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

        restorevm = VirtualMachine.create(
            self.user_api_client,
            self.services["small"],
            networkids=vm1network.id,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            mode=self.services['mode'],
            startvm="true"
        )


        time.sleep(600)

        list_vm_response = VirtualMachine.list(
                                            self.user_api_client,
                                            id=restorevm.id
                                            )
        self.assertEqual(
                            list_vm_response[0].state,
                            "Running",
                            "Check virtual machine is in running state"
                        )


        custom_disk_offering=DiskOffering.list(
                                self.user_api_client,
                                 name="custom"
                                 )

        newvolume = Volume.create(
            self.user_api_client,
            self.services["volume"],
            zoneid=self.zone.id,
            account=self.account.name,
            domainid=self.domain.id,
            diskofferingid=custom_disk_offering[0].id,
            size=1
        )

                # Attach volume to VM
        cmd = attachVolume.attachVolumeCmd()
        cmd.id = newvolume.id
        cmd.virtualmachineid = restorevm.id
        cmd.deviceid=1
        vol1=self.user_api_client.attachVolume(cmd)

        cmd = restoreVirtualMachine.restoreVirtualMachineCmd()
        cmd.virtualmachineid = restorevm.id
        cmd.templateid = self.xtemplate.id
        self.user_api_client.restoreVirtualMachine(cmd)

        time.sleep(600)

        list_vm_response = VirtualMachine.list(
                                            self.user_api_client,
                                            id=restorevm.id
                                            )
        self.assertEqual(
                            isinstance(list_vm_response, list),
                            True,
                            "Check list response returns a valid list"
                        )

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

        self.assertEqual(
                            list_vm_response[0].state,
                            "Running",
                            "Check virtual machine is in Stopped state"
                        )

        restorevm.delete(self.apiclient)

        vm1network.delete(self.user_api_client)

        return
Esempio n. 41
0
    def setUpClass(cls):
        cls.testClient = super(TestDirectDownloadTemplates, cls).getClsTestClient()
        cls.apiclient = cls.testClient.getApiClient()
        cls.hypervisor = cls.testClient.getHypervisorInfo()
        cls.dbclient = cls.testClient.getDbConnection()
        cls.zone = get_zone(cls.apiclient, cls.testClient.getZoneForTests())
        cls.pod = get_pod(cls.apiclient, cls.zone.id)
        cls.services = cls.testClient.getParsedTestDataConfig()

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

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

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

            cls.services["virtual_machine"]["zoneid"] = cls.zone.id
            cls.services["virtual_machine"]["template"] = cls.template.id
            cls.services["virtual_machine"]["hypervisor"] = cls.hypervisor
            cls.service_offering = ServiceOffering.create(
                cls.apiclient,
                cls.services["service_offerings"]["tiny"]
            )
            cls._cleanup.append(cls.service_offering)

            if cls.zone.networktype == 'Basic' :
                networks = Network.list(cls.apiclient)
                if len(networks) == 0 :
                    self.skipTest("Skipping test since no network found in basic zone")
                else :
                    cls.network = networks[0]
            else :
                cls.network_offering = NetworkOffering.create(
                    cls.apiclient,
                    cls.services["l2-network_offering"],
                )
                cls._cleanup.append(cls.network_offering)
                cls.network_offering.update(cls.apiclient, state='Enabled')
                cls.services["network"]["networkoffering"] = cls.network_offering.id
                cls.network = Network.create(
                    cls.apiclient,
                    cls.services["l2-network"],
                    zoneid=cls.zone.id,
                    networkofferingid=cls.network_offering.id
                )
                cls._cleanup.append(cls.network)

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

        cls.nfsKvmNotAvailable = not cls.hypervisorSupported or not cls.nfsStorageFound
        cls.localStorageKvmNotAvailable = not cls.hypervisorSupported or not cls.localStorageFound
        cls.sharedMountPointKvmNotAvailable = not cls.hypervisorSupported or not cls.sharedMountPointFound
        return
    def test_01_create_delete_portforwarding_fornonvpc(self):
        """
        @summary: Test to list, create and delete Port Forwarding for
        IP Address associated to Non VPC network
        @Steps:
        Step1: Creating a Network for the user
        Step2: Associating an IP Addresses for Network
        Step3: Launching Virtual Machine in network created in step 2
        Step4: Listing Port Forwarding Rules for the IP Address associated
               in Step2
        Step5: Verifying that no Port Forwarding Rules are listed
        Step6: Creating a Port Forwarding Rule for IP Address associated in
               Step2
        Step7: Listing Port Forwarding Rules for the IP Address associated in
               Step2
        Step8: Verifying 1 Port Forwarding Rule is listed
        Step9: Deleting the Port Forwarding Rule created in Step6
        Step10: Listing Port Forwarding Rules for the IP Address associated in
               Step2
        Step11: Verifying that no Port Forwarding Rules are listed
        """
        # Listing all the Networks's for a user
        list_networks_before = Network.list(
            self.userapiclient,
            listall=self.services["listall"],
            type="Isolated"
        )
        # Verifying No Networks are listed
        self.assertIsNone(
            list_networks_before,
            "Networks listed for newly created User"
        )
        # Listing Network Offerings
        network_offerings_list = NetworkOffering.list(
            self.apiClient,
            forvpc="false",
            guestiptype="Isolated",
            state="Enabled",
            supportedservices="SourceNat,PortForwarding",
            zoneid=self.zone.id
        )
        status = validateList(network_offerings_list)
        self.assertEquals(
            PASS,
            status[0],
            "Isolated Network Offerings with sourceNat,\
                    PortForwarding enabled are not found"
        )
        # Creating a network
        network = Network.create(
            self.userapiclient,
            self.services["network"],
            accountid=self.account.name,
            domainid=self.domain.id,
            networkofferingid=network_offerings_list[0].id,
            zoneid=self.zone.id
        )
        self.assertIsNotNone(
            network,
            "Network creation failed"
        )
        # Listing all the IP Addresses for a user
        list_ipaddresses_before = PublicIPAddress.list(
            self.userapiclient,
            listall=self.services["listall"]
        )
        # Verifying no IP Addresses are listed
        self.assertIsNone(
            list_ipaddresses_before,
            "IP Addresses listed for newly created User"
        )
        # Associating an IP Addresses to Network created
        associated_ipaddress = PublicIPAddress.create(
            self.userapiclient,
            services=self.services["network"],
            networkid=network.id
        )
        self.assertIsNotNone(
            associated_ipaddress,
            "Failed to Associate IP Address"
        )
        # Listing all the IP Addresses for a user
        list_ipaddresses_after = PublicIPAddress.list(
            self.userapiclient,
            listall=self.services["listall"]
        )
        status = validateList(list_ipaddresses_after)
        self.assertEquals(
            PASS,
            status[0],
            "IP Addresses Association Failed"
        )
        # Verifying the length of the list is 1
        self.assertEqual(
            1,
            len(list_ipaddresses_after),
            "Number of IP Addresses associated are not matching expected"
        )
        # Launching a Virtual Machine with above created Network
        vm_created = VirtualMachine.create(
            self.userapiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            networkids=network.id,
            serviceofferingid=self.service_offering.id,
        )
        self.assertIsNotNone(
            vm_created,
            "Failed to launch a VM under network created"
        )
        self.cleanup.append(network)
        # Listing Virtual Machines in running state in above created network
        list_vms_running = VirtualMachine.list(
            self.userapiclient,
            listall=self.services["listall"],
            state="Running",
            networkid=network.id
        )
        status = validateList(list_vms_running)
        self.assertEquals(
            PASS,
            status[0],
            "VM Created is not in Running state"
        )
        # Verifying the length of the list is 1
        self.assertEqual(
            1,
            len(list_ipaddresses_after),
            "VM Created is not in Running state"
        )
        self.assertEquals(
            vm_created.id,
            list_vms_running[0].id,
            "VM Created is not in Running state"
        )
        # Listing Virtual Machines in stopped state in above created network
        list_vms_stopped = VirtualMachine.list(
            self.userapiclient,
            listall=self.services["listall"],
            state="Stopped",
            networkid=network.id
        )
        # Verifying no VMs are in stopped state
        self.assertIsNone(
            list_vms_stopped,
            "VM Created is in stopped state"
        )
        # Listing Port Forwarding Rules for the IP Address associated
        list_prtfwdrule_before = NATRule.list(
            self.userapiclient,
            listall=self.services["listall"],
            ipaddressid=associated_ipaddress.ipaddress.id
        )
        # Verifying no port forwarding rules are listed
        self.assertIsNone(
            list_prtfwdrule_before,
            "Port Forwarding Rules listed for newly associated IP Address"
        )
        # Creating a Port Forwarding rule
        portfwd_rule = NATRule.create(
            self.userapiclient,
            virtual_machine=vm_created,
            services=self.services["natrule"],
            ipaddressid=associated_ipaddress.ipaddress.id,
        )
        self.assertIsNotNone(
            portfwd_rule,
            "Failed to create Port Forwarding Rule"
        )
        # Verifying details of Sticky Policy created
        # Creating expected and actual values dictionaries
        expected_dict = {
            "ipaddressid": associated_ipaddress.ipaddress.id,
            "privateport": str(self.services["natrule"]["privateport"]),
            "publicport": str(self.services["natrule"]["publicport"]),
            "protocol": str(self.services["natrule"]["protocol"]).lower(),
        }
        actual_dict = {
            "ipaddressid": portfwd_rule.ipaddressid,
            "privateport": str(portfwd_rule.privateport),
            "publicport": str(portfwd_rule.publicport),
            "protocol": portfwd_rule.protocol,
        }
        portfwd_status = self.__verify_values(
            expected_dict,
            actual_dict
        )
        self.assertEqual(
            True,
            portfwd_status,
            "Created Port Forward Rule details are not as expected"
        )
        # Listing Port Forwarding Rules for the IP Address associated
        list_prtfwdrule_after = NATRule.list(
            self.userapiclient,
            listall=self.services["listall"],
            ipaddressid=associated_ipaddress.ipaddress.id
        )
        status = validateList(list_prtfwdrule_after)
        self.assertEquals(
            PASS,
            status[0],
            "Failed to create Port Forwarding Rule"
        )
        # Verifying the length of the list is 1
        self.assertEqual(
            1,
            len(list_prtfwdrule_after),
            "Failed to create Port Forwarding Rule"
        )
        # Deleting Port Forwarding Rule
        portfwd_rule.delete(self.userapiclient)


        # Creating a Port Forwarding rule with port range
        portfwd_rule = NATRule.create(
            self.userapiclient,
            virtual_machine=vm_created,
            services=self.services["natrulerange"],
            ipaddressid=associated_ipaddress.ipaddress.id,
            )
        self.assertIsNotNone(
            portfwd_rule,
            "Failed to create Port Forwarding Rule"
        )
        #update the private port for port forwarding rule
        updatefwd_rule = portfwd_rule.update(self.userapiclient,
                            portfwd_rule.id,
                            virtual_machine=vm_created,
                            services=self.services["updatenatrulerange"],
                            )

        # Verifying details of Sticky Policy created
        # Creating expected and actual values dictionaries
        expected_dict = {
            "privateport": str(self.services["updatenatrulerange"]["privateport"]),
            "privateendport": str(self.services["updatenatrulerange"]["privateendport"]),
            }
        actual_dict = {
            "privateport": str(updatefwd_rule.privateport),
            "privateendport": str(updatefwd_rule.privateendport),
            }
        portfwd_status = self.__verify_values(
            expected_dict,
            actual_dict
        )
        self.assertEqual(
            True,
            portfwd_status,
            "Updated Port Forward Rule details are not as expected"
        )
        # Deleting Port Forwarding Rule
        portfwd_rule.delete(self.userapiclient)
        # Listing Port Forwarding Rules for the IP Address associated
        list_prtfwdrule_after = NATRule.list(
            self.userapiclient,
            listall=self.services["listall"],
            ipaddressid=associated_ipaddress.ipaddress.id
        )
        # Verifying no port forwarding rules are listed
        self.assertIsNone(
            list_prtfwdrule_after,
            "Port Forwarding Rules listed after deletion"
        )
        # Destroying the VM Launched
        vm_created.delete(self.apiClient)
        self.cleanup.append(self.account)
        return
    def test_02_RVR_Network_FW_PF_SSH_default_routes_egress_false(self):
        """ Test redundant router internals """
        self.logger.debug("Starting test_02_RVR_Network_FW_PF_SSH_default_routes_egress_false...")

        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.api_client, 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)"
                    )

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

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

        public_ip = public_ips[0]

        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"]["protocol"],
            cidrlist=['0.0.0.0/0'],
            startport=self.services["natrule"]["publicport"],
            endport=self.services["natrule"]["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"],
            public_ip.id
        )

        expected = 0
        ssh_command = "ping -c 3 8.8.8.8"
        check_string = " 0% packet loss"
        result = check_router_command(virtual_machine, nat_rule.ipaddress, ssh_command, check_string, self)

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

        expected = 0
        ssh_command = "wget -t 1 -T 1 www.google.com"
        check_string = "HTTP request sent, awaiting response... 200 OK"
        result = check_router_command(virtual_machine, nat_rule.ipaddress, ssh_command, check_string, self)

        self.assertEqual(
                         result,
                         expected,
                         "Attempt to retrieve google.com index page should NOT be successful"
                         )

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

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

        expected = 1
        ssh_command = "wget -t 1 -T 5 www.google.com"
        check_string = "HTTP request sent, awaiting response... 200 OK"
        result = check_router_command(virtual_machine, nat_rule.ipaddress, ssh_command, check_string, self)

        self.assertEqual(
                         result,
                         expected,
                         "Attempt to retrieve google.com index page should be successful once rule is added!"
                         )

        return
Esempio n. 44
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_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_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
    def test_forceDeleteDomain(self):
        """ Test delete domain with force option"""

        # Steps for validations
        # 1. create a domain DOM
        # 2. create 2 users under this domain
        # 3. deploy 1 VM into each of these user accounts
        # 4. create PF / FW rules for port 22 on these VMs for their
        #    respective accounts
        # 5. delete the domain with force=true option
        # Validate the following
        # 1. listDomains should list the created domain
        # 2. listAccounts should list the created accounts
        # 3. listvirtualmachines should show the Running VMs
        # 4. PF and FW rules should be shown in listFirewallRules
        # 5. domain should delete successfully and above three list calls
        #    should show all the resources now deleted. listRouters should
        #    not return any routers in the deleted accounts/domains

        self.debug("Creating a domain for login with API domain test")
        domain = Domain.create(
                                self.apiclient,
                                self.services["domain"],
                                parentdomainid=self.domain.id
                                )
        self.debug("Domain is created succesfully.")
        self.debug(
            "Checking if the created domain is listed in list domains API")
        domains = Domain.list(self.apiclient, id=domain.id, listall=True)

        self.assertEqual(
                         isinstance(domains, list),
                         True,
                         "List domains shall return a valid response"
                         )
        self.debug("Creating 2 user accounts in domain: %s" % domain.name)
        self.account_1 = Account.create(
                                     self.apiclient,
                                     self.services["account"],
                                     domainid=domain.id
                                     )

        self.account_2 = Account.create(
                                     self.apiclient,
                                     self.services["account"],
                                     domainid=domain.id
                                     )

        try:
            self.debug("Creating a tiny service offering for VM deployment")
            self.service_offering = ServiceOffering.create(
                                    self.apiclient,
                                    self.services["service_offering"],
                                    domainid=self.domain.id
                                    )

            self.debug("Deploying virtual machine in account 1: %s" %
                                                self.account_1.name)
            vm_1 = VirtualMachine.create(
                                    self.apiclient,
                                    self.services["virtual_machine"],
                                    templateid=self.template.id,
                                    accountid=self.account_1.name,
                                    domainid=self.account_1.domainid,
                                    serviceofferingid=self.service_offering.id
                                    )

            self.debug("Deploying virtual machine in account 2: %s" %
                                                self.account_2.name)
            VirtualMachine.create(
                                    self.apiclient,
                                    self.services["virtual_machine"],
                                    templateid=self.template.id,
                                    accountid=self.account_2.name,
                                    domainid=self.account_2.domainid,
                                    serviceofferingid=self.service_offering.id
                                    )

            networks = Network.list(
                                self.apiclient,
                                account=self.account_1.name,
                                domainid=self.account_1.domainid,
                                listall=True
                                )
            self.assertEqual(
                         isinstance(networks, list),
                         True,
                         "List networks should return a valid response"
                         )
            network_1 = networks[0]
            self.debug("Default network in account 1: %s is %s" % (
                                                self.account_1.name,
                                                network_1.name))
            src_nat_list = PublicIPAddress.list(
                                    self.apiclient,
                                    associatednetworkid=network_1.id,
                                    account=self.account_1.name,
                                    domainid=self.account_1.domainid,
                                    listall=True,
                                    issourcenat=True,
                                    )
            self.assertEqual(
                         isinstance(src_nat_list, list),
                         True,
                         "List Public IP should return a valid source NAT"
                         )
            self.assertNotEqual(
                    len(src_nat_list),
                    0,
                    "Length of response from listPublicIp should not be 0"
                    )

            src_nat = src_nat_list[0]

            self.debug(
                      "Trying to create a port forwarding rule in source NAT: %s" %
                                                            src_nat.ipaddress)
            #Create NAT rule
            nat_rule = NATRule.create(
                                  self.apiclient,
                                  vm_1,
                                  self.services["natrule"],
                                  ipaddressid=src_nat.id
                           )
            self.debug("Created PF rule on source NAT: %s" % src_nat.ipaddress)

            nat_rules = NATRule.list(self.apiclient, id=nat_rule.id)

            self.assertEqual(
                         isinstance(nat_rules, list),
                         True,
                         "List NAT should return a valid port forwarding rules"
                         )

            self.assertNotEqual(
                    len(nat_rules),
                    0,
                    "Length of response from listLbRules should not be 0"
                    )
        except Exception as e:
            self._cleanup.append(self.account_1)
            self._cleanup.append(self.account_2)
            self.fail(e)

        self.debug("Deleting domain with force option")
        try:
            domain.delete(self.apiclient, cleanup=True)
        except Exception as e:
            self.debug("Waiting for account.cleanup.interval" +
                " to cleanup any remaining resouces")
            # Sleep 3*account.gc to ensure that all resources are deleted
            wait_for_cleanup(self.apiclient, ["account.cleanup.interval"]*3)
            with self.assertRaises(CloudstackAPIException):
                Domain.list(
                        self.apiclient,
                        id=domain.id,
                        listall=True
                        )

        self.debug("Checking if the resources in domain are deleted")
        with self.assertRaises(CloudstackAPIException):
            Account.list(
                        self.apiclient,
                        name=self.account_1.name,
                        domainid=self.account_1.domainid,
                        listall=True
                        )
        return
    def test_15_restore_vm_with_template_id(self):
        """
        Test restoring Virtual Machine with template id
        """

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

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

        restorevm = VirtualMachine.create(
            self.user_api_client,
            self.services["small"],
            networkids=vm1network.id,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            mode=self.services['mode'],
            startvm="true")

        time.sleep(600)

        list_vm_response = VirtualMachine.list(self.user_api_client,
                                               id=restorevm.id)
        self.assertEqual(list_vm_response[0].state, "Running",
                         "Check virtual machine is in running state")

        custom_disk_offering = DiskOffering.list(self.user_api_client,
                                                 name="custom")

        newvolume = Volume.create(self.user_api_client,
                                  self.services["volume"],
                                  zoneid=self.zone.id,
                                  account=self.account.name,
                                  domainid=self.domain.id,
                                  diskofferingid=custom_disk_offering[0].id,
                                  size=1)

        # Attach volume to VM
        cmd = attachVolume.attachVolumeCmd()
        cmd.id = newvolume.id
        cmd.virtualmachineid = restorevm.id
        cmd.deviceid = 1
        vol1 = self.user_api_client.attachVolume(cmd)

        cmd = restoreVirtualMachine.restoreVirtualMachineCmd()
        cmd.virtualmachineid = restorevm.id
        cmd.templateid = self.xtemplate.id
        self.user_api_client.restoreVirtualMachine(cmd)

        time.sleep(600)

        list_vm_response = VirtualMachine.list(self.user_api_client,
                                               id=restorevm.id)
        self.assertEqual(isinstance(list_vm_response, list), True,
                         "Check list response returns a valid list")

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

        self.assertEqual(list_vm_response[0].state, "Running",
                         "Check virtual machine is in Stopped state")

        restorevm.delete(self.apiclient)

        vm1network.delete(self.user_api_client)

        return
    def test_RVR_Network_FW_PF_SSH_default_routes(self):
        """ Test redundant router internals """
        self.logger.debug("Starting test_RVR_Network_FW_PF_SSH_default_routes...")

        self.logger.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.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)

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

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

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

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

        public_ip_1 = public_ips[0]

        self.logger.debug("Creating Firewall rule for VM ID: %s" % virtual_machine.id)
        FireWallRule.create(
            self.apiclient,
            ipaddressid=public_ip_1.id,
            protocol=self.services["natrule"]["protocol"],
            cidrlist=['0.0.0.0/0'],
            startport=self.services["natrule"]["publicport"],
            endport=self.services["natrule"]["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"],
            public_ip_1.id
        )

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

        result = 'failed'
        try:
            ssh_command = "ping -c 3 8.8.8.8"
            ssh = virtual_machine.get_ssh_client(ipaddress=public_ip.ipaddress.ipaddress, retries=5)
            self.logger.debug("Ping to google.com from VM")

            result = str(ssh.execute(ssh_command))
            self.logger.debug("SSH result: %s; COUNT is ==> %s" % (result, result.count("3 packets received")))
        except:
            self.fail("Failed to SSH into VM - %s" % (public_ip.ipaddress.ipaddress))

        self.assertEqual(
                         result.count("3 packets received"),
                         1,
                         "Ping to outside world from VM should be successful"
                         )

        return
    def test_19_template_tag(self):
        """ Test creation, listing and deletion tag on templates
        """

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

        try:

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

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

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

        timeout = self.services["timeout"]
        while True:
            list_volume = Volume.list(self.user_api_client,
                                      virtualmachineid=vm_1.id,
                                      type='ROOT',
                                      listall=True)
            if isinstance(list_volume, list):
                break
            elif timeout == 0:
                raise Exception("List volumes failed.")

            time.sleep(5)
            timeout = timeout - 1

        self.volume = list_volume[0]

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

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

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

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

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

        self.debug("Verifying if tag is actually deleted!")
        tags = Tag.list(self.user_api_client,
                        listall=True,
                        resourceType='Template',
                        key='OS',
                        value='windows8')
        self.assertEqual(tags, None, "List tags should return empty response")
        return
    def test_07_associate_public_ip(self):
        """Test associate public IP within the project
        """
        # Validate the following
        # 1. Create a project
        # 2. Add some public Ips to the project
        # 3. Verify public IP assigned can only used to create PF/LB rules
        #    inside project

        networks = Network.list(self.apiclient, projectid=self.project.id, listall=True)
        self.assertEqual(isinstance(networks, list), True, "Check list networks response returns a valid response")
        self.assertNotEqual(len(networks), 0, "Check list networks response returns a valid network")
        network = networks[0]
        self.debug("Associating public IP for project: %s" % self.project.id)
        public_ip = PublicIPAddress.create(
            self.apiclient,
            zoneid=self.virtual_machine.zoneid,
            services=self.services["server"],
            networkid=network.id,
            projectid=self.project.id,
        )
        self.cleanup.append(public_ip)

        # Create NAT rule
        self.debug("Creating a NAT rule within project, VM ID: %s" % self.virtual_machine.id)
        nat_rule = NATRule.create(
            self.apiclient,
            self.virtual_machine,
            self.services["natrule"],
            public_ip.ipaddress.id,
            projectid=self.project.id,
        )
        self.debug("created a NAT rule with ID: %s" % nat_rule.id)
        nat_rule_response = NATRule.list(self.apiclient, id=nat_rule.id)
        self.assertEqual(isinstance(nat_rule_response, list), True, "Check list response returns a valid list")
        self.assertNotEqual(len(nat_rule_response), 0, "Check Port Forwarding Rule is created")
        self.assertEqual(nat_rule_response[0].id, nat_rule.id, "Check Correct Port forwarding Rule is returned")

        # Create Load Balancer rule and assign VMs to rule
        self.debug("Created LB rule for public IP: %s" % public_ip.ipaddress)
        lb_rule = LoadBalancerRule.create(
            self.apiclient, self.services["lbrule"], public_ip.ipaddress.id, projectid=self.project.id
        )
        self.debug("Assigning VM: %s to LB rule: %s" % (self.virtual_machine.name, lb_rule.id))
        lb_rule.assign(self.apiclient, [self.virtual_machine])

        lb_rules = list_lb_rules(self.apiclient, id=lb_rule.id)
        self.assertEqual(isinstance(lb_rules, list), True, "Check list response returns a valid list")
        # verify listLoadBalancerRules lists the added load balancing rule
        self.assertNotEqual(len(lb_rules), 0, "Check Load Balancer Rule in its List")
        self.assertEqual(lb_rules[0].id, lb_rule.id, "Check List Load Balancer Rules returns valid Rule")

        # Create Firewall rule with configurations from settings file
        fw_rule = FireWallRule.create(
            self.apiclient,
            ipaddressid=public_ip.ipaddress.id,
            protocol="TCP",
            cidrlist=[self.services["fw_rule"]["cidr"]],
            startport=self.services["fw_rule"]["startport"],
            endport=self.services["fw_rule"]["endport"],
            projectid=self.project.id,
        )
        self.debug("Created firewall rule: %s" % fw_rule.id)

        # After Router start, FW rule should be in Active state
        fw_rules = FireWallRule.list(self.apiclient, id=fw_rule.id)
        self.assertEqual(isinstance(fw_rules, list), True, "Check for list FW rules response return valid data")

        self.assertEqual(fw_rules[0].state, "Active", "Check list load balancing rules")
        self.assertEqual(
            fw_rules[0].startport, str(self.services["fw_rule"]["startport"]), "Check start port of firewall rule"
        )

        self.assertEqual(
            fw_rules[0].endport, str(self.services["fw_rule"]["endport"]), "Check end port of firewall rule"
        )

        self.debug("Deploying VM for account: %s" % self.account.name)
        virtual_machine_1 = VirtualMachine.create(
            self.apiclient,
            self.services["server"],
            templateid=self.template.id,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
        )
        self.cleanup.append(virtual_machine_1)

        self.debug("VM state after deploy: %s" % virtual_machine_1.state)
        # Verify VM state
        self.assertEqual(virtual_machine_1.state, "Running", "Check VM state is Running or not")

        self.debug("Creating NAT rule for VM (ID: %s) outside project" % virtual_machine_1.id)
        with self.assertRaises(Exception):
            NATRule.create(self.apiclient, virtual_machine_1, self.services["natrule"], public_ip.ipaddress.id)

        self.debug("Creating LB rule for public IP: %s outside project" % public_ip.ipaddress)
        with self.assertRaises(Exception):
            LoadBalancerRule.create(
                self.apiclient, self.services["lbrule"], public_ip.ipaddress.id, accountid=self.account.name
            )
        return
Esempio n. 52
0
    def test_02_host_maintenance_mode_with_activities(self):
        """Test host maintenance mode with activities
        """

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        # Poll and check the status of VMs
        timeout = self.services["timeout"]
        while True:
            vms = VirtualMachine.list(self.apiclient,
                                      account=self.account.name,
                                      domainid=self.account.domainid,
                                      listall=True)
            self.assertEqual(
                isinstance(vms, list), True,
                "List VMs should return valid response for deployed VM")
            self.assertNotEqual(
                len(vms), 0,
                "List VMs should return valid response for deployed VM")
            vm = vms[0]
            self.debug(
                "VM state after enabling maintenance on first host: %s" %
                vm.state)
            if vm.state in [
                    "Stopping", "Stopped", "Running", "Starting", "Migrating"
            ]:
                if vm.state == "Running":
                    break
                else:
                    time.sleep(self.services["sleep"])
                    timeout = timeout - 1
            else:
                self.fail("VM migration from one-host-to-other failed\
                            while enabling maintenance")

        # Poll and check the status of VMs
        timeout = self.services["timeout"]
        while True:
            vms = VirtualMachine.list(self.apiclient,
                                      account=self.account.name,
                                      domainid=self.account.domainid,
                                      listall=True)
            self.assertEqual(
                isinstance(vms, list), True,
                "List VMs should return valid response for deployed VM")
            self.assertNotEqual(
                len(vms), 0,
                "List VMs should return valid response for deployed VM")
            vm = vms[1]
            self.debug(
                "VM state after enabling maintenance on first host: %s" %
                vm.state)
            if vm.state in [
                    "Stopping", "Stopped", "Running", "Starting", "Migrating"
            ]:
                if vm.state == "Running":
                    break
                else:
                    time.sleep(self.services["sleep"])
                    timeout = timeout - 1
            else:
                self.fail("VM migration from one-host-to-other failed\
                            while enabling maintenance")

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

        # Spawn an instance on other host
        virtual_machine_3 = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id)
        vms = VirtualMachine.list(self.apiclient,
                                  id=virtual_machine_3.id,
                                  listall=True)
        self.assertEqual(
            isinstance(vms, list), True,
            "List VMs should return valid response for deployed VM")
        self.assertNotEqual(
            len(vms), 0,
            "List VMs should return valid response for deployed VM")
        vm = vms[0]

        self.debug("Deployed VM on host: %s" % vm.hostid)
        self.debug("VM 3 state: %s" % vm.state)
        self.assertEqual(vm.state, "Running",
                         "Deployed VM should be in Running state")

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

        self.debug("Waiting for SSVMs to come up")
        wait_for_ssvms(
            self.apiclient,
            zoneid=self.zone.id,
            podid=self.pod.id,
        )
        return
    def test_downgradeRvR_to_VR(self):
        """Test downgrade redundant virtual router to virtual router
        """

        # Steps to validate
        # 1. create a network Offering that has redundant router enabled and
        #    all VR based services
        # 2. create a network with above offering
        # 3. deploy a VM in the above network and listRouters
        # 4. create a network Offering that has redundant router disabled and
        #    all VR based services
        # 5. updateNetwork - downgrade - created above to the offfering in 4.
        # 6. listRouters in the network
        # 7. delete account in which resources are created
        # Validate the following
        # 1. listNetworkOfferings should show craeted offering for RvR
        # 2. listNetworks should show the created network in allocated state
        # 3. VM should be deployed and in Running state and there should be
        #    two routers (MASTER and BACKUP) for this network
        # 4. listNetworkOfferings should show craeted offering for VR
        # 5. listNetworks shows the network still successfully implemented
        # 6. listRouters shows only one router for this network in Running

        # 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("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 the account: %s" %
                   self.account.name)

        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 account: %s" %
                   self.account.name)
        routers = Router.list(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
            listall=True
        )
        self.assertEqual(
            isinstance(routers, list),
            True,
            "list router should return two routers"
        )
        self.assertEqual(
            len(routers),
            2,
            "Length of the list router should be 2 (MASTER & BACKUP)"
        )

        network_offerings = NetworkOffering.list(
            self.apiclient,
            name='DefaultIsolatedNetworkOfferingWithSourceNatService',
            listall=True
        )
        self.assertEqual(
            isinstance(network_offerings, list),
            True,
            "List network offering should not return empty response"
        )

        network_off_vr = network_offerings[0]

        self.debug("Upgrading the network to RVR network offering..")
        try:
            network.update(
                self.apiclient,
                networkofferingid=network_off_vr.id
            )
        except Exception as e:
            self.fail("Failed to upgrade the network from VR to RVR: %s" % e)

        self.debug("Listing routers for account: %s" %
                   self.account.name)
        routers = Router.list(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
            listall=True
        )
        self.assertEqual(
            isinstance(routers, list),
            True,
            "list router should return only one router"
        )
        self.assertEqual(
            len(routers),
            1,
            "Length of the list router should be 1"
        )
        return