예제 #1
0
    def acquire_Public_Ip(self):
        """Acquires the public IP"""

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

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

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

            return public_ip
        except Exception as e:
            self.fail("Failed to acquire new public IP: %s" % e)
    def create_vm(self, pfrule=False, egress_policy=True, RR=False):
        self.create_network_offering(egress_policy, RR)
        # Creating network using the network offering created
        self.debug("Creating network with network offering: %s" % self.network_offering.id)
        self.network = Network.create(
            self.apiclient,
            self.services["network"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            networkofferingid=self.network_offering.id,
            zoneid=self.zone.id,
        )
        self.debug("Created network with ID: %s" % self.network.id)
        self.debug("Deploying instance in the account: %s" % self.account.name)

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

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

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

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

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

        self.debug("Creating NAT rule for VM ID: %s" % self.virtual_machine.id)
        # Create NAT rule
        NATRule.create(self.apiclient, self.virtual_machine, self.services["natrule"], self.public_ip.ipaddress.id)
        return
예제 #3
0
    def setUp(self):
        self.apiclient = self.testClient.getApiClient()
        self.dbclient = self.testClient.getDbConnection()
        self.account = Account.create(self.apiclient, self.services["account"], domainid=self.domain.id)
        self.virtual_machine = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            templateid=self.template.id,
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
        )

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

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

        self.cleanup = [self.account]
        return
예제 #4
0
    def test_02_use_vpn_port(self):
        """Test create VPN when L2TP port in use"""

        # Validate the following
        # 1. set a port forward for UDP: 1701 and enable VPN
        # 2. set port forward rule for the udp port 1701 over which L2TP works
        # 3. port forward should prevent VPN from being enabled

        self.debug("Creating a port forwarding rule on port 1701")
        # Create NAT rule
        nat_rule = NATRule.create(
                        self.apiclient,
                        self.virtual_machine,
                        self.services["natrule"],
                        self.public_ip.ipaddress.id)

        self.debug("Verifying the NAT rule created")
        nat_rules = NATRule.list(self.apiclient, id=nat_rule.id, listall=True)

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

        self.debug("Enabling the VPN connection for IP: %s" %
                                            self.public_ip.ipaddress)
        with self.assertRaises(Exception):
            self.create_VPN(self.public_ip)
        self.debug("Create VPN connection failed! Test successful!")
        return
예제 #5
0
def createNetworkRulesForVM(apiclient, virtualmachine, ruletype,
                            account, networkruledata):
    """Acquire IP, create Firewall and NAT/StaticNAT rule
        (associating it with given vm) for that IP"""

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

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

        if ruletype == NAT_RULE:
            # Create NAT rule
            NATRule.create(apiclient, virtualmachine,
                                 networkruledata["natrule"],ipaddressid=public_ip.ipaddress.id,
                                 networkid=virtualmachine.nic[0].networkid)
        elif ruletype == STATIC_NAT_RULE:
            # Enable Static NAT for VM
            StaticNATRule.enable(apiclient,public_ip.ipaddress.id,
                                     virtualmachine.id, networkid=virtualmachine.nic[0].networkid)
    except Exception as e:
        [FAIL, e]
    return [PASS, public_ip]
예제 #6
0
    def _create_natrule(self, vpc, vm, public_port, private_port, public_ip, network, services=None):
        self.logger.debug("Creating NAT rule in network for vm with public IP")
        if not services:
            self.services["natrule"]["privateport"] = private_port
            self.services["natrule"]["publicport"] = public_port
            self.services["natrule"]["startport"] = public_port
            self.services["natrule"]["endport"] = public_port
            services = self.services["natrule"]

        nat_rule = NATRule.create(
            apiclient=self.apiclient,
            services=services,
            ipaddressid=public_ip.ipaddress.id,
            virtual_machine=vm,
            networkid=network.id
        )
        self.assertIsNotNone(
            nat_rule, "Failed to create NAT Rule for %s" % public_ip.ipaddress.ipaddress)
        self.logger.debug(
            "Adding NetworkACL rules to make NAT rule accessible")

        vm.ssh_ip = nat_rule.ipaddress
        vm.public_ip = nat_rule.ipaddress
        vm.public_port = int(public_port)
        return nat_rule
