Exemplo n.º 1
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
Exemplo n.º 2
0
 def validate_PublicIPAddress(self, public_ip, network, static_nat=False,
                              vm=None):
     """Validates the Public IP Address"""
     self.debug("Validating the assignment and state of public IP address "
                "- %s" % public_ip.ipaddress.ipaddress)
     public_ips = PublicIPAddress.list(self.api_client,
                                       id=public_ip.ipaddress.id,
                                       networkid=network.id,
                                       isstaticnat=static_nat,
                                       listall=True
                                       )
     self.assertEqual(isinstance(public_ips, list), True,
                      "List public IP for network should return a "
                      "valid list"
                      )
     self.assertEqual(public_ips[0].ipaddress,
                      public_ip.ipaddress.ipaddress,
                      "List public IP for network should list the assigned "
                      "public IP address"
                      )
     self.assertEqual(public_ips[0].state, "Allocated",
                      "Assigned public IP is not in the allocated state"
                      )
     if static_nat and vm:
         self.assertEqual(public_ips[0].virtualmachineid, vm.id,
                          "Static NAT rule is not enabled for the VM on "
                          "the assigned public IP"
                          )
     self.debug("Successfully validated the assignment and state of public "
                "IP address - %s" % public_ip.ipaddress.ipaddress)
Exemplo n.º 3
0
def isIpInDesiredState(apiclient, ipaddressid, state):
    """ Check if the given IP is in the correct state (given)
    and return True/False accordingly"""
    retriesCount = 10
    ipInDesiredState = False
    exceptionOccured = False
    exceptionMessage = ""
    try:
        while retriesCount >= 0:
            portableips = PublicIPAddress.list(apiclient, id=ipaddressid)
            assert validateList(
                portableips)[0] == PASS, "IPs list validation failed"
            if str(portableips[0].state).lower() == state:
                ipInDesiredState = True
                break
            retriesCount -= 1
            time.sleep(60)
    except Exception as e:
        exceptionOccured = True
        exceptionMessage = e
        return [exceptionOccured, ipInDesiredState, e]
    if not ipInDesiredState:
        exceptionMessage = "Ip should be in %s state, it is in %s" %\
                            (state, portableips[0].state)
    return [False, ipInDesiredState, exceptionMessage]
Exemplo n.º 4
0
    def acquire_Public_Ip(self):
        """Acquires the public IP"""

        try:
            self.debug("Acquiring public IP for account: %s" %
                                                    self.account.name)
            public_ip = PublicIPAddress.create(
                                           self.apiclient,
                                           self.virtual_machine.account,
                                           self.virtual_machine.zoneid,
                                           self.virtual_machine.domainid,
                                           self.services["virtual_machine"]
                                           )
            self.debug("Acquired public IP: %s" %
                                                public_ip.ipaddress.ipaddress)

            self.debug("Configuring NAT rule for the acquired public ip")

            NATRule.create(
                        self.apiclient,
                        self.virtual_machine,
                        self.services["natrule"],
                        ipaddressid=public_ip.ipaddress.id
                        )

            return public_ip
        except Exception as e:
            self.fail("Failed to acquire new public IP: %s" % e)
Exemplo n.º 5
0
def createNetworkRulesForVM(apiclient, virtualmachine, ruletype,
                            account, networkruledata):
    """Acquire IP, create Firewall and NAT/StaticNAT rule
        (associating it with given vm) for that IP"""

    try:
        public_ip = PublicIPAddress.create(
                apiclient,accountid=account.name,
                zoneid=virtualmachine.zoneid,domainid=account.domainid,
                networkid=virtualmachine.nic[0].networkid)

        FireWallRule.create(
            apiclient,ipaddressid=public_ip.ipaddress.id,
            protocol='TCP', cidrlist=[networkruledata["fwrule"]["cidr"]],
            startport=networkruledata["fwrule"]["startport"],
            endport=networkruledata["fwrule"]["endport"]
            )

        if ruletype == NAT_RULE:
            # Create NAT rule
            NATRule.create(apiclient, virtualmachine,
                                 networkruledata["natrule"],ipaddressid=public_ip.ipaddress.id,
                                 networkid=virtualmachine.nic[0].networkid)
        elif ruletype == STATIC_NAT_RULE:
            # Enable Static NAT for VM
            StaticNATRule.enable(apiclient,public_ip.ipaddress.id,
                                     virtualmachine.id, networkid=virtualmachine.nic[0].networkid)
    except Exception as e:
        [FAIL, e]
    return [PASS, public_ip]
Exemplo n.º 6
0
 def setUp(self):
     try:
         self.apiclient = self.testClient.getApiClient()
         self.dbclient = self.testClient.getDbConnection()
         self.account = Account.create(
                             self.apiclient,
                             self.services["account"],
                             domainid=self.domain.id
                             )
         self.cleanup = [
                         self.account,
                         ]
         self.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
                                 )
         self.public_ip = PublicIPAddress.create(
                                            self.apiclient,
                                            accountid=self.virtual_machine.account,
                                            zoneid=self.virtual_machine.zoneid,
                                            domainid=self.virtual_machine.domainid,
                                            services=self.services["virtual_machine"]
                                            )
         return
     except CloudstackAPIException as e:
             self.tearDown()
             raise e
Exemplo n.º 7
0
    def acquire_Public_Ip(self):
        """Acquires the public IP"""

        try:
            self.debug("Acquiring public IP for account: %s" %
                       self.account.name)
            public_ip = PublicIPAddress.create(
                self.apiclient,
                self.virtual_machine.account,
                self.virtual_machine.zoneid,
                self.virtual_machine.domainid,
                self.services["virtual_machine"]
            )
            self.debug("Acquired public IP: %s" %
                       public_ip.ipaddress.ipaddress)

            FireWallRule.create(
                self.apiclient,
                ipaddressid=public_ip.ipaddress.id,
                protocol='TCP',
                cidrlist=[self.services["fwrule"]["cidr"]],
                startport=self.services["fwrule"]["startport"],
                endport=self.services["fwrule"]["endport"]
            )
            return public_ip
        except Exception as e:
            self.fail("Failed to acquire new public IP: %s" % e)
Exemplo n.º 8
0
    def setUp(self):
        self.apiclient = self.testClient.getApiClient()
        self.dbclient = self.testClient.getDbConnection()
        self.account = Account.create(self.apiclient, self.services["account"], domainid=self.domain.id)
        self.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,
        )

        self.virtual_machine_2 = 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,
        )
        self.public_ip = PublicIPAddress.create(
            self.apiclient,
            self.virtual_machine.account,
            self.virtual_machine.zoneid,
            self.virtual_machine.domainid,
            self.services["virtual_machine"],
        )

        NATRule.create(
            self.apiclient, self.virtual_machine, self.services["natrule"], ipaddressid=self.public_ip.ipaddress.id
        )

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

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

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

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

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

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

        self.debug("Creating NAT rule for VM ID: %s" % self.virtual_machine.id)
        # Create NAT rule
        NATRule.create(self.apiclient, self.virtual_machine, self.services["natrule"], self.public_ip.ipaddress.id)
        return
Exemplo n.º 10
0
 def acquire_publicip(self, network):
     self.logger.debug('Associating public IP for network: %s' % network.name)
     public_ip = PublicIPAddress.create(
         self.api_client,
         accountid='admin',
         zoneid=self.zone.id,
         domainid=self.domain.id,
         networkids=[str(network.id)]
     )
     self.logger.debug('Associated %s with network %s' % (public_ip.ipaddress.ipaddress, network.id))
     self.test_cleanup.append(public_ip)
     return public_ip
Exemplo n.º 11
0
 def acquire_PublicIPAddress(self, network, vpc=None):
     self.debug("Associating public IP for network with ID - %s" % network.id)
     public_ip = PublicIPAddress.create(self.api_client,
                                        accountid=self.account.name,
                                        zoneid=self.zone.id,
                                        domainid=self.account.domainid,
                                        networkid=network.id if vpc is None else None,
                                        vpcid=vpc.id if vpc else self.vpc.id if hasattr(self, "vpc") else None
                                        )
     self.debug("Associated public IP address - %s with network with ID - %s" %
                (public_ip.ipaddress.ipaddress, network.id))
     return public_ip
    def deploy_isolatednetwork_publicipaddress(self, ipaddress_data, virtualmachines_data, network):
        self.logger.debug('>>>  ISOLATED NETWORK PUBLIC IP ADDRESS  =>  Creating...')
        publicipaddress = PublicIPAddress.create(
            api_client=self.api_client,
            data=ipaddress_data,
            network=network
        )

        self.logger.debug('>>>  ISOLATED NETWORK PUBLIC IP ADDRESS  =>  Created!  TODO:  MISSING FIELDS!')

        self.deploy_firewallrules(ipaddress_data, publicipaddress)
        self.deploy_portforwards(ipaddress_data['portforwards'], virtualmachines_data, None, publicipaddress)
Exemplo n.º 13
0
    def test_public_ip_admin_account(self):
        """Test for Associate/Disassociate public IP address for admin account"""

        # Validate the following:
        # 1. listPubliIpAddresses API returns the list of acquired addresses
        # 2. the returned list should contain our acquired IP address

        ip_address = PublicIPAddress.create(
            self.apiclient,
            self.account.name,
            self.zone.id,
            self.account.domainid
        )
        list_pub_ip_addr_resp = list_publicIP(
            self.apiclient,
            id=ip_address.ipaddress.id
        )
        self.assertEqual(
            isinstance(list_pub_ip_addr_resp, list),
            True,
            "Check list response returns a valid list"
        )
        # listPublicIpAddresses should return newly created public IP
        self.assertNotEqual(
            len(list_pub_ip_addr_resp),
            0,
            "Check if new IP Address is associated"
        )
        self.assertEqual(
            list_pub_ip_addr_resp[0].id,
            ip_address.ipaddress.id,
            "Check Correct IP Address is returned in the List Cacls"
        )

        ip_address.delete(self.apiclient)
        time.sleep(30)

        # Validate the following:
        # 1.listPublicIpAddresses should no more return the released address
        list_pub_ip_addr_resp = list_publicIP(
            self.apiclient,
            id=ip_address.ipaddress.id
        )
        if list_pub_ip_addr_resp is None:
            return
        if (list_pub_ip_addr_resp) and (
            isinstance(
                list_pub_ip_addr_resp,
                list)) and (
                len(list_pub_ip_addr_resp) > 0):
            self.fail("list public ip response is not empty")
        return
 def get_free_ipaddress(self, vlanId):
     ipaddresses = PublicIPAddress.list(
         self.apiclient,
         vlanid=vlanId,
         state='Free'
     )
     self.assertEqual(
         isinstance(ipaddresses, list),
         True,
         "List ipaddresses should return a valid response for Free ipaddresses"
          )
     random.shuffle(ipaddresses)
     return ipaddresses[0].ipaddress
Exemplo n.º 15
0
 def acquire_Public_IP(self, network):
     self.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=None,  #network.id,
         vpcid=self.vpc.id)
     self.cleanup.append(public_ip)
     self.debug("Associated %s with network %s" %
                (public_ip.ipaddress.ipaddress, network.id))
     return public_ip
 def acquire_publicip(self, network):
     self.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,
                                     vpcid=self.vpc.id
                                     )
     self.debug("Associated %s with network %s" % (public_ip.ipaddress.ipaddress,
                                                 network.id
                                                 ))
     return public_ip
Exemplo n.º 17
0
 def acquire_publicip(self, vpc, network):
     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,
                                        vpcid=vpc.id)
     self.assertIsNotNone(public_ip, "Failed to acquire public IP")
     self.logger.debug("Associated %s with network %s" %
                       (public_ip.ipaddress.ipaddress, network.id))
     return public_ip
Exemplo n.º 18
0
 def acquire_Public_IP(self, network, vpc=None):
     self.debug("Associating public IP for network: %s" % network.name)
     public_ip = PublicIPAddress.create(
         self.api_client,
         accountid=self.account.name,
         zoneid=self.zone.id,
         domainid=self.account.domainid,
         networkid=network.id if vpc is None else None,
         vpcid=vpc.id
         if vpc else self.vpc.id if hasattr(self, "vpc") else None)
     self.debug("Associated %s with network %s" %
                (public_ip.ipaddress.ipaddress, network.id))
     return public_ip
