Exemple #1
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
Exemple #2
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 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 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 test_router_common(self):
        """Performs common router tests and returns router public_ips"""

        routers = list_routers(self.apiclient,
                               account=self.account.name,
                               domainid=self.account.domainid)

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

        self.assertTrue(len(routers) >= 1, "Check list router response")

        router = routers[0]

        self.assertEqual(router.state, 'Running',
                         "Check list router response for router state")

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

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

        self.assertTrue(
            len(public_ips) >= 1, "Check public IP list has at least one IP")

        return public_ips
Exemple #6
0
    def test_releaseIP(self):
        """Test for release public IP address"""

        logger.debug("Deleting Public IP : %s" % self.ip_addr.id)

        self.ip_address.delete(self.apiclient)

        retriesCount = 10
        isIpAddressDisassociated = False
        while retriesCount > 0:
            listResponse = list_publicIP(
                self.apiclient,
                id=self.ip_addr.id
            )
            if listResponse is None:
                isIpAddressDisassociated = True
                break
            retriesCount -= 1
            time.sleep(60)
        # End while

        self.assertTrue(
            isIpAddressDisassociated,
            "Failed to disassociate IP address")

        # ListPortForwardingRules should not list
        # associated rules with Public IP address
        try:
            list_nat_rule = list_nat_rules(
                self.apiclient,
                id=self.nat_rule.id
            )
            logger.debug("List NAT Rule response" + str(list_nat_rule))
        except CloudstackAPIException:
            logger.debug("Port Forwarding Rule is deleted")

        # listLoadBalancerRules should not list
        # associated rules with Public IP address
        try:
            list_lb_rule = list_lb_rules(
                self.apiclient,
                id=self.lb_rule.id
            )
            logger.debug("List LB Rule response" + str(list_lb_rule))
        except CloudstackAPIException:
            logger.debug("Port Forwarding Rule is deleted")

        # SSH Attempt though public IP should fail
        with self.assertRaises(Exception):
            SshClient(
                self.ip_addr.ipaddress,
                self.services["natrule"]["publicport"],
                self.virtual_machine.username,
                self.virtual_machine.password,
                retries=2,
                delay=0
            )
        return
    def test_releaseIP(self):
        """Test for release public IP address"""

        self.debug("Deleting Public IP : %s" % self.ip_addr.id)

        self.ip_address.delete(self.apiclient)

        retriesCount = 10
        isIpAddressDisassociated = False
        while retriesCount > 0:
            listResponse = list_publicIP(
                self.apiclient,
                id=self.ip_addr.id
            )
            if listResponse is None:
                isIpAddressDisassociated = True
                break
            retriesCount -= 1
            time.sleep(60)
        # End while

        self.assertTrue(
            isIpAddressDisassociated,
            "Failed to disassociate IP address")

        # ListPortForwardingRules should not list
        # associated rules with Public IP address
        try:
            list_nat_rule = list_nat_rules(
                self.apiclient,
                id=self.nat_rule.id
            )
            self.debug("List NAT Rule response" + str(list_nat_rule))
        except CloudstackAPIException:
            self.debug("Port Forwarding Rule is deleted")

        # listLoadBalancerRules should not list
        # associated rules with Public IP address
        try:
            list_lb_rule = list_lb_rules(
                self.apiclient,
                id=self.lb_rule.id
            )
            self.debug("List LB Rule response" + str(list_lb_rule))
        except CloudstackAPIException:
            self.debug("Port Forwarding Rule is deleted")

        # SSH Attempt though public IP should fail
        with self.assertRaises(Exception):
            SshClient(
                self.ip_addr.ipaddress,
                self.services["natrule"]["publicport"],
                self.virtual_machine.username,
                self.virtual_machine.password,
                retries=2,
                delay=0
            )
        return
    def test_isolate_network_FW_PF_default_routes(self):
        """Stop existing router, add a PF rule and check we can access the VM """

        self.logger.debug("Starting test_isolate_network_FW_PF_default_routes...")
        routers = list_routers(self.apiclient, account=self.account.name, domainid=self.account.domainid)

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

        self.assertNotEqual(len(routers), 0, "Check list router response")

        router = routers[0]

        self.assertEqual(router.state, "Running", "Check list router response for router state")

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

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

        public_ip = public_ips[0]

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

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

        nat_rules = list_nat_rules(self.apiclient, id=nat_rule.id)
        self.assertEqual(isinstance(nat_rules, list), True, "Check for list NAT rules response return valid data")
        self.assertEqual(nat_rules[0].state, "Active", "Check list port forwarding rules")

        result = "failed"
        try:
            ssh_command = "ping -c 3 8.8.8.8"
            self.logger.debug("SSH into VM with ID: %s" % nat_rule.ipaddress)

            ssh = self.vm_1.get_ssh_client(
                ipaddress=nat_rule.ipaddress, port=self.services["natrule"]["publicport"], retries=5
            )
            result = str(ssh.execute(ssh_command))
            self.logger.debug("SSH result: %s; COUNT is ==> %s" % (result, result.count("3 packets received")))
        except:
            self.fail("Failed to SSH into VM - %s" % (public_ip.ipaddress.ipaddress))

        self.assertEqual(result.count("3 packets received"), 1, "Ping to outside world from VM should be successful")
        return
Exemple #9
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
Exemple #10
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 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)

        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:
            self.fail("SSH failed for VM with IP: %s %s" %
                      (src_nat_ip_addr.ipaddress, e))

        self.lb_rule = LoadBalancerRule.create(self.apiclient,
                                               self.services["lbrule"],
                                               src_nat_ip_addr.id,
                                               self.account.name)
        self.lb_rule.assign(self.apiclient, [self.vm_1])

        self.nat_rule = NATRule.create(self.apiclient, self.vm_1,
                                       self.services["natrule"],
                                       src_nat_ip_addr.id)
        self.cleanup = []
        return
    def test_router_common(self):
        """Performs common router tests and returns router public_ips"""

        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid
        )

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

        self.assertTrue(
            len(routers) >= 1,
            "Check list router response"
        )

        router = routers[0]

        self.assertEqual(
            router.state,
            'Running',
            "Check list router response for router state"
        )

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

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

        self.assertTrue(
            len(public_ips) >= 1,
            "Check public IP list has at least one IP"
        )

        return public_ips
    def test_router_dhcphosts(self):
        """Check that the /etc/dhcphosts.txt doesn't contain duplicate IPs"""

        self.logger.debug("Starting test_router_dhcphosts...")
        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid
        )

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

        self.assertNotEqual(
            len(routers),
            0,
            "Check list router response"
        )

        router = routers[0]

        self.assertEqual(
            router.state,
            'Running',
            "Check list router response for router state"
        )

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

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

        public_ip = public_ips[0]

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

        self.logger.debug("Creating NAT rule for VM ID: %s" % self.vm_1.id)
        # Create NAT rule
        nat_rule1 = NATRule.create(
            self.apiclient,
            self.vm_1,
            self.services["natrule1"],
            public_ip.id
        )

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

        self.logger.debug("Creating NAT rule for VM ID: %s" % self.vm_2.id)
        # Create NAT rule
        nat_rule2 = NATRule.create(
            self.apiclient,
            self.vm_2,
            self.services["natrule2"],
            public_ip.id
        )

        nat_rules = list_nat_rules(
            self.apiclient,
            id=nat_rule1.id
        )
        self.assertEqual(
            isinstance(nat_rules, list),
            True,
            "Check for list NAT rules response return valid data"
        )
        self.assertEqual(
            nat_rules[0].state,
            'Active',
            "Check list port forwarding rules"
        )

        nat_rules = list_nat_rules(
            self.apiclient,
            id=nat_rule2.id
        )
        self.assertEqual(
            isinstance(nat_rules, list),
            True,
            "Check for list NAT rules response return valid data"
        )
        self.assertEqual(
            nat_rules[0].state,
            'Active',
            "Check list port forwarding rules"
        )

        self.logger.debug("Testing SSH to VMs %s and %s" % (self.vm_1.id, self.vm_2.id))
        self.test_ssh_command(self.vm_1, nat_rule1, "natrule1")
        self.test_ssh_command(self.vm_2, nat_rule2, "natrule2")

        self.logger.debug("Testing DHCP hosts for VMs %s and %s" % (self.vm_1.id, self.vm_2.id))
        self.test_dhcphosts(self.vm_1, router)
        self.test_dhcphosts(self.vm_2, router)

        self.logger.debug("Deleting and Expunging VM %s with ip %s" % (self.vm_1.id, self.vm_1.nic[0].ipaddress))
        self.vm_1.delete(self.apiclient)

        self.logger.debug("Creating new VM using the same IP as the one which was deleted => IP 10.1.1.50")
        self.vm_1 = VirtualMachine.create(self.apiclient,
                                         self.services["virtual_machine"],
                                         templateid=self.template.id,
                                         accountid=self.account.name,
                                         domainid=self.domain.id,
                                         serviceofferingid=self.service_offering.id,
                                         networkids=[str(self.network.id)],
                                         ipaddress="10.1.1.50")

        self.cleanup.append(self.vm_1)

        self.logger.debug("Testing DHCP hosts for VMs %s and %s" % (self.vm_1.id, self.vm_2.id))
        self.test_dhcphosts(self.vm_1, router)
        self.test_dhcphosts(self.vm_2, router)

        return
    def test_isolate_network_FW_PF_default_routes(self):
        """Stop existing router, add a PF rule and check we can access the VM """

        self.logger.debug("Starting test_isolate_network_FW_PF_default_routes...")
        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid
        )

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

        self.assertNotEqual(
            len(routers),
            0,
            "Check list router response"
        )

        router = routers[0]

        self.assertEqual(
            router.state,
            'Running',
            "Check list router response for router state"
        )

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

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

        public_ip = public_ips[0]

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

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

        nat_rules = list_nat_rules(
            self.apiclient,
            id=nat_rule.id
        )
        self.assertEqual(
            isinstance(nat_rules, list),
            True,
            "Check for list NAT rules response return valid data"
        )
        self.assertEqual(
            nat_rules[0].state,
            'Active',
            "Check list port forwarding rules"
        )

        result = 'failed'
        try:
            ssh_command = "ping -c 3 8.8.8.8"
            self.logger.debug("SSH into VM with IP: %s" % nat_rule.ipaddress)

            ssh = self.vm_1.get_ssh_client(ipaddress=nat_rule.ipaddress, port=self.services["natrule"]["publicport"], retries=5)
            result = str(ssh.execute(ssh_command))
            self.logger.debug("SSH result: %s; COUNT is ==> %s" % (result, result.count("3 packets received")))
        except:
            self.fail("Failed to SSH into VM - %s" % (nat_rule.ipaddress))

        self.assertEqual(
                         result.count("3 packets received"),
                         1,
                         "Ping to outside world from VM should be successful"
                         )
        return