예제 #7
0
    def test_router_dns_guestipquery(self):
        """Checks that guest VM can query VR DNS"""

        self.logger.debug("Starting test_router_dns_guestipquery...")
        public_ip = self.test_router_common()[0]

        self.logger.debug("Creating Firewall rule for VM ID: %s" % self.vm.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.id)
        nat_rule1 = NATRule.create(
            self.apiclient,
            self.vm,
            self.services["natrule1"],
            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.assertTrue(
            len(nat_rules) >= 1,
            "Check for list NAT rules to have at least one rule"
        )
        self.assertEqual(
            nat_rules[0].state,
            'Active',
            "Check list port forwarding rules"
        )

        result = None
        try:
            self.logger.debug("SSH into guest VM with IP: %s" % nat_rule1.ipaddress)
            ssh = self.vm.get_ssh_client(ipaddress=nat_rule1.ipaddress, port=self.services['natrule1']["publicport"], retries=8)
            result = str(ssh.execute("nslookup google.com"))
        except Exception as e:
            self.fail("Failed to SSH into VM - %s due to exception: %s" % (nat_rule1.ipaddress, e))

        if not result:
            self.fail("Did not to receive any response from the guest VM, failing.")

        self.assertTrue("google.com" in result and "#53" in result,
                        "VR DNS should serve requests from guest network, unable to get valid nslookup result from guest VM.")
예제 #8
0
    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
예제 #9
0
 def create_natrule(self, vm, public_ip, network):
     self.logger.debug('Creating NAT rule in network for vm with public IP')
     nat_rule = NATRule.create(
         self.api_client,
         vm,
         self.vm_services['small'],
         ipaddressid=public_ip.ipaddress.id,
         openfirewall=True,
         networkid=network.id
     )
     self.test_cleanup.append(nat_rule)
     return nat_rule
    def deploy_portforwards(self, portforwards_data, virtualmachines_data, vpc, publicipaddress):
        for portforward_data in portforwards_data:
            for virtualmachine_data in virtualmachines_data:
                if virtualmachine_data['data']['name'] == portforward_data['data']['virtualmachinename']:
                    for nic_data in virtualmachine_data['data']['nics']:
                        if nic_data['data']['guestip'] == portforward_data['data']['nic']:
                            network = get_network(
                                api_client=self.api_client,
                                name=nic_data['data']['networkname'],
                                vpc=vpc
                            )
                            virtualmachine = get_virtual_machine(
                                api_client=self.api_client,
                                name=self.dynamic_names['vms'][virtualmachine_data['data']['name']],
                                network=network
                            )

                            self.logger.debug('>>>  PORT FORWARD  =>  Creating...')
                            portforward = NATRule.create(
                                api_client=self.api_client,
                                data=portforward_data['data'],
                                network=network,
                                virtual_machine=virtualmachine,
                                ipaddress=publicipaddress
                            )

                            Tag.create(
                                api_client=self.api_client,
                                resourceType='UserVm',
                                resourceIds=[virtualmachine.id],
                                tags=[
                                    {
                                        'key': 'sship',
                                        'value': publicipaddress.ipaddress.ipaddress
                                    },
                                    {
                                        'key': 'sshport',
                                        'value': portforward_data['data']['publicport']
                                    }
                                ]
                            )

                            self.logger.debug('>>>  PORT FORWARD  =>  ID: %s  =>  Public Start Port: %s  '
                                              '=>  Public End Port: %s  =>  Private Start Port: %s  '
                                              '=>  Private End Port: %s  =>  CIDR List: %s  =>  Protocol: %s  '
                                              '=>  State: %s  =>  IP: %s  =>  VM: %s', portforward.id,
                                              portforward.publicport, portforward.publicendport,
                                              portforward.privateport, portforward.privateendport, portforward.cidrlist,
                                              portforward.protocol, portforward.state, portforward.ipaddressid,
                                              portforward.virtualmachineid)
예제 #11
0
    def test_03_enable_vpn_use_port(self):
        """Test create NAT rule when VPN when L2TP enabled"""

        # Validate the following
        # 1. Enable a VPN connection on source NAT
        # 2. Add a VPN user
        # 3. add a port forward rule for UDP port 1701.  Should result in error
        #    saying that VPN is enabled over port 1701

        self.debug("Enabling the VPN connection for IP: %s" %
                                            self.public_ip.ipaddress)
        self.create_VPN(self.public_ip)

        self.debug("Creating a port forwarding rule on port 1701")
        # Create NAT rule
        with self.assertRaises(Exception):
            NATRule.create(
                        self.apiclient,
                        self.virtual_machine,
                        self.services["natrule"],
                        self.public_ip.ipaddress.id)

        self.debug("Create NAT rule failed! Test successful!")
        return
예제 #12
0
    def createNetworkRules(self, rule, ipaddressobj, networkid):
        """ Create specified rule on acquired public IP and
        default network of virtual machine
        """
        # Open up firewall port for SSH
        self.fw_rule = FireWallRule.create(
            self.apiclient,
            ipaddressid=ipaddressobj.ipaddress.id,
            protocol=self.services["fwrule"]["protocol"],
            cidrlist=['0.0.0.0/0'],
            startport=self.services["fwrule"]["startport"],
            endport=self.services["fwrule"]["endport"]
        )

        if rule == STATIC_NAT_RULE:
            StaticNATRule.enable(
                self.apiclient,
                ipaddressobj.ipaddress.id,
                self.virtual_machine.id,
                networkid
            )

        elif rule == LB_RULE:
            self.lb_rule = LoadBalancerRule.create(
                self.apiclient,
                self.services["lbrule"],
                ipaddressid=ipaddressobj.ipaddress.id,
                accountid=self.account.name,
                networkid=self.virtual_machine.nic[0].networkid,
                domainid=self.account.domainid)

            vmidipmap = [{"vmid": str(self.virtual_machine.id),
                          "vmip": str(self.virtual_machine.nic[0].ipaddress)}]

            self.lb_rule.assign(
                self.apiclient,
                vmidipmap=vmidipmap
            )
        else:
            self.nat_rule = NATRule.create(
                self.apiclient,
                self.virtual_machine,
                self.services["natrule"],
                ipaddressobj.ipaddress.id
            )
        return
    def create_NatRule_For_VM(self, vm, public_ip, network):
        self.debug("Creatinng NAT rule in network for vm with public IP")
        nat_rule = NATRule.create(self.apiclient,
                                vm,
                                self.services["natrule"],
                                ipaddressid=public_ip.ipaddress.id,
                                openfirewall=False,
                                networkid=network.id,
                                vpcid=self.vpc.id
                                )

        self.debug("Adding NetwrokACl rules to make NAT rule accessible")
        nwacl_nat = NetworkACL.create(self.apiclient,
                                    networkid=network.id,
                                    services=self.services["natrule"],
                                    traffictype='Ingress'
                                    )
        self.debug('nwacl_nat=%s' % nwacl_nat.__dict__)
        return nat_rule
    def create_natrule(self, vm, public_ip, network, vpc_id):
        self.logger.debug("Creating NAT rule in network for vm with public IP")

        nat_rule_services = self.services["natrule"]

        nat_rule = NATRule.create(
            self.apiclient,
            vm,
            nat_rule_services,
            ipaddressid=public_ip.ipaddress.id,
            openfirewall=False,
            networkid=network.id,
            vpcid=vpc_id,
        )

        self.logger.debug("Adding NetworkACL rules to make NAT rule accessible")
        nwacl_nat = NetworkACL.create(
            self.apiclient, networkid=network.id, services=nat_rule_services, traffictype="Ingress"
        )
        self.logger.debug("nwacl_nat=%s" % nwacl_nat.__dict__)
        return nat_rule
    def create_natrule(self, vm, public_ip, network, vpc_id):
        self.logger.debug("Creating NAT rule in network for vm with public IP")

        nat_rule_services = self.services["natrule"]

        nat_rule = NATRule.create(self.apiclient,
                                  vm,
                                  nat_rule_services,
                                  ipaddressid=public_ip.ipaddress.id,
                                  openfirewall=False,
                                  networkid=network.id,
                                  vpcid=vpc_id)

        self.logger.debug(
            "Adding NetworkACL rules to make NAT rule accessible")
        nwacl_nat = NetworkACL.create(self.apiclient,
                                      networkid=network.id,
                                      services=nat_rule_services,
                                      traffictype='Ingress')
        self.logger.debug('nwacl_nat=%s' % nwacl_nat.__dict__)
        return nat_rule
예제 #16
0
    def createNetworkRules(self, rule, ipaddressobj, networkid):
        """ Create specified rule on acquired public IP and
        default network of virtual machine
        """
        # Open up firewall port for SSH
        self.fw_rule = FireWallRule.create(
            self.apiclient,
            ipaddressid=ipaddressobj.ipaddress.id,
            protocol=self.services["fwrule"]["protocol"],
            cidrlist=['0.0.0.0/0'],
            startport=self.services["fwrule"]["startport"],
            endport=self.services["fwrule"]["endport"])

        if rule == STATIC_NAT_RULE:
            StaticNATRule.enable(self.apiclient, ipaddressobj.ipaddress.id,
                                 self.virtual_machine.id, networkid)

        elif rule == LB_RULE:
            self.lb_rule = LoadBalancerRule.create(
                self.apiclient,
                self.services["lbrule"],
                ipaddressid=ipaddressobj.ipaddress.id,
                accountid=self.account.name,
                networkid=self.virtual_machine.nic[0].networkid,
                domainid=self.account.domainid)

            vmidipmap = [{
                "vmid": str(self.virtual_machine.id),
                "vmip": str(self.virtual_machine.nic[0].ipaddress)
            }]

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


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

        # Verifying details of Sticky Policy created
        # Creating expected and actual values dictionaries
        expected_dict = {
            "privateport": str(self.services["updatenatrulerange"]["privateport"]),
            "privateendport": str(self.services["updatenatrulerange"]["privateendport"]),
            }
        actual_dict = {
            "privateport": str(updatefwd_rule.privateport),
            "privateendport": str(updatefwd_rule.privateendport),
            }
        portfwd_status = self.__verify_values(
            expected_dict,
            actual_dict
        )
        self.assertEqual(
            True,
            portfwd_status,
            "Updated Port Forward Rule details are not as expected"
        )
        # Deleting Port Forwarding Rule
        portfwd_rule.delete(self.userapiclient)
        # Listing Port Forwarding Rules for the IP Address associated
        list_prtfwdrule_after = NATRule.list(
            self.userapiclient,
            listall=self.services["listall"],
            ipaddressid=associated_ipaddress.ipaddress.id
        )
        # Verifying no port forwarding rules are listed
        self.assertIsNone(
            list_prtfwdrule_after,
            "Port Forwarding Rules listed after deletion"
        )
        # Destroying the VM Launched
        vm_created.delete(self.apiClient)
        self.cleanup.append(self.account)
        return
예제 #19
0
    def setUpClass(cls):
        cls._cleanup = []
        cls.testClient = super(TestVPCRouterOneNetwork, cls).getClsTestClient()
        cls.api_client = cls.testClient.getApiClient()
        cls.hypervisor = cls.testClient.getHypervisorInfo()
        cls.vpcSupported = True
        cls._cleanup = []
        cls.services = Services().services
        # Get Zone, Domain and templates
        cls.domain = get_domain(cls.api_client)
        cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
        cls.template = get_template(cls.api_client, cls.zone.id,
                                    cls.services["ostype"])
        cls.services["virtual_machine"]["zoneid"] = cls.zone.id
        cls.services["virtual_machine"]["template"] = cls.template.id

        cls.service_offering = ServiceOffering.create(
            cls.api_client, cls.services["service_offering"])
        cls._cleanup.append(cls.service_offering)
        cls.vpc_off = VpcOffering.create(cls.api_client,
                                         cls.services["vpc_offering"])
        cls.vpc_off.update(cls.api_client, state='Enabled')
        cls._cleanup.append(cls.vpc_off)

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

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

        private_gateway = PrivateGateway.create(cls.api_client,
                                                gateway='10.1.3.1',
                                                ipaddress='10.1.3.100',
                                                netmask='255.255.255.0',
                                                vlan=678,
                                                vpcid=cls.vpc.id)
        cls.gateways = PrivateGateway.list(cls.api_client,
                                           id=private_gateway.id,
                                           listall=True)

        static_route = StaticRoute.create(cls.api_client,
                                          cidr='11.1.1.1/24',
                                          gatewayid=private_gateway.id)
        cls.static_routes = StaticRoute.list(cls.api_client,
                                             id=static_route.id,
                                             listall=True)

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

        # Creating network using the network offering created
        cls.network_1 = Network.create(cls.api_client,
                                       cls.services["network"],
                                       accountid=cls.account.name,
                                       domainid=cls.account.domainid,
                                       networkofferingid=cls.nw_off.id,
                                       zoneid=cls.zone.id,
                                       gateway='10.1.1.1',
                                       vpcid=cls.vpc.id)

        # Spawn an instance in that network
        vm_1 = VirtualMachine.create(cls.api_client,
                                     cls.services["virtual_machine"],
                                     accountid=cls.account.name,
                                     domainid=cls.account.domainid,
                                     serviceofferingid=cls.service_offering.id,
                                     networkids=[str(cls.network_1.id)])
        vm_2 = VirtualMachine.create(cls.api_client,
                                     cls.services["virtual_machine"],
                                     accountid=cls.account.name,
                                     domainid=cls.account.domainid,
                                     serviceofferingid=cls.service_offering.id,
                                     networkids=[str(cls.network_1.id)])

        # Spawn an instance in that network
        vm_3 = VirtualMachine.create(cls.api_client,
                                     cls.services["virtual_machine"],
                                     accountid=cls.account.name,
                                     domainid=cls.account.domainid,
                                     serviceofferingid=cls.service_offering.id,
                                     networkids=[str(cls.network_1.id)])

        VirtualMachine.list(cls.api_client,
                            account=cls.account.name,
                            domainid=cls.account.domainid,
                            listall=True)

        public_ip_1 = PublicIPAddress.create(cls.api_client,
                                             accountid=cls.account.name,
                                             zoneid=cls.zone.id,
                                             domainid=cls.account.domainid,
                                             networkid=cls.network_1.id,
                                             vpcid=cls.vpc.id)

        NATRule.create(cls.api_client,
                       vm_1,
                       cls.services["natrule"],
                       ipaddressid=public_ip_1.ipaddress.id,
                       openfirewall=False,
                       networkid=cls.network_1.id,
                       vpcid=cls.vpc.id)

        NetworkACL.create(cls.api_client,
                          networkid=cls.network_1.id,
                          services=cls.services["natrule"],
                          traffictype='Ingress')

        public_ip_2 = PublicIPAddress.create(cls.api_client,
                                             accountid=cls.account.name,
                                             zoneid=cls.zone.id,
                                             domainid=cls.account.domainid,
                                             networkid=cls.network_1.id,
                                             vpcid=cls.vpc.id)
        try:
            StaticNATRule.enable(cls.api_client,
                                 ipaddressid=public_ip_2.ipaddress.id,
                                 virtualmachineid=vm_2.id,
                                 networkid=cls.network_1.id)
        except Exception as e:
            cls.fail("Failed to enable static NAT on IP: %s - %s" %
                     (public_ip_2.ipaddress.ipaddress, e))

        PublicIPAddress.list(cls.api_client,
                             networkid=cls.network_1.id,
                             listall=True,
                             isstaticnat=True,
                             account=cls.account.name,
                             domainid=cls.account.domainid)
        public_ip_3 = PublicIPAddress.create(cls.api_client,
                                             accountid=cls.account.name,
                                             zoneid=cls.zone.id,
                                             domainid=cls.account.domainid,
                                             networkid=cls.network_1.id,
                                             vpcid=cls.vpc.id)

        lb_rule = LoadBalancerRule.create(cls.api_client,
                                          cls.services["lbrule"],
                                          ipaddressid=public_ip_3.ipaddress.id,
                                          accountid=cls.account.name,
                                          networkid=cls.network_1.id,
                                          vpcid=cls.vpc.id,
                                          domainid=cls.account.domainid)

        lb_rule.assign(cls.api_client, [vm_3])

        NetworkACL.create(cls.api_client,
                          networkid=cls.network_1.id,
                          services=cls.services["lbrule"],
                          traffictype='Ingress')

        NetworkACL.create(cls.api_client,
                          networkid=cls.network_1.id,
                          services=cls.services["http_rule"],
                          traffictype='Egress')
예제 #20
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
예제 #21
0
    def test_01_RVR_Network_FW_PF_SSH_default_routes_egress_true(self):
        """ Test redundant router internals """
        self.logger.debug(
            "Starting test_01_RVR_Network_FW_PF_SSH_default_routes_egress_true..."
        )

        network_offering_egress_true = get_default_redundant_isolated_network_offering_with_egress(
            self.apiclient)

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

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

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

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

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

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

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

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

        public_ip = public_ips[0]

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

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

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

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

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

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

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

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

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

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

        return
예제 #22
0
    def test_02_port_fwd_on_non_src_nat(self):
        """Test for port forwarding on non source NAT"""

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

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

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

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

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

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

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

        nat_rule.delete(self.apiclient)

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

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

            SshClient(
                ip_address.ipaddress.ipaddress,
                self.virtual_machine.ssh_port,
                self.virtual_machine.username,
                self.virtual_machine.password,
                retries=2,
                delay=0
            )
        return
예제 #23
0
    def test_01_create_delete_portforwarding_fornonvpc(self):
        """
        @summary: Test to list, create and delete Port Forwarding for
        IP Address associated to Non VPC network
        @Steps:
        Step1: Creating a Network for the user
        Step2: Associating an IP Addresses for Network
        Step3: Launching Virtual Machine in network created in step 2
        Step4: Listing Port Forwarding Rules for the IP Address associated
               in Step2
        Step5: Verifying that no Port Forwarding Rules are listed
        Step6: Creating a Port Forwarding Rule for IP Address associated in
               Step2
        Step7: Listing Port Forwarding Rules for the IP Address associated in
               Step2
        Step8: Verifying 1 Port Forwarding Rule is listed
        Step9: Deleting the Port Forwarding Rule created in Step6
        Step10: Listing Port Forwarding Rules for the IP Address associated in
               Step2
        Step11: Verifying that no Port Forwarding Rules are listed
        """
        # Listing all the Networks's for a user
        list_networks_before = Network.list(
            self.userapiclient,
            listall=self.services["listall"],
            type="Isolated"
        )
        # Verifying No Networks are listed
        self.assertIsNone(
            list_networks_before,
            "Networks listed for newly created User"
        )
        # Listing Network Offerings
        network_offerings_list = NetworkOffering.list(
            self.apiClient,
            forvpc="false",
            guestiptype="Isolated",
            state="Enabled",
            supportedservices="SourceNat,PortForwarding",
            zoneid=self.zone.id
        )
        status = validateList(network_offerings_list)
        self.assertEqual(
            PASS,
            status[0],
            "Isolated Network Offerings with sourceNat,\
                    PortForwarding enabled are not found"
        )
        # Creating a network
        network = Network.create(
            self.userapiclient,
            self.services["network"],
            accountid=self.account.name,
            domainid=self.domain.id,
            networkofferingid=network_offerings_list[0].id,
            zoneid=self.zone.id
        )

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        self.debug("Waiting for SSVMs to come up")
        wait_for_ssvms(
            self.apiclient,
            zoneid=self.zone.id,
            podid=self.pod.id,
        )
        return
예제 #26
0
    def setUp(self):
        self.logger = MarvinLog(MarvinLog.LOGGER_TEST).get_logger()

        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["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.vpc_offering = get_default_vpc_offering(self.apiclient)
        self.logger.debug("VPC Offering '%s' selected", self.vpc_offering.name)

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

        self.virtual_machine_offering = get_default_virtual_machine_offering(self.apiclient)
        self.logger.debug("Virtual Machine Offering '%s' selected", self.virtual_machine_offering.name)

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

        self.template = get_template(self.apiclient, self.zone.id)
        self.logger.debug("Template '%s' selected" % self.template.name)

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

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

        self.vm1 = VirtualMachine.create(self.apiclient,
                                        self.services['vms']['vm1'],
                                        templateid=self.template.id,
                                        serviceofferingid=self.virtual_machine_offering.id,
                                        networkids=[self.network1.id],
                                        zoneid=self.zone.id,
                                        domainid=self.domain.id,
                                        accountid=self.account.name)
        self.logger.debug("VM '%s' created, Network: %s, IP %s", self.vm1.name, self.network1.name, self.vm1.nic[0].ipaddress)

        src_nat_ip_addrs = list_public_ip(
            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.network1.id,
            self.vpc1.id
        )
        self.lb_rule.assign(self.apiclient, [self.vm1])

        self.nat_rule = NATRule.create(
            self.apiclient,
            self.vm1,
            self.services["natrule"],
            src_nat_ip_addr.id
        )
        self.cleanup = []
        return
예제 #27
0
    def test_port_forwarding_on_ip_from_non_src_nat_ip_range(self):
        """Test for port forwarding on a IP which is in pubic IP range different
           from public IP range that has source NAT IP associated with network
        """

        # Validate the following:
        # 1. Create a new public IP range and dedicate to a account
        # 2. Acquire a IP from new public range
        # 3. create a port forwarding on acquired IP from new range
        # 4. Create a firewall rule to open up the port
        # 5. Test SSH works to the VM

        self.services["extrapubliciprange"]["zoneid"] = self.services["zoneid"]
        self.public_ip_range = PublicIpRange.create(
                                    self.apiclient,
                                    self.services["extrapubliciprange"]
                               )
        self.cleanup.append(self.public_ip_range)

        logger.debug("Dedicating Public IP range to the account");
        dedicate_public_ip_range_response = PublicIpRange.dedicate(
                                                self.apiclient,
                                                self.public_ip_range.vlan.id,
                                                account=self.account.name,
                                                domainid=self.account.domainid
                                            )
        ip_address = PublicIPAddress.create(
            self.apiclient,
            self.account.name,
            self.zone.id,
            self.account.domainid,
            self.services["virtual_machine"]
        )
        self.cleanup.append(ip_address)
        # Check if VM is in Running state before creating NAT and firewall rules
        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
        fwr = FireWallRule.create(
            self.apiclient,
            ipaddressid=ip_address.ipaddress.id,
            protocol=self.services["natrule"]["protocol"],
            cidrlist=['0.0.0.0/0'],
            startport=self.services["natrule"]["publicport"],
            endport=self.services["natrule"]["publicport"]
        )
        self.cleanup.append(fwr)

        # Create PF rule
        nat_rule = NATRule.create(
            self.apiclient,
            self.virtual_machine,
            self.services["natrule"],
            ip_address.ipaddress.id
        )

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

        nat_rule.delete(self.apiclient)
예제 #28
0
    def test_08_add_TCP_PF_Rule_In_VPN(self):
        """
        Test to add TCP Port Forwarding rule for specific ports(500,1701 and 4500) in VPN
        """
        # Steps for verification
        # 1. Enable vpn on SourceNAT IP address
        # 2. Configure PF with TCP ports 500,1701 and 4500. It should be allowed
        # Should not conflict with UPD ports used for VPN

        vm_res = VirtualMachine.list(
            self.apiclient,
            id=self.virtual_machine.id,
            listall=True
        )
        self.assertEqual(
            validateList(vm_res)[0],
            PASS,
            "Failed to list virtual machine"
        )
        network_id = vm_res[0].nic[0].networkid
        src_nat_list = PublicIPAddress.list(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
            listall=True,
            issourcenat=True,
            associatednetworkid=network_id
        )
        self.assertEqual(
            validateList(src_nat_list)[0],
            PASS,
            "Failed to list source nat ip address"
        )
        ip = src_nat_list[0]
        try:
            vpn = Vpn.create(
                self.apiclient,
                publicipid=ip.id,
                account=self.account.name,
                domainid=self.account.domainid,
            )
            self.assertIsNotNone(
                vpn,
                "Failed to create remote access vpn"
            )
        except Exception as e:
            self.fail("Failed to enable vpn on SourceNAT IP with error: %s" % e)

        #Create PF rule with TCP ports 500,4500 and 1701
        self.services['natrule']['protocol']="TCP"
        for port in [500, 4500, 1701]:
            self.services['natrule']['privateport'] = port
            self.services['natrule']['publicport'] = port
            try:
                nat = NATRule.create(
                    self.apiclient,
                    self.virtual_machine,
                    self.services["natrule"],
                    ip.id
                )
                self.assertIsNotNone(
                    nat,
                    "Failed to add PF rule with tcp parts matching vpn"
                )
            except Exception as e:
                self.fail("Creating PF rule for TCP port %s in VPN failed : %s" % (port, e))
        return
예제 #29
0
    def setup_infra(cls, redundant=False):

        if len(cls.class_cleanup) > 0:
            cleanup_resources(cls.api_client, cls.class_cleanup, cls.logger)
            cls.class_cleanup = []

        cls.zone = get_zone(cls.api_client, cls.test_client.getZoneForTests())
        cls.logger.debug("Zone '%s' selected" % cls.zone.name)

        cls.domain = get_domain(cls.api_client)
        cls.logger.debug("Domain '%s' selected" % cls.domain.name)

        cls.template = get_template(cls.api_client, cls.zone.id)

        cls.logger.debug("Template '%s' selected" % cls.template.name)

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

        cls.class_cleanup += [cls.account]
        cls.logger.debug("Account '%s' created", cls.account.name)

        cls.vpc_offering = get_default_redundant_vpc_offering(
            cls.api_client) if redundant else get_default_vpc_offering(
                cls.api_client)
        cls.logger.debug("VPC Offering '%s' selected", cls.vpc_offering.name)

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

        cls.virtual_machine_offering = get_default_virtual_machine_offering(
            cls.api_client)
        cls.logger.debug("Virtual Machine Offering '%s' selected",
                         cls.virtual_machine_offering.name)

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

        cls.default_deny_acl = get_network_acl(cls.api_client, 'default_deny')
        cls.logger.debug("ACL '%s' selected", cls.default_deny_acl.name)

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

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

        cls.vm1 = VirtualMachine.create(
            cls.api_client,
            cls.attributes['vms']['vm1'],
            templateid=cls.template.id,
            serviceofferingid=cls.virtual_machine_offering.id,
            networkids=[cls.network1.id],
            zoneid=cls.zone.id,
            domainid=cls.domain.id,
            accountid=cls.account.name)
        cls.logger.debug("VM '%s' created, Network: %s, IP %s", cls.vm1.name,
                         cls.network1.name, cls.vm1.nic[0].ipaddress)

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

        cls.nat_rule1 = NATRule.create(cls.api_client,
                                       cls.vm1,
                                       cls.attributes['nat_rule'],
                                       vpcid=cls.vpc1.id,
                                       networkid=cls.network1.id,
                                       ipaddressid=cls.public_ip1.ipaddress.id)
        cls.logger.debug("Port Forwarding Rule '%s (%s) %s => %s' created",
                         cls.nat_rule1.ipaddress, cls.nat_rule1.protocol,
                         cls.nat_rule1.publicport, cls.nat_rule1.privateport)
    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
예제 #31
0
    def setUp(self):
        self.logger = MarvinLog(MarvinLog.LOGGER_TEST).get_logger()

        self.apiclient = self.testClient.getApiClient()
        self.services = self.testClient.getParsedTestDataConfig()
        self.vpc_offering = get_default_vpc_offering(self.apiclient)
        self.network_offering = get_default_network_offering(self.apiclient)

        # 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["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 = get_default_virtual_machine_offering(
            self.apiclient)
        self.vpc = VPC.create(self.apiclient,
                              self.services["vpc"],
                              vpcofferingid=self.vpc_offering.id,
                              zoneid=self.zone.id,
                              account=self.account.name,
                              domainid=self.account.domainid)

        ntwk = Network.create(api_client=self.apiclient,
                              services=self.services["network_1"],
                              accountid=self.account.name,
                              domainid=self.domain.id,
                              networkofferingid=self.network_offering.id,
                              zoneid=self.zone.id,
                              vpcid=self.vpc.id)

        networkids = []
        networkids.append(ntwk.id)

        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,
            networkids=networkids)

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

        ip_addrs = list_public_ip(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,
                                       networkid=ntwk.id)
        self.lb_rule = LoadBalancerRule.create(self.apiclient,
                                               self.services["lbrule"],
                                               self.ip_addr.id,
                                               accountid=self.account.name,
                                               networkid=ntwk.id)
        self.cleanup = [self.virtual_machine, self.account]
        return