Exemplo n.º 19
0
 def acquire_publicip(self, vpc, network):
     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,
         vpcid=vpc.id,
     )
     self.assertIsNotNone(public_ip, "Failed to acquire public IP")
     self.logger.debug("Associated %s with network %s" % (public_ip.ipaddress.ipaddress, network.id))
     return public_ip
    def acquire_publicip(self, network, vpc_id):
        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,
                                           vpcid=vpc_id)
        self.logger.debug("Associated %s with network %s" %
                          (public_ip.ipaddress.ipaddress, network.id))

        self.ips.append(public_ip)
        return public_ip
Exemplo n.º 21
0
    def deploy_isolatednetwork_publicipaddress(self, ipaddress_data,
                                               virtualmachines_data, network):
        self.logger.debug(
            '>>>  ISOLATED NETWORK PUBLIC IP ADDRESS  =>  Creating...')
        publicipaddress = PublicIPAddress.create(api_client=self.api_client,
                                                 data=ipaddress_data,
                                                 network=network)

        self.logger.debug(
            '>>>  ISOLATED NETWORK PUBLIC IP ADDRESS  =>  Created!  TODO:  MISSING FIELDS!'
        )

        self.deploy_firewallrules(ipaddress_data, publicipaddress)
        self.deploy_portforwards(ipaddress_data['portforwards'],
                                 virtualmachines_data, None, publicipaddress)
Exemplo n.º 22
0
    def setUpClass(cls):

        cls.testClient = super(TestNATRules, cls).getClsTestClient()
        cls.api_client = cls.testClient.getApiClient()

        cls.services = Services().services
        # Get Zone, Domain and templates
        cls.domain = get_domain(cls.api_client)
        cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())

        cls.services['mode'] = cls.zone.networktype
        template = get_template(
                            cls.api_client,
                            cls.zone.id,
                            cls.services["ostype"]
                            )
        #Create an account, network, VM and IP addresses
        cls.account = Account.create(
                                cls.api_client,
                                cls.services["account"],
                                admin=True,
                                domainid=cls.domain.id
                                )
        cls.services["virtual_machine"]["zoneid"] = cls.zone.id
        cls.service_offering = ServiceOffering.create(
                                cls.api_client,
                                cls.services["service_offering"]
                                )
        cls.virtual_machine = VirtualMachine.create(
                                    cls.api_client,
                                    cls.services["virtual_machine"],
                                    templateid=template.id,
                                    accountid=cls.account.name,
                                    domainid=cls.account.domainid,
                                    serviceofferingid=cls.service_offering.id
                                )
        cls.public_ip = PublicIPAddress.create(
                                    cls.api_client,
                                    accountid=cls.account.name,
                                    zoneid=cls.zone.id,
                                    domainid=cls.account.domainid,
                                    services=cls.services["virtual_machine"]
                                    )
        cls._cleanup = [
                        cls.virtual_machine,
                        cls.account,
                        cls.service_offering
                        ]
    def setUpClass(cls):

        cls.testClient = super(TestNATRules, cls).getClsTestClient()
        cls.api_client = cls.testClient.getApiClient()

        cls.services = Services().services
        # Get Zone, Domain and templates
        cls.domain = get_domain(cls.api_client)
        cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())

        cls.services['mode'] = cls.zone.networktype
        template = get_template(
                            cls.api_client,
                            cls.zone.id,
                            cls.services["ostype"]
                            )
        #Create an account, network, VM and IP addresses
        cls.account = Account.create(
                                cls.api_client,
                                cls.services["account"],
                                admin=True,
                                domainid=cls.domain.id
                                )
        cls.services["virtual_machine"]["zoneid"] = cls.zone.id
        cls.service_offering = ServiceOffering.create(
                                cls.api_client,
                                cls.services["service_offering"]
                                )
        cls.virtual_machine = VirtualMachine.create(
                                    cls.api_client,
                                    cls.services["virtual_machine"],
                                    templateid=template.id,
                                    accountid=cls.account.name,
                                    domainid=cls.account.domainid,
                                    serviceofferingid=cls.service_offering.id
                                )
        cls.public_ip = PublicIPAddress.create(
                                    cls.api_client,
                                    accountid=cls.account.name,
                                    zoneid=cls.zone.id,
                                    domainid=cls.account.domainid,
                                    services=cls.services["virtual_machine"]
                                    )
        cls._cleanup = [
                        cls.virtual_machine,
                        cls.account,
                        cls.service_offering
                        ]
Exemplo n.º 24
0
    def test_public_ip_user_account(self):
        """Test for Associate/Disassociate public IP address for user account"""

        # Validate the following:
        # 1. listPubliIpAddresses API returns the list of acquired addresses
        # 2. the returned list should contain our acquired IP address

        ip_address = PublicIPAddress.create(
            self.apiclient,
            self.user.name,
            self.zone.id,
            self.user.domainid
        )

        # listPublicIpAddresses should return newly created public IP
        list_pub_ip_addr_resp = list_publicIP(
            self.apiclient,
            id=ip_address.ipaddress.id
        )
        self.assertEqual(
            isinstance(list_pub_ip_addr_resp, list),
            True,
            "Check list response returns a valid list"
        )
        self.assertNotEqual(
            len(list_pub_ip_addr_resp),
            0,
            "Check if new IP Address is associated"
        )
        self.assertEqual(
            list_pub_ip_addr_resp[0].id,
            ip_address.ipaddress.id,
            "Check Correct IP Address is returned in the List Call"
        )

        ip_address.delete(self.apiclient)

        list_pub_ip_addr_resp = list_publicIP(
            self.apiclient,
            id=ip_address.ipaddress.id
        )

        self.assertEqual(
            list_pub_ip_addr_resp,
            None,
            "Check if disassociated IP Address is no longer available"
        )
        return
Exemplo n.º 25
0
    def test_public_ip_user_account(self):
        """Test for Associate/Disassociate public IP address for user account"""

        # Validate the following:
        # 1. listPubliIpAddresses API returns the list of acquired addresses
        # 2. the returned list should contain our acquired IP address

        ip_address = PublicIPAddress.create(
            self.apiclient,
            self.user.name,
            self.zone.id,
            self.user.domainid
        )

        # listPublicIpAddresses should return newly created public IP
        list_pub_ip_addr_resp = list_publicIP(
            self.apiclient,
            id=ip_address.ipaddress.id
        )
        self.assertEqual(
            isinstance(list_pub_ip_addr_resp, list),
            True,
            "Check list response returns a valid list"
        )
        self.assertNotEqual(
            len(list_pub_ip_addr_resp),
            0,
            "Check if new IP Address is associated"
        )
        self.assertEqual(
            list_pub_ip_addr_resp[0].id,
            ip_address.ipaddress.id,
            "Check Correct IP Address is returned in the List Call"
        )

        ip_address.delete(self.apiclient)

        list_pub_ip_addr_resp = list_publicIP(
            self.apiclient,
            id=ip_address.ipaddress.id
        )

        self.assertEqual(
            list_pub_ip_addr_resp,
            None,
            "Check if disassociated IP Address is no longer available"
        )
        return
    def deploy_publicipaddress(self, publicipaddress_data, virtualmachines_data, vpc):
        self.logger.debug('>>>  PUBLIC IP ADDRESS  =>  Creating...')
        publicipaddress = PublicIPAddress.create(
            api_client=self.api_client,
            data=publicipaddress_data,
            vpc=vpc
        )

        ipaddress = publicipaddress.ipaddress
        self.logger.debug('>>>  PUBLIC IP ADDRESS  =>  ID: %s  =>  IP: %s  =>  State: %s  =>  Source NAT: %s  '
                          '=>  Static NAT: %s  =>  ACL: %s  =>  VLAN: %s  =>  Physical Network: %s  =>  Network: %s  '
                          '=>  VPC: %s  =>  Domain: %s', ipaddress.id, ipaddress.ipaddress, ipaddress.state,
                          ipaddress.issourcenat, ipaddress.isstaticnat, ipaddress.aclid, ipaddress.vlanid,
                          ipaddress.physicalnetworkid, ipaddress.networkid, ipaddress.vpcid, ipaddress.domainid)

        self.deploy_portforwards(publicipaddress_data['portforwards'], virtualmachines_data, vpc, publicipaddress)
Exemplo n.º 27
0
    def deploy_publicipaddress(self, publicipaddress_data,
                               virtualmachines_data, vpc):
        self.logger.debug('>>>  PUBLIC IP ADDRESS  =>  Creating...')
        publicipaddress = PublicIPAddress.create(api_client=self.api_client,
                                                 data=publicipaddress_data,
                                                 vpc=vpc)

        ipaddress = publicipaddress.ipaddress
        self.logger.debug(
            '>>>  PUBLIC IP ADDRESS  =>  ID: %s  =>  IP: %s  =>  State: %s  =>  Source NAT: %s  '
            '=>  Static NAT: %s  =>  ACL: %s  =>  VLAN: %s  =>  Physical Network: %s  =>  Network: %s  '
            '=>  VPC: %s  =>  Domain: %s', ipaddress.id, ipaddress.ipaddress,
            ipaddress.state, ipaddress.issourcenat, ipaddress.isstaticnat,
            ipaddress.aclid, ipaddress.vlanid, ipaddress.physicalnetworkid,
            ipaddress.networkid, ipaddress.vpcid, ipaddress.domainid)

        self.deploy_portforwards(publicipaddress_data['portforwards'],
                                 virtualmachines_data, vpc, publicipaddress)
Exemplo n.º 28
0
 def acquire_PublicIPAddress(self, network, vpc=None, account=None):
     if not account:
         account = self.account
     self.debug(
         "Associating public IP for network with ID - %s in the account - %s"
         % (network.id, account.name))
     public_ip = PublicIPAddress.create(
         self.api_client,
         accountid=account.name,
         domainid=account.domainid,
         zoneid=self.zone.id,
         networkid=network.id if vpc is None else None,
         vpcid=vpc.id
         if vpc else self.vpc.id if hasattr(self, "vpc") else None)
     self.debug(
         "Associated public IP address - %s with network with ID - %s" %
         (public_ip.ipaddress.ipaddress, network.id))
     return public_ip
Exemplo n.º 29
0
    def setUp(self):
        self.apiclient = self.testClient.getApiClient()
        self.dbclient = self.testClient.getDbConnection()
        self.account = Account.create(
            self.apiclient,
            self.services["account"],
            domainid=self.domain.id
        )
        self.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
        )

        self.virtual_machine_2 = 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
        )
        self.public_ip = PublicIPAddress.create(
            self.apiclient,
            self.virtual_machine.account,
            self.virtual_machine.zoneid,
            self.virtual_machine.domainid,
            self.services["virtual_machine"]
        )
        FireWallRule.create(
            self.apiclient,
            ipaddressid=self.public_ip.ipaddress.id,
            protocol='TCP',
            cidrlist=[self.services["fwrule"]["cidr"]],
            startport=self.services["fwrule"]["startport"],
            endport=self.services["fwrule"]["endport"]
        )
        self.cleanup = [self.account, ]
        return
Exemplo n.º 30
0
    def setUp(self):
        self.apiclient = self.testClient.getApiClient()
        self.dbclient = self.testClient.getDbConnection()
        self.account = Account.create(
                            self.apiclient,
                            self.services["account"],
                            domainid=self.domain.id
                            )
        self.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
                                )

        self.virtual_machine_2 = 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
                                )
        self.public_ip = PublicIPAddress.create(
                                           self.apiclient,
                                           self.virtual_machine.account,
                                           self.virtual_machine.zoneid,
                                           self.virtual_machine.domainid,
                                           self.services["virtual_machine"]
                                           )

        NATRule.create(
                        self.apiclient,
                        self.virtual_machine,
                        self.services["natrule"],
                        ipaddressid=self.public_ip.ipaddress.id
                        )

        self.cleanup = [self.account, ]
        return
Exemplo n.º 31
0
    def validate_network_rules(self):
        """ Validate network rules
        """
        vms = VirtualMachine.list(
            self.api_client,
            account=self.account.name,
            domainid=self.account.domainid,
            listall=True
        )
        public_ips = PublicIPAddress.list(
            self.api_client,
            account=self.account.name,
            domainid=self.account.domainid,
            listall=True
        )
        for vm, public_ip in zip(vms, public_ips):
            try:
                ssh_1 = vm.get_ssh_client(
                    ipaddress=public_ip.ipaddress.ipaddress)
                self.debug("SSH into VM is successfully")

                self.debug(
                    "Verifying if we can ping to outside world from VM?")
                # Ping to outsite world
                res = ssh_1.execute("ping -c 1 www.google.com")
                # res = 64 bytes from maa03s17-in-f20.1e100.net (74.125.236.212):
                # icmp_req=1 ttl=57 time=25.9 ms
                # --- www.l.google.com ping statistics ---
                # 1 packets transmitted, 1 received, 0% packet loss, time 0ms
                # rtt min/avg/max/mdev = 25.970/25.970/25.970/0.000 ms
            except Exception as e:
                self.fail("Failed to SSH into VM - %s, %s" %
                          (public_ip.ipaddress.ipaddress, e))

            result = str(res)
            self.assertEqual(
                result.count("1 received"),
                1,
                "Ping to outside world from VM should be successful"
            )