Exemple #14
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
Exemple #15
0
    def test_isolate_network_password_server(self):
        """Check the password file in the Router VM"""

        self.logger.debug("Starting test_isolate_network_password_server...")
        routers = list_routers(self.apiclient,
                               account=self.account.name,
                               domainid=self.account.domainid)

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

        self.assertNotEqual(len(routers), 0, "Check list router response")

        router = routers[0]

        self.assertEqual(router.state, 'Running',
                         "Check list router response for router state")

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

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

        public_ip = public_ips[0]

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

        self.logger.debug("Creating NAT rule for VM ID: %s" % self.vm_1.id)
        # Create NAT rule
        nat_rule1 = NATRule.create(self.apiclient, self.vm_1,
                                   self.services["natrule1"], public_ip.id)

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

        self.logger.debug("Creating NAT rule for VM ID: %s" % self.vm_2.id)
        # Create NAT rule
        nat_rule2 = NATRule.create(self.apiclient, self.vm_2,
                                   self.services["natrule2"], public_ip.id)

        nat_rules = list_nat_rules(self.apiclient, id=nat_rule1.id)
        self.assertEqual(
            isinstance(nat_rules, list), True,
            "Check for list NAT rules response return valid data")
        self.assertEqual(nat_rules[0].state, 'Active',
                         "Check list port forwarding rules")

        nat_rules = list_nat_rules(self.apiclient, id=nat_rule2.id)
        self.assertEqual(
            isinstance(nat_rules, list), True,
            "Check for list NAT rules response return valid data")
        self.assertEqual(nat_rules[0].state, 'Active',
                         "Check list port forwarding rules")

        self.test_ssh_command(self.vm_1, nat_rule1, "natrule1")
        self.test_ssh_command(self.vm_2, nat_rule2, "natrule2")

        self.test_password_file_not_empty(self.vm_1, router)
        self.test_password_file_not_empty(self.vm_2, router)

        return