예제 #32
0
    def test_01_positive_tests_vm_operations_advanced_zone(self, value):
        """ Positive tests for VMLC test path - Advanced Zone

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

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

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

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

        network = CreateNetwork(self, value)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        return
예제 #33
0
    def setUp(self):
        self.apiclient = self.testClient.getApiClient()
        self.services = self.testClient.getParsedTestDataConfig()

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

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

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

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

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

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

        self.nat_rule = NATRule.create(
            self.apiclient,
            self.virtual_machine,
            self.services["natrule"],
            self.ip_addr.id
        )
        self.lb_rule = LoadBalancerRule.create(
            self.apiclient,
            self.services["lbrule"],
            self.ip_addr.id,
            accountid=self.account.name
        )
        self.cleanup = [
            self.virtual_machine,
            self.account
        ]
        return
    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
예제 #35
0
    def test_01_host_maintenance_mode(self):
        """Test host maintenance mode
        """

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        self.debug("Waiting for SSVMs to come up")
        wait_for_ssvms(
            self.apiclient,
            zoneid=self.zone.id,
            podid=self.pod.id,
        )
        return
    def test_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_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
예제 #38
0
    def create_vm(self, pfrule=False, egress_policy=True, RR=False):
        self.create_network_offering(egress_policy, RR)
        # Creating network using the network offering created
        self.debug("Creating network with network offering: %s" %
                   self.network_offering.id)
        self.network = Network.create(
            self.apiclient,
            self.services["network"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            networkofferingid=self.network_offering.id,
            zoneid=self.zone.id)
        self.cleanup_networks.append(self.network)
        self.debug("Created network with ID: %s" % self.network.id)
        self.debug("Deploying instance in the account: %s" % self.account.name)

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

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

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

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

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

        self.debug("Creating NAT rule for VM ID: %s" % self.virtual_machine.id)
        #Create NAT rule
        NATRule.create(self.apiclient, self.virtual_machine,
                       self.services["natrule"], self.public_ip.ipaddress.id)
        return
예제 #39
0
    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..."
        )

        network_offering_egress_true = get_default_isolated_network_offering_with_egress(
            self.apiclient)

        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)
        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_public_ip(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_ssh"]["protocol"],
            cidrlist=['0.0.0.0/0'],
            startport=self.services["natrule_ssh"]["publicport"],
            endport=self.services["natrule_ssh"]["publicport"])

        self.logger.debug("Creating NAT rule for VM ID: %s" %
                          virtual_machine.id)
        # Create NAT rule
        nat_rule = NATRule.create(self.apiclient, virtual_machine,
                                  self.services["natrule_ssh"], 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 = "3 packets received"
        result = self.check_router_command(virtual_machine, nat_rule.ipaddress,
                                           ssh_command, check_string, self)

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

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

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

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

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

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

        return
    def test_forceDeleteDomain(self):
        """ Test delete domain with force option"""

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

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

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

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

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

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

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

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

            src_nat = src_nat_list[0]

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

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

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

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

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

        self.debug("Checking if the resources in domain are deleted")
        with self.assertRaises(CloudstackAPIException):
            Account.list(
                        self.apiclient,
                        name=self.account_1.name,
                        domainid=self.account_1.domainid,
                        listall=True
                        )
        return
    def test_01_acquire_public_ips_in_isolated_network_with_single_vr(self):
        """ Acquire IPs in multiple subnets in isolated networks with single VR

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        # 22. restart network with cleanup, makeredundant=true
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 6
        self.network1.restart(self.apiclient, cleanup=True, makeredundant=True)
        routers = self.get_routers(self.network1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host,
                                                     "eth0,eth1,eth2,eth3,")
            guestIp, controlIp, sourcenatIp = self.get_router_ips(router)
            self.verify_ip_address_in_router(router, host, guestIp, "eth0",
                                             True)
            self.verify_ip_address_in_router(router, host, controlIp, "eth1",
                                             True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth2",
                                             True)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_4.ipaddress.ipaddress,
                                             "eth3", False)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_5.ipaddress.ipaddress,
                                             "eth3", False)
            self.verify_ip_address_in_router(router, host,
                                             ipaddress_6.ipaddress.ipaddress,
                                             "eth3", True)
            self.verify_router_publicnic_state(router, host, "eth2|eth3")
    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