Exemplo n.º 32
0
    def acquire_Public_Ip(self):
        """Acquires the public IP"""

        try:
            self.debug("Acquiring public IP for account: %s" %
                       self.account.name)
            public_ip = PublicIPAddress.create(
                self.apiclient, self.virtual_machine.account,
                self.virtual_machine.zoneid, self.virtual_machine.domainid,
                self.services["virtual_machine"])
            self.debug("Acquired public IP: %s" %
                       public_ip.ipaddress.ipaddress)

            FireWallRule.create(self.apiclient,
                                ipaddressid=public_ip.ipaddress.id,
                                protocol='TCP',
                                cidrlist=[self.services["fwrule"]["cidr"]],
                                startport=self.services["fwrule"]["startport"],
                                endport=self.services["fwrule"]["endport"])
            return public_ip
        except Exception as e:
            self.fail("Failed to acquire new public IP: %s" % e)
Exemplo n.º 33
0
    def acquire_Public_Ip(self):
        """Acquires the public IP"""

        try:
            self.debug("Acquiring public IP for account: %s" %
                       self.account.name)
            public_ip = PublicIPAddress.create(
                self.apiclient, self.virtual_machine.account,
                self.virtual_machine.zoneid, self.virtual_machine.domainid,
                self.services["virtual_machine"])
            self.debug("Acquired public IP: %s" %
                       public_ip.ipaddress.ipaddress)

            self.debug("Configuring NAT rule for the acquired public ip")

            NATRule.create(self.apiclient,
                           self.virtual_machine,
                           self.services["natrule"],
                           ipaddressid=public_ip.ipaddress.id)

            return public_ip
        except Exception as e:
            self.fail("Failed to acquire new public IP: %s" % e)
Exemplo n.º 34
0
 def validate_PublicIPAddress(self, public_ip, network, static_nat=False, vm=None):
     """Validates the Public IP Address"""
     self.debug("Check if the public IP is successfully assigned to the network ?")
     public_ips = PublicIPAddress.list(self.api_client,
                                       id=public_ip.ipaddress.id,
                                       networkid=network.id,
                                       isstaticnat=static_nat,
                                       listall=True
                                       )
     self.assertEqual(isinstance(public_ips, list), True,
                      "List public IP for network should return a valid list"
                      )
     self.assertEqual(public_ips[0].ipaddress, public_ip.ipaddress.ipaddress,
                      "List public IP for network should list the assigned public IP address"
                      )
     self.assertEqual(public_ips[0].state, "Allocated",
                      "Assigned public IP is not in the allocated state"
                      )
     if static_nat and vm:
         self.assertEqual(public_ips[0].virtualmachineid, vm.id,
                          "Static NAT Rule not enabled for the VM using the assigned public IP"
                          )
     self.debug("Assigned Public IP address - %s is successfully validated" % public_ip.ipaddress.ipaddress)
Exemplo n.º 35
0
 def validate_Public_IP(self, public_ip, network, static_nat=False, vm=None):
     """Validates the Public IP"""
     self.debug("Check if the Public IP is successfully assigned to the network ?")
     public_ips = PublicIPAddress.list(self.api_client,
                                       id=public_ip.ipaddress.id,
                                       networkid=network.id,
                                       isstaticnat=static_nat,
                                       listall=True
                                       )
     self.assertEqual(isinstance(public_ips, list), True,
                      "List public Ip for network should return a valid list"
                      )
     self.assertEqual(public_ips[0].ipaddress, public_ip.ipaddress.ipaddress,
                      "List public Ip for network should list the assigned public Ip address"
                      )
     self.assertEqual(public_ips[0].state, "Allocated",
                      "Assigned public Ip is not in the allocated state"
                      )
     if static_nat and vm:
         self.assertEqual(public_ips[0].virtualmachineid, vm.id,
                          "Static NAT Rule not enabled for the VM using the assigned public Ip"
                          )
     self.debug("Assigned Public IP is successfully validated - %s" % public_ip.ipaddress.ipaddress)
Exemplo n.º 36
0
def createNetworkRulesForVM(apiclient, virtualmachine, ruletype, account,
                            networkruledata):
    """Acquire IP, create Firewall and NAT/StaticNAT rule
        (associating it with given vm) for that IP"""

    try:
        public_ip = PublicIPAddress.create(
            apiclient,
            accountid=account.name,
            zoneid=virtualmachine.zoneid,
            domainid=account.domainid,
            networkid=virtualmachine.nic[0].networkid)

        FireWallRule.create(apiclient,
                            ipaddressid=public_ip.ipaddress.id,
                            protocol='TCP',
                            cidrlist=[networkruledata["fwrule"]["cidr"]],
                            startport=networkruledata["fwrule"]["startport"],
                            endport=networkruledata["fwrule"]["endport"])

        if ruletype == NAT_RULE:
            # Create NAT rule
            NATRule.create(apiclient,
                           virtualmachine,
                           networkruledata["natrule"],
                           ipaddressid=public_ip.ipaddress.id,
                           networkid=virtualmachine.nic[0].networkid)
        elif ruletype == STATIC_NAT_RULE:
            # Enable Static NAT for VM
            StaticNATRule.enable(apiclient,
                                 public_ip.ipaddress.id,
                                 virtualmachine.id,
                                 networkid=virtualmachine.nic[0].networkid)
    except Exception as e:
        [FAIL, e]
    return [PASS, public_ip]
Exemplo n.º 37
0
    def _test_vpc_site2site_vpn(self, vpc_offering, num_VPCs=3):
        # Number of VPNs (to test) is number_of_VPCs - 1
        # By default test setting up 2 VPNs from VPC0, requiring total of 3 VPCs

        maxnumVM = num_VPCs - 1
        # Create VPC i
        vpc_list = []
        for i in range(num_VPCs):
            # Generate VPC (mostly subnet) info
            vpcservice_n = copy.deepcopy(self.services["vpcN"])
            for key in vpcservice_n.keys():
                vpcservice_n[key] = vpcservice_n[key].format(N=` i `)

            vpc_n = VPC.create(apiclient=self.apiclient,
                               services=vpcservice_n,
                               networkDomain="vpc%d.vpn" % i,
                               vpcofferingid=vpc_offering.id,
                               zoneid=self.zone.id,
                               account=self.account.name,
                               domainid=self.domain.id)
            self.assertIsNotNone(vpc_n, "VPC%d creation failed" % i)
            vpc_list.append(vpc_n)
            self.cleanup.append(vpc_n)
            self.logger.debug("VPC%d %s created" % (i, vpc_list[i].id))

        default_acl = NetworkACLList.list(self.apiclient,
                                          name="default_allow")[0]

        # Create network in VPC i
        ntwk_list = []
        for i in range(num_VPCs):
            # Generate network (mostly subnet) info
            ntwk_info_n = copy.deepcopy(self.services["network_N"])
            for key in ntwk_info_n.keys():
                ntwk_info_n[key] = ntwk_info_n[key].format(N=` i `)

            ntwk_n = Network.create(
                apiclient=self.apiclient,
                services=ntwk_info_n,
                accountid=self.account.name,
                domainid=self.account.domainid,
                networkofferingid=self.network_offerings[0].id,
                zoneid=self.zone.id,
                vpcid=vpc_list[i].id,
                aclid=default_acl.id)
            self.assertIsNotNone(ntwk_n, "Network%d failed to create" % i)
            self.cleanup.append(ntwk_n)
            ntwk_list.append(ntwk_n)
            self.logger.debug("Network%d %s created in VPC %s" %
                              (i, ntwk_list[i].id, vpc_list[i].id))

        # Deploy a vm in network i
        vm_list = []
        vm_n = None

        for i in range(num_VPCs):
            vm_n = VirtualMachine.create(
                self.apiclient,
                services=self.services["virtual_machine"],
                templateid=self.template.id,
                zoneid=self.zone.id,
                accountid=self.account.name,
                domainid=self.account.domainid,
                serviceofferingid=self.compute_offering.id,
                networkids=[ntwk_list[i].id],
                hypervisor=self.hypervisor,
                mode='advanced' if (i == 0) or (i == maxnumVM) else 'default')
            self.assertIsNotNone(vm_n, "VM%d failed to deploy" % i)
            self.cleanup.append(vm_n)
            vm_list.append(vm_n)
            self.logger.debug("VM%d %s deployed in VPC %s" %
                              (i, vm_list[i].id, vpc_list[i].id))
            self.assertEquals(vm_n.state, 'Running', "VM%d is not running" % i)

        # 4) Enable Site-to-Site VPN for VPC
        vpn_response_list = []
        for i in range(num_VPCs):
            vpn_response = Vpn.createVpnGateway(self.apiclient, vpc_list[i].id)
            self.assertIsNotNone(vpn_response,
                                 "Failed to enable VPN Gateway %d" % i)
            vpn_response_list.append(vpn_response)
            self.logger.debug("VPN gateway for VPC%d %s enabled" %
                              (i, vpc_list[i].id))

        # 5) Add VPN Customer gateway info
        vpn_cust_gw_list = []
        services = self.services["vpncustomergateway"]
        for i in range(num_VPCs):
            src_nat_list = PublicIPAddress.list(self.apiclient,
                                                account=self.account.name,
                                                domainid=self.account.domainid,
                                                listall=True,
                                                issourcenat=True,
                                                vpcid=vpc_list[i].id)
            ip = src_nat_list[0]

            customer_response = VpnCustomerGateway.create(
                self.apiclient, services, "Peer VPC" + ` i `, ip.ipaddress,
                vpc_list[i].cidr, self.account.name, self.domain.id)
            self.cleanup.insert(
                0, customer_response
            )  # this has to be cleaned up after the VPCs have been destroyed (due to client connectionsonections)
            vpn_cust_gw_list.append(customer_response)
            self.logger.debug(
                "VPN customer gateway added for VPC%d %s enabled" %
                (i, vpc_list[i].id))

        # Before the next step ensure the last VPC is up and running
        # Routers in the right state?
        self.assertEqual(
            self.routers_in_right_state(vpcid=vpc_list[maxnumVM].id), True,
            "Check whether the routers are in the right state.")

        # 6) Connect VPCi with VPC0
        for i in range(num_VPCs)[1:]:
            Vpn.createVpnConnection(self.apiclient, vpn_cust_gw_list[0].id,
                                    vpn_response_list[i]['id'], True)
            self.logger.debug("VPN passive connection created for VPC%d %s" %
                              (i, vpc_list[i].id))

            vpnconn2_response = Vpn.createVpnConnection(
                self.apiclient, vpn_cust_gw_list[i].id,
                vpn_response_list[0]['id'])
            self.logger.debug("VPN connection created for VPC%d %s" %
                              (0, vpc_list[0].id))

            self.assertEqual(vpnconn2_response['state'], "Connected",
                             "Failed to connect between VPCs 0 and %d!" % i)
            self.logger.debug("VPN connected between VPC0 and VPC%d" % i)

        # First the last VM
        # setup ssh connection to vm maxnumVM
        self.logger.debug(
            "Setup SSH connection to last VM created (%d) to ensure availability for ping tests"
            % maxnumVM)
        ssh_max_client = vm_list[maxnumVM].get_ssh_client(retries=20)
        self.assertIsNotNone(
            ssh_max_client,
            "Failed to setup SSH to last VM created (%d)" % maxnumVM)

        self.logger.debug(
            "Setup SSH connection to first VM created (0) to ensure availability for ping tests"
        )
        ssh_client = vm_list[0].get_ssh_client(retries=10)
        self.assertIsNotNone(ssh_client, "Failed to setup SSH to VM0")

        if ssh_client:
            # run ping test
            for i in range(num_VPCs)[1:]:
                packet_loss = ssh_client.execute(
                    "/bin/ping -c 3 -t 10 " + vm_list[i].nic[0].ipaddress +
                    " |grep packet|cut -d ' ' -f 7| cut -f1 -d'%'")[0]
                self.assertEquals(
                    int(packet_loss), 0,
                    "Ping towards vm" + ` i ` + "did not succeed")
                self.logger.debug("Ping from vm0 to vm%d did succeed" % i)
        else:
            self.fail("Failed to setup ssh connection to %s" %
                      vm_list[0].public_ip)

        return