Exemple #16
0
    def test_01_RouterStopCreatePF(self):
        """Test router stop create port forwarding
        """
        # validate the following
        # 1. wait for router to start, guest network to be implemented and
        #    VM to report Running
        # 2. stopRouter for this account
        # 3. wait for listRouters to report Router as 'Stopped'
        # 4. listPublicIpAddresses account=user, domainid=1 - pick ipaddressid
        # 5. createPortForwardingRule (ipaddressid from step 5.)
        #    a. for port 22 (ssh) for user VM deployed in step 1.
        #    b. public port 22 , private port 22
        # 6. startRouter stopped for this account
        # 7. wait for listRouters to show router as Running

        # Get router details associated for that account
        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
        )

        self.assertEqual(
            isinstance(routers, list),
            True,
            "Check for list routers response return valid data"
        )
        self.assertNotEqual(
            len(routers),
            0,
            "Check list router response"
        )
        router = routers[0]

        self.debug("Stopping router ID: %s" % router.id)

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

        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
        )
        self.assertEqual(
            isinstance(routers, list),
            True,
            "Check for list routers response return valid data"
        )
        router = routers[0]

        self.assertEqual(
            router.state,
            'Stopped',
            "Check list router response for router state"
        )

        public_ips = list_publicIP(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
            zoneid=self.zone.id
        )
        self.assertEqual(
            isinstance(public_ips, list),
            True,
            "Check for list public IPs response return valid data"
        )

        public_ip = public_ips[0]

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

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

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

        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
            zoneid=self.zone.id
        )
        self.assertEqual(
            isinstance(routers, list),
            True,
            "Check for list routers response return valid data"
        )
        router = routers[0]

        self.assertEqual(
            router.state,
            'Running',
            "Check list router response for router state"
        )
        # NAT Rule should be in Active state after router start
        nat_rules = list_nat_rules(
            self.apiclient,
            id=nat_rule.id
        )
        self.assertEqual(
            isinstance(nat_rules, list),
            True,
            "Check for list NAT rules response return valid data"
        )
        self.assertEqual(
            nat_rules[0].state,
            'Active',
            "Check list port forwarding rules"
        )
        try:

            self.debug("SSH into VM with ID: %s" % nat_rule.ipaddress)

            self.vm_1.get_ssh_client(
                ipaddress=nat_rule.ipaddress,
                port=self.services["natrule"]["publicport"])
        except Exception as e:
            self.fail(
                "SSH Access failed for %s: %s" %
                (nat_rule.ipaddress, e)
            )
        return
    def test_RVR_Network_FW_PF_SSH_default_routes(self):
        """ Test redundant router internals """
        self.logger.debug("Starting test_RVR_Network_FW_PF_SSH_default_routes...")

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

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

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

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

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

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

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

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

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

        public_ip_1 = public_ips[0]

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

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

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

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

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

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

        return
    def test_router_dhcphosts(self):
        """Check that the /etc/dhcphosts.txt doesn't contain duplicate IPs"""

        self.logger.debug("Starting test_router_dhcphosts...")
        routers = list_routers(self.apiclient,
                               account=self.account.name,
                               domainid=self.account.domainid)

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

        self.assertNotEqual(len(routers), 0, "Check list router response")

        router = routers[0]

        self.assertEqual(router.state, 'Running',
                         "Check list router response for router state")

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

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

        public_ip = public_ips[0]

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

        self.logger.debug("Creating NAT rule for VM ID: %s" % self.vm_1.id)
        # Create NAT rule
        nat_rule1 = NATRule.create(self.apiclient, self.vm_1,
                                   self.services["natrule1"], public_ip.id)

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

        self.logger.debug("Creating NAT rule for VM ID: %s" % self.vm_2.id)
        # Create NAT rule
        nat_rule2 = NATRule.create(self.apiclient, self.vm_2,
                                   self.services["natrule2"], public_ip.id)

        nat_rules = list_nat_rules(self.apiclient, id=nat_rule1.id)
        self.assertEqual(
            isinstance(nat_rules, list), True,
            "Check for list NAT rules response return valid data")
        self.assertEqual(nat_rules[0].state, 'Active',
                         "Check list port forwarding rules")

        nat_rules = list_nat_rules(self.apiclient, id=nat_rule2.id)
        self.assertEqual(
            isinstance(nat_rules, list), True,
            "Check for list NAT rules response return valid data")
        self.assertEqual(nat_rules[0].state, 'Active',
                         "Check list port forwarding rules")

        self.logger.debug("Testing SSH to VMs %s and %s" %
                          (self.vm_1.id, self.vm_2.id))
        self.test_ssh_command(self.vm_1, nat_rule1, "natrule1")
        self.test_ssh_command(self.vm_2, nat_rule2, "natrule2")

        self.logger.debug("Testing DHCP hosts for VMs %s and %s" %
                          (self.vm_1.id, self.vm_2.id))
        self.test_dhcphosts(self.vm_1, router)
        self.test_dhcphosts(self.vm_2, router)

        self.logger.debug("Deleting and Expunging VM %s with ip %s" %
                          (self.vm_1.id, self.vm_1.nic[0].ipaddress))
        self.vm_1.delete(self.apiclient)

        self.logger.debug(
            "Creating new VM using the same IP as the one which was deleted => IP 10.1.1.50"
        )
        self.vm_1 = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            templateid=self.template.id,
            accountid=self.account.name,
            domainid=self.domain.id,
            serviceofferingid=self.service_offering.id,
            networkids=[str(self.network.id)],
            ipaddress="10.1.1.50")

        self.cleanup.append(self.vm_1)

        self.logger.debug("Testing DHCP hosts for VMs %s and %s" %
                          (self.vm_1.id, self.vm_2.id))
        self.test_dhcphosts(self.vm_1, router)
        self.test_dhcphosts(self.vm_2, router)

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

        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:
            self.fail("SSH failed for VM with IP: %s %s" %
                      (src_nat_ip_addr.ipaddress, e))

        self.lb_rule = LoadBalancerRule.create(
            self.apiclient,
            self.services["lbrule"],
            src_nat_ip_addr.id,
            self.account.name
        )
        self.lb_rule.assign(self.apiclient, [self.vm_1])

        self.nat_rule = NATRule.create(
            self.apiclient,
            self.vm_1,
            self.services["natrule"],
            src_nat_ip_addr.id
        )
        self.cleanup = []
        return
    def test_02_isolate_network_FW_PF_default_routes_egress_false(self):
        """ Test redundant router internals """
        self.logger.debug("Starting test_02_isolate_network_FW_PF_default_routes_egress_false...")

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

        network_offering_egress_false.update(self.apiclient, state='Enabled')

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

        self.logger.debug("Deploying Virtual Machine on Network %s" % network.id)
        virtual_machine = VirtualMachine.create(self.apiclient,
                                         self.services["virtual_machine"],
                                         templateid=self.template.id,
                                         accountid=self.account.name,
                                         domainid=self.domain.id,
                                         serviceofferingid=self.service_offering.id,
                                         networkids=[str(network.id)])

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

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

        self.logger.debug("Starting test_isolate_network_FW_PF_default_routes...")
        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid
        )

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

        self.assertNotEqual(
            len(routers),
            0,
            "Check list router response"
        )

        router = routers[0]

        self.assertEqual(
            router.state,
            'Running',
            "Check list router response for router state"
        )

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

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

        public_ip = public_ips[0]

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

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

        nat_rules = list_nat_rules(
            self.apiclient,
            id=nat_rule.id
        )
        self.assertEqual(
            isinstance(nat_rules, list),
            True,
            "Check for list NAT rules response return valid data"
        )
        self.assertEqual(
            nat_rules[0].state,
            'Active',
            "Check list port forwarding rules"
        )

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

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

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

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

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

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

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

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

        self.logger.debug("Creating Network Offering with default egress TRUE")
        network_offering_egress_true = NetworkOffering.create(self.apiclient,
                                                       self.services["network_offering_egress_true"],
                                                       conservemode=True)

        network_offering_egress_true.update(self.apiclient, state='Enabled')

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

        self.logger.debug("Deploying Virtual Machine on Network %s" % network.id)
        virtual_machine = VirtualMachine.create(self.apiclient,
                                         self.services["virtual_machine"],
                                         templateid=self.template.id,
                                         accountid=self.account.name,
                                         domainid=self.domain.id,
                                         serviceofferingid=self.service_offering.id,
                                         networkids=[str(network.id)])

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

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

        self.logger.debug("Starting test_isolate_network_FW_PF_default_routes...")
        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid
        )

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

        self.assertNotEqual(
            len(routers),
            0,
            "Check list router response"
        )

        router = routers[0]

        self.assertEqual(
            router.state,
            'Running',
            "Check list router response for router state"
        )

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

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

        public_ip = public_ips[0]

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

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

        nat_rules = list_nat_rules(
            self.apiclient,
            id=nat_rule.id
        )
        self.assertEqual(
            isinstance(nat_rules, list),
            True,
            "Check for list NAT rules response return valid data"
        )
        self.assertEqual(
            nat_rules[0].state,
            'Active',
            "Check list port forwarding rules"
        )

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        public_ip = public_ips[0]

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

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

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

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

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

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

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

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

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

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

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

        self.logger.debug("Creating Network Offering with default egress TRUE")
        network_offering_egress_true = NetworkOffering.create(
                                            self.apiclient,
                                            self.services["nw_off_persistent_RVR_egress_true"],
                                            conservemode=True
                                            )
        network_offering_egress_true.update(self.api_client, state='Enabled')

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

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

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

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

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

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

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

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

        public_ip = public_ips[0]

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

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

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

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

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

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

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

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

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

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

        return