예제 #43
0
    def test_01_positive_tests_vm_operations_advanced_zone(self, value):
        """ Positive tests for VMLC test path - Advanced Zone

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

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

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

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

        network = CreateNetwork(self, value)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        return
예제 #44
0
    def test_08_add_TCP_PF_Rule_In_VPN(self):
        """
        Test to add TCP Port Forwarding rule for specific ports(500,1701 and 4500) in VPN
        """
        # Steps for verification
        # 1. Enable vpn on SourceNAT IP address
        # 2. Configure PF with TCP ports 500,1701 and 4500. It should be allowed
        # Should not conflict with UPD ports used for VPN

        vm_res = VirtualMachine.list(
            self.apiclient,
            id=self.virtual_machine.id,
            listall=True
        )
        self.assertEqual(
            validateList(vm_res)[0],
            PASS,
            "Failed to list virtual machine"
        )
        network_id = vm_res[0].nic[0].networkid
        src_nat_list = PublicIPAddress.list(
            self.apiclient,
            account=self.account.name,
            domainid=self.account.domainid,
            listall=True,
            issourcenat=True,
            associatednetworkid=network_id
        )
        self.assertEqual(
            validateList(src_nat_list)[0],
            PASS,
            "Failed to list source nat ip address"
        )
        ip = src_nat_list[0]
        try:
            vpn = Vpn.create(
                self.apiclient,
                publicipid=ip.id,
                account=self.account.name,
                domainid=self.account.domainid,
            )
            self.assertIsNotNone(
                vpn,
                "Failed to create remote access vpn"
            )
            self.cleanup.append(vpn)
        except Exception as e:
            self.fail("Failed to enable vpn on SourceNAT IP with error: %s" % e)

        # Create PF rule with TCP ports 500,4500 and 1701
        self.services['natrule']['protocol'] = "TCP"
        for port in [500, 4500, 1701]:
            self.services['natrule']['privateport'] = port
            self.services['natrule']['publicport'] = port
            try:
                nat = NATRule.create(
                    self.apiclient,
                    self.virtual_machine,
                    self.services["natrule"],
                    ip.id
                )
                self.assertIsNotNone(
                    nat,
                    "Failed to add PF rule with tcp parts matching vpn"
                )
                self.cleanup.append(nat)
            except Exception as e:
                self.fail("Creating PF rule for TCP port %s in VPN failed : %s" % (port, 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
예제 #46
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_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
예제 #48
0
    def test_02_port_fwd_on_non_src_nat(self):
        """Test for port forwarding on non source NAT"""

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

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

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

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

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

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

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

        nat_rule.delete(self.apiclient)

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

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

            SshClient(
                ip_address.ipaddress.ipaddress,
                self.virtual_machine.ssh_port,
                self.virtual_machine.username,
                self.virtual_machine.password,
                retries=2,
                delay=0
            )
        return
예제 #49
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:
            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
예제 #50
0
    def setUp(self):

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

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

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

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

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

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

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

        lb_rule = LoadBalancerRule.create(
            self.apiclient,
            self.services["lbrule"],
            src_nat_ip_addr.id,
            self.account.name
        )
        lb_rule.assign(self.apiclient, [self.vm_1])
        self.nat_rule = NATRule.create(
            self.apiclient,
            self.vm_1,
            self.services["natrule"],
            ipaddressid=self.public_ip.ipaddress.id
        )
        self.cleanup = [self.nat_rule,
                        lb_rule,
                        self.vm_1,
                        self.service_offering,
                        self.account,
                        ]
        return
예제 #51
0
    def setUp(self):

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

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

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

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

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

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

        lb_rule = LoadBalancerRule.create(
            self.apiclient,
            self.services["lbrule"],
            src_nat_ip_addr.id,
            self.account.name
        )
        lb_rule.assign(self.apiclient, [self.vm_1])
        self.nat_rule = NATRule.create(
            self.apiclient,
            self.vm_1,
            self.services["natrule"],
            ipaddressid=self.public_ip.ipaddress.id
        )
        self.cleanup = [self.nat_rule,
                        lb_rule,
                        self.vm_1,
                        self.service_offering,
                        self.account,
                        ]
        return
예제 #52
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
예제 #53
0
    def setUp(self):

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

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

        # Create an account, network, VM 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
예제 #54
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
예제 #55
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_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
예제 #57
0
    def test_02_host_maintenance_mode_with_activities(self):
        """Test host maintenance mode with activities
        """

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        self.debug("Waiting for SSVMs to come up")
        wait_for_ssvms(
            self.apiclient,
            zoneid=self.zone.id,
            podid=self.pod.id,
        )
        return
예제 #58
0
    def test_03_deploy_vms_in_vpc_with_regionlevelvpc(self):
        """Test deploy virtual machines in VPC networks"""

        # 1. Create VPC Offering by specifying all supported Services
        #   (Vpn,dhcpdns,UserData, SourceNat,Static NAT and PF,LB,NetworkAcl)
        # 2. Create a VPC using the above VPC offering
        # 3. Create a network as part of this VPC.
        # 4. Deploy few Vms.
        # 5. Create a LB rule for this VM.
        # 6. Create a PF rule for this VM.
        # 7. Create a  Static Nat rule for this VM.
        # 8. Create Ingress rules on the network to open the above created
        #    LB PF and Static Nat rule
        # 9. Create Egress Network ACL for this network to access google.com.
        # 10. Enable VPN services

        if not self.isOvsPluginEnabled:
            self.skipTest("OVS plugin should be enabled to run this test case")

        self.debug("Creating a VPC offering..")
        vpc_off = VpcOffering.create(self.apiclient,
                                     self.services["vpc_offering"])

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

        self.debug("creating a VPC network in the account: %s" %
                   self.account.name)
        vpc = VPC.create(self.apiclient,
                         self.services["vpc"],
                         vpcofferingid=vpc_off.id,
                         zoneid=self.zone.id,
                         account=self.account.name,
                         domainid=self.account.domainid,
                         networkDomain=self.account.domainid)
        self.validate_vpc_network(vpc)

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

        gateway = vpc.cidr.split('/')[0]
        # Split the cidr to retrieve gateway
        # for eg. cidr = 10.0.0.1/24
        # Gateway = 10.0.0.1

        # Creating network using the network offering created
        self.debug("Creating network with network offering: %s" %
                   self.network_offering.id)
        network = Network.create(self.apiclient,
                                 self.services["network"],
                                 accountid=self.account.name,
                                 domainid=self.account.domainid,
                                 networkofferingid=self.network_offering.id,
                                 zoneid=self.zone.id,
                                 gateway=gateway,
                                 vpcid=vpc.id)
        self.debug("Created network with ID: %s" % network.id)
        # Spawn an instance in that network
        virtual_machine = VirtualMachine.create(
            self.apiclient,
            self.services["virtual_machine"],
            accountid=self.account.name,
            domainid=self.account.domainid,
            serviceofferingid=self.service_offering.id,
            networkids=[str(network.id)])
        self.debug("Deployed VM in network: %s" % network.id)

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

        self.debug("Creating LB rule for IP address: %s" %
                   public_ip.ipaddress.ipaddress)

        LoadBalancerRule.create(self.apiclient,
                                self.services["lbrule"],
                                ipaddressid=public_ip.ipaddress.id,
                                accountid=self.account.name,
                                networkid=network.id,
                                vpcid=vpc.id,
                                domainid=self.account.domainid)

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

        NATRule.create(self.apiclient,
                       virtual_machine,
                       self.services["natrule"],
                       ipaddressid=public_ip_2.ipaddress.id,
                       openfirewall=False,
                       networkid=network.id,
                       vpcid=vpc.id)

        self.debug("Adding NetwrokACl rules to make PF and LB accessible")
        NetworkACL.create(self.apiclient,
                          networkid=network.id,
                          services=self.services["natrule"],
                          traffictype='Ingress')

        NetworkACL.create(self.apiclient,
                          networkid=network.id,
                          services=self.services["lbrule"],
                          traffictype='Ingress')
        self.debug("Checking if we can SSH into VM?")
        try:
            virtual_machine.get_ssh_client(
                ipaddress=public_ip_2.ipaddress.ipaddress, )
            self.debug("SSH into VM is successfully")
        except Exception as e:
            self.fail("Failed to SSH into VM - %s, %s" %
                      (public_ip_2.ipaddress.ipaddress, e))

        self.debug("Associating public IP for network: %s" % network.name)
        public_ip_3 = PublicIPAddress.create(self.apiclient,
                                             accountid=self.account.name,
                                             zoneid=self.zone.id,
                                             domainid=self.account.domainid,
                                             networkid=network.id,
                                             vpcid=vpc.id)
        self.debug("Associated %s with network %s" %
                   (public_ip_3.ipaddress.ipaddress, network.id))
        self.debug("Enabling static NAT for IP: %s" %
                   public_ip_3.ipaddress.ipaddress)
        try:
            StaticNATRule.enable(self.apiclient,
                                 ipaddressid=public_ip_3.ipaddress.id,
                                 virtualmachineid=virtual_machine.id,
                                 networkid=network.id)
            self.debug("Static NAT enabled for IP: %s" %
                       public_ip_3.ipaddress.ipaddress)
        except Exception as e:
            self.fail("Failed to enable static NAT on IP: %s - %s" %
                      (public_ip_3.ipaddress.ipaddress, e))

        public_ips = PublicIPAddress.list(self.apiclient,
                                          networkid=network.id,
                                          listall=True,
                                          isstaticnat=True,
                                          account=self.account.name,
                                          domainid=self.account.domainid)
        self.assertEqual(isinstance(public_ips, list), True,
                         "List public Ip for network should list the Ip addr")
        self.assertEqual(public_ips[0].ipaddress,
                         public_ip_3.ipaddress.ipaddress,
                         "List public Ip for network should list the Ip addr")
        # TODO: Remote Access VPN is not yet supported in VPC
        return