Exemplo n.º 38
0
    def test_network_rules_acquired_public_ip(self, value):
        """Test for Router rules for network rules on acquired public IP"""

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

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

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

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

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

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

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

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

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

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

            SshClient(
                self.ipaddress.ipaddress.ipaddress,
                self.virtual_machine.ssh_port,
                self.virtual_machine.username,
                self.virtual_machine.password,
                retries=2,
                delay=0
            )
        return
Exemplo n.º 39
0
    def test_01_vpc_remote_access_vpn(self):
        """Test Remote Access VPN in VPC"""
        # 1) Create VPC
        vpc_offering = VpcOffering.list(self.apiclient, isdefault=True)
        self.assertTrue(vpc_offering is not None and len(vpc_offering) > 0,
                        "No VPC offerings found")

        vpc = VPC.create(apiclient=self.apiclient,
                         services=self.services["vpc"],
                         networkDomain="vpc.vpn",
                         vpcofferingid=vpc_offering[0].id,
                         zoneid=self.zone.id,
                         account=self.account.name,
                         domainid=self.domain.id)

        self.assertIsNotNone(vpc, "VPC creation failed")
        self.logger.debug("VPC %s created" % (vpc.id))

        self.cleanup.append(vpc)

        # 2) Create network in VPC
        ntwk = Network.create(apiclient=self.apiclient,
                              services=self.services["network_1"],
                              accountid=self.account.name,
                              domainid=self.domain.id,
                              networkofferingid=self.network_offerings[0].id,
                              zoneid=self.zone.id,
                              vpcid=vpc.id)

        self.assertIsNotNone(ntwk, "Network failed to create")
        self.logger.debug("Network %s created in VPC %s" % (ntwk.id, vpc.id))

        self.cleanup.append(ntwk)

        # 3) Deploy a vm
        vm = VirtualMachine.create(self.apiclient,
                                   services=self.services["virtual_machine"],
                                   templateid=self.template.id,
                                   zoneid=self.zone.id,
                                   accountid=self.account.name,
                                   domainid=self.domain.id,
                                   serviceofferingid=self.compute_offering.id,
                                   networkids=ntwk.id,
                                   hypervisor=self.hypervisor)
        self.assertIsNotNone(vm, "VM failed to deploy")
        self.assertEquals(vm.state, 'Running', "VM is not running")
        self.debug("VM %s deployed in VPC %s" % (vm.id, vpc.id))

        self.logger.debug("Deployed virtual machine: OK")
        self.cleanup.append(vm)

        # 4) Enable VPN for VPC
        src_nat_list = PublicIPAddress.list(self.apiclient,
                                            account=self.account.name,
                                            domainid=self.account.domainid,
                                            listall=True,
                                            issourcenat=True,
                                            vpcid=vpc.id)
        ip = src_nat_list[0]

        self.logger.debug("Acquired public ip address: OK")

        vpn = Vpn.create(self.apiclient,
                         publicipid=ip.id,
                         account=self.account.name,
                         domainid=self.account.domainid,
                         iprange=self.services["vpn"]["iprange"],
                         fordisplay=self.services["vpn"]["fordisplay"])

        self.assertIsNotNone(vpn, "Failed to create Remote Access VPN")
        self.logger.debug("Created Remote Access VPN: OK")

        vpn_user = None
        # 5) Add VPN user for VPC
        vpn_user = VpnUser.create(self.apiclient,
                                  account=self.account.name,
                                  domainid=self.account.domainid,
                                  username=self.services["vpn"]["vpn_user"],
                                  password=self.services["vpn"]["vpn_pass"])

        self.assertIsNotNone(vpn_user,
                             "Failed to create Remote Access VPN User")
        self.logger.debug("Created VPN User: OK")

        # TODO: Add an actual remote vpn connection test from a remote vpc

        # 9) Disable VPN for VPC
        vpn.delete(self.apiclient)

        self.logger.debug("Deleted the Remote Access VPN: OK")
Exemplo n.º 40
0
    def test_01_positive_tests_vm_operations_advanced_zone(self, value):
        """ Positive tests for VMLC test path - Advanced Zone

        # 1.  List created service offering in setUpClass by name
        # 2.  List registered template with name
        # 3.  Create VM in account
        # 4.  Enable networking for reaching to VM thorugh SSH
        # 5.  Check VM accessibility through SSH
        # 6.  Stop vm and verify vm is not accessible
        # 7.  Start vm and verify vm is not accessible
        # 8.  Reboot vm and verify vm is not accessible
        # 9.  Destroy and recover VM
        # 10. Change service offering of VM to a different service offering
        # 11. Verify that the cpuspeed, cpunumber and memory of VM matches to
        #     as specified in new service offering
        # 12. Start VM and verify VM accessibility
        # 13. Find suitable host for VM to migrate and migrate the VM
        # 14. Verify VM accessibility on new host
        """
        # List created service offering in setUpClass by name
        listServiceOfferings = ServiceOffering.list(
            self.apiclient,
            name=self.service_offering_1.name,
            listall=True
        )
        self.assertEqual(validateList(listServiceOfferings)[0], PASS,
                         "List validation failed for service offerings list")

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

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

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

        network = CreateNetwork(self, value)

        # Create VM in account
        self.virtual_machine = VirtualMachine.create(
            self.userapiclient,
            self.testdata["small"],
            templateid=self.template.id,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering_1.id,
            networkids=[network.id, ],
            zoneid=self.zone.id
        )
        self.cleanup.append(self.virtual_machine)
        publicip = PublicIPAddress.create(
            self.userapiclient, accountid=self.account.name,
            zoneid=self.zone.id, domainid=self.account.domainid,
            networkid=network.id, vpcid=self.vpcid
        )

        if value == VPC_NETWORK:
            lb_rule = LoadBalancerRule.create(
                self.apiclient,
                self.testdata["vpclbrule"],
                ipaddressid=publicip.ipaddress.id,
                accountid=self.account.name,
                domainid=self.account.domainid,
                networkid=network.id,
                vpcid=self.vpcid
            )
            lb_rule.assign(self.apiclient, [self.virtual_machine])

            # Opening up the ports in VPC
            NetworkACL.create(
                self.apiclient,
                networkid=network.id,
                services=self.testdata["natrule"],
                traffictype='Ingress'
            )
        elif value == ISOLATED_NETWORK:
            FireWallRule.create(
                self.userapiclient,
                ipaddressid=publicip.ipaddress.id,
                protocol='TCP',
                cidrlist=[self.testdata["fwrule"]["cidr"]],
                startport=self.testdata["fwrule"]["startport"],
                endport=self.testdata["fwrule"]["endport"]
            )

            NATRule.create(
                self.userapiclient,
                self.virtual_machine,
                self.testdata["natrule"],
                ipaddressid=publicip.ipaddress.id,
                networkid=network.id
            )

        # Check VM accessibility
        try:
            SshClient(host=publicip.ipaddress.ipaddress,
                      port=22,
                      user=self.virtual_machine.username,
                      passwd=self.virtual_machine.password)
        except Exception as e:
            self.fail("Exception while SSHing to VM: %s" % e)

        # Stop VM and verify VM is not accessible
        self.virtual_machine.stop(self.userapiclient)

        with self.assertRaises(Exception):
            SshClient(host=publicip.ipaddress.ipaddress,
                      port=22,
                      user=self.virtual_machine.username,
                      passwd=self.virtual_machine.password,
                      retries=0)

        # Start VM and verify that it is accessible
        self.virtual_machine.start(self.userapiclient)

        try:
            SshClient(host=publicip.ipaddress.ipaddress,
                      port=22,
                      user=self.virtual_machine.username,
                      passwd=self.virtual_machine.password)
        except Exception as e:
            self.fail("Exception while SSHing to VM: %s" % e)

        # Reboot VM and verify that it is accessible
        self.virtual_machine.reboot(self.userapiclient)

        try:
            SshClient(host=publicip.ipaddress.ipaddress,
                      port=22,
                      user=self.virtual_machine.username,
                      passwd=self.virtual_machine.password)
        except Exception as e:
            self.fail("Exception while SSHing to VM: %s" % e)

        # Destroy and recover VM
        self.virtual_machine.delete(self.apiclient, expunge=False)
        self.virtual_machine.recover(self.apiclient)

        # Change service offering of VM and verify that it is changed
        self.virtual_machine.change_service_offering(
            self.userapiclient,
            serviceOfferingId=self.service_offering_2.id
        )

        VerifyChangeInServiceOffering(self,
                                      self.virtual_machine,
                                      self.service_offering_2)

        # Start VM and verify that it is accessible
        self.virtual_machine.start(self.userapiclient)

        try:
            SshClient(host=publicip.ipaddress.ipaddress,
                      port=22,
                      user=self.virtual_machine.username,
                      passwd=self.virtual_machine.password)
        except Exception as e:
            self.fail("Exception while SSHing to VM: %s" % e)

        return
Exemplo n.º 41
0
    def test_02_port_fwd_on_non_src_nat(self):
        """Test for port forwarding on non source NAT"""

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

        ip_address = PublicIPAddress.create(
            self.apiclient,
            self.account.name,
            self.zone.id,
            self.account.domainid,
            self.services["virtual_machine"]
        )
        self.cleanup.append(ip_address)

        # Check if VM is in Running state before creating NAT rule
        vm_response = VirtualMachine.list(
            self.apiclient,
            id=self.virtual_machine.id
        )

        self.assertEqual(
            isinstance(vm_response, list),
            True,
            "Check list VM returns a valid list"
        )

        self.assertNotEqual(
            len(vm_response),
            0,
            "Check Port Forwarding Rule is created"
        )
        self.assertEqual(
            vm_response[0].state,
            'Running',
            "VM state should be Running before creating a NAT rule."
        )
        # Open up firewall port for SSH
        FireWallRule.create(
            self.apiclient,
            ipaddressid=ip_address.ipaddress.id,
            protocol=self.services["natrule"]["protocol"],
            cidrlist=['0.0.0.0/0'],
            startport=self.services["natrule"]["publicport"],
            endport=self.services["natrule"]["publicport"]
        )
        # Create NAT rule
        nat_rule = NATRule.create(
            self.apiclient,
            self.virtual_machine,
            self.services["natrule"],
            ip_address.ipaddress.id
        )
        # Validate the following:
        # 1. listPortForwardingRules should not return the deleted rule anymore
        # 2. attempt to do ssh should now fail

        list_nat_rule_response = list_nat_rules(
            self.apiclient,
            id=nat_rule.id
        )
        self.assertEqual(
            isinstance(list_nat_rule_response, list),
            True,
            "Check list response returns a valid list"
        )
        self.assertNotEqual(
            len(list_nat_rule_response),
            0,
            "Check Port Forwarding Rule is created"
        )
        self.assertEqual(
            list_nat_rule_response[0].id,
            nat_rule.id,
            "Check Correct Port forwarding Rule is returned"
        )

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

        nat_rule.delete(self.apiclient)

        try:
            list_nat_rule_response = list_nat_rules(
                self.apiclient,
                id=nat_rule.id
            )
        except CloudstackAPIException:
            logger.debug("Nat Rule is deleted")

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

            SshClient(
                ip_address.ipaddress.ipaddress,
                self.virtual_machine.ssh_port,
                self.virtual_machine.username,
                self.virtual_machine.password,
                retries=2,
                delay=0
            )
        return
Exemplo n.º 42
0
    def setUp(self):
        self.apiclient = self.testClient.getApiClient()
        self.services = self.testClient.getParsedTestDataConfig()

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

        # Create an account, network, VM, Port forwarding rule, LB rules
        self.account = Account.create(
            self.apiclient,
            self.services["account"],
            admin=True,
            domainid=self.domain.id
        )

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

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

        self.ip_address = PublicIPAddress.create(
            self.apiclient,
            self.account.name,
            self.zone.id,
            self.account.domainid
        )

        ip_addrs = list_publicIP(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
            issourcenat=False
        )
        try:
            self.ip_addr = ip_addrs[0]
        except Exception as e:
            raise Exception(
                "Failed: During acquiring source NAT for account: %s, :%s" %
                (self.account.name, e))

        self.nat_rule = NATRule.create(
            self.apiclient,
            self.virtual_machine,
            self.services["natrule"],
            self.ip_addr.id
        )
        self.lb_rule = LoadBalancerRule.create(
            self.apiclient,
            self.services["lbrule"],
            self.ip_addr.id,
            accountid=self.account.name
        )
        self.cleanup = [
            self.virtual_machine,
            self.account
        ]
        return