Exemple #24
0
    def test_01_RouterStopCreateLB(self):
        """Test router stop create Load balancing
        """
        # validate the following
        # 1. listLoadBalancerRules (publicipid=ipaddressid of source NAT)
        # 2. rule should be for port 22 as applied and
        #    should be in state=Active
        # 3. ssh access should be allowed to the userVMs over the source NAT IP
        #    and port 22

        # Get router details associated for that account
        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
        )

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

        self.assertNotEqual(
            len(routers),
            0,
            "Check list router response"
        )

        router = routers[0]

        self.debug("Stopping router with ID: %s" % router.id)
        # Stop the router
        cmd = stopRouter.stopRouterCmd()
        cmd.id = router.id
        self.apiclient.stopRouter(cmd)

        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
        )
        self.assertEqual(
            isinstance(routers, list),
            True,
            "Check for list routers response return valid data"
        )
        router = routers[0]

        self.assertEqual(
            router.state,
            'Stopped',
            "Check list router response for router state"
        )

        public_ips = list_publicIP(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid
        )
        self.assertEqual(
            isinstance(public_ips, list),
            True,
            "Check for list public IPs response return valid data"
        )
        public_ip = public_ips[0]

        # Open up firewall port for SSH
        FireWallRule.create(
            self.apiclient,
            ipaddressid=public_ip.id,
            protocol=self.services["lbrule"]["protocol"],
            cidrlist=['0.0.0.0/0'],
            startport=self.services["lbrule"]["publicport"],
            endport=self.services["lbrule"]["publicport"]
        )
        self.debug("Creating LB rule for public IP: %s" % public_ip.id)
        # Create Load Balancer rule and assign VMs to rule
        lb_rule = LoadBalancerRule.create(
            self.apiclient,
            self.services["lbrule"],
            public_ip.id,
            accountid=self.account.name
        )
        self.debug("Assigning VM %s to LB rule: %s" % (
            self.vm_1.id,
            lb_rule.id
        ))
        lb_rule.assign(self.apiclient, [self.vm_1])

        # Start the router
        cmd = startRouter.startRouterCmd()
        cmd.id = router.id
        self.apiclient.startRouter(cmd)

        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
        )
        self.assertEqual(
            isinstance(routers, list),
            True,
            "Check for list routers response return valid data"
        )
        router = routers[0]

        self.assertEqual(
            router.state,
            'Running',
            "Check list router response for router state"
        )
        # After router start, LB RUle should be in Active state
        lb_rules = list_lb_rules(
            self.apiclient,
            id=lb_rule.id
        )
        self.assertEqual(
            isinstance(lb_rules, list),
            True,
            "Check for list LB rules response return valid data"
        )
        self.assertEqual(
            lb_rules[0].state,
            'Active',
            "Check list load balancing rules"
        )
        self.assertEqual(
            lb_rules[0].publicport,
            str(self.services["lbrule"]["publicport"]),
            "Check list load balancing rules"
        )

        try:
            self.debug("SSH into VM with IP: %s" % public_ip.ipaddress)
            self.vm_1.ssh_port = self.services["lbrule"]["publicport"]
            self.vm_1.get_ssh_client(public_ip.ipaddress)
        except Exception as e:
            self.fail(
                "SSH Access failed for %s: %s" %
                (self.vm_1.ipaddress, e)
            )
        return
    def test_router_dhcp_opts(self):
        """Check that the /etc/dhcpopts.txt has entries for the"""

        self.logger.debug("Starting test_router_dhcphosts...")
        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
            networkid=self.network1.id
        )
        self.assertEqual(
            isinstance(routers, list),
            True,
            "Check for list routers response return valid data"
        )

        self.assertNotEqual(
            len(routers),
            0,
            "Check list router response"
        )
        network1_router = routers[0]

        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
            networkid=self.network2.id
        )
        self.assertEqual(
            isinstance(routers, list),
            True,
            "Check for list routers response return valid data"
        )

        self.assertNotEqual(
            len(routers),
            0,
            "Check list router response"
        )
        network2_router = routers[0]

        self.assertEqual(
            network1_router.state,
            'Running',
            "Check list router response for router state"
        )
        self.assertEqual(
            network2_router.state,
            'Running',
            "Check list router response for router state"
        )
        public_ips = list_publicIP(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
            zoneid=self.zone.id,
            associatednetworkid=self.network1.id
        )

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

        network1_public_ip = public_ips[0]

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

        self.assertEqual(
            isinstance(public_ips, list),
            True,
            "Check for list public IPs response return valid data"
        )
        network2_public_ip = public_ips[0]

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

        self.logger.debug("Creating NAT rule for VM ID: %s" % self.vm_1.id)
        # Create NAT rule
        nat_rule1 = NATRule.create(
            self.apiclient,
            self.vm_1,
            self.services["natrule1"],
            network1_public_ip.id
        )

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

        self.logger.debug("Creating NAT rule for VM ID: %s" % self.vm_2.id)
        # Create NAT rule
        nat_rule2 = NATRule.create(
            self.apiclient,
            self.vm_2,
            self.services["natrule2"],
            network2_public_ip.id
        )

        nat_rules = list_nat_rules(
            self.apiclient,
            id=nat_rule1.id
        )
        self.assertEqual(
            isinstance(nat_rules, list),
            True,
            "Check for list NAT rules response return valid data"
        )
        self.assertEqual(
            nat_rules[0].state,
            'Active',
            "Check list port forwarding rules"
        )

        nat_rules = list_nat_rules(
            self.apiclient,
            id=nat_rule2.id
        )
        self.assertEqual(
            isinstance(nat_rules, list),
            True,
            "Check for list NAT rules response return valid data"
        )
        self.assertEqual(
            nat_rules[0].state,
            'Active',
            "Check list port forwarding rules"
        )

        self.logger.debug("Testing DHCP options for VMs %s and %s" % (self.vm_1.id, self.vm_2.id))
        self.test_dhcphopts(self.vm_2.nic[1].ipaddress, network1_router)
        self.test_dhcphopts(self.vm_1.nic[0].ipaddress, network2_router)

        return
    def test_01_RouterStopCreateLB(self):
        """Test router stop create Load balancing
        """
        # validate the following
        # 1. listLoadBalancerRules (publicipid=ipaddressid of source NAT)
        # 2. rule should be for port 22 as applied and
        #    should be in state=Active
        # 3. ssh access should be allowed to the userVMs over the source NAT IP
        #    and port 22

        # Get router details associated for that account
        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
        )

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

        self.assertNotEqual(len(routers), 0, "Check list router response")

        router = routers[0]

        self.debug("Stopping router with ID: %s" % router.id)
        # Stop the router
        cmd = stopRouter.stopRouterCmd()
        cmd.id = router.id
        self.apiclient.stopRouter(cmd)

        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
        )
        self.assertEqual(isinstance(routers, list), True,
                         "Check for list routers response return valid data")
        router = routers[0]

        self.assertEqual(router.state, 'Stopped',
                         "Check list router response for router state")

        public_ips = list_publicIP(self.apiclient,
                                   account=self.account.name,
                                   domainid=self.account.domainid)
        self.assertEqual(
            isinstance(public_ips, list), True,
            "Check for list public IPs response return valid data")
        public_ip = public_ips[0]

        # Open up firewall port for SSH
        FireWallRule.create(self.apiclient,
                            ipaddressid=public_ip.id,
                            protocol=self.services["lbrule"]["protocol"],
                            cidrlist=['0.0.0.0/0'],
                            startport=self.services["lbrule"]["publicport"],
                            endport=self.services["lbrule"]["publicport"])
        self.debug("Creating LB rule for public IP: %s" % public_ip.id)
        # Create Load Balancer rule and assign VMs to rule
        lb_rule = LoadBalancerRule.create(self.apiclient,
                                          self.services["lbrule"],
                                          public_ip.id,
                                          accountid=self.account.name)
        self.debug("Assigning VM %s to LB rule: %s" %
                   (self.vm_1.id, lb_rule.id))
        lb_rule.assign(self.apiclient, [self.vm_1])

        # Start the router
        cmd = startRouter.startRouterCmd()
        cmd.id = router.id
        self.apiclient.startRouter(cmd)

        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
        )
        self.assertEqual(isinstance(routers, list), True,
                         "Check for list routers response return valid data")
        router = routers[0]

        self.assertEqual(router.state, 'Running',
                         "Check list router response for router state")
        # After router start, LB RUle should be in Active state
        lb_rules = list_lb_rules(self.apiclient, id=lb_rule.id)
        self.assertEqual(isinstance(lb_rules, list), True,
                         "Check for list LB rules response return valid data")
        self.assertEqual(lb_rules[0].state, 'Active',
                         "Check list load balancing rules")
        self.assertEqual(lb_rules[0].publicport,
                         str(self.services["lbrule"]["publicport"]),
                         "Check list load balancing rules")

        try:
            self.debug("SSH into VM with IP: %s" % public_ip.ipaddress)
            self.vm_1.ssh_port = self.services["lbrule"]["publicport"]
            self.vm_1.get_ssh_client(public_ip.ipaddress)
        except Exception as e:
            self.fail("SSH Access failed for %s: %s" %
                      (self.vm_1.ipaddress, e))
        return
    def test_01_port_fwd_on_src_nat(self):
        """Test for port forwarding on source NAT"""

        # Validate the following:
        # 1. listPortForwarding rules API should return the added PF rule
        # 2. attempt to do an ssh into the  user VM through the sourceNAT

        src_nat_ip_addrs = list_publicIP(
            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 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=src_nat_ip_addr.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"],
            src_nat_ip_addr.id
        )

        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"
        )
        # SSH virtual machine to test port forwarding
        try:
            self.debug("SSHing into VM with IP address %s with NAT IP %s" %
                       (
                           self.virtual_machine.ipaddress,
                           src_nat_ip_addr.ipaddress
                       ))

            self.virtual_machine.get_ssh_client(src_nat_ip_addr.ipaddress)
            vm_response = VirtualMachine.list(
                self.apiclient,
                id=self.virtual_machine.id
            )
            if vm_response[0].state != 'Running':
                self.fail(
                    "State of VM : %s is not found to be Running" % str(
                        self.virtual_machine.ipaddress))

        except Exception as e:
            self.fail(
                "SSH Access failed for %s: %s" %
                (self.virtual_machine.ipaddress, e)
            )

        try:
            nat_rule.delete(self.apiclient)
        except Exception as e:
            self.fail("NAT Rule Deletion Failed: %s" % e)

        # NAT rule listing should fail as the nat rule does not exist
        with self.assertRaises(Exception):
            list_nat_rules(self.apiclient,
                           id=nat_rule.id)

        # 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(
                src_nat_ip_addr.ipaddress,
                self.virtual_machine.ssh_port,
                self.virtual_machine.username,
                self.virtual_machine.password
            )
        return
    def test_router_dhcp_opts(self):
        """Check that the /etc/dhcpopts.txt has entries for the"""

        self.logger.debug("Starting test_router_dhcphosts...")
        routers = list_routers(self.apiclient,
                               account=self.account.name,
                               domainid=self.account.domainid,
                               networkid=self.network1.id)
        self.assertEqual(isinstance(routers, list), True,
                         "Check for list routers response return valid data")

        self.assertNotEqual(len(routers), 0, "Check list router response")
        network1_router = routers[0]

        routers = list_routers(self.apiclient,
                               account=self.account.name,
                               domainid=self.account.domainid,
                               networkid=self.network2.id)
        self.assertEqual(isinstance(routers, list), True,
                         "Check for list routers response return valid data")

        self.assertNotEqual(len(routers), 0, "Check list router response")
        network2_router = routers[0]

        self.assertEqual(network1_router.state, 'Running',
                         "Check list router response for router state")
        self.assertEqual(network2_router.state, 'Running',
                         "Check list router response for router state")
        public_ips = list_publicIP(self.apiclient,
                                   account=self.account.name,
                                   domainid=self.account.domainid,
                                   zoneid=self.zone.id,
                                   associatednetworkid=self.network1.id)

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

        network1_public_ip = public_ips[0]

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

        self.assertEqual(
            isinstance(public_ips, list), True,
            "Check for list public IPs response return valid data")
        network2_public_ip = public_ips[0]

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

        self.logger.debug("Creating NAT rule for VM ID: %s" % self.vm_1.id)
        # Create NAT rule
        nat_rule1 = NATRule.create(self.apiclient, self.vm_1,
                                   self.services["natrule1"],
                                   network1_public_ip.id)

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

        self.logger.debug("Creating NAT rule for VM ID: %s" % self.vm_2.id)
        # Create NAT rule
        nat_rule2 = NATRule.create(self.apiclient, self.vm_2,
                                   self.services["natrule2"],
                                   network2_public_ip.id)

        nat_rules = list_nat_rules(self.apiclient, id=nat_rule1.id)
        self.assertEqual(
            isinstance(nat_rules, list), True,
            "Check for list NAT rules response return valid data")
        self.assertEqual(nat_rules[0].state, 'Active',
                         "Check list port forwarding rules")

        nat_rules = list_nat_rules(self.apiclient, id=nat_rule2.id)
        self.assertEqual(
            isinstance(nat_rules, list), True,
            "Check for list NAT rules response return valid data")
        self.assertEqual(nat_rules[0].state, 'Active',
                         "Check list port forwarding rules")

        self.logger.debug("Testing DHCP options for VMs %s and %s" %
                          (self.vm_1.id, self.vm_2.id))
        self.test_dhcphopts(self.vm_2.nic[1].ipaddress, network1_router)
        self.test_dhcphopts(self.vm_1.nic[0].ipaddress, network2_router)

        return
    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
    def setUpClass(cls):
                    
        
        cloudstackTestClient = super(
                                     TestMultipleVPNAccessonVPC,
                                     cls
                                    ).getClsTestClient()
        
        cls.debug("Obtain the Admin's API Client")                                
        cls.api_client = cloudstackTestClient.getApiClient()
        cls.debug("Get the dictionary information that will be used during CCP tests, from test_data.py present on the Client")
        cls.services = cloudstackTestClient.getParsedTestDataConfig()
        
        if cls.services is None:
            cls.debug("Services Object is None")
            raise Exception("Services Object is None")
        
        cls.debug("Procure the CloudStack Setup configuration Information")
        with open(cls.services["config_path"], 'rb') as fp:
            cls.pullconfig = json.load(fp)
        
        cls.debug("Update 'remote.access.vpn.client.iprange','remote.access.vpn.user.limit','max.account.primary.storage','max.account.public.ips','max.account.user.vms','max.account.volumes','max.account.cpus', Global Configuration Parameters")
        
        update_vpn_client_iprange = Configurations.update(
            cls.api_client, 
            name="remote.access.vpn.client.iprange", 
            value="10.1.2.1-10.1.2.120")
        
        cls.debug("'remote.access.vpn.client.iprange' Global Configuration Parameter Updated Successfully")
        
        update_vpn_user_limit = Configurations.update(
            cls.api_client,
            name="remote.access.vpn.user.limit", 
            value=str(int(cls.services["vpnclient_count"]*2))
        )    
        
        cls.debug("'remote.access.vpn.user.limit' Global Configuration Parameter Updated Successfully")

        update_max_account_primary_stg_limit = Configurations.update(
            cls.api_client,
            name="max.account.primary.storage", 
            value=str(int(cls.services["vpnclient_count"]*20 + 100))
        )
        cls.debug("'max.account.primary.storage' Global Configuration Parameter Updated Successfully")

        update_max_account_public_ips_limit = Configurations.update(
            cls.api_client,
            name="max.account.public.ips", 
            value=str(int(cls.services["vpnclient_count"]*2 + 10))
        )
        cls.debug("'max.account.public.ips' Global Configuration Parameter Updated Successfully")
        
        update_max_account_user_vms_limit = Configurations.update(
            cls.api_client,
            name="max.account.user.vms", 
            value=str(int(cls.services["vpnclient_count"]*2))
        )
        cls.debug("'max.account.user.vms' Global Configuration Parameter Updated Successfully")
        
        update_max_account_volumes_limit = Configurations.update(
            cls.api_client,
            name="max.account.volumes", 
            value=str(int(cls.services["vpnclient_count"]*2))
        )
        cls.debug("'max.account.volumes' Global Configuration Parameter Updated Successfully")

        update_max_account_cpus_limit = Configurations.update(
            cls.api_client,
            name="max.account.cpus", 
            value=str(int(cls.services["vpnclient_count"]*2))
        )
        cls.debug("'max.account.cpus' Global Configuration Parameter Updated Successfully")
        
        cls.debug("Restart the Management Server")
        TestMultipleVPNAccessonVPC.restart_mgmt_server(cls.services["config_path"])
        cls.debug("Completed restarting the Management Server")
        
        cls.debug("Wait for 120 seconds...")
        time.sleep(120)
        cls.debug("End of 120 seconds wait time....")
        
        # Get Zone, Domain and templates
        cls.domain = get_domain(cls.api_client)
        cls.zone = get_zone(
            cls.api_client,
            zone_name = cls.services["zone_vpn"]["name"])
        
        cls.debug("Use an Existing 'Tiny Instance' Service Offering on the Setup")
        list_service_offerings = []
        list_service_offerings = list_service_offering(
            cls.api_client,
            keyword="Tiny Instance",
        )
        
        cls._cleanup = []
            
        if list_service_offerings is not None:
            cls.debug("Found an Existing 'Tiny Instance' Service Offering on the Setup")
            cls.service_offering = list_service_offerings[0]
            
        else:
            cls.debug("Create a service offering which will be used for VM deployments in this test")
            cls.service_offering = ServiceOffering.create(
                cls.api_client,
                cls.services["service_offering"]
            )
            
            cls.debug("Add the created service offering to the _cleanup queue")
            cls._cleanup.append(cls.service_offering)
        
        try:
            cls.debug("Create or Use Existing Account to own the VPN Clients, which is used to test Remote VPN Access to VPC")
            cls.api_client_vpn_client_reg_user = cloudstackTestClient.getUserApiClient(
                UserName="******",
                DomainName="ROOT"
            )

            list_vpn_client_regular_user = User.list(
                cls.api_client,
                username="******"
            )
            
            cls.debug("Procure the Account Name and DomainID Information of the Regular Account")
            cls.vpn_client_reg_acct_name = list_vpn_client_regular_user[0].account
            cls.vpn_client_reg_domain_id = list_vpn_client_regular_user[0].domainid
            
            list_vpn_client_regular_user_acct = Account.list(
                cls.api_client,
                name = cls.vpn_client_reg_acct_name,
                listall = True
            )
            
            cls._cleanup.append(Account(list_vpn_client_regular_user_acct[0].__dict__))
            
            # Register a Template that already has VPN client installed on it. The template registered here
            # has extra scripts to facilitate automated operations to execute Test Cases.
            # Template has pre-configured configuration files required for the VPN Client operations.
            # The following files are present on the registered template. The location of the files are locations
            # on a VM deployed from this template
            #            1. "/tmp/ipsec.conf"
            #            2. "/tmp/ipsec.secrets"
            #            3. "/tmp/options.xl2tpd.client"
            #            4. "/tmp/xl2tpd.conf"
            #            5  "/tmp/vpnclient_services.sh"
            #            6. "/tmp/firstconn_expectscript.exp"
            #            7. "/tmp/secondconn_expectscript.exp"
            
            cls.debug("Use an Existing VPN Client Template on the Setup")
            list_vpn_client_templates = list_templates(
                cls.api_client_vpn_client_reg_user,
                keyword="VPNClient",
                templatefilter="featured",
                zoneid = cls.zone.id
            )
            
            if list_vpn_client_templates is not None:
                cls.debug("Found an Existing VPN Client Template on the Setup")
                cls.template = list_vpn_client_templates[0]
            
            else:
                cls.debug("Register a Template that already has VPN client installed on it")
                cls.template = Template.register(
                    cls.api_client, 
                    cls.services["vpn_template"], 
                    zoneid=cls.zone.id,
                    hypervisor='XenServer' 
                )

                cls._cleanup.append(cls.template)

                cls.debug("Sleep for {0} seconds specified in the dictionary before checking for Template's Availability".format(cls.services["sleep"]))
                time.sleep(cls.services["sleep"])
                
            cls.debug("Procure Timeout Value from the dictionary")
            timeout = cls.services["timeout"]
            
            while True:
                list_template_response = list_templates(
                    cls.api_client_vpn_client_reg_user,
                    templatefilter='featured',
                    id=cls.template.id,
                )
            
                if isinstance(list_template_response, list):
                    break
                elif timeout == 0:
                    raise Exception("List template failed!")

                time.sleep(5)
                timeout = timeout - 1
            
            cls.debug("Verify template response to check whether template is present")
            
            if list_template_response is None: 
                raise Exception("Check whether the VPN Client Template is available")
            template_response = list_template_response[0]
            if template_response.isready == False: 
                raise Exception("Template state is not ready, it is %r" % template_response.isready)
            
            # Queue that holds all the VPN Client VMs Information
            cls.vpnclientvms = []
            
            cls.debug("Deploy {0} VPN Clients in the account".format(int(cls.services["vpnclient_count"])))
            
            for vm in xrange(0,int(cls.services["vpnclient_count"])):
                
                cls.debug("Deploy a new VM {0} in first account. This VM which will be configured as VPN Client".format(int(vm)))
                new_vpnclient_vm = VirtualMachine.create(
                    cls.api_client_vpn_client_reg_user,
                    cls.services["virtual_machine"],
                    zoneid=cls.zone.id,
                    serviceofferingid=cls.service_offering.id,
                    templateid=cls.template.id,
                )
                
                cls.debug("Add new VM {0} to the vpnclientvms Queue".format(int(vm)))
                cls.vpnclientvms.append(new_vpnclient_vm)                

                cls.debug("Allow SSH Access to the new VPN Client VM {0}".format(int(vm)))
                new_vpnclient_vm.access_ssh_over_nat(
                    cls.api_client_vpn_client_reg_user, 
                    cls.services, 
                    new_vpnclient_vm, 
                    allow_egress=True
                )
                cls.debug("VM for VPNClient Access Got Created with Public IP Address %s" % new_vpnclient_vm.public_ip)
            
            cls.debug("Create or Use existing Account in which we deploy VPCs and test remote access to them from the First Account's VMs present on isolated Network")          
            cls.api_client_vpn_server_reg_user = cloudstackTestClient.getUserApiClient(
                UserName="******",
                DomainName="ROOT"
            )

            list_vpn_server_regular_user = User.list(
                cls.api_client,
                username="******"
            )
            
            cls.debug("Procure the Account Name and DomainID Information of the Regular Account")
            cls.vpn_server_reg_acct_name = list_vpn_server_regular_user[0].account
            cls.vpn_server_reg_domain_id = list_vpn_server_regular_user[0].domainid
        
            list_vpn_server_regular_user_acct = Account.list(
                cls.api_client,
                name = cls.vpn_server_reg_acct_name,
                listall = True
            )
            
            cls._cleanup.append(Account(list_vpn_server_regular_user_acct[0].__dict__))        
        
            cls.debug("Use an Existing 'VPC off-' Service Offering on the Setup")
            list_available_vpc_offerings = list_vpc_offerings(
                cls.api_client,
                keyword="VPC off-",
            )
            
            if list_available_vpc_offerings is not None:
                cls.debug("Found an Existing 'VPC off-' Service Offering on the Setup")
                cls.vpc_offering = VpcOffering(list_available_vpc_offerings[0].__dict__)
            
            else:
                cls.debug("Creating a VPC offering..")
                cls.vpc_offering = VpcOffering.create(
                    cls.api_client,
                    cls.services["vpc_offering"]
                )

                # Add the created VPC Offering to __cleanup queue
                cls._cleanup.append(cls.vpc_offering)

            # Enable to created VPC Offering inorder to deploy VPCs with it       
            cls.debug("Enabling the VPC offering created")
            cls.vpc_offering.update(cls.api_client, state='Enabled')
            cls.debug("Enabled the VPC Offering")

            # Create a VPC for the second account
            cls.debug("Creating a VPC in the account: %s" % cls.vpn_server_reg_acct_name)
            cls.firstvpc = VPC.create(
                cls.api_client_vpn_server_reg_user,
                cls.services["vpc_remote_vpn"],
                vpcofferingid=cls.vpc_offering.id,
                zoneid=cls.zone.id
            )        
        
            cls.debug("Use an Existing 'NET_OFF-RemoteAccessVPNTest-' Network Offering on the Setup")
            list_available_network_offerings = list_network_offerings(
                cls.api_client,
                keyword="NET_OFF-RemoteAccessVPNTest-",
            )
            
            if list_available_network_offerings is not None:
                cls.debug("Found an Existing 'NET_OFF-RemoteAccessVPNTest-' Network Offering on the Setup")
                cls.network_off = NetworkOffering(list_available_network_offerings[0].__dict__)
            
            else:
                cls.debug('Create NetworkOffering for Networks in VPC')
                cls.services["vpc_network_offering"]["name"] = "NET_OFF-RemoteAccessVPNTest-"+ random_gen()
                cls.network_off = NetworkOffering.create(
                    cls.api_client,
                    cls.services["vpc_network_offering"],
                    conservemode=False
                )

                # Add the created Network Offering to __cleanup queue
                cls._cleanup.append(cls.network_off)
        
            # Enable Network offering
            cls.network_off.update(cls.api_client, state='Enabled')
                    
            cls.debug('Created and Enabled NetworkOffering')
            cls.services["network"]["name"] = "NETWORK-" + random_gen()
            
            # Create First Network Tier in the First VPC created for second account using the network offering created above.    
            cls.debug('Adding Network=%s' % cls.services["network"])
            cls.firstnetworktier = Network.create(
                cls.api_client_vpn_server_reg_user,
                cls.services["network"],
                networkofferingid=cls.network_off.id,
                zoneid=cls.zone.id,
                gateway=cls.services["firstnetwork_tier"]["gateway"],
                netmask=cls.services["firstnetwork_tier"]["netmask"],
                vpcid=cls.firstvpc.id 
            )
        
            cls.debug("Created network with ID: %s" % cls.firstnetworktier.id)
        
            # Create Ingress and Egress NetworkACL rules for First Network Tier in the First VPC created for second account.
            cls.debug("Adding NetworkACL rules to make Network accessible for all Protocols and all CIDRs ")
            NetworkACL.create(
                cls.api_client_vpn_server_reg_user,
                cls.services["all_rule"],
                networkid=cls.firstnetworktier.id,
                traffictype='Ingress'
            )
        
            NetworkACL.create(
                cls.api_client_vpn_server_reg_user,
                cls.services["all_rule"],
                networkid=cls.firstnetworktier.id,
                traffictype='Egress'
            )
         
            listFirstVPC = VPC.list(
                cls.api_client_vpn_server_reg_user,
                id=cls.firstvpc.id
            )
            
            cls.debug("Information about the VPC: {0}".format(str(listFirstVPC)))
        
            cls.debug("Obtain the source nat IP Address of the first VPC.")
            cls.listFirstVPCPublicIpAddress = list_publicIP(
                cls.api_client_vpn_server_reg_user,
                issourcenat="true",
                vpcid=listFirstVPC[0].id,
                listall="true"
            )
            cls.debug("Information about the VPC's Source NAT IP Address: {0}".format(str(cls.listFirstVPCPublicIpAddress)))
        
            cls.debug("Enable Remote Access VPN on the source nat Public IP Address of the first VPC")
            cls.FirstVPNonFirstVPC = Vpn.create(
                cls.api_client_vpn_server_reg_user,
                cls.listFirstVPCPublicIpAddress[0].id
            )

            cls.debug("Successfully Created First VPN on VPC with preshared key:"+ cls.FirstVPNonFirstVPC.presharedkey)
            cls.listfirstNetworkTier = list_networks(
                cls.api_client_vpn_server_reg_user,
                id=cls.firstnetworktier.id,
                listall=True
            )


            cls.debug("Create a VM using the default template on the First Network Tier in the First VPC of the Second Account")
            cls.vm1 = VirtualMachine.create(
                cls.api_client_vpn_server_reg_user,
                cls.services["virtual_machine"],
                zoneid=cls.zone.id,
                serviceofferingid=cls.service_offering.id,
                templateid=cls.template.id,
                networkids=[str(cls.firstnetworktier.id)]
            )
        
            cls.debug("First VM deployed in the first Network Tier")
        
        except Exception as e:
            cleanup_resources(cls.api_client, cls._cleanup)
            printex = traceback.format_exc()
            cls.debug("Exception Occurred : {0}".format(printex))
            raise Exception("Warning: Exception during Setting Up the Test Suite Configuration : %s" % e)
        
        return