Exemplo n.º 43
0
    def setUp(self):

        self.apiclient = self.testClient.getApiClient()
        self.services = self.testClient.getParsedTestDataConfig()

        # Get Zone, Domain and templates
        self.domain = get_domain(self.apiclient)
        self.zone = get_zone(self.apiclient, self.testClient.getZoneForTests())
        template = get_template(
            self.apiclient,
            self.zone.id,
            self.services["ostype"]
        )
        if template == FAILED:
            self.fail(
                "get_template() failed to return template with description %s" %
                self.services["ostype"])
        self.services["virtual_machine"]["zoneid"] = self.zone.id

        # Create an account, network, VM and IP addresses
        self.account = Account.create(
            self.apiclient,
            self.services["account"],
            admin=True,
            domainid=self.domain.id
        )
        self.service_offering = ServiceOffering.create(
            self.apiclient,
            self.services["service_offerings"]
        )
        self.vm_1 = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            templateid=template.id,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id
        )

        # Wait for VM to come up
        time.sleep(120)

        src_nat_ip_addrs = list_publicIP(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid
        )
        try:
            src_nat_ip_addr = src_nat_ip_addrs[0]
        except Exception as e:
            raise Exception(
                "Warning: Exception during fetching source NAT: %s" %
                e)

        self.public_ip = PublicIPAddress.create(
            self.apiclient,
            self.vm_1.account,
            self.vm_1.zoneid,
            self.vm_1.domainid,
            self.services["virtual_machine"]
        )
        # Open up firewall port for SSH
        FireWallRule.create(
            self.apiclient,
            ipaddressid=self.public_ip.ipaddress.id,
            protocol=self.services["lbrule"]["protocol"],
            cidrlist=['0.0.0.0/0'],
            startport=self.services["lbrule"]["publicport"],
            endport=self.services["lbrule"]["publicport"]
        )

        lb_rule = LoadBalancerRule.create(
            self.apiclient,
            self.services["lbrule"],
            src_nat_ip_addr.id,
            self.account.name
        )
        lb_rule.assign(self.apiclient, [self.vm_1])
        self.nat_rule = NATRule.create(
            self.apiclient,
            self.vm_1,
            self.services["natrule"],
            ipaddressid=self.public_ip.ipaddress.id
        )
        self.cleanup = [self.nat_rule,
                        lb_rule,
                        self.vm_1,
                        self.service_offering,
                        self.account,
                        ]
        return
    def test_01_acquire_public_ips_in_isolated_network_with_single_vr(self):
        """ Acquire IPs in multiple subnets in isolated networks with single VR

        # Steps
        # 1. Create network offering with single VR, and enable it
        # 2. create isolated network with the network offering
        # 3. create a vm in the network.
        #   verify the available nics in VR should be "eth0,eth1,eth2"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP
        # 4. get a free public ip, assign to network, and create port forwarding rules (ssh) to the vm
        #   verify the available nics in VR should be "eth0,eth1,eth2"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP and new ip
        # 5. remove the port forwarding rule, and release the new ip
        #   verify the available nics in VR should be "eth0,eth1,eth2"
        #   verify the IPs in VR. eth0 -> guest nic IP, eth2 -> source nat IP

        # 6. create new public ip range 1
        # 7. get a free ip 4 in new ip range 2, assign to network, and enable static nat to vm
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 1
        # 8. get a free ip in new ip range, assign to network, and create port forwarding rules (ssh) to the vm
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 1, new ip 2,
        # 9. get a free ip in new ip range, assign to network, and create port forwarding rules (ssh) to the vm
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 1, new ip 2, new ip 3
        # 10. release new ip 2
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 1, new ip 3
        # 11. release new ip 1
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 3
        # 12. create new public ip range 2
        # 13. get a free ip 4 in new ip range 2, assign to network, and create port forwarding rules (ssh) to the vm
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 3, eth4 -> new ip 4
        # 14. get a free ip 5 in new ip range 2, assign to network, and create port forwarding rules (ssh) to the vm
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 3, eth4 -> new ip 4/5
        # 15. get a free ip 6 in new ip range 2, assign to network, and create port forwarding rules (ssh) to the vm
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 3, eth4 -> new ip 4/5/6
        # 16. release new ip 5
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 3, eth4 -> new ip 4/6
        # 17. release new ip 4
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 3, eth4 -> new ip 6
        # 18. release new ip 3
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth4,"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth4 -> new ip 6
        # 19. restart network
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth4,"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth4 -> new ip 6
        # 20. reboot router
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 6
        # 21. restart network with cleanup
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 6
        # 22. restart network with cleanup, makeredundant=true
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 6
        """

        # Create new domain1
        self.domain1 = Domain.create(self.apiclient,
                                     services=self.services["acl"]["domain1"],
                                     parentdomainid=self.domain.id)
        # Create account1
        self.account1 = Account.create(self.apiclient,
                                       self.services["acl"]["accountD1"],
                                       domainid=self.domain1.id)
        self.cleanup.append(self.account1)
        self.cleanup.append(self.domain1)

        # 1. Create network offering with single VR, and enable it
        self.network_offering = NetworkOffering.create(
            self.apiclient,
            self.services["isolated_network_offering"],
        )
        self.network_offering.update(self.apiclient, state='Enabled')
        self.cleanup.append(self.network_offering)

        # 2. create isolated network with the network offering
        self.services["network"]["zoneid"] = self.zone.id
        self.services["network"]["networkoffering"] = self.network_offering.id
        self.network1 = Network.create(self.apiclient,
                                       self.services["network"],
                                       self.account1.name,
                                       self.account1.domainid)

        # 3. create a vm in the network.
        try:
            self.virtual_machine1 = VirtualMachine.create(
                self.apiclient,
                self.services["virtual_machine"],
                accountid=self.account1.name,
                domainid=self.account1.domainid,
                serviceofferingid=self.service_offering.id,
                templateid=self.template.id,
                zoneid=self.zone.id,
                networkids=self.network1.id)
        except Exception as e:
            self.fail("Exception while deploying virtual machine: %s" % e)

        #   verify the available nics in VR should be "eth0,eth1,eth2"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP
        routers = self.get_routers(self.network1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host,
                                                     "eth0,eth1,eth2,")
            guestIp, controlIp, sourcenatIp = self.get_router_ips(router)
            self.verify_ip_address_in_router(router, host, guestIp, "eth0",
                                             True)
            self.verify_ip_address_in_router(router, host, controlIp, "eth1",
                                             True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth2",
                                             True)
            self.verify_router_publicnic_state(router, host, "eth2")

        # 4. get a free public ip, assign to network, and create port forwarding rules (ssh) to the vm
        ipaddress = PublicIPAddress.create(
            self.apiclient,
            zoneid=self.zone.id,
            networkid=self.network1.id,
        )
        nat_rule = NATRule.create(self.apiclient,
                                  self.virtual_machine1,
                                  self.services["natrule"],
                                  ipaddressid=ipaddress.ipaddress.id,
                                  openfirewall=True)
        #   verify the available nics in VR should be "eth0,eth1,eth2"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP/new ip
        routers = self.get_routers(self.network1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host,
                                                     "eth0,eth1,eth2,")
            guestIp, controlIp, sourcenatIp = self.get_router_ips(router)
            self.verify_ip_address_in_router(router, host, guestIp, "eth0",
                                             True)
            self.verify_ip_address_in_router(router, host, controlIp, "eth1",
                                             True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth2",
                                             True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress.ipaddress.ipaddress,
                                             "eth2", True)
            self.verify_router_publicnic_state(router, host, "eth2")

        # 5. release the new ip
        ipaddress.delete(self.apiclient)

        #   verify the available nics in VR should be "eth0,eth1,eth2"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP
        routers = self.get_routers(self.network1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host,
                                                     "eth0,eth1,eth2,")
            guestIp, controlIp, sourcenatIp = self.get_router_ips(router)
            self.verify_ip_address_in_router(router, host, guestIp, "eth0",
                                             True)
            self.verify_ip_address_in_router(router, host, controlIp, "eth1",
                                             True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth2",
                                             True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress.ipaddress.ipaddress,
                                             "eth2", False)
            self.verify_router_publicnic_state(router, host, "eth2")

        # 6. create new public ip range 1
        self.services["publiciprange"]["zoneid"] = self.zone.id
        self.services["publiciprange"]["forvirtualnetwork"] = "true"
        random_subnet_number = random.randrange(10, 50)
        self.services["publiciprange"]["vlan"] = get_free_vlan(
            self.apiclient, self.zone.id)[1]
        self.services["publiciprange"]["gateway"] = "172.16." + str(
            random_subnet_number) + ".1"
        self.services["publiciprange"]["startip"] = "172.16." + str(
            random_subnet_number) + ".2"
        self.services["publiciprange"]["endip"] = "172.16." + str(
            random_subnet_number) + ".10"
        self.services["publiciprange"]["netmask"] = "255.255.255.0"
        self.public_ip_range1 = PublicIpRange.create(
            self.apiclient, self.services["publiciprange"])
        self.cleanup.append(self.public_ip_range1)

        # 7. get a free ip 4 in new ip range 2, assign to network, and enable static nat to vm
        ip_address_1 = self.get_free_ipaddress(self.public_ip_range1.vlan.id)
        ipaddress_1 = PublicIPAddress.create(self.apiclient,
                                             zoneid=self.zone.id,
                                             networkid=self.network1.id,
                                             ipaddress=ip_address_1)

        StaticNATRule.enable(self.apiclient,
                             virtualmachineid=self.virtual_machine1.id,
                             ipaddressid=ipaddress_1.ipaddress.id,
                             networkid=self.network1.id)

        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 1
        routers = self.get_routers(self.network1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host,
                                                     "eth0,eth1,eth2,eth3,")
            guestIp, controlIp, sourcenatIp = self.get_router_ips(router)
            self.verify_ip_address_in_router(router, host, guestIp, "eth0",
                                             True)
            self.verify_ip_address_in_router(router, host, controlIp, "eth1",
                                             True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth2",
                                             True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_1.ipaddress.ipaddress,
                                             "eth3", True)
            self.verify_router_publicnic_state(router, host, "eth2|eth3")

        # 8. get a free ip in new ip range, assign to network, and create port forwarding rules (ssh) to the vm
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 1, new ip 2,
        ip_address_2 = self.get_free_ipaddress(self.public_ip_range1.vlan.id)
        ipaddress_2 = PublicIPAddress.create(self.apiclient,
                                             zoneid=self.zone.id,
                                             networkid=self.network1.id,
                                             ipaddress=ip_address_2)

        nat_rule = NATRule.create(self.apiclient,
                                  self.virtual_machine1,
                                  self.services["natrule"],
                                  ipaddressid=ipaddress_2.ipaddress.id,
                                  openfirewall=True)
        routers = self.get_routers(self.network1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host,
                                                     "eth0,eth1,eth2,eth3,")
            guestIp, controlIp, sourcenatIp = self.get_router_ips(router)
            self.verify_ip_address_in_router(router, host, guestIp, "eth0",
                                             True)
            self.verify_ip_address_in_router(router, host, controlIp, "eth1",
                                             True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth2",
                                             True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_1.ipaddress.ipaddress,
                                             "eth3", True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_2.ipaddress.ipaddress,
                                             "eth3", True)
            self.verify_router_publicnic_state(router, host, "eth2|eth3")

        # 9. get a free ip in new ip range, assign to network, and create port forwarding rules (ssh) to the vm
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 1, new ip 2, new ip 3
        ip_address_3 = self.get_free_ipaddress(self.public_ip_range1.vlan.id)
        ipaddress_3 = PublicIPAddress.create(self.apiclient,
                                             zoneid=self.zone.id,
                                             networkid=self.network1.id,
                                             ipaddress=ip_address_3)

        nat_rule = NATRule.create(self.apiclient,
                                  self.virtual_machine1,
                                  self.services["natrule"],
                                  ipaddressid=ipaddress_3.ipaddress.id,
                                  openfirewall=True)
        routers = self.get_routers(self.network1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host,
                                                     "eth0,eth1,eth2,eth3,")
            guestIp, controlIp, sourcenatIp = self.get_router_ips(router)
            self.verify_ip_address_in_router(router, host, guestIp, "eth0",
                                             True)
            self.verify_ip_address_in_router(router, host, controlIp, "eth1",
                                             True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth2",
                                             True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_1.ipaddress.ipaddress,
                                             "eth3", True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_2.ipaddress.ipaddress,
                                             "eth3", True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_3.ipaddress.ipaddress,
                                             "eth3", True)
            self.verify_router_publicnic_state(router, host, "eth2|eth3")

        # 10. release new ip 2
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 1, new ip 3
        ipaddress_2.delete(self.apiclient)

        routers = self.get_routers(self.network1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host,
                                                     "eth0,eth1,eth2,eth3,")
            guestIp, controlIp, sourcenatIp = self.get_router_ips(router)
            self.verify_ip_address_in_router(router, host, guestIp, "eth0",
                                             True)
            self.verify_ip_address_in_router(router, host, controlIp, "eth1",
                                             True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth2",
                                             True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_1.ipaddress.ipaddress,
                                             "eth3", True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_2.ipaddress.ipaddress,
                                             "eth3", False)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_3.ipaddress.ipaddress,
                                             "eth3", True)
            self.verify_router_publicnic_state(router, host, "eth2|eth3")

        # 11. release new ip 1
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 3
        ipaddress_1.delete(self.apiclient)
        routers = self.get_routers(self.network1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host,
                                                     "eth0,eth1,eth2,eth3,")
            guestIp, controlIp, sourcenatIp = self.get_router_ips(router)
            self.verify_ip_address_in_router(router, host, guestIp, "eth0",
                                             True)
            self.verify_ip_address_in_router(router, host, controlIp, "eth1",
                                             True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth2",
                                             True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_1.ipaddress.ipaddress,
                                             "eth3", False)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_2.ipaddress.ipaddress,
                                             "eth3", False)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_3.ipaddress.ipaddress,
                                             "eth3", True)
            self.verify_router_publicnic_state(router, host, "eth2|eth3")

        # 12. create new public ip range 2
        self.services["publiciprange"]["zoneid"] = self.zone.id
        self.services["publiciprange"]["forvirtualnetwork"] = "true"
        self.services["publiciprange"]["vlan"] = get_free_vlan(
            self.apiclient, self.zone.id)[1]
        self.services["publiciprange"]["gateway"] = "172.16." + str(
            random_subnet_number + 1) + ".1"
        self.services["publiciprange"]["startip"] = "172.16." + str(
            random_subnet_number + 1) + ".2"
        self.services["publiciprange"]["endip"] = "172.16." + str(
            random_subnet_number + 1) + ".10"
        self.services["publiciprange"]["netmask"] = "255.255.255.0"
        self.public_ip_range2 = PublicIpRange.create(
            self.apiclient, self.services["publiciprange"])
        self.cleanup.append(self.public_ip_range2)

        # 13. get a free ip 4 in new ip range 2, assign to network, and create port forwarding rules (ssh) to the vm
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 3, eth4 -> new ip 4

        ip_address_4 = self.get_free_ipaddress(self.public_ip_range2.vlan.id)
        ipaddress_4 = PublicIPAddress.create(self.apiclient,
                                             zoneid=self.zone.id,
                                             networkid=self.network1.id,
                                             ipaddress=ip_address_4)

        StaticNATRule.enable(self.apiclient,
                             virtualmachineid=self.virtual_machine1.id,
                             ipaddressid=ipaddress_4.ipaddress.id,
                             networkid=self.network1.id)

        routers = self.get_routers(self.network1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(
                router, host, "eth0,eth1,eth2,eth3,eth4,")
            guestIp, controlIp, sourcenatIp = self.get_router_ips(router)
            self.verify_ip_address_in_router(router, host, guestIp, "eth0",
                                             True)
            self.verify_ip_address_in_router(router, host, controlIp, "eth1",
                                             True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth2",
                                             True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_3.ipaddress.ipaddress,
                                             "eth3", True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_4.ipaddress.ipaddress,
                                             "eth4", True)
            self.verify_router_publicnic_state(router, host, "eth2|eth3|eth4")

        # 14. get a free ip 5 in new ip range 2, assign to network, and create port forwarding rules (ssh) to the vm
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 3, eth4 -> new ip 4/5
        ip_address_5 = self.get_free_ipaddress(self.public_ip_range2.vlan.id)
        ipaddress_5 = PublicIPAddress.create(self.apiclient,
                                             zoneid=self.zone.id,
                                             networkid=self.network1.id,
                                             ipaddress=ip_address_5)

        nat_rule = NATRule.create(self.apiclient,
                                  self.virtual_machine1,
                                  self.services["natrule"],
                                  ipaddressid=ipaddress_5.ipaddress.id,
                                  openfirewall=True)
        routers = self.get_routers(self.network1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(
                router, host, "eth0,eth1,eth2,eth3,eth4,")
            guestIp, controlIp, sourcenatIp = self.get_router_ips(router)
            self.verify_ip_address_in_router(router, host, guestIp, "eth0",
                                             True)
            self.verify_ip_address_in_router(router, host, controlIp, "eth1",
                                             True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth2",
                                             True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_3.ipaddress.ipaddress,
                                             "eth3", True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_4.ipaddress.ipaddress,
                                             "eth4", True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_5.ipaddress.ipaddress,
                                             "eth4", True)
            self.verify_router_publicnic_state(router, host, "eth2|eth3|eth4")

        # 15. get a free ip 6 in new ip range 2, assign to network, and create port forwarding rules (ssh) to the vm
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 3, eth4 -> new ip 4/5/6
        ip_address_6 = self.get_free_ipaddress(self.public_ip_range2.vlan.id)
        ipaddress_6 = PublicIPAddress.create(self.apiclient,
                                             zoneid=self.zone.id,
                                             networkid=self.network1.id,
                                             ipaddress=ip_address_6)

        nat_rule = NATRule.create(self.apiclient,
                                  self.virtual_machine1,
                                  self.services["natrule"],
                                  ipaddressid=ipaddress_6.ipaddress.id,
                                  openfirewall=True)
        routers = self.get_routers(self.network1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(
                router, host, "eth0,eth1,eth2,eth3,eth4,")
            guestIp, controlIp, sourcenatIp = self.get_router_ips(router)
            self.verify_ip_address_in_router(router, host, guestIp, "eth0",
                                             True)
            self.verify_ip_address_in_router(router, host, controlIp, "eth1",
                                             True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth2",
                                             True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_3.ipaddress.ipaddress,
                                             "eth3", True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_4.ipaddress.ipaddress,
                                             "eth4", True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_5.ipaddress.ipaddress,
                                             "eth4", True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_6.ipaddress.ipaddress,
                                             "eth4", True)
            self.verify_router_publicnic_state(router, host, "eth2|eth3|eth4")

        # 16. release new ip 5
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 3, eth4 -> new ip 4/6
        ipaddress_5.delete(self.apiclient)

        routers = self.get_routers(self.network1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(
                router, host, "eth0,eth1,eth2,eth3,eth4,")
            guestIp, controlIp, sourcenatIp = self.get_router_ips(router)
            self.verify_ip_address_in_router(router, host, guestIp, "eth0",
                                             True)
            self.verify_ip_address_in_router(router, host, controlIp, "eth1",
                                             True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth2",
                                             True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_3.ipaddress.ipaddress,
                                             "eth3", True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_4.ipaddress.ipaddress,
                                             "eth4", True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_5.ipaddress.ipaddress,
                                             "eth4", False)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_6.ipaddress.ipaddress,
                                             "eth4", True)
            self.verify_router_publicnic_state(router, host, "eth2|eth3|eth4")

        # 17. release new ip 4
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 3, eth4 -> new ip 6
        ipaddress_4.delete(self.apiclient)
        routers = self.get_routers(self.network1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(
                router, host, "eth0,eth1,eth2,eth3,eth4,")
            guestIp, controlIp, sourcenatIp = self.get_router_ips(router)
            self.verify_ip_address_in_router(router, host, guestIp, "eth0",
                                             True)
            self.verify_ip_address_in_router(router, host, controlIp, "eth1",
                                             True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth2",
                                             True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_3.ipaddress.ipaddress,
                                             "eth3", True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_4.ipaddress.ipaddress,
                                             "eth4", False)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_5.ipaddress.ipaddress,
                                             "eth4", False)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_6.ipaddress.ipaddress,
                                             "eth4", True)
            self.verify_router_publicnic_state(router, host, "eth2|eth3|eth4")

        # 18. release new ip 3
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth4,"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth4 -> new ip 6
        ipaddress_3.delete(self.apiclient)
        routers = self.get_routers(self.network1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host,
                                                     "eth0,eth1,eth2,eth4,")
            guestIp, controlIp, sourcenatIp = self.get_router_ips(router)
            self.verify_ip_address_in_router(router, host, guestIp, "eth0",
                                             True)
            self.verify_ip_address_in_router(router, host, controlIp, "eth1",
                                             True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth2",
                                             True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_4.ipaddress.ipaddress,
                                             "eth4", False)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_5.ipaddress.ipaddress,
                                             "eth4", False)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_6.ipaddress.ipaddress,
                                             "eth4", True)
            self.verify_router_publicnic_state(router, host, "eth2|eth4")

        # 19. restart network
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth4,"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth4 -> new ip 6
        self.network1.restart(self.apiclient)
        routers = self.get_routers(self.network1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host,
                                                     "eth0,eth1,eth2,eth4,")
            guestIp, controlIp, sourcenatIp = self.get_router_ips(router)
            self.verify_ip_address_in_router(router, host, guestIp, "eth0",
                                             True)
            self.verify_ip_address_in_router(router, host, controlIp, "eth1",
                                             True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth2",
                                             True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_4.ipaddress.ipaddress,
                                             "eth4", False)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_5.ipaddress.ipaddress,
                                             "eth4", False)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_6.ipaddress.ipaddress,
                                             "eth4", True)
            self.verify_router_publicnic_state(router, host, "eth2|eth4")

        # 20. reboot router
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 6
        if len(routers) > 0:
            router = routers[0]
            cmd = rebootRouter.rebootRouterCmd()
            cmd.id = router.id
            self.apiclient.rebootRouter(cmd)
            router = self.get_router(router.id)
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host,
                                                     "eth0,eth1,eth2,eth3,")
            guestIp, controlIp, sourcenatIp = self.get_router_ips(router)
            self.verify_ip_address_in_router(router, host, guestIp, "eth0",
                                             True)
            self.verify_ip_address_in_router(router, host, controlIp, "eth1",
                                             True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth2",
                                             True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_4.ipaddress.ipaddress,
                                             "eth3", False)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_5.ipaddress.ipaddress,
                                             "eth3", False)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_6.ipaddress.ipaddress,
                                             "eth3", True)
            self.verify_router_publicnic_state(router, host, "eth2|eth3")

        # 21. restart network with cleanup
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 6
        self.network1.restart(self.apiclient, cleanup=True)
        routers = self.get_routers(self.network1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host,
                                                     "eth0,eth1,eth2,eth3,")
            guestIp, controlIp, sourcenatIp = self.get_router_ips(router)
            self.verify_ip_address_in_router(router, host, guestIp, "eth0",
                                             True)
            self.verify_ip_address_in_router(router, host, controlIp, "eth1",
                                             True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth2",
                                             True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_4.ipaddress.ipaddress,
                                             "eth3", False)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_5.ipaddress.ipaddress,
                                             "eth3", False)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_6.ipaddress.ipaddress,
                                             "eth3", True)

        # 22. restart network with cleanup, makeredundant=true
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 6
        self.network1.restart(self.apiclient, cleanup=True, makeredundant=True)
        routers = self.get_routers(self.network1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host,
                                                     "eth0,eth1,eth2,eth3,")
            guestIp, controlIp, sourcenatIp = self.get_router_ips(router)
            self.verify_ip_address_in_router(router, host, guestIp, "eth0",
                                             True)
            self.verify_ip_address_in_router(router, host, controlIp, "eth1",
                                             True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth2",
                                             True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_4.ipaddress.ipaddress,
                                             "eth3", False)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_5.ipaddress.ipaddress,
                                             "eth3", False)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_6.ipaddress.ipaddress,
                                             "eth3", True)
            self.verify_router_publicnic_state(router, host, "eth2|eth3")
Exemplo n.º 45
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
Exemplo n.º 46
0
    def test_01_firewall_rules_port_fw(self):
        """"Checking firewall rules deletion after static NAT disable"""

        # Validate the following:
        #1. Enable static NAT for a VM
        #2. Open up some ports. At this point there will be new rows in the
        #   firewall_rules table.
        #3. Disable static NAT for the VM.
        #4. Check fire wall rules are deleted from firewall_rules table.

        public_ip = self.public_ip.ipaddress

        # Enable Static NAT for VM
        StaticNATRule.enable(self.apiclient, public_ip.id,
                             self.virtual_machine.id)
        self.debug("Enabled static NAT for public IP ID: %s" % public_ip.id)

        #Create Static NAT rule, in fact it's firewall rule
        nat_rule = StaticNATRule.create(self.apiclient,
                                        self.services["firewall_rule"],
                                        public_ip.id)
        self.debug("Created Static NAT rule for public IP ID: %s" %
                   public_ip.id)
        self.debug("Checking IP address")
        ip_response = PublicIPAddress.list(self.apiclient, id=public_ip.id)
        self.assertEqual(isinstance(ip_response, list), True,
                         "Check ip response returns a valid list")
        self.assertNotEqual(len(ip_response), 0,
                            "Check static NAT Rule is created")
        self.assertTrue(ip_response[0].isstaticnat,
                        "IP is not static nat enabled")
        self.assertEqual(ip_response[0].virtualmachineid,
                         self.virtual_machine.id,
                         "IP is not binding with the VM")

        self.debug("Checking Firewall rule")
        firewall_response = FireWallRule.list(self.apiclient,
                                              ipaddressid=public_ip.id,
                                              listall=True)
        self.assertEqual(isinstance(firewall_response, list), True,
                         "Check firewall response returns a valid list")
        self.assertNotEqual(len(firewall_response), 0,
                            "Check firewall rule is created")
        self.assertEqual(firewall_response[0].state, "Active",
                         "Firewall rule is not active")
        self.assertEqual(firewall_response[0].ipaddressid, public_ip.id,
                         "Firewall rule is not static nat related")
        self.assertEqual(firewall_response[0].startport,
                         str(self.services["firewall_rule"]["startport"]),
                         "Firewall rule is not with specific port")

        self.debug("Removed the firewall rule")
        nat_rule.delete(self.apiclient)

        self.debug("Checking IP address, it should still existed")
        ip_response = PublicIPAddress.list(self.apiclient, id=public_ip.id)
        self.assertEqual(isinstance(ip_response, list), True,
                         "Check ip response returns a valid list")
        self.assertNotEqual(len(ip_response), 0,
                            "Check static NAT Rule is created")
        self.assertTrue(ip_response[0].isstaticnat,
                        "IP is not static nat enabled")
        self.assertEqual(ip_response[0].virtualmachineid,
                         self.virtual_machine.id,
                         "IP is not binding with the VM")

        self.debug("Checking Firewall rule, it should be removed")
        firewall_response = FireWallRule.list(self.apiclient,
                                              ipaddressid=public_ip.id,
                                              listall=True)
        self.assertEqual(isinstance(firewall_response, list), True,
                         "Check firewall response returns a valid list")
        if len(firewall_response) != 0:
            self.assertEqual(
                firewall_response[0].state, "Deleting",
                "Firewall rule should be deleted or in deleting state")
        return