Exemple #31
0
    def test_01_RouterStopCreateFW(self):
        """Test router stop create Firewall rule
        """
        # validate the following
        # 1. 1. listFirewallRules (filter by ipaddressid of sourcenat)
        # 2. rule should be for ports 1-600 and in state=Active
        #    (optional backend)
        # 3. verify on router using iptables -t nat -nvx if rules are applied

        # Get the router details associated with account
        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
        )

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

        self.assertNotEqual(
            len(routers),
            0,
            "Check list router response"
        )

        router = routers[0]

        self.debug("Stopping the router: %s" % router.id)
        # Stop the router
        cmd = stopRouter.stopRouterCmd()
        cmd.id = router.id
        self.apiclient.stopRouter(cmd)

        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
        )
        self.assertEqual(
            isinstance(routers, list),
            True,
            "Check for list routers response return valid data"
        )
        router = routers[0]

        self.assertEqual(
            router.state,
            'Stopped',
            "Check list router response for router state"
        )

        public_ips = list_publicIP(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid
        )
        self.assertEqual(
            isinstance(public_ips, list),
            True,
            "Check for list public IP response return valid data"
        )
        public_ip = public_ips[0]

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

        self.debug("Starting the router: %s" % router.id)
        # Start the router
        cmd = startRouter.startRouterCmd()
        cmd.id = router.id
        self.apiclient.startRouter(cmd)

        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
        )
        self.assertEqual(
            isinstance(routers, list),
            True,
            "Check for list routers response return valid data"
        )

        router = routers[0]

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

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

        self.assertEqual(
            fw_rules[0].endport,
            self.services["fwrule"]["endport"],
            "Check end port of firewall rule"
        )
        # For DNS and DHCP check 'dnsmasq' process status
        if (self.hypervisor.lower() == 'vmware'
                or self.hypervisor.lower() == 'hyperv'):
            result = get_process_status(
                self.apiclient.connection.mgtSvr,
                22,
                self.apiclient.connection.user,
                self.apiclient.connection.passwd,
                router.linklocalip,
                'iptables -t nat -L',
                hypervisor=self.hypervisor
            )
        else:
            hosts = list_hosts(
                self.apiclient,
                id=router.hostid,
            )
            self.assertEqual(
                isinstance(hosts, list),
                True,
                "Check for list hosts response return valid data"
            )

            host = hosts[0]
            try:
                result = get_process_status(
                    host.ipaddress,
                    22,
                    self.hostConfig['username'],
                    self.hostConfig['password'],
                    router.linklocalip,
                    'iptables -t nat -L'
                )
            except KeyError:
                self.skipTest(
                    "Provide a marvin config file with host\
                            credentials to run %s" %
                    self._testMethodName)

        self.debug("iptables -t nat -L: %s" % result)
        self.debug("Public IP: %s" % public_ip.ipaddress)
        res = str(result)
        self.assertEqual(
            res.count(str(public_ip.ipaddress)),
            1,
            "Check public IP address"
        )

        return
    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