Exemplo n.º 47
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, # 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"
                        )

        # 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
Exemplo n.º 48
0
    def setUp(self):
        self.apiclient = self.testClient.getApiClient()
        self.services = self.testClient.getParsedTestDataConfig()

        # Get Zone, Domain and templates
        self.domain = get_domain(self.apiclient)
        self.zone = get_zone(self.apiclient, self.testClient.getZoneForTests())
        self.hypervisor = self.testClient.getHypervisorInfo()
        template = get_test_template(
            self.apiclient,
            self.zone.id,
            self.hypervisor
        )
        self.services["virtual_machine"]["zoneid"] = self.zone.id

        # Create an account, network, VM, Port forwarding rule, LB rules
        self.account = Account.create(
            self.apiclient,
            self.services["account"],
            admin=True,
            domainid=self.domain.id
        )

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

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

        self.ip_address = PublicIPAddress.create(
            self.apiclient,
            self.account.name,
            self.zone.id,
            self.account.domainid
        )

        ip_addrs = list_publicIP(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
            issourcenat=False
        )
        try:
            self.ip_addr = ip_addrs[0]
        except Exception as e:
            raise Exception(
                "Failed: During acquiring source NAT for account: %s, :%s" %
                (self.account.name, e))

        self.nat_rule = NATRule.create(
            self.apiclient,
            self.virtual_machine,
            self.services["natrule"],
            self.ip_addr.id
        )
        self.lb_rule = LoadBalancerRule.create(
            self.apiclient,
            self.services["lbrule"],
            self.ip_addr.id,
            accountid=self.account.name
        )
        self.cleanup = [
            self.virtual_machine,
            self.account
        ]
        return
Exemplo n.º 49
0
    def setUpClass(cls):
        testClient = super(TestPublicIP, cls).getClsTestClient()
        cls.apiclient = testClient.getApiClient()
        cls.services = testClient.getParsedTestDataConfig()

        # Get Zone, Domain and templates
        cls.domain = get_domain(cls.apiclient)
        cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
        cls.services['mode'] = cls.zone.networktype
        # Create Accounts & networks
        cls.account = Account.create(
            cls.apiclient,
            cls.services["account"],
            admin=True,
            domainid=cls.domain.id
        )

        cls.user = Account.create(
            cls.apiclient,
            cls.services["account"],
            domainid=cls.domain.id
        )
        cls.services["network"]["zoneid"] = cls.zone.id

        cls.network_offering = NetworkOffering.create(
            cls.apiclient,
            cls.services["network_offering"],
        )
        # Enable Network offering
        cls.network_offering.update(cls.apiclient, state='Enabled')

        cls.services["network"]["networkoffering"] = cls.network_offering.id
        cls.account_network = Network.create(
            cls.apiclient,
            cls.services["network"],
            cls.account.name,
            cls.account.domainid
        )
        cls.user_network = Network.create(
            cls.apiclient,
            cls.services["network"],
            cls.user.name,
            cls.user.domainid
        )

        # Create Source NAT IP addresses
        PublicIPAddress.create(
            cls.apiclient,
            cls.account.name,
            cls.zone.id,
            cls.account.domainid
        )
        PublicIPAddress.create(
            cls.apiclient,
            cls.user.name,
            cls.zone.id,
            cls.user.domainid
        )
        cls._cleanup = [
            cls.account_network,
            cls.user_network,
            cls.account,
            cls.user,
            cls.network_offering
        ]
        return
Exemplo n.º 50
0
    def setUp(self):

        self.apiclient = self.testClient.getApiClient()
        self.services = self.testClient.getParsedTestDataConfig()

        # Get Zone, Domain and templates
        self.domain = get_domain(self.apiclient)
        self.zone = get_zone(self.apiclient, self.testClient.getZoneForTests())
        self.hypervisor = self.testClient.getHypervisorInfo()
        template = get_test_template(
            self.apiclient,
            self.zone.id,
            self.hypervisor
        )
        if template == FAILED:
            self.fail("get_test_template() failed to return template")

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

        # Create an account, network, VM and IP addresses
        self.account = Account.create(
            self.apiclient,
            self.services["account"],
            admin=True,
            domainid=self.domain.id
        )
        self.service_offering = ServiceOffering.create(
            self.apiclient,
            self.services["service_offerings"]["tiny"]
        )
        self.vm_1 = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            templateid=template.id,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id
        )

        # Wait for VM to come up
        time.sleep(120)

        src_nat_ip_addrs = list_publicIP(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid
        )
        try:
            src_nat_ip_addr = src_nat_ip_addrs[0]
        except Exception as e:
            raise Exception(
                "Warning: Exception during fetching source NAT: %s" %
                e)

        self.public_ip = PublicIPAddress.create(
            self.apiclient,
            self.vm_1.account,
            self.vm_1.zoneid,
            self.vm_1.domainid,
            self.services["virtual_machine"]
        )
        # Open up firewall port for SSH
        FireWallRule.create(
            self.apiclient,
            ipaddressid=self.public_ip.ipaddress.id,
            protocol=self.services["lbrule"]["protocol"],
            cidrlist=['0.0.0.0/0'],
            startport=self.services["lbrule"]["publicport"],
            endport=self.services["lbrule"]["publicport"]
        )

        lb_rule = LoadBalancerRule.create(
            self.apiclient,
            self.services["lbrule"],
            src_nat_ip_addr.id,
            self.account.name
        )
        lb_rule.assign(self.apiclient, [self.vm_1])
        self.nat_rule = NATRule.create(
            self.apiclient,
            self.vm_1,
            self.services["natrule"],
            ipaddressid=self.public_ip.ipaddress.id
        )
        self.cleanup = [self.nat_rule,
                        lb_rule,
                        self.vm_1,
                        self.service_offering,
                        self.account,
                        ]
        return
Exemplo n.º 51
0
    def test_01_create_lb_rule_src_nat(self):
        """Test to create Load balancing rule with source NAT"""

        # Validate the Following:
        # 1. listLoadBalancerRules should return the added rule
        # 2. attempt to ssh twice on the load balanced IP
        # 3. verify using the UNAME of the VM
        #   that round robin is indeed happening as expected
        src_nat_ip_addrs = PublicIPAddress.list(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid
        )
        self.assertEqual(
            isinstance(src_nat_ip_addrs, list),
            True,
            "Check list response returns a valid list"
        )
        src_nat_ip_addr = src_nat_ip_addrs[0]

        # Check if VM is in Running state before creating LB rule
        vm_response = VirtualMachine.list(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid
        )

        self.assertEqual(
            isinstance(vm_response, list),
            True,
            "Check list VM returns a valid list"
        )

        self.assertNotEqual(
            len(vm_response),
            0,
            "Check Port Forwarding Rule is created"
        )
        for vm in vm_response:
            self.assertEqual(
                vm.state,
                'Running',
                "VM state should be Running before creating a NAT rule."
            )

        # Create Load Balancer rule and assign VMs to rule
        lb_rule = LoadBalancerRule.create(
            self.apiclient,
            self.services["lbrule"],
            src_nat_ip_addr.id,
            accountid=self.account.name,
            vpcid=self.vpc1.id,
            networkid=self.network1.id
        )
        self.cleanup.append(lb_rule)
        lb_rule.assign(self.apiclient, [self.vm_1, self.vm_2])
        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"
        )

        # listLoadBalancerRuleInstances should list all
        # instances associated with that LB rule
        lb_instance_rules = list_lb_instances(
            self.apiclient,
            id=lb_rule.id
        )
        self.assertEqual(
            isinstance(lb_instance_rules, list),
            True,
            "Check list response returns a valid list"
        )
        self.assertNotEqual(
            len(lb_instance_rules),
            0,
            "Check Load Balancer instances Rule in its List"
        )
        self.logger.debug("lb_instance_rules Ids: %s, %s" % (
            lb_instance_rules[0].id,
            lb_instance_rules[1].id
        ))
        self.logger.debug("VM ids: %s, %s" % (self.vm_1.id, self.vm_2.id))

        self.assertIn(
            lb_instance_rules[0].id,
            [self.vm_1.id, self.vm_2.id],
            "Check List Load Balancer instances Rules returns valid VM ID"
        )

        self.assertIn(
            lb_instance_rules[1].id,
            [self.vm_1.id, self.vm_2.id],
            "Check List Load Balancer instances Rules returns valid VM ID"
        )

        unameResults = []
        self.try_ssh(src_nat_ip_addr.ipaddress, unameResults)
        self.try_ssh(src_nat_ip_addr.ipaddress, unameResults)
        self.try_ssh(src_nat_ip_addr.ipaddress, unameResults)
        self.try_ssh(src_nat_ip_addr.ipaddress, unameResults)
        self.try_ssh(src_nat_ip_addr.ipaddress, unameResults)

        self.logger.debug("UNAME: %s" % str(unameResults))
        self.assertIn(
            "Linux",
            unameResults,
            "Check if ssh succeeded for server1"
        )
        self.assertIn(
            "Linux",
            unameResults,
            "Check if ssh succeeded for server2"
        )

        # SSH should pass till there is a last VM associated with LB rule
        lb_rule.remove(self.apiclient, [self.vm_2])

        # making unameResultss list empty
        unameResults[:] = []

        try:
            self.logger.debug("SSHing into IP address: %s after removing VM (ID: %s)" %
                       (
                           src_nat_ip_addr.ipaddress,
                           self.vm_2.id
                       ))

            self.try_ssh(src_nat_ip_addr.ipaddress, unameResults)
            self.assertIn(
                "Linux",
                unameResults,
                "Check if ssh succeeded for server1"
            )
        except Exception as e:
            self.fail("%s: SSH failed for VM with IP Address: %s" %
                      (e, src_nat_ip_addr.ipaddress))

        lb_rule.remove(self.apiclient, [self.vm_1])

        with self.assertRaises(Exception):
            self.logger.debug("Removed all VMs, trying to SSH")
            self.try_ssh(src_nat_ip_addr.ipaddress, unameResults)
        return