Exemple #33
0
    def test_01_port_fwd_on_src_nat(self):
        """Test for port forwarding on source NAT"""

        # Validate the following:
        # 1. listPortForwarding rules API should return the added PF rule
        # 2. attempt to do an ssh into the  user VM through the sourceNAT

        src_nat_ip_addrs = list_publicIP(
            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 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=src_nat_ip_addr.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"],
            src_nat_ip_addr.id
        )

        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"
        )
        # SSH virtual machine to test port forwarding
        try:
            logger.debug("SSHing into VM with IP address %s with NAT IP %s" %
                       (
                           self.virtual_machine.ipaddress,
                           src_nat_ip_addr.ipaddress
                       ))

            self.virtual_machine.get_ssh_client(src_nat_ip_addr.ipaddress)
            vm_response = VirtualMachine.list(
                self.apiclient,
                id=self.virtual_machine.id
            )
            if vm_response[0].state != 'Running':
                self.fail(
                    "State of VM : %s is not found to be Running" % str(
                        self.virtual_machine.ipaddress))

        except Exception as e:
            self.fail(
                "SSH Access failed for %s: %s" %
                (self.virtual_machine.ipaddress, e)
            )

        try:
            nat_rule.delete(self.apiclient)
        except Exception as e:
            self.fail("NAT Rule Deletion Failed: %s" % e)

        # NAT rule listing should fail as the nat rule does not exist
        with self.assertRaises(Exception):
            list_nat_rules(self.apiclient,
                           id=nat_rule.id)

        # 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(
                src_nat_ip_addr.ipaddress,
                self.virtual_machine.ssh_port,
                self.virtual_machine.username,
                self.virtual_machine.password,
                retries=2,
                delay=0
            )
        return
    def test_isolate_network_password_server(self):
        """Check the password file in the Router VM"""

        self.logger.debug("Starting test_isolate_network_password_server...")
        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid
        )

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

        self.assertNotEqual(
            len(routers),
            0,
            "Check list router response"
        )

        router = routers[0]

        self.assertEqual(
            router.state,
            'Running',
            "Check list router response for router state"
        )

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

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

        public_ip = public_ips[0]

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

        self.logger.debug("Creating NAT rule for VM ID: %s" % self.vm_1.id)
        # Create NAT rule
        nat_rule1 = NATRule.create(
            self.apiclient,
            self.vm_1,
            self.services["natrule1"],
            public_ip.id
        )

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

        self.logger.debug("Creating NAT rule for VM ID: %s" % self.vm_2.id)
        # Create NAT rule
        nat_rule2 = NATRule.create(
            self.apiclient,
            self.vm_2,
            self.services["natrule2"],
            public_ip.id
        )

        nat_rules = list_nat_rules(
            self.apiclient,
            id=nat_rule1.id
        )
        self.assertEqual(
            isinstance(nat_rules, list),
            True,
            "Check for list NAT rules response return valid data"
        )
        self.assertEqual(
            nat_rules[0].state,
            'Active',
            "Check list port forwarding rules"
        )
        
        nat_rules = list_nat_rules(
            self.apiclient,
            id=nat_rule2.id
        )
        self.assertEqual(
            isinstance(nat_rules, list),
            True,
            "Check for list NAT rules response return valid data"
        )
        self.assertEqual(
            nat_rules[0].state,
            'Active',
            "Check list port forwarding rules"
        )
        
        self.test_ssh_command(self.vm_1, nat_rule1, "natrule1")
        self.test_ssh_command(self.vm_2, nat_rule2, "natrule2")

        self.test_password_file_not_empty(self.vm_1, router)
        self.test_password_file_not_empty(self.vm_2, router)

        return
    def test_01_CreatePFOnStoppedRouter(self):
        """Stop existing router, add a PF rule and check we can access the VM """

        # Get router details associated for that account
        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid
        )

        self.assertEqual(
            isinstance(routers, list),
            True,
            "Check for list routers response return valid data"
        )
        self.assertNotEqual(
            len(routers),
            0,
            "Check list router response"
        )
        router = routers[0]

        self.logger.debug("Stopping router ID: %s" % router.id)

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

        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid
        )
        self.assertEqual(
            isinstance(routers, list),
            True,
            "Check for list routers response return valid data"
        )
        router = routers[0]

        self.assertEqual(
            router.state,
            'Stopped',
            "Check list router response for router state"
        )

        public_ips = list_publicIP(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
            zoneid=self.zone.id
        )
        self.assertEqual(
            isinstance(public_ips, list),
            True,
            "Check for list public IPs response return valid data"
        )

        public_ip = public_ips[0]

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

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

        self.logger.debug("Starting router ID: %s" % router.id)
        # Start the router
        cmd = startRouter.startRouterCmd()
        cmd.id = router.id
        self.apiclient.startRouter(cmd)

        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
            zoneid=self.zone.id
        )
        self.assertEqual(
            isinstance(routers, list),
            True,
            "Check for list routers response return valid data"
        )
        router = routers[0]

        self.assertEqual(
            router.state,
            'Running',
            "Check list router response for router state"
        )
        # NAT Rule should be in Active state after router start
        nat_rules = list_nat_rules(
            self.apiclient,
            id=nat_rule.id
        )
        self.assertEqual(
            isinstance(nat_rules, list),
            True,
            "Check for list NAT rules response return valid data"
        )
        self.assertEqual(
            nat_rules[0].state,
            'Active',
            "Check list port forwarding rules"
        )
        try:

            self.logger.debug("SSH into VM with ID: %s" % nat_rule.ipaddress)

            self.vm_1.get_ssh_client(
                ipaddress=nat_rule.ipaddress,
                port=self.services["natrule"]["publicport"])
        except Exception as e:
            self.fail(
                "SSH Access failed for %s: %s" %
                (nat_rule.ipaddress, e)
            )
        return
    def test_01_RouterStopCreatePF(self):
        """Test router stop create port forwarding
        """
        # validate the following
        # 1. wait for router to start, guest network to be implemented and
        #    VM to report Running
        # 2. stopRouter for this account
        # 3. wait for listRouters to report Router as 'Stopped'
        # 4. listPublicIpAddresses account=user, domainid=1 - pick ipaddressid
        # 5. createPortForwardingRule (ipaddressid from step 5.)
        #    a. for port 22 (ssh) for user VM deployed in step 1.
        #    b. public port 22 , private port 22
        # 6. startRouter stopped for this account
        # 7. wait for listRouters to show router as Running

        # Get router details associated for that account
        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
        )

        self.assertEqual(isinstance(routers, list), True,
                         "Check for list routers response return valid data")
        self.assertNotEqual(len(routers), 0, "Check list router response")
        router = routers[0]

        self.debug("Stopping router ID: %s" % router.id)

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

        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
        )
        self.assertEqual(isinstance(routers, list), True,
                         "Check for list routers response return valid data")
        router = routers[0]

        self.assertEqual(router.state, 'Stopped',
                         "Check list router response for router state")

        public_ips = list_publicIP(self.apiclient,
                                   account=self.account.name,
                                   domainid=self.account.domainid,
                                   zoneid=self.zone.id)
        self.assertEqual(
            isinstance(public_ips, list), True,
            "Check for list public IPs response return valid data")

        public_ip = public_ips[0]

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

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

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

        routers = list_routers(self.apiclient,
                               account=self.account.name,
                               domainid=self.account.domainid,
                               zoneid=self.zone.id)
        self.assertEqual(isinstance(routers, list), True,
                         "Check for list routers response return valid data")
        router = routers[0]

        self.assertEqual(router.state, 'Running',
                         "Check list router response for router state")
        # NAT Rule should be in Active state after router start
        nat_rules = list_nat_rules(self.apiclient, id=nat_rule.id)
        self.assertEqual(
            isinstance(nat_rules, list), True,
            "Check for list NAT rules response return valid data")
        self.assertEqual(nat_rules[0].state, 'Active',
                         "Check list port forwarding rules")
        try:

            self.debug("SSH into VM with ID: %s" % nat_rule.ipaddress)

            self.vm_1.get_ssh_client(
                ipaddress=nat_rule.ipaddress,
                port=self.services["natrule"]["publicport"])
        except Exception as e:
            self.fail("SSH Access failed for %s: %s" % (nat_rule.ipaddress, e))
        return
    def test_02_RVR_Network_FW_PF_SSH_default_routes_egress_false(self):
        """ Test redundant router internals """
        self.logger.debug("Starting test_02_RVR_Network_FW_PF_SSH_default_routes_egress_false...")

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

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

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

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

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

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

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

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

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

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

        public_ip = public_ips[0]

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

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

        expected = 0
        gateway = find_public_gateway(self)
        ssh_command = "ping -c 3 %s" % gateway
        check_string = "3 packets received"
        result = check_router_command(virtual_machine, nat_rule.ipaddress, ssh_command, check_string, self)

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

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

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

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

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

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

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

        return
    def test_01_RouterStopCreateFW(self):
        """Test router stop create Firewall rule
        """
        # validate the following
        # 1. 1. listFirewallRules (filter by ipaddressid of sourcenat)
        # 2. rule should be for ports 1-600 and in state=Active
        #    (optional backend)
        # 3. verify on router using iptables -t nat -nvx if rules are applied

        # Get the router details associated with account
        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
        )

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

        self.assertNotEqual(len(routers), 0, "Check list router response")

        router = routers[0]

        self.debug("Stopping the router: %s" % router.id)
        # Stop the router
        cmd = stopRouter.stopRouterCmd()
        cmd.id = router.id
        self.apiclient.stopRouter(cmd)

        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
        )
        self.assertEqual(isinstance(routers, list), True,
                         "Check for list routers response return valid data")
        router = routers[0]

        self.assertEqual(router.state, 'Stopped',
                         "Check list router response for router state")

        public_ips = list_publicIP(self.apiclient,
                                   account=self.account.name,
                                   domainid=self.account.domainid)
        self.assertEqual(
            isinstance(public_ips, list), True,
            "Check for list public IP response return valid data")
        public_ip = public_ips[0]

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

        self.debug("Starting the router: %s" % router.id)
        # Start the router
        cmd = startRouter.startRouterCmd()
        cmd.id = router.id
        self.apiclient.startRouter(cmd)

        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
        )
        self.assertEqual(isinstance(routers, list), True,
                         "Check for list routers response return valid data")

        router = routers[0]

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

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

        self.assertEqual(fw_rules[0].endport,
                         str(self.services["fwrule"]["endport"]),
                         "Check end port of firewall rule")
        # For DNS and DHCP check 'dnsmasq' process status
        if (self.hypervisor.lower() == 'vmware'
                or self.hypervisor.lower() == 'hyperv'):
            result = get_process_status(self.apiclient.connection.mgtSvr,
                                        22,
                                        self.apiclient.connection.user,
                                        self.apiclient.connection.passwd,
                                        router.linklocalip,
                                        'iptables -t nat -L',
                                        hypervisor=self.hypervisor)
        else:
            hosts = list_hosts(
                self.apiclient,
                id=router.hostid,
            )
            self.assertEqual(
                isinstance(hosts, list), True,
                "Check for list hosts response return valid data")
            host = hosts[0]
            host.user = self.services["configurableData"]["host"]["username"]
            host.passwd = self.services["configurableData"]["host"]["password"]
            try:
                result = get_process_status(host.ipaddress, 22, host.user,
                                            host.passwd, router.linklocalip,
                                            'iptables -t nat -L')
            except KeyError:
                self.skipTest("Provide a marvin config file with host\
                            credentials to run %s" % self._testMethodName)

        self.debug("iptables -t nat -L: %s" % result)
        self.debug("Public IP: %s" % public_ip.ipaddress)
        res = str(result)
        self.assertEqual(res.count(str(public_ip.ipaddress)), 1,
                         "Check public IP address")

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

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

        network_offering_egress_false.update(self.apiclient, state='Enabled')

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

        self.logger.debug("Deploying Virtual Machine on Network %s" % network.id)
        virtual_machine = VirtualMachine.create(self.apiclient,
                                                self.services["virtual_machine"],
                                                templateid=self.template.id,
                                                accountid=self.account.name,
                                                domainid=self.domain.id,
                                                serviceofferingid=self.service_offering.id,
                                                networkids=[str(network.id)])

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

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

        self.logger.debug("Starting test_isolate_network_FW_PF_default_routes...")
        routers = list_routers(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid
        )

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

        self.assertNotEqual(
            len(routers),
            0,
            "Check list router response"
        )

        router = routers[0]

        self.assertEqual(
            router.state,
            'Running',
            "Check list router response for router state"
        )

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

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

        public_ip = public_ips[0]

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

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

        nat_rules = list_nat_rules(
            self.apiclient,
            id=nat_rule.id
        )
        self.assertEqual(
            isinstance(nat_rules, list),
            True,
            "Check for list NAT rules response return valid data"
        )
        self.assertEqual(
            nat_rules[0].state,
            'Active',
            "Check list port forwarding rules"
        )

        expected = 0
        gateway = find_public_gateway(self)
        ssh_command = "ping -c 3 %s" % gateway
        check_string = "3 packets received"
        result = check_router_command(virtual_machine, nat_rule.ipaddress, ssh_command, check_string, self)

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

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

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

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

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

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

        return