Exemplo n.º 52
0
    def test_02_port_fwd_on_non_src_nat(self):
        """Test for port forwarding on non source NAT"""

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

        ip_address = PublicIPAddress.create(
            self.apiclient,
            self.account.name,
            self.zone.id,
            self.account.domainid,
            self.services["virtual_machine"]
        )
        self.cleanup.append(ip_address)

        # Check if VM is in Running state before creating NAT rule
        vm_response = VirtualMachine.list(
            self.apiclient,
            id=self.virtual_machine.id
        )

        self.assertEqual(
            isinstance(vm_response, list),
            True,
            "Check list VM returns a valid list"
        )

        self.assertNotEqual(
            len(vm_response),
            0,
            "Check Port Forwarding Rule is created"
        )
        self.assertEqual(
            vm_response[0].state,
            'Running',
            "VM state should be Running before creating a NAT rule."
        )
        # Open up firewall port for SSH
        FireWallRule.create(
            self.apiclient,
            ipaddressid=ip_address.ipaddress.id,
            protocol=self.services["natrule"]["protocol"],
            cidrlist=['0.0.0.0/0'],
            startport=self.services["natrule"]["publicport"],
            endport=self.services["natrule"]["publicport"]
        )
        # Create NAT rule
        nat_rule = NATRule.create(
            self.apiclient,
            self.virtual_machine,
            self.services["natrule"],
            ip_address.ipaddress.id
        )
        # Validate the following:
        # 1. listPortForwardingRules should not return the deleted rule anymore
        # 2. attempt to do ssh should now fail

        list_nat_rule_response = list_nat_rules(
            self.apiclient,
            id=nat_rule.id
        )
        self.assertEqual(
            isinstance(list_nat_rule_response, list),
            True,
            "Check list response returns a valid list"
        )
        self.assertNotEqual(
            len(list_nat_rule_response),
            0,
            "Check Port Forwarding Rule is created"
        )
        self.assertEqual(
            list_nat_rule_response[0].id,
            nat_rule.id,
            "Check Correct Port forwarding Rule is returned"
        )

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

        nat_rule.delete(self.apiclient)

        try:
            list_nat_rule_response = list_nat_rules(
                self.apiclient,
                id=nat_rule.id
            )
        except CloudstackAPIException:
            self.debug("Nat Rule is deleted")

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

            SshClient(
                ip_address.ipaddress.ipaddress,
                self.virtual_machine.ssh_port,
                self.virtual_machine.username,
                self.virtual_machine.password,
                retries=2,
                delay=0
            )
        return
Exemplo n.º 53
0
    def setUpClass(cls):
        cls.logger = MarvinLog(MarvinLog.LOGGER_TEST).get_logger()
        testClient = super(TestLoadBalance, cls).getClsTestClient()
        cls.apiclient = testClient.getApiClient()
        cls.services = testClient.getParsedTestDataConfig()

        # Get Zone, Domain and templates
        cls.domain = get_domain(cls.apiclient)
        cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
        cls.template = get_template(
            cls.apiclient,
            cls.zone.id
        )
        if cls.template == FAILED:
            assert False, "get_template() failed to return template with description %s" % cls.services["ostype"]

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

        # Create an account, network, VM and IP addresses
        cls.account = Account.create(
            cls.apiclient,
            cls.services["account"],
            admin=True,
            domainid=cls.domain.id
        )
        cls.service_offering = get_default_virtual_machine_offering(cls.apiclient)

        cls.network_offering = get_default_network_offering(cls.apiclient)
        cls.logger.debug("Network Offering '%s' selected", cls.network_offering.name)

        cls.vpc_offering = get_default_vpc_offering(cls.apiclient)
        cls.logger.debug("VPC Offering '%s' selected", cls.vpc_offering.name)

        cls.vpc1 = VPC.create(cls.apiclient,
                               cls.services['vpcs']['vpc1'],
                               vpcofferingid=cls.vpc_offering.id,
                               zoneid=cls.zone.id,
                               domainid=cls.domain.id,
                               account=cls.account.name)
        cls.logger.debug("VPC '%s' created, CIDR: %s", cls.vpc1.name, cls.vpc1.cidr)

        cls.default_allow_acl = get_network_acl(cls.apiclient, 'default_allow')
        cls.logger.debug("ACL '%s' selected", cls.default_allow_acl.name)

        cls.network1 = Network.create(cls.apiclient,
                                       cls.services['networks']['network1'],
                                       networkofferingid=cls.network_offering.id,
                                       aclid=cls.default_allow_acl.id,
                                       vpcid=cls.vpc1.id,
                                       zoneid=cls.zone.id,
                                       domainid=cls.domain.id,
                                       accountid=cls.account.name)
        cls.logger.debug("Network '%s' created, CIDR: %s, Gateway: %s", cls.network1.name, cls.network1.cidr, cls.network1.gateway)

        cls.vm_1 = VirtualMachine.create(
            cls.apiclient,
            cls.services["virtual_machine"],
            templateid=cls.template.id,
            accountid=cls.account.name,
            domainid=cls.account.domainid,
            serviceofferingid=cls.service_offering.id,
            networkids=[cls.network1.id]
        )
        cls.vm_2 = VirtualMachine.create(
            cls.apiclient,
            cls.services["virtual_machine"],
            templateid=cls.template.id,
            accountid=cls.account.name,
            domainid=cls.account.domainid,
            serviceofferingid=cls.service_offering.id,
            networkids=[cls.network1.id]
        )
        cls.vm_3 = VirtualMachine.create(
            cls.apiclient,
            cls.services["virtual_machine"],
            templateid=cls.template.id,
            accountid=cls.account.name,
            domainid=cls.account.domainid,
            serviceofferingid=cls.service_offering.id,
            networkids=[cls.network1.id]
        )

        cls.non_src_nat_ip = PublicIPAddress.create(cls.apiclient,
            zoneid=cls.zone.id,
            domainid=cls.account.domainid,
            accountid=cls.account.name,
            vpcid=cls.vpc1.id,
            networkid=cls.network1.id)
        cls.logger.debug("Public IP '%s' acquired, VPC: %s, Network: %s", cls.non_src_nat_ip.ipaddress.ipaddress, cls.vpc1.name, cls.network1.name)

        command = replaceNetworkACLList.replaceNetworkACLListCmd()
        command.aclid = cls.default_allow_acl.id
        command.publicipid = cls.non_src_nat_ip.ipaddress.id
        cls.apiclient.replaceNetworkACLList(command)

        cls._cleanup = [
            cls.account
        ]
Exemplo n.º 54
0
    def setUpClass(cls):
        testClient = super(TestPublicIP, cls).getClsTestClient()
        cls.apiclient = testClient.getApiClient()
        cls.services = testClient.getParsedTestDataConfig()

        # Get Zone, Domain and templates
        cls.domain = get_domain(cls.apiclient)
        cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
        cls.services['mode'] = cls.zone.networktype
        # Create Accounts & networks
        cls.account = Account.create(
            cls.apiclient,
            cls.services["account"],
            admin=True,
            domainid=cls.domain.id
        )

        cls.user = Account.create(
            cls.apiclient,
            cls.services["account"],
            domainid=cls.domain.id
        )
        cls.services["network"]["zoneid"] = cls.zone.id

        cls.network_offering = NetworkOffering.create(
            cls.apiclient,
            cls.services["network_offering"],
        )
        # Enable Network offering
        cls.network_offering.update(cls.apiclient, state='Enabled')

        cls.services["network"]["networkoffering"] = cls.network_offering.id
        cls.account_network = Network.create(
            cls.apiclient,
            cls.services["network"],
            cls.account.name,
            cls.account.domainid
        )
        cls.user_network = Network.create(
            cls.apiclient,
            cls.services["network"],
            cls.user.name,
            cls.user.domainid
        )

        # Create Source NAT IP addresses
        PublicIPAddress.create(
            cls.apiclient,
            cls.account.name,
            cls.zone.id,
            cls.account.domainid
        )
        PublicIPAddress.create(
            cls.apiclient,
            cls.user.name,
            cls.zone.id,
            cls.user.domainid
        )
        cls._cleanup = [
            cls.account_network,
            cls.user_network,
            cls.account,
            cls.user,
            cls.network_offering
        ]
        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_add_multiple_admins_in_project(self):
        """
            1. Create a User Account
            2. Add user account with 'Admin' project account role  and associate it with a Project role;
                The role defines what APIs are allowed/disallowed for the user: here, 'listPublicIpAddresses'
                is denied for the user account
            3. Execute the 'listPublicIpAddresses' API and verify/confirm that the user/account can execute the
            API as it is a project admin
        """
        self.useraccount = Account.create(self.apiclient,
                                          self.testdata["account"],
                                          roleid=4)
        self.cleanup.append(self.useraccount)

        self.useraccount1 = Account.create(self.apiclient,
                                           self.testdata["useracc"],
                                           roleid=4)

        self.cleanup.append(self.useraccount1)

        self.project.addAccount(self.apiclient,
                                account=self.useraccount.name,
                                projectroleid=self.projectrole.id,
                                roletype='Admin')

        self.project.addAccount(self.apiclient,
                                account=self.useraccount1.name,
                                projectroleid=self.projectrole.id)

        project_accounts = Project.listAccounts(self.apiclient,
                                                projectid=self.project.id,
                                                role='Admin')
        self.assertEqual(len(project_accounts), 2,
                         "account not added with admin Role")

        self.userapiclientAdminRole = self.testClient.getUserApiClient(
            UserName=self.useraccount.name,
            DomainName=self.useraccount.domain,
            type=0)

        self.userapiclientRegularRole = self.testClient.getUserApiClient(
            UserName=self.useraccount1.name,
            DomainName=self.useraccount1.domain,
            type=0)

        try:
            PublicIPAddress.list(self.userapiclientAdminRole,
                                 projectid=self.project.id)
            self.debug(
                "User added to the project could execute the listPublicIpAddresses API despite the project "
                "role as it is the Admin")
            pass
        except CloudstackAPIException:
            self.fail(
                "User is an Admin, should be able to execute the command despite Project role"
            )

        try:
            self.project.suspend(self.userapiclientAdminRole, )
            self.debug(
                "The user can perform Project administrative operations as it is added as "
                "an Admin to the project")
            pass
        except CloudstackAPIException:
            self.fail(
                "User should be allowed to execute project administrative operations"
                "as it is the Project Admin")

        try:
            self.project.suspend(self.userapiclientRegularRole, )
        except Exception as e:
            pass
Exemplo n.º 57
0
    def test_network_rules_acquired_public_ip(self, value):
        """Test for Router rules for network rules on acquired public IP"""

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

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

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

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

        response = self.getCommandResultFromRouter(router, "ip addr")
        logger.debug(response)
        stringToMatch = "inet %s" % self.ipaddress.ipaddress.ipaddress
        self.assertTrue(stringToMatch in str(response), "IP address is\
                not added to the VR!")

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

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

        self.removeNetworkRules(rule=value)

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

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

            SshClient(
                self.ipaddress.ipaddress.ipaddress,
                self.virtual_machine.ssh_port,
                self.virtual_machine.username,
                self.virtual_machine.password,
                retries=2,
                delay=0
            )
        return
Exemplo n.º 58
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
Exemplo n.º 59
0
    def create_vm(self, pfrule=False, egress_policy=True, RR=False):
        self.create_network_offering(egress_policy, RR)
        # Creating network using the network offering created
        self.debug("Creating network with network offering: %s" %
                   self.network_offering.id)
        self.network = Network.create(
            self.apiclient,
            self.services["network"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            networkofferingid=self.network_offering.id,
            zoneid=self.zone.id)
        self.cleanup_networks.append(self.network)
        self.debug("Created network with ID: %s" % self.network.id)
        self.debug("Deploying instance in the account: %s" % self.account.name)

        project = None
        try:
            self.virtual_machine = VirtualMachine.create(
                self.apiclient,
                self.services["virtual_machine"],
                accountid=self.account.name,
                domainid=self.domain.id,
                serviceofferingid=self.service_offering.id,
                mode=self.zone.networktype if pfrule else 'basic',
                networkids=[str(self.network.id)],
                projectid=project.id if project else None)
            self.cleanup_vms.append(self.virtual_machine)
        except Exception as e:
            self.fail("Virtual machine deployment failed with exception: %s" %
                      e)
        self.debug("Deployed instance %s in account: %s" %
                   (self.virtual_machine.id, self.account.name))

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

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

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

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

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