Esempio n. 1
0
    def test_get_traffic_counters_with_zero(self):
        iptables_dump = (
            'Chain OUTPUT (policy ACCEPT 400 packets, 65901 bytes)\n'
            '    pkts      bytes target     prot opt in     out     source'
            '               destination         \n'
            '     400   65901 chain1     all  --  *      *       0.0.0.0/0'
            '            0.0.0.0/0           \n'
            '     400   65901 chain2     all  --  *      *       0.0.0.0/0'
            '            0.0.0.0/0           \n')

        expected_calls_and_values = [
            (mock.call(['iptables', '-t', 'filter', '-L', 'OUTPUT',
                        '-n', '-v', '-x', '-Z'],
                       root_helper=self.root_helper),
             iptables_dump),
            (mock.call(['iptables', '-t', 'nat', '-L', 'OUTPUT', '-n',
                        '-v', '-x', '-Z'],
                       root_helper=self.root_helper),
             ''),
            (mock.call(['ip6tables', '-t', 'filter', '-L', 'OUTPUT',
                        '-n', '-v', '-x', '-Z'],
                       root_helper=self.root_helper),
             iptables_dump),
        ]
        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        acc = self.iptables.get_traffic_counters('OUTPUT', zero=True)
        self.assertEqual(acc['pkts'], 1600)
        self.assertEqual(acc['bytes'], 263604)

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 2
0
 def test_delete_neutron_ports_list_error(self):
     expected_calls_and_values = [
         (self._vsctl_mock("list-ports", self.BR_NAME), RuntimeError()),
     ]
     tools.setup_mock_calls(self.execute, expected_calls_and_values)
     self.assertRaises(RuntimeError, self.br.delete_ports, all_ports=False)
     tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 3
0
    def _test_get_vif_port_by_id(self, iface_id, data, br_name=None,
                                 extra_calls_and_values=None):
        headings = ['external_ids', 'name', 'ofport']

        # Each element is a tuple of (expected mock call, return_value)
        expected_calls_and_values = [
            (self._vsctl_mock("--columns=external_ids,name,ofport", "find",
                              "Interface",
                              'external_ids:iface-id=%s' % iface_id,
                              'external_ids:attached-mac!=""'),
             self._encode_ovs_json(headings, data))]
        if data:
            if not br_name:
                br_name = self.BR_NAME

            # Only the last information list in 'data' is used, so if more
            # than one vif is described in data, the rest must be declared
            # in the argument 'expected_calls_and_values'.
            if extra_calls_and_values:
                expected_calls_and_values.extend(extra_calls_and_values)

            expected_calls_and_values.append(
                (self._vsctl_mock("iface-to-br",
                                  data[-1][headings.index('name')]), br_name))
        tools.setup_mock_calls(self.execute, expected_calls_and_values)
        vif_port = self.br.get_vif_port_by_id(iface_id)

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
        return vif_port
Esempio n. 4
0
 def test_get_vif_port_set_list_ports_error(self):
     expected_calls_and_values = [
         (self._vsctl_mock("list-ports", self.BR_NAME), RuntimeError()),
     ]
     tools.setup_mock_calls(self.execute, expected_calls_and_values)
     self.assertRaises(RuntimeError, self.br.get_vif_port_set)
     tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 5
0
    def _test_get_traffic_counters_with_zero_helper(self, use_ipv6):
        self.iptables = iptables_manager.IptablesManager(use_ipv6=use_ipv6)
        self.execute = mock.patch.object(self.iptables, "execute").start()
        exp_packets = 800
        exp_bytes = 131802

        expected_calls_and_values = [
            (
                mock.call(["iptables", "-t", "filter", "-L", "OUTPUT", "-n", "-v", "-x", "-Z"], run_as_root=True),
                TRAFFIC_COUNTERS_DUMP,
            ),
            (mock.call(["iptables", "-t", "raw", "-L", "OUTPUT", "-n", "-v", "-x", "-Z"], run_as_root=True), ""),
            (mock.call(["iptables", "-t", "mangle", "-L", "OUTPUT", "-n", "-v", "-x", "-Z"], run_as_root=True), ""),
            (mock.call(["iptables", "-t", "nat", "-L", "OUTPUT", "-n", "-v", "-x", "-Z"], run_as_root=True), ""),
        ]
        if use_ipv6:
            expected_calls_and_values.append(
                (mock.call(["ip6tables", "-t", "raw", "-L", "OUTPUT", "-n", "-v", "-x", "-Z"], run_as_root=True), "")
            )
            expected_calls_and_values.append(
                (
                    mock.call(["ip6tables", "-t", "filter", "-L", "OUTPUT", "-n", "-v", "-x", "-Z"], run_as_root=True),
                    TRAFFIC_COUNTERS_DUMP,
                )
            )
            exp_packets *= 2
            exp_bytes *= 2

        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        acc = self.iptables.get_traffic_counters("OUTPUT", zero=True)
        self.assertEqual(acc["pkts"], exp_packets)
        self.assertEqual(acc["bytes"], exp_bytes)

        tools.verify_mock_calls(self.execute, expected_calls_and_values, any_order=True)
    def test_add_tunnel_port(self):
        pname = "tap99"
        local_ip = "1.1.1.1"
        remote_ip = "9.9.9.9"
        ofport = 6
        command = ["--may-exist", "add-port", self.BR_NAME, pname]
        command.extend(["--", "set", "Interface", pname])
        command.extend(
            [
                "type=gre",
                "options:df_default=true",
                "options:remote_ip=" + remote_ip,
                "options:local_ip=" + local_ip,
                "options:in_key=flow",
                "options:out_key=flow",
            ]
        )
        # Each element is a tuple of (expected mock call, return_value)
        expected_calls_and_values = [
            (self._vsctl_mock(*command), None),
            (
                self._vsctl_mock("--columns=ofport", "list", "Interface", pname),
                self._encode_ovs_json(["ofport"], [[ofport]]),
            ),
        ]
        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.assertEqual(self.br.add_tunnel_port(pname, remote_ip, local_ip), ofport)

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 7
0
    def test_get_vif_port_set(self):
        id_key = 'iface-id'
        headings = ['name', 'external_ids', 'ofport']
        data = [
            # A vif port on this bridge:
            ['tap99', {id_key: 'tap99id', 'attached-mac': 'tap99mac'}, 1],
            # A vif port on this bridge not yet configured
            ['tap98', {id_key: 'tap98id', 'attached-mac': 'tap98mac'}, []],
            # Another vif port on this bridge not yet configured
            ['tap97', {id_key: 'tap97id', 'attached-mac': 'tap97mac'},
             ['set', []]],

            # Non-vif port on this bridge:
            ['bogus', {}, 2],
        ]

        # Each element is a tuple of (expected mock call, return_value)
        expected_calls_and_values = [
            (self._vsctl_mock("list-ports", self.BR_NAME), 'tap99\\ntun22'),
            (self._vsctl_mock("--if-exists",
                              "--columns=name,external_ids,ofport",
                              "list", "Interface", 'tap99', 'tun22'),
             self._encode_ovs_json(headings, data)),
        ]
        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        port_set = self.br.get_vif_port_set()
        self.assertEqual(set(['tap99id']), port_set)
        tools.verify_mock_calls(self.execute, expected_calls_and_values)
    def test_add_blank_rule(self):
        self.iptables = iptables_manager.IptablesManager(
            use_ipv6=False)
        self.execute = mock.patch.object(self.iptables, "execute").start()

        iptables_args = {}
        iptables_args.update(IPTABLES_ARG)
        filter_rules = ('-A %(bn)s-test-filter\n' % iptables_args)
        iptables_args['filter_rules'] = filter_rules
        filter_dump_mod = FILTER_RESTORE_DUMP % iptables_args

        expected_calls_and_values = [
            (mock.call(['iptables-save'],
                       run_as_root=True),
             (filter_dump_mod + MANGLE_RESTORE_DUMP +
              NAT_RESTORE_DUMP + RAW_RESTORE_DUMP)),
        ]

        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.iptables.ipv4['filter'].add_chain('test-filter')
        self.iptables.ipv4['filter'].add_rule('test-filter', '')

        self.iptables.apply()

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 9
0
    def test_rule_with_wrap_target(self):
        name = '0123456789' * 5
        wrap = "%s-%s" % (iptables_manager.binary_name,
                          iptables_manager.get_chain_name(name))

        iptables_args = {'bn': iptables_manager.binary_name,
                         'wrap': wrap}

        filter_dump_mod = ('# Generated by iptables_manager\n'
                           '*filter\n'
                           ':neutron-filter-top - [0:0]\n'
                           ':%(bn)s-FORWARD - [0:0]\n'
                           ':%(bn)s-INPUT - [0:0]\n'
                           ':%(bn)s-local - [0:0]\n'
                           ':%(wrap)s - [0:0]\n'
                           ':%(bn)s-OUTPUT - [0:0]\n'
                           '[0:0] -A FORWARD -j neutron-filter-top\n'
                           '[0:0] -A OUTPUT -j neutron-filter-top\n'
                           '[0:0] -A neutron-filter-top -j %(bn)s-local\n'
                           '[0:0] -A INPUT -j %(bn)s-INPUT\n'
                           '[0:0] -A OUTPUT -j %(bn)s-OUTPUT\n'
                           '[0:0] -A FORWARD -j %(bn)s-FORWARD\n'
                           '[0:0] -A %(bn)s-INPUT -s 0/0 -d 192.168.0.2 -j '
                           '%(wrap)s\n'
                           'COMMIT\n'
                           '# Completed by iptables_manager\n'
                           % iptables_args)

        expected_calls_and_values = [
            (mock.call(['iptables-save', '-c'],
                       root_helper=self.root_helper),
             ''),
            (mock.call(['iptables-restore', '-c'],
                       process_input=NAT_DUMP + filter_dump_mod,
                       root_helper=self.root_helper),
             None),
            (mock.call(['iptables-save', '-c'],
                       root_helper=self.root_helper),
             ''),
            (mock.call(['iptables-restore', '-c'],
                       process_input=NAT_DUMP + FILTER_DUMP,
                       root_helper=self.root_helper),
             None),
        ]
        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.iptables.ipv4['filter'].add_chain(name)
        self.iptables.ipv4['filter'].add_rule('INPUT',
                                              '-s 0/0 -d 192.168.0.2 -j'
                                              ' $%s' % name)
        self.iptables.apply()

        self.iptables.ipv4['filter'].remove_rule('INPUT',
                                                 '-s 0/0 -d 192.168.0.2 -j'
                                                 ' $%s' % name)
        self.iptables.ipv4['filter'].remove_chain(name)

        self.iptables.apply()

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 10
0
    def test_add_tunnel_port(self):
        pname = "tap99"
        local_ip = "1.1.1.1"
        remote_ip = "9.9.9.9"
        ofport = "6"
        command = ["ovs-vsctl", self.TO, '--', "--may-exist", "add-port",
                   self.BR_NAME, pname]
        command.extend(["--", "set", "Interface", pname])
        command.extend(["type=gre", "options:remote_ip=" + remote_ip,
                        "options:local_ip=" + local_ip,
                        "options:in_key=flow",
                        "options:out_key=flow"])
        # Each element is a tuple of (expected mock call, return_value)
        expected_calls_and_values = [
            (mock.call(command, root_helper=self.root_helper), None),
            (mock.call(["ovs-vsctl", self.TO, "get",
                        "Interface", pname, "ofport"],
                       root_helper=self.root_helper),
             ofport),
        ]
        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.assertEqual(
            self.br.add_tunnel_port(pname, remote_ip, local_ip),
            ofport)

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 11
0
    def test_add_vxlan_fragmented_tunnel_port(self):
        pname = "tap99"
        local_ip = "1.1.1.1"
        remote_ip = "9.9.9.9"
        ofport = 6
        vxlan_udp_port = "9999"
        dont_fragment = False
        command = ["--may-exist", "add-port", self.BR_NAME, pname]
        command.extend(["--", "set", "Interface", pname])
        command.extend(["type=" + constants.TYPE_VXLAN,
                        "options:dst_port=" + vxlan_udp_port,
                        "options:df_default=false",
                        "options:remote_ip=" + remote_ip,
                        "options:local_ip=" + local_ip,
                        "options:in_key=flow",
                        "options:out_key=flow"])
        # Each element is a tuple of (expected mock call, return_value)
        expected_calls_and_values = [
            (self._vsctl_mock(*command), None),
            (self._vsctl_mock("--columns=ofport", "list", "Interface", pname),
             self._encode_ovs_json(['ofport'], [[ofport]])),
        ]
        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.assertEqual(
            self.br.add_tunnel_port(pname, remote_ip, local_ip,
                                    constants.TYPE_VXLAN, vxlan_udp_port,
                                    dont_fragment),
            ofport)

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 12
0
    def test_add_patch_port(self):
        pname = "tap99"
        peer = "bar10"
        ofport = "6"

        # Each element is a tuple of (expected mock call, return_value)
        expected_calls_and_values = [
            (mock.call(["ovs-vsctl", self.TO, "add-port",
                        self.BR_NAME, pname], root_helper=self.root_helper),
             None),
            (mock.call(["ovs-vsctl", self.TO, "set", "Interface",
                        pname, "type=patch"], root_helper=self.root_helper),
             None),
            (mock.call(["ovs-vsctl", self.TO, "set",
                        "Interface", pname, "options:peer=" + peer],
                       root_helper=self.root_helper),
             None),
            (mock.call(["ovs-vsctl", self.TO, "get",
                        "Interface", pname, "ofport"],
                       root_helper=self.root_helper),
             ofport)
        ]
        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.assertEqual(self.br.add_patch_port(pname, peer), ofport)
        tools.verify_mock_calls(self.execute, expected_calls_and_values)
    def _test_add_filter_rule_helper(self, use_ipv6):
        self.iptables = iptables_manager.IptablesManager(
            root_helper=self.root_helper, use_ipv6=use_ipv6)
        self.execute = mock.patch.object(self.iptables, "execute").start()

        filter_dump_mod = ('# Generated by iptables_manager\n'
                           '*filter\n'
                           ':neutron-filter-top - [0:0]\n'
                           ':%(bn)s-FORWARD - [0:0]\n'
                           ':%(bn)s-INPUT - [0:0]\n'
                           ':%(bn)s-OUTPUT - [0:0]\n'
                           ':%(bn)s-filter - [0:0]\n'
                           ':%(bn)s-local - [0:0]\n'
                           '[0:0] -A FORWARD -j neutron-filter-top\n'
                           '[0:0] -A OUTPUT -j neutron-filter-top\n'
                           '[0:0] -A neutron-filter-top -j %(bn)s-local\n'
                           '[0:0] -A INPUT -j %(bn)s-INPUT\n'
                           '[0:0] -A OUTPUT -j %(bn)s-OUTPUT\n'
                           '[0:0] -A FORWARD -j %(bn)s-FORWARD\n'
                           '[0:0] -A %(bn)s-filter -j DROP\n'
                           '[0:0] -A %(bn)s-INPUT -s 0/0 -d 192.168.0.2 -j '
                           '%(bn)s-filter\n'
                           'COMMIT\n'
                           '# Completed by iptables_manager\n' % IPTABLES_ARG)

        expected_calls_and_values = [
            (mock.call(['iptables-save', '-c'], root_helper=self.root_helper),
             ''),
            (mock.call(['iptables-restore', '-c'],
                       process_input=RAW_DUMP + NAT_DUMP + filter_dump_mod,
                       root_helper=self.root_helper), None),
            (mock.call(['iptables-save', '-c'], root_helper=self.root_helper),
             ''),
            (mock.call(['iptables-restore', '-c'],
                       process_input=RAW_DUMP + NAT_DUMP + FILTER_DUMP,
                       root_helper=self.root_helper), None),
        ]
        if use_ipv6:
            self._extend_with_ip6tables_filter(expected_calls_and_values,
                                               FILTER_DUMP)

        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.iptables.ipv4['filter'].add_chain('filter')
        self.iptables.ipv4['filter'].add_rule('filter', '-j DROP')
        self.iptables.ipv4['filter'].add_rule(
            'INPUT', '-s 0/0 -d 192.168.0.2 -j'
            ' %(bn)s-filter' % IPTABLES_ARG)
        self.iptables.apply()

        self.iptables.ipv4['filter'].remove_rule('filter', '-j DROP')
        self.iptables.ipv4['filter'].remove_rule(
            'INPUT', '-s 0/0 -d 192.168.0.2 -j'
            ' %(bn)s-filter' % IPTABLES_ARG)
        self.iptables.ipv4['filter'].remove_chain('filter')

        self.iptables.apply()

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 14
0
    def test_add_filter_rule(self):
        filter_dump_mod = (
            "# Generated by iptables_manager\n"
            "*filter\n"
            ":neutron-filter-top - [0:0]\n"
            ":%(bn)s-FORWARD - [0:0]\n"
            ":%(bn)s-INPUT - [0:0]\n"
            ":%(bn)s-OUTPUT - [0:0]\n"
            ":%(bn)s-filter - [0:0]\n"
            ":%(bn)s-local - [0:0]\n"
            "[0:0] -A FORWARD -j neutron-filter-top\n"
            "[0:0] -A OUTPUT -j neutron-filter-top\n"
            "[0:0] -A neutron-filter-top -j %(bn)s-local\n"
            "[0:0] -A INPUT -j %(bn)s-INPUT\n"
            "[0:0] -A OUTPUT -j %(bn)s-OUTPUT\n"
            "[0:0] -A FORWARD -j %(bn)s-FORWARD\n"
            "[0:0] -A %(bn)s-filter -j DROP\n"
            "[0:0] -A %(bn)s-INPUT -s 0/0 -d 192.168.0.2 -j "
            "%(bn)s-filter\n"
            "COMMIT\n"
            "# Completed by iptables_manager\n" % IPTABLES_ARG
        )

        raw_dump = _generate_raw_dump(IPTABLES_ARG)

        expected_calls_and_values = [
            (mock.call(["iptables-save", "-c"], root_helper=self.root_helper), ""),
            (
                mock.call(
                    ["iptables-restore", "-c"],
                    process_input=(raw_dump + COMMENTED_NAT_DUMP + filter_dump_mod),
                    root_helper=self.root_helper,
                ),
                None,
            ),
            (mock.call(["iptables-save", "-c"], root_helper=self.root_helper), ""),
            (
                mock.call(
                    ["iptables-restore", "-c"],
                    process_input=(raw_dump + COMMENTED_NAT_DUMP + FILTER_DUMP),
                    root_helper=self.root_helper,
                ),
                None,
            ),
        ]
        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.iptables.ipv4["filter"].add_chain("filter")
        self.iptables.ipv4["filter"].add_rule("filter", "-j DROP")
        self.iptables.ipv4["filter"].add_rule("INPUT", "-s 0/0 -d 192.168.0.2 -j" " %(bn)s-filter" % IPTABLES_ARG)
        self.iptables.apply()

        self.iptables.ipv4["filter"].remove_rule("filter", "-j DROP")
        self.iptables.ipv4["filter"].remove_rule("INPUT", "-s 0/0 -d 192.168.0.2 -j" " %(bn)s-filter" % IPTABLES_ARG)
        self.iptables.ipv4["filter"].remove_chain("filter")

        self.iptables.apply()

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 15
0
    def _test_add_filter_rule_helper(self, use_ipv6):
        self.iptables = iptables_manager.IptablesManager(
            use_ipv6=use_ipv6)
        self.execute = mock.patch.object(self.iptables, "execute").start()

        iptables_args = {}
        iptables_args.update(IPTABLES_ARG)
        filter_rules = ('-I %(bn)s-INPUT 1 -s 0/0 -d 192.168.0.2 -j '
                        '%(bn)s-filter\n-I %(bn)s-filter 1 -j DROP\n'
                        % iptables_args)
        iptables_args['filter_rules'] = filter_rules
        filter_dump_mod = FILTER_WITH_RULES_TEMPLATE % iptables_args

        raw_dump = RAW_DUMP % IPTABLES_ARG

        expected_calls_and_values = [
            (mock.call(['iptables-save'],
                       run_as_root=True),
             ''),
            (mock.call(['iptables-restore', '-n'],
                       process_input=(filter_dump_mod + MANGLE_DUMP +
                                      NAT_DUMP + RAW_DUMP),
                       run_as_root=True),
             None),
            (mock.call(['iptables-save'],
                       run_as_root=True),
             ''),
            (mock.call(['iptables-restore', '-n'],
                       process_input=(FILTER_DUMP + MANGLE_DUMP + NAT_DUMP +
                                      RAW_DUMP),
                       run_as_root=True
                       ),
             None),
        ]
        if use_ipv6:
            self._extend_with_ip6tables_filter(
                expected_calls_and_values,
                FILTER_DUMP + MANGLE_DUMP_V6 + raw_dump)

        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.iptables.ipv4['filter'].add_chain('filter')
        self.iptables.ipv4['filter'].add_rule('filter', '-j DROP')
        self.iptables.ipv4['filter'].add_rule('INPUT',
                                              '-s 0/0 -d 192.168.0.2 -j'
                                              ' %(bn)s-filter' % IPTABLES_ARG)
        self.iptables.apply()

        self.iptables.ipv4['filter'].remove_rule('filter', '-j DROP')
        self.iptables.ipv4['filter'].remove_rule('INPUT',
                                                 '-s 0/0 -d 192.168.0.2 -j'
                                                 ' %(bn)s-filter'
                                                 % IPTABLES_ARG)
        self.iptables.ipv4['filter'].remove_chain('filter')

        self.iptables.apply()

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 16
0
    def test_add_filter_rule(self):
        filter_dump_mod = ('# Generated by iptables_manager\n'
                           '*filter\n'
                           ':neutron-filter-top - [0:0]\n'
                           ':%(bn)s-FORWARD - [0:0]\n'
                           ':%(bn)s-INPUT - [0:0]\n'
                           ':%(bn)s-local - [0:0]\n'
                           ':%(bn)s-filter - [0:0]\n'
                           ':%(bn)s-OUTPUT - [0:0]\n'
                           '[0:0] -A FORWARD -j neutron-filter-top\n'
                           '[0:0] -A OUTPUT -j neutron-filter-top\n'
                           '[0:0] -A neutron-filter-top -j %(bn)s-local\n'
                           '[0:0] -A INPUT -j %(bn)s-INPUT\n'
                           '[0:0] -A OUTPUT -j %(bn)s-OUTPUT\n'
                           '[0:0] -A FORWARD -j %(bn)s-FORWARD\n'
                           '[0:0] -A %(bn)s-filter -j DROP\n'
                           '[0:0] -A %(bn)s-INPUT -s 0/0 -d 192.168.0.2 -j '
                           '%(bn)s-filter\n'
                           'COMMIT\n'
                           '# Completed by iptables_manager\n'
                           % IPTABLES_ARG)

        expected_calls_and_values = [
            (mock.call(['iptables-save', '-c'],
                       root_helper=self.root_helper),
             ''),
            (mock.call(['iptables-restore', '-c'],
                       process_input=NAT_DUMP + filter_dump_mod,
                       root_helper=self.root_helper),
             None),
            (mock.call(['iptables-save', '-c'],
                       root_helper=self.root_helper),
             ''),
            (mock.call(['iptables-restore', '-c'],
                       process_input=NAT_DUMP + FILTER_DUMP,
                       root_helper=self.root_helper
                       ),
             None),
        ]
        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.iptables.ipv4['filter'].add_chain('filter')
        self.iptables.ipv4['filter'].add_rule('filter', '-j DROP')
        self.iptables.ipv4['filter'].add_rule('INPUT',
                                              '-s 0/0 -d 192.168.0.2 -j'
                                              ' %(bn)s-filter' % IPTABLES_ARG)
        self.iptables.apply()

        self.iptables.ipv4['filter'].remove_rule('filter', '-j DROP')
        self.iptables.ipv4['filter'].remove_rule('INPUT',
                                                 '-s 0/0 -d 192.168.0.2 -j'
                                                 ' %(bn)s-filter'
                                                 % IPTABLES_ARG)
        self.iptables.ipv4['filter'].remove_chain('filter')

        self.iptables.apply()

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 17
0
    def _test_add_mangle_rule_helper(self, use_ipv6):
        self.iptables = iptables_manager.IptablesManager(use_ipv6=use_ipv6)
        self.execute = mock.patch.object(self.iptables, "execute").start()

        mangle_dump_mod = (
            '# Generated by iptables_manager\n'
            '*mangle\n'
            ':%(bn)s-FORWARD - [0:0]\n'
            ':%(bn)s-INPUT - [0:0]\n'
            ':%(bn)s-OUTPUT - [0:0]\n'
            ':%(bn)s-POSTROUTING - [0:0]\n'
            ':%(bn)s-PREROUTING - [0:0]\n'
            ':%(bn)s-mangle - [0:0]\n'
            ':%(bn)s-mark - [0:0]\n'
            '[0:0] -A PREROUTING -j %(bn)s-PREROUTING\n'
            '[0:0] -A INPUT -j %(bn)s-INPUT\n'
            '[0:0] -A FORWARD -j %(bn)s-FORWARD\n'
            '[0:0] -A OUTPUT -j %(bn)s-OUTPUT\n'
            '[0:0] -A POSTROUTING -j %(bn)s-POSTROUTING\n'
            '[0:0] -A %(bn)s-PREROUTING -j %(bn)s-mark\n'
            '[0:0] -A %(bn)s-PREROUTING -j MARK --set-xmark 0x1/%(mark)s\n'
            'COMMIT\n'
            '# Completed by iptables_manager\n' % IPTABLES_ARG)

        expected_calls_and_values = [
            (mock.call(['iptables-save', '-c'], run_as_root=True), ''),
            (mock.call(['iptables-restore', '-c'],
                       process_input=(RAW_DUMP + NAT_DUMP + mangle_dump_mod +
                                      FILTER_DUMP),
                       run_as_root=True), None),
            (mock.call(['iptables-save', '-c'], run_as_root=True), ''),
            (mock.call(['iptables-restore', '-c'],
                       process_input=(RAW_DUMP + NAT_DUMP + MANGLE_DUMP +
                                      FILTER_DUMP),
                       run_as_root=True), None),
        ]
        if use_ipv6:
            self._extend_with_ip6tables_filter(expected_calls_and_values,
                                               RAW_DUMP + FILTER_DUMP)

        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.iptables.ipv4['mangle'].add_chain('mangle')
        self.iptables.ipv4['mangle'].add_rule(
            'PREROUTING',
            '-j MARK --set-xmark 0x1/%s' % constants.ROUTER_MARK_MASK)

        self.iptables.apply()

        self.iptables.ipv4['mangle'].remove_rule(
            'PREROUTING',
            '-j MARK --set-xmark 0x1/%s' % constants.ROUTER_MARK_MASK)
        self.iptables.ipv4['mangle'].remove_chain('mangle')

        self.iptables.apply()

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 18
0
 def test_delete_neutron_ports_list_error(self):
     expected_calls_and_values = [
         (mock.call(["ovs-vsctl", self.TO, "list-ports", self.BR_NAME],
                    root_helper=self.root_helper),
          RuntimeError()),
     ]
     tools.setup_mock_calls(self.execute, expected_calls_and_values)
     self.assertRaises(RuntimeError, self.br.delete_ports, all_ports=False)
     tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 19
0
 def test_get_vif_port_set_list_ports_error(self):
     expected_calls_and_values = [
         (mock.call(["ovs-vsctl", self.TO, "list-ports", self.BR_NAME],
                    root_helper=self.root_helper),
          RuntimeError()),
     ]
     tools.setup_mock_calls(self.execute, expected_calls_and_values)
     self.assertRaises(RuntimeError, self.br.get_vif_port_set)
     tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 20
0
    def _test_empty_chain_custom_binary_name_helper(self, use_ipv6):
        bn = ("xbcdef" * 5)[:16]

        self.iptables = iptables_manager.IptablesManager(
            binary_name=bn,
            use_ipv6=use_ipv6)
        self.execute = mock.patch.object(self.iptables, "execute").start()

        iptables_args = {'bn': bn}

        filter_dump = FILTER_TEMPLATE % iptables_args

        filter_rules = ('-I %(bn)s-filter 1 -s 0/0 -d 192.168.0.2\n'
                        % iptables_args)
        iptables_args['filter_rules'] = filter_rules
        filter_dump_mod = FILTER_WITH_RULES_TEMPLATE % iptables_args

        nat_dump = NAT_TEMPLATE % iptables_args

        raw_dump = _generate_raw_dump(iptables_args)
        mangle_dump = _generate_mangle_dump(iptables_args)

        expected_calls_and_values = [
            (mock.call(['iptables-save'],
                       run_as_root=True),
             ''),
            (mock.call(['iptables-restore', '-n'],
                       process_input=(filter_dump_mod + mangle_dump +
                                      nat_dump + raw_dump),
                       run_as_root=True),
             None),
            (mock.call(['iptables-save'],
                       run_as_root=True),
             ''),
            (mock.call(['iptables-restore', '-n'],
                       process_input=(filter_dump + mangle_dump +
                                      nat_dump + raw_dump),
                       run_as_root=True),
             None),
        ]
        if use_ipv6:
            mangle_dump_v6 = _generate_mangle_dump_v6(iptables_args)
            self._extend_with_ip6tables_filter(
                expected_calls_and_values,
                filter_dump + mangle_dump_v6 + raw_dump)

        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.iptables.ipv4['filter'].add_chain('filter')
        self.iptables.ipv4['filter'].add_rule('filter',
                                              '-s 0/0 -d 192.168.0.2')
        self.iptables.apply()

        self.iptables.ipv4['filter'].remove_chain('filter')
        self.iptables.apply()

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 21
0
    def _test_add_raw_rule_helper(self, use_ipv6):
        self.iptables = iptables_manager.IptablesManager(
            use_ipv6=use_ipv6)
        self.execute = mock.patch.object(self.iptables, "execute").start()

        raw_dump_mod = ('# Generated by iptables_manager\n'
                        '*raw\n'
                        ':OUTPUT - [0:0]\n'
                        ':PREROUTING - [0:0]\n'
                        ':%(bn)s-OUTPUT - [0:0]\n'
                        ':%(bn)s-PREROUTING - [0:0]\n'
                        ':%(bn)s-raw - [0:0]\n'
                        '-I OUTPUT 1 -j %(bn)s-OUTPUT\n'
                        '-I PREROUTING 1 -j %(bn)s-PREROUTING\n'
                        '-I %(bn)s-PREROUTING 1 -j CT --notrack\n'
                        'COMMIT\n'
                        '# Completed by iptables_manager\n'
                        % IPTABLES_ARG)

        expected_calls_and_values = [
            (mock.call(['iptables-save'],
                       run_as_root=True),
             ''),
            (mock.call(['iptables-restore', '-n'],
                       process_input=(FILTER_DUMP + MANGLE_DUMP + NAT_DUMP +
                                      raw_dump_mod),
                       run_as_root=True),
             None),
            (mock.call(['iptables-save'],
                       run_as_root=True),
             ''),
            (mock.call(['iptables-restore', '-n'],
                       process_input=(FILTER_DUMP + MANGLE_DUMP + NAT_DUMP +
                                      RAW_DUMP),
                       run_as_root=True),
             None),
        ]
        if use_ipv6:
            self._extend_with_ip6tables_filter(
                expected_calls_and_values,
                FILTER_DUMP + MANGLE_DUMP_V6 + RAW_DUMP)

        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.iptables.ipv4['raw'].add_chain('raw')
        self.iptables.ipv4['raw'].add_rule('PREROUTING',
                                           '-j CT --notrack')

        self.iptables.apply()

        self.iptables.ipv4['raw'].remove_rule('PREROUTING',
                                              '-j CT --notrack')
        self.iptables.ipv4['raw'].remove_chain('raw')

        self.iptables.apply()

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 22
0
 def test_delete_neutron_ports_list_error(self):
     expected_calls_and_values = [
         (mock.call(["ovs-vsctl", self.TO, "list-ports", self.BR_NAME],
                    root_helper=self.root_helper),
          RuntimeError()),
     ]
     tools.setup_mock_calls(self.execute, expected_calls_and_values)
     self.assertRaises(RuntimeError, self.br.delete_ports, all_ports=False)
     tools.verify_mock_calls(self.execute, expected_calls_and_values)
    def _test_empty_chain_custom_binary_name_helper(self, use_ipv6):
        bn = ("xbcdef" * 5)[:16]

        self.iptables = iptables_manager.IptablesManager(
            binary_name=bn,
            use_ipv6=use_ipv6)
        self.execute = mock.patch.object(self.iptables, "execute").start()

        iptables_args = {'bn': bn}

        filter_dump = FILTER_TEMPLATE % iptables_args

        filter_rules = ('-I %(bn)s-filter 1 -s 0/0 -d 192.168.0.2\n'
                        % iptables_args)
        iptables_args['filter_rules'] = filter_rules
        filter_dump_mod = FILTER_WITH_RULES_TEMPLATE % iptables_args

        nat_dump = NAT_TEMPLATE % iptables_args

        raw_dump = _generate_raw_dump(iptables_args)
        mangle_dump = _generate_mangle_dump(iptables_args)

        expected_calls_and_values = [
            (mock.call(['iptables-save'],
                       run_as_root=True),
             ''),
            (mock.call(['iptables-restore', '-n'],
                       process_input=(filter_dump_mod + mangle_dump +
                                      nat_dump + raw_dump),
                       run_as_root=True),
             None),
            (mock.call(['iptables-save'],
                       run_as_root=True),
             ''),
            (mock.call(['iptables-restore', '-n'],
                       process_input=(filter_dump + mangle_dump +
                                      nat_dump + raw_dump),
                       run_as_root=True),
             None),
        ]
        if use_ipv6:
            mangle_dump_v6 = _generate_mangle_dump_v6(iptables_args)
            self._extend_with_ip6tables_filter(
                expected_calls_and_values,
                filter_dump + mangle_dump_v6 + raw_dump)

        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.iptables.ipv4['filter'].add_chain('filter')
        self.iptables.ipv4['filter'].add_rule('filter',
                                              '-s 0/0 -d 192.168.0.2')
        self.iptables.apply()

        self.iptables.ipv4['filter'].remove_chain('filter')
        self.iptables.apply()

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 24
0
 def test_get_vif_port_set_list_ports_error(self):
     expected_calls_and_values = [
         (mock.call(["ovs-vsctl", self.TO, "list-ports", self.BR_NAME],
                    root_helper=self.root_helper),
          RuntimeError()),
     ]
     tools.setup_mock_calls(self.execute, expected_calls_and_values)
     self.assertRaises(RuntimeError, self.br.get_vif_port_set)
     tools.verify_mock_calls(self.execute, expected_calls_and_values)
    def _test_add_raw_rule_helper(self, use_ipv6):
        self.iptables = iptables_manager.IptablesManager(
            use_ipv6=use_ipv6)
        self.execute = mock.patch.object(self.iptables, "execute").start()

        raw_dump_mod = ('# Generated by iptables_manager\n'
                        '*raw\n'
                        ':OUTPUT - [0:0]\n'
                        ':PREROUTING - [0:0]\n'
                        ':%(bn)s-OUTPUT - [0:0]\n'
                        ':%(bn)s-PREROUTING - [0:0]\n'
                        ':%(bn)s-raw - [0:0]\n'
                        '-I OUTPUT 1 -j %(bn)s-OUTPUT\n'
                        '-I PREROUTING 1 -j %(bn)s-PREROUTING\n'
                        '-I %(bn)s-PREROUTING 1 -j CT --notrack\n'
                        'COMMIT\n'
                        '# Completed by iptables_manager\n'
                        % IPTABLES_ARG)

        expected_calls_and_values = [
            (mock.call(['iptables-save'],
                       run_as_root=True),
             ''),
            (mock.call(['iptables-restore', '-n'],
                       process_input=(FILTER_DUMP + MANGLE_DUMP + NAT_DUMP +
                                      raw_dump_mod),
                       run_as_root=True),
             None),
            (mock.call(['iptables-save'],
                       run_as_root=True),
             ''),
            (mock.call(['iptables-restore', '-n'],
                       process_input=(FILTER_DUMP + MANGLE_DUMP + NAT_DUMP +
                                      RAW_DUMP),
                       run_as_root=True),
             None),
        ]
        if use_ipv6:
            self._extend_with_ip6tables_filter(
                expected_calls_and_values,
                FILTER_DUMP + MANGLE_DUMP_V6 + RAW_DUMP)

        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.iptables.ipv4['raw'].add_chain('raw')
        self.iptables.ipv4['raw'].add_rule('PREROUTING',
                                           '-j CT --notrack')

        self.iptables.apply()

        self.iptables.ipv4['raw'].remove_rule('PREROUTING',
                                              '-j CT --notrack')
        self.iptables.ipv4['raw'].remove_chain('raw')

        self.iptables.apply()

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
    def _test_add_filter_rule_helper(self, use_ipv6):
        self.iptables = iptables_manager.IptablesManager(
            root_helper=self.root_helper,
            use_ipv6=use_ipv6)
        self.execute = mock.patch.object(self.iptables, "execute").start()

        iptables_args = {}
        iptables_args.update(IPTABLES_ARG)
        filter_rules = ('[0:0] -A %(bn)s-filter -j DROP\n'
                        '[0:0] -A %(bn)s-INPUT -s 0/0 -d 192.168.0.2 -j '
                        '%(bn)s-filter\n' % iptables_args)
        iptables_args['filter_rules'] = filter_rules
        filter_dump_mod = FILTER_WITH_RULES_TEMPLATE % iptables_args

        expected_calls_and_values = [
            (mock.call(['iptables-save', '-c'],
                       root_helper=self.root_helper),
             ''),
            (mock.call(['iptables-restore', '-c'],
                       process_input=(RAW_DUMP + NAT_DUMP + MANGLE_DUMP +
                                      filter_dump_mod),
                       root_helper=self.root_helper),
             None),
            (mock.call(['iptables-save', '-c'],
                       root_helper=self.root_helper),
             ''),
            (mock.call(['iptables-restore', '-c'],
                       process_input=(RAW_DUMP + NAT_DUMP + MANGLE_DUMP +
                                      FILTER_DUMP),
                       root_helper=self.root_helper
                       ),
             None),
        ]
        if use_ipv6:
            self._extend_with_ip6tables_filter(expected_calls_and_values,
                                               FILTER_DUMP)

        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.iptables.ipv4['filter'].add_chain('filter')
        self.iptables.ipv4['filter'].add_rule('filter', '-j DROP')
        self.iptables.ipv4['filter'].add_rule('INPUT',
                                              '-s 0/0 -d 192.168.0.2 -j'
                                              ' %(bn)s-filter' % IPTABLES_ARG)
        self.iptables.apply()

        self.iptables.ipv4['filter'].remove_rule('filter', '-j DROP')
        self.iptables.ipv4['filter'].remove_rule('INPUT',
                                                 '-s 0/0 -d 192.168.0.2 -j'
                                                 ' %(bn)s-filter'
                                                 % IPTABLES_ARG)
        self.iptables.ipv4['filter'].remove_chain('filter')

        self.iptables.apply()

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 27
0
    def _test_get_traffic_counters_with_zero_helper(self, use_ipv6):
        self.iptables = iptables_manager.IptablesManager(root_helper=self.root_helper, use_ipv6=use_ipv6)
        self.execute = mock.patch.object(self.iptables, "execute").start()
        exp_packets = 800
        exp_bytes = 131802

        iptables_dump = (
            "Chain OUTPUT (policy ACCEPT 400 packets, 65901 bytes)\n"
            "    pkts      bytes target     prot opt in     out     source"
            "               destination         \n"
            "     400   65901 chain1     all  --  *      *       0.0.0.0/0"
            "            0.0.0.0/0           \n"
            "     400   65901 chain2     all  --  *      *       0.0.0.0/0"
            "            0.0.0.0/0           \n"
        )

        expected_calls_and_values = [
            (
                mock.call(
                    ["iptables", "-t", "filter", "-L", "OUTPUT", "-n", "-v", "-x", "-Z"], root_helper=self.root_helper
                ),
                iptables_dump,
            ),
            (
                mock.call(
                    ["iptables", "-t", "raw", "-L", "OUTPUT", "-n", "-v", "-x", "-Z"], root_helper=self.root_helper
                ),
                "",
            ),
            (
                mock.call(
                    ["iptables", "-t", "nat", "-L", "OUTPUT", "-n", "-v", "-x", "-Z"], root_helper=self.root_helper
                ),
                "",
            ),
        ]
        if use_ipv6:
            expected_calls_and_values.append(
                (
                    mock.call(
                        ["ip6tables", "-t", "filter", "-L", "OUTPUT", "-n", "-v", "-x", "-Z"],
                        root_helper=self.root_helper,
                    ),
                    iptables_dump,
                )
            )
            exp_packets *= 2
            exp_bytes *= 2

        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        acc = self.iptables.get_traffic_counters("OUTPUT", zero=True)
        self.assertEqual(acc["pkts"], exp_packets)
        self.assertEqual(acc["bytes"], exp_bytes)

        tools.verify_mock_calls(self.execute, expected_calls_and_values, any_order=True)
Esempio n. 28
0
 def test_get_vif_port_set_list_interface_error(self):
     expected_calls_and_values = [
         (self._vsctl_mock("list-ports", self.BR_NAME), 'tap99\n'),
         (self._vsctl_mock("--if-exists",
                           "--columns=name,external_ids,ofport", "list",
                           "Interface", "tap99"), RuntimeError()),
     ]
     tools.setup_mock_calls(self.execute, expected_calls_and_values)
     self.assertRaises(RuntimeError, self.br.get_vif_port_set)
     tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 29
0
 def test_get_vif_port_set_list_interface_error(self):
     expected_calls_and_values = [
         (self._vsctl_mock("list-ports", self.BR_NAME), 'tap99\n'),
         (self._vsctl_mock("--if-exists",
                           "--columns=name,external_ids,ofport",
                           "list", "Interface", "tap99"), RuntimeError()),
     ]
     tools.setup_mock_calls(self.execute, expected_calls_and_values)
     self.assertRaises(RuntimeError, self.br.get_vif_port_set)
     tools.verify_mock_calls(self.execute, expected_calls_and_values)
    def test_add_filter_rule(self):
        filter_dump_mod = ('# Generated by iptables_manager\n'
                           '*filter\n'
                           ':neutron-filter-top - [0:0]\n'
                           ':%(bn)s-FORWARD - [0:0]\n'
                           ':%(bn)s-INPUT - [0:0]\n'
                           ':%(bn)s-OUTPUT - [0:0]\n'
                           ':%(bn)s-filter - [0:0]\n'
                           ':%(bn)s-local - [0:0]\n'
                           '[0:0] -A FORWARD -j neutron-filter-top\n'
                           '[0:0] -A OUTPUT -j neutron-filter-top\n'
                           '[0:0] -A neutron-filter-top -j %(bn)s-local\n'
                           '[0:0] -A INPUT -j %(bn)s-INPUT\n'
                           '[0:0] -A OUTPUT -j %(bn)s-OUTPUT\n'
                           '[0:0] -A FORWARD -j %(bn)s-FORWARD\n'
                           '[0:0] -A %(bn)s-filter -j DROP\n'
                           '[0:0] -A %(bn)s-INPUT -s 0/0 -d 192.168.0.2 -j '
                           '%(bn)s-filter\n'
                           'COMMIT\n'
                           '# Completed by iptables_manager\n' % IPTABLES_ARG)

        raw_dump = _generate_raw_dump(IPTABLES_ARG)

        expected_calls_and_values = [
            (mock.call(['iptables-save', '-c'],
                       root_helper=self.root_helper), ''),
            (mock.call(['iptables-restore', '-c'],
                       process_input=(raw_dump + COMMENTED_NAT_DUMP +
                                      filter_dump_mod),
                       root_helper=self.root_helper), None),
            (mock.call(['iptables-save', '-c'],
                       root_helper=self.root_helper), ''),
            (mock.call(['iptables-restore', '-c'],
                       process_input=(raw_dump + COMMENTED_NAT_DUMP +
                                      FILTER_DUMP),
                       root_helper=self.root_helper), None),
        ]
        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.iptables.ipv4['filter'].add_chain('filter')
        self.iptables.ipv4['filter'].add_rule('filter', '-j DROP')
        self.iptables.ipv4['filter'].add_rule(
            'INPUT', '-s 0/0 -d 192.168.0.2 -j'
            ' %(bn)s-filter' % IPTABLES_ARG)
        self.iptables.apply()

        self.iptables.ipv4['filter'].remove_rule('filter', '-j DROP')
        self.iptables.ipv4['filter'].remove_rule(
            'INPUT', '-s 0/0 -d 192.168.0.2 -j'
            ' %(bn)s-filter' % IPTABLES_ARG)
        self.iptables.ipv4['filter'].remove_chain('filter')

        self.iptables.apply()

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 31
0
    def _test_get_traffic_counters_with_zero_helper(self, use_ipv6):
        self.iptables = iptables_manager.IptablesManager(use_ipv6=use_ipv6)
        self.execute = mock.patch.object(self.iptables, "execute").start()
        exp_packets = 800
        exp_bytes = 131802

        expected_calls_and_values = [
            (mock.call([
                'iptables', '-t', 'filter', '-L', 'OUTPUT', '-n', '-v', '-x',
                '-Z'
            ],
                       run_as_root=True), TRAFFIC_COUNTERS_DUMP),
            (mock.call([
                'iptables', '-t', 'raw', '-L', 'OUTPUT', '-n', '-v', '-x', '-Z'
            ],
                       run_as_root=True), ''),
            (mock.call([
                'iptables', '-t', 'mangle', '-L', 'OUTPUT', '-n', '-v', '-x',
                '-Z'
            ],
                       run_as_root=True), ''),
            (mock.call([
                'iptables', '-t', 'nat', '-L', 'OUTPUT', '-n', '-v', '-x', '-Z'
            ],
                       run_as_root=True), '')
        ]
        if use_ipv6:
            expected_calls_and_values.append((mock.call([
                'ip6tables', '-t', 'raw', '-L', 'OUTPUT', '-n', '-v', '-x',
                '-Z'
            ],
                                                        run_as_root=True), ''))
            expected_calls_and_values.append(
                (mock.call([
                    'ip6tables', '-t', 'filter', '-L', 'OUTPUT', '-n', '-v',
                    '-x', '-Z'
                ],
                           run_as_root=True), TRAFFIC_COUNTERS_DUMP))
            expected_calls_and_values.append((mock.call([
                'ip6tables', '-t', 'mangle', '-L', 'OUTPUT', '-n', '-v', '-x',
                '-Z'
            ],
                                                        run_as_root=True), ''))
            exp_packets *= 2
            exp_bytes *= 2

        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        acc = self.iptables.get_traffic_counters('OUTPUT', zero=True)
        self.assertEqual(acc['pkts'], exp_packets)
        self.assertEqual(acc['bytes'], exp_bytes)

        tools.verify_mock_calls(self.execute,
                                expected_calls_and_values,
                                any_order=True)
Esempio n. 32
0
    def _test_get_traffic_counters_with_zero_helper(self, use_ipv6):
        self.iptables = iptables_manager.IptablesManager(
            root_helper=self.root_helper, use_ipv6=use_ipv6)
        self.execute = mock.patch.object(self.iptables, "execute").start()
        exp_packets = 800
        exp_bytes = 131802

        iptables_dump = (
            'Chain OUTPUT (policy ACCEPT 400 packets, 65901 bytes)\n'
            '    pkts      bytes target     prot opt in     out     source'
            '               destination         \n'
            '     400   65901 chain1     all  --  *      *       0.0.0.0/0'
            '            0.0.0.0/0           \n'
            '     400   65901 chain2     all  --  *      *       0.0.0.0/0'
            '            0.0.0.0/0           \n')

        expected_calls_and_values = [
            (mock.call([
                'iptables', '-t', 'filter', '-L', 'OUTPUT', '-n', '-v', '-x',
                '-Z'
            ],
                       root_helper=self.root_helper), iptables_dump),
            (mock.call([
                'iptables', '-t', 'raw', '-L', 'OUTPUT', '-n', '-v', '-x', '-Z'
            ],
                       root_helper=self.root_helper), ''),
            (mock.call([
                'iptables', '-t', 'mangle', '-L', 'OUTPUT', '-n', '-v', '-x',
                '-Z'
            ],
                       root_helper=self.root_helper), ''),
            (mock.call([
                'iptables', '-t', 'nat', '-L', 'OUTPUT', '-n', '-v', '-x', '-Z'
            ],
                       root_helper=self.root_helper), '')
        ]
        if use_ipv6:
            expected_calls_and_values.append(
                (mock.call([
                    'ip6tables', '-t', 'filter', '-L', 'OUTPUT', '-n', '-v',
                    '-x', '-Z'
                ],
                           root_helper=self.root_helper), iptables_dump))
            exp_packets *= 2
            exp_bytes *= 2

        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        acc = self.iptables.get_traffic_counters('OUTPUT', zero=True)
        self.assertEqual(acc['pkts'], exp_packets)
        self.assertEqual(acc['bytes'], exp_bytes)

        tools.verify_mock_calls(self.execute,
                                expected_calls_and_values,
                                any_order=True)
Esempio n. 33
0
    def _test_add_and_remove_chain_helper(self, use_ipv6):
        self.iptables = iptables_manager.IptablesManager(root_helper=self.root_helper, use_ipv6=use_ipv6)
        self.execute = mock.patch.object(self.iptables, "execute").start()

        filter_dump_mod = (
            "# Generated by iptables_manager\n"
            "*filter\n"
            ":neutron-filter-top - [0:0]\n"
            ":%(bn)s-FORWARD - [0:0]\n"
            ":%(bn)s-INPUT - [0:0]\n"
            ":%(bn)s-OUTPUT - [0:0]\n"
            ":%(bn)s-filter - [0:0]\n"
            ":%(bn)s-local - [0:0]\n"
            "[0:0] -A FORWARD -j neutron-filter-top\n"
            "[0:0] -A OUTPUT -j neutron-filter-top\n"
            "[0:0] -A neutron-filter-top -j %(bn)s-local\n"
            "[0:0] -A INPUT -j %(bn)s-INPUT\n"
            "[0:0] -A OUTPUT -j %(bn)s-OUTPUT\n"
            "[0:0] -A FORWARD -j %(bn)s-FORWARD\n"
            "COMMIT\n"
            "# Completed by iptables_manager\n" % IPTABLES_ARG
        )

        expected_calls_and_values = [
            (mock.call(["iptables-save", "-c"], root_helper=self.root_helper), ""),
            (
                mock.call(
                    ["iptables-restore", "-c"],
                    process_input=RAW_DUMP + NAT_DUMP + filter_dump_mod,
                    root_helper=self.root_helper,
                ),
                None,
            ),
            (mock.call(["iptables-save", "-c"], root_helper=self.root_helper), ""),
            (
                mock.call(
                    ["iptables-restore", "-c"],
                    process_input=RAW_DUMP + NAT_DUMP + FILTER_DUMP,
                    root_helper=self.root_helper,
                ),
                None,
            ),
        ]
        if use_ipv6:
            self._extend_with_ip6tables_filter(expected_calls_and_values, FILTER_DUMP)

        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.iptables.ipv4["filter"].add_chain("filter")
        self.iptables.apply()

        self.iptables.ipv4["filter"].remove_chain("filter")
        self.iptables.apply()

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 34
0
    def test_rule_with_wrap_target(self):
        name = '0123456789' * 5
        wrap = "%s-%s" % (iptables_manager.binary_name,
                          iptables_manager.get_chain_name(name))

        iptables_args = {'bn': iptables_manager.binary_name, 'wrap': wrap}

        filter_dump_mod = ('# Generated by iptables_manager\n'
                           '*filter\n'
                           ':neutron-filter-top - [0:0]\n'
                           ':%(bn)s-FORWARD - [0:0]\n'
                           ':%(bn)s-INPUT - [0:0]\n'
                           ':%(bn)s-local - [0:0]\n'
                           ':%(wrap)s - [0:0]\n'
                           ':%(bn)s-OUTPUT - [0:0]\n'
                           '[0:0] -A FORWARD -j neutron-filter-top\n'
                           '[0:0] -A OUTPUT -j neutron-filter-top\n'
                           '[0:0] -A neutron-filter-top -j %(bn)s-local\n'
                           '[0:0] -A INPUT -j %(bn)s-INPUT\n'
                           '[0:0] -A OUTPUT -j %(bn)s-OUTPUT\n'
                           '[0:0] -A FORWARD -j %(bn)s-FORWARD\n'
                           '[0:0] -A %(bn)s-INPUT -s 0/0 -d 192.168.0.2 -j '
                           '%(wrap)s\n'
                           'COMMIT\n'
                           '# Completed by iptables_manager\n' % iptables_args)

        expected_calls_and_values = [
            (mock.call(['iptables-save', '-c'],
                       root_helper=self.root_helper), ''),
            (mock.call(['iptables-restore', '-c'],
                       process_input=NAT_DUMP + filter_dump_mod,
                       root_helper=self.root_helper), None),
            (mock.call(['iptables-save', '-c'],
                       root_helper=self.root_helper), ''),
            (mock.call(['iptables-restore', '-c'],
                       process_input=NAT_DUMP + FILTER_DUMP,
                       root_helper=self.root_helper), None),
        ]
        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.iptables.ipv4['filter'].add_chain(name)
        self.iptables.ipv4['filter'].add_rule(
            'INPUT', '-s 0/0 -d 192.168.0.2 -j'
            ' $%s' % name)
        self.iptables.apply()

        self.iptables.ipv4['filter'].remove_rule(
            'INPUT', '-s 0/0 -d 192.168.0.2 -j'
            ' $%s' % name)
        self.iptables.ipv4['filter'].remove_chain(name)

        self.iptables.apply()

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 35
0
    def _test_get_vif_ports(self, is_xen=False):
        pname = "tap99"
        ofport = "6"
        vif_id = uuidutils.generate_uuid()
        mac = "ca:fe:de:ad:be:ef"

        if is_xen:
            external_ids = '{xs-vif-uuid="%s", attached-mac="%s"}' % (vif_id, mac)
        else:
            external_ids = '{iface-id="%s", attached-mac="%s"}' % (vif_id, mac)

        # Each element is a tuple of (expected mock call, return_value)
        expected_calls_and_values = [
            (
                mock.call(["ovs-vsctl", self.TO, "list-ports", self.BR_NAME], root_helper=self.root_helper),
                "%s\n" % pname,
            ),
            (
                mock.call(
                    ["ovs-vsctl", self.TO, "get", "Interface", pname, "external_ids"], root_helper=self.root_helper
                ),
                external_ids,
            ),
            (
                mock.call(["ovs-vsctl", self.TO, "get", "Interface", pname, "ofport"], root_helper=self.root_helper),
                ofport,
            ),
        ]
        if is_xen:
            expected_calls_and_values.append(
                (
                    mock.call(
                        [
                            "xe",
                            "vif-param-get",
                            "param-name=other-config",
                            "param-key=nicira-iface-id",
                            "uuid=" + vif_id,
                        ],
                        root_helper=self.root_helper,
                    ),
                    vif_id,
                )
            )
        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        ports = self.br.get_vif_ports()
        self.assertEqual(1, len(ports))
        self.assertEqual(ports[0].port_name, pname)
        self.assertEqual(ports[0].ofport, ofport)
        self.assertEqual(ports[0].vif_id, vif_id)
        self.assertEqual(ports[0].vif_mac, mac)
        self.assertEqual(ports[0].switch.br_name, self.BR_NAME)
        tools.verify_mock_calls(self.execute, expected_calls_and_values)
    def _test_add_and_remove_chain_custom_binary_name_helper(self, use_ipv6):
        bn = ("abcdef" * 5)

        self.iptables = iptables_manager.IptablesManager(
            root_helper=self.root_helper,
            binary_name=bn,
            use_ipv6=use_ipv6)
        self.execute = mock.patch.object(self.iptables, "execute").start()

        iptables_args = {'bn': bn[:16], 'filter_rules': ''}

        filter_dump = FILTER_WITH_RULES_TEMPLATE % iptables_args

        filter_dump_ipv6 = FILTER_TEMPLATE % iptables_args

        filter_dump_mod = filter_dump

        nat_dump = NAT_TEMPLATE % iptables_args

        raw_dump = _generate_raw_dump(iptables_args)
        mangle_dump = _generate_mangle_dump(iptables_args)

        expected_calls_and_values = [
            (mock.call(['iptables-save', '-c'],
                       root_helper=self.root_helper),
             ''),
            (mock.call(['iptables-restore', '-c'],
                       process_input=(raw_dump + nat_dump + mangle_dump +
                                      filter_dump_mod),
                       root_helper=self.root_helper),
             None),
            (mock.call(['iptables-save', '-c'],
                       root_helper=self.root_helper),
             ''),
            (mock.call(['iptables-restore', '-c'],
                       process_input=(raw_dump + nat_dump + mangle_dump +
                                      filter_dump),
                       root_helper=self.root_helper),
             None),
        ]
        if use_ipv6:
            self._extend_with_ip6tables_filter(expected_calls_and_values,
                                               filter_dump_ipv6)

        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.iptables.ipv4['filter'].add_chain('filter')
        self.iptables.apply()

        self.iptables.ipv4['filter'].empty_chain('filter')
        self.iptables.apply()

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 37
0
    def _test_get_vif_port_set(self, is_xen):
        if is_xen:
            id_key = "xs-vif-uuid"
        else:
            id_key = "iface-id"

        headings = ["name", "external_ids"]
        data = [
            # A vif port on this bridge:
            ["tap99", {id_key: "tap99id", "attached-mac": "tap99mac"}, 1],
            # A vif port on this bridge not yet configured
            ["tap98", {id_key: "tap98id", "attached-mac": "tap98mac"}, []],
            # Another vif port on this bridge not yet configured
            ["tap97", {id_key: "tap97id", "attached-mac": "tap97mac"}, ["set", []]],
            # A vif port on another bridge:
            ["tap88", {id_key: "tap88id", "attached-mac": "tap88id"}, 1],
            # Non-vif port on this bridge:
            ["tun22", {}, 2],
        ]

        # Each element is a tuple of (expected mock call, return_value)
        expected_calls_and_values = [
            (
                mock.call(["ovs-vsctl", self.TO, "list-ports", self.BR_NAME], root_helper=self.root_helper),
                "tap99\ntun22",
            ),
            (
                mock.call(
                    [
                        "ovs-vsctl",
                        self.TO,
                        "--format=json",
                        "--",
                        "--columns=name,external_ids,ofport",
                        "list",
                        "Interface",
                    ],
                    root_helper=self.root_helper,
                ),
                self._encode_ovs_json(headings, data),
            ),
        ]
        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        if is_xen:
            get_xapi_iface_id = mock.patch.object(self.br, "get_xapi_iface_id").start()
            get_xapi_iface_id.return_value = "tap99id"

        port_set = self.br.get_vif_port_set()
        self.assertEqual(set(["tap99id"]), port_set)
        tools.verify_mock_calls(self.execute, expected_calls_and_values)
        if is_xen:
            get_xapi_iface_id.assert_called_once_with("tap99id")
Esempio n. 38
0
    def _test_add_raw_rule_helper(self, use_ipv6):
        self.iptables = iptables_manager.IptablesManager(root_helper=self.root_helper, use_ipv6=use_ipv6)
        self.execute = mock.patch.object(self.iptables, "execute").start()

        raw_dump_mod = (
            "# Generated by iptables_manager\n"
            "*raw\n"
            ":%(bn)s-OUTPUT - [0:0]\n"
            ":%(bn)s-PREROUTING - [0:0]\n"
            ":%(bn)s-raw - [0:0]\n"
            "[0:0] -A PREROUTING -j %(bn)s-PREROUTING\n"
            "[0:0] -A OUTPUT -j %(bn)s-OUTPUT\n"
            "[0:0] -A %(bn)s-PREROUTING -j CT --notrack\n"
            "COMMIT\n"
            "# Completed by iptables_manager\n" % IPTABLES_ARG
        )

        expected_calls_and_values = [
            (mock.call(["iptables-save", "-c"], root_helper=self.root_helper), ""),
            (
                mock.call(
                    ["iptables-restore", "-c"],
                    process_input=raw_dump_mod + NAT_DUMP + FILTER_DUMP,
                    root_helper=self.root_helper,
                ),
                None,
            ),
            (mock.call(["iptables-save", "-c"], root_helper=self.root_helper), ""),
            (
                mock.call(
                    ["iptables-restore", "-c"],
                    process_input=RAW_DUMP + NAT_DUMP + FILTER_DUMP,
                    root_helper=self.root_helper,
                ),
                None,
            ),
        ]
        if use_ipv6:
            self._extend_with_ip6tables_filter(expected_calls_and_values, FILTER_DUMP)

        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.iptables.ipv4["raw"].add_chain("raw")
        self.iptables.ipv4["raw"].add_rule("PREROUTING", "-j CT --notrack")

        self.iptables.apply()

        self.iptables.ipv4["raw"].remove_rule("PREROUTING", "-j CT --notrack")
        self.iptables.ipv4["raw"].remove_chain("raw")

        self.iptables.apply()

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 39
0
    def _test_add_filter_rule_helper(self, use_ipv6):
        self.iptables = iptables_manager.IptablesManager(use_ipv6=use_ipv6)
        self.execute = mock.patch.object(self.iptables, "execute").start()

        iptables_args = {}
        iptables_args.update(IPTABLES_ARG)
        filter_rules = (
            "[0:0] -A %(bn)s-filter -j DROP\n"
            "[0:0] -A %(bn)s-INPUT -s 0/0 -d 192.168.0.2 -j "
            "%(bn)s-filter\n" % iptables_args
        )
        iptables_args["filter_rules"] = filter_rules
        filter_dump_mod = FILTER_WITH_RULES_TEMPLATE % iptables_args

        raw_dump = RAW_DUMP % IPTABLES_ARG

        expected_calls_and_values = [
            (mock.call(["iptables-save", "-c"], run_as_root=True), ""),
            (
                mock.call(
                    ["iptables-restore", "-c"],
                    process_input=(RAW_DUMP + NAT_DUMP + MANGLE_DUMP + filter_dump_mod),
                    run_as_root=True,
                ),
                None,
            ),
            (mock.call(["iptables-save", "-c"], run_as_root=True), ""),
            (
                mock.call(
                    ["iptables-restore", "-c"],
                    process_input=(RAW_DUMP + NAT_DUMP + MANGLE_DUMP + FILTER_DUMP),
                    run_as_root=True,
                ),
                None,
            ),
        ]
        if use_ipv6:
            self._extend_with_ip6tables_filter(expected_calls_and_values, raw_dump + FILTER_DUMP)

        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.iptables.ipv4["filter"].add_chain("filter")
        self.iptables.ipv4["filter"].add_rule("filter", "-j DROP")
        self.iptables.ipv4["filter"].add_rule("INPUT", "-s 0/0 -d 192.168.0.2 -j" " %(bn)s-filter" % IPTABLES_ARG)
        self.iptables.apply()

        self.iptables.ipv4["filter"].remove_rule("filter", "-j DROP")
        self.iptables.ipv4["filter"].remove_rule("INPUT", "-s 0/0 -d 192.168.0.2 -j" " %(bn)s-filter" % IPTABLES_ARG)
        self.iptables.ipv4["filter"].remove_chain("filter")

        self.iptables.apply()

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 40
0
    def _test_empty_chain_custom_binary_name_helper(self, use_ipv6):
        bn = ("abcdef" * 5)[:16]

        self.iptables = iptables_manager.IptablesManager(binary_name=bn, use_ipv6=use_ipv6)
        self.execute = mock.patch.object(self.iptables, "execute").start()

        iptables_args = {"bn": bn}

        filter_dump = FILTER_TEMPLATE % iptables_args

        filter_rules = "[0:0] -A %(bn)s-filter -s 0/0 -d 192.168.0.2\n" % iptables_args
        iptables_args["filter_rules"] = filter_rules
        filter_dump_mod = FILTER_WITH_RULES_TEMPLATE % iptables_args

        nat_dump = NAT_TEMPLATE % iptables_args

        raw_dump = _generate_raw_dump(iptables_args)
        mangle_dump = _generate_mangle_dump(iptables_args)

        expected_calls_and_values = [
            (mock.call(["iptables-save", "-c"], run_as_root=True), ""),
            (
                mock.call(
                    ["iptables-restore", "-c"],
                    process_input=(raw_dump + nat_dump + mangle_dump + filter_dump_mod),
                    run_as_root=True,
                ),
                None,
            ),
            (mock.call(["iptables-save", "-c"], run_as_root=True), ""),
            (
                mock.call(
                    ["iptables-restore", "-c"],
                    process_input=(raw_dump + nat_dump + mangle_dump + filter_dump),
                    run_as_root=True,
                ),
                None,
            ),
        ]
        if use_ipv6:
            self._extend_with_ip6tables_filter(expected_calls_and_values, raw_dump + filter_dump)

        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.iptables.ipv4["filter"].add_chain("filter")
        self.iptables.ipv4["filter"].add_rule("filter", "-s 0/0 -d 192.168.0.2")
        self.iptables.apply()

        self.iptables.ipv4["filter"].remove_chain("filter")
        self.iptables.apply()

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
    def _test_get_traffic_counters_with_zero_helper(self, use_ipv6):
        self.iptables = iptables_manager.IptablesManager(
            root_helper=self.root_helper,
            use_ipv6=use_ipv6)
        self.execute = mock.patch.object(self.iptables, "execute").start()
        exp_packets = 800
        exp_bytes = 131802

        iptables_dump = (
            'Chain OUTPUT (policy ACCEPT 400 packets, 65901 bytes)\n'
            '    pkts      bytes target     prot opt in     out     source'
            '               destination         \n'
            '     400   65901 chain1     all  --  *      *       0.0.0.0/0'
            '            0.0.0.0/0           \n'
            '     400   65901 chain2     all  --  *      *       0.0.0.0/0'
            '            0.0.0.0/0           \n')

        expected_calls_and_values = [
            (mock.call(['iptables', '-t', 'filter', '-L', 'OUTPUT',
                        '-n', '-v', '-x', '-Z'],
                       root_helper=self.root_helper),
             iptables_dump),
            (mock.call(['iptables', '-t', 'raw', '-L', 'OUTPUT', '-n',
                        '-v', '-x', '-Z'],
                       root_helper=self.root_helper),
             ''),
            (mock.call(['iptables', '-t', 'mangle', '-L', 'OUTPUT', '-n',
                        '-v', '-x', '-Z'],
                       root_helper=self.root_helper),
             ''),
            (mock.call(['iptables', '-t', 'nat', '-L', 'OUTPUT', '-n',
                        '-v', '-x', '-Z'],
                       root_helper=self.root_helper),
             '')
        ]
        if use_ipv6:
            expected_calls_and_values.append(
                (mock.call(['ip6tables', '-t', 'filter', '-L', 'OUTPUT',
                            '-n', '-v', '-x', '-Z'],
                           root_helper=self.root_helper),
                 iptables_dump))
            exp_packets *= 2
            exp_bytes *= 2

        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        acc = self.iptables.get_traffic_counters('OUTPUT', zero=True)
        self.assertEqual(acc['pkts'], exp_packets)
        self.assertEqual(acc['bytes'], exp_bytes)

        tools.verify_mock_calls(self.execute, expected_calls_and_values,
                                any_order=True)
Esempio n. 42
0
 def test_get_vif_port_set_list_interface_error(self):
     expected_calls_and_values = [
         (mock.call(["ovs-vsctl", self.TO, "list-ports", self.BR_NAME],
                    root_helper=self.root_helper), 'tap99\n'),
         (mock.call([
             "ovs-vsctl", self.TO, "--format=json", "--",
             "--columns=name,external_ids", "list", "Interface"
         ],
                    root_helper=self.root_helper), RuntimeError()),
     ]
     tools.setup_mock_calls(self.execute, expected_calls_and_values)
     self.assertEqual(set(), self.br.get_vif_port_set())
     tools.verify_mock_calls(self.execute, expected_calls_and_values)
    def test_add_filter_rule(self):
        iptables_args = {}
        iptables_args.update(IPTABLES_ARG)
        filter_rules = ('[0:0] -A %(bn)s-filter -j DROP\n'
                        '[0:0] -A %(bn)s-INPUT -s 0/0 -d 192.168.0.2 -j '
                        '%(bn)s-filter\n' % iptables_args)
        iptables_args['filter_rules'] = filter_rules
        filter_dump_mod = FILTER_WITH_RULES_TEMPLATE % iptables_args

        raw_dump = _generate_raw_dump(IPTABLES_ARG)
        mangle_dump = _generate_mangle_dump(IPTABLES_ARG)

        expected_calls_and_values = [
            (mock.call(['iptables-save', '-c'],
                       root_helper=self.root_helper),
             ''),
            (mock.call(['iptables-restore', '-c'],
                       process_input=(raw_dump + COMMENTED_NAT_DUMP +
                                      mangle_dump + filter_dump_mod),
                       root_helper=self.root_helper),
             None),
            (mock.call(['iptables-save', '-c'],
                       root_helper=self.root_helper),
             ''),
            (mock.call(['iptables-restore', '-c'],
                       process_input=(raw_dump + COMMENTED_NAT_DUMP +
                                      mangle_dump + FILTER_DUMP),
                       root_helper=self.root_helper
                       ),
             None),
        ]
        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.iptables.ipv4['filter'].add_chain('filter')
        self.iptables.ipv4['filter'].add_rule('filter', '-j DROP')
        self.iptables.ipv4['filter'].add_rule('INPUT',
                                              '-s 0/0 -d 192.168.0.2 -j'
                                              ' %(bn)s-filter' % IPTABLES_ARG)
        self.iptables.apply()

        self.iptables.ipv4['filter'].remove_rule('filter', '-j DROP')
        self.iptables.ipv4['filter'].remove_rule('INPUT',
                                                 '-s 0/0 -d 192.168.0.2 -j'
                                                 ' %(bn)s-filter'
                                                 % IPTABLES_ARG)
        self.iptables.ipv4['filter'].remove_chain('filter')

        self.iptables.apply()

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 44
0
    def _test_get_vif_port_set(self, is_xen):
        if is_xen:
            id_key = 'xs-vif-uuid'
        else:
            id_key = 'iface-id'

        headings = ['name', 'external_ids', 'ofport']
        data = [
            # A vif port on this bridge:
            ['tap99', {
                id_key: 'tap99id',
                'attached-mac': 'tap99mac'
            }, 1],
            # A vif port on this bridge not yet configured
            ['tap98', {
                id_key: 'tap98id',
                'attached-mac': 'tap98mac'
            }, []],
            # Another vif port on this bridge not yet configured
            [
                'tap97', {
                    id_key: 'tap97id',
                    'attached-mac': 'tap97mac'
                }, ['set', []]
            ],

            # Non-vif port on this bridge:
            ['bogus', {}, 2],
        ]

        # Each element is a tuple of (expected mock call, return_value)
        expected_calls_and_values = [
            (self._vsctl_mock("list-ports", self.BR_NAME), 'tap99\\ntun22'),
            (self._vsctl_mock("--if-exists",
                              "--columns=name,external_ids,ofport", "list",
                              "Interface", 'tap99', 'tun22'),
             self._encode_ovs_json(headings, data)),
        ]
        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        if is_xen:
            get_xapi_iface_id = mock.patch.object(self.br,
                                                  'get_xapi_iface_id').start()
            get_xapi_iface_id.return_value = 'tap99id'

        port_set = self.br.get_vif_port_set()
        self.assertEqual(set(['tap99id']), port_set)
        tools.verify_mock_calls(self.execute, expected_calls_and_values)
        if is_xen:
            get_xapi_iface_id.assert_called_once_with('tap99id')
Esempio n. 45
0
    def _test_add_and_remove_chain_helper(self, use_ipv6):
        self.iptables = iptables_manager.IptablesManager(
            root_helper=self.root_helper, use_ipv6=use_ipv6)
        self.execute = mock.patch.object(self.iptables, "execute").start()

        filter_dump_mod = ('# Generated by iptables_manager\n'
                           '*filter\n'
                           ':neutron-filter-top - [0:0]\n'
                           ':%(bn)s-FORWARD - [0:0]\n'
                           ':%(bn)s-INPUT - [0:0]\n'
                           ':%(bn)s-OUTPUT - [0:0]\n'
                           ':%(bn)s-filter - [0:0]\n'
                           ':%(bn)s-local - [0:0]\n'
                           '[0:0] -A FORWARD -j neutron-filter-top\n'
                           '[0:0] -A OUTPUT -j neutron-filter-top\n'
                           '[0:0] -A neutron-filter-top -j %(bn)s-local\n'
                           '[0:0] -A INPUT -j %(bn)s-INPUT\n'
                           '[0:0] -A OUTPUT -j %(bn)s-OUTPUT\n'
                           '[0:0] -A FORWARD -j %(bn)s-FORWARD\n'
                           'COMMIT\n'
                           '# Completed by iptables_manager\n' % IPTABLES_ARG)

        expected_calls_and_values = [
            (mock.call(['iptables-save', '-c'],
                       root_helper=self.root_helper), ''),
            (mock.call(['iptables-restore', '-c'],
                       process_input=(RAW_DUMP + NAT_DUMP + MANGLE_DUMP +
                                      filter_dump_mod),
                       root_helper=self.root_helper), None),
            (mock.call(['iptables-save', '-c'],
                       root_helper=self.root_helper), ''),
            (mock.call(['iptables-restore', '-c'],
                       process_input=(RAW_DUMP + NAT_DUMP + MANGLE_DUMP +
                                      FILTER_DUMP),
                       root_helper=self.root_helper), None),
        ]
        if use_ipv6:
            self._extend_with_ip6tables_filter(expected_calls_and_values,
                                               FILTER_DUMP)

        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.iptables.ipv4['filter'].add_chain('filter')
        self.iptables.apply()

        self.iptables.ipv4['filter'].remove_chain('filter')
        self.iptables.apply()

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 46
0
    def test_get_vif_ports_with_bond(self):
        pname = "bond0"
        #NOTE(dprince): bond ports don't have records in the Interface table
        external_ids = ('{"data":[], "headings":[]}')

        # Each element is a tuple of (expected mock call, return_value)
        expected_calls_and_values = [
            (self._vsctl_mock("list-ports", self.BR_NAME), "%s\n" % pname),
            (self._vsctl_mock("--columns=name,external_ids,ofport", "list",
                              "Interface"), external_ids),
        ]
        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        ports = self.br.get_vif_ports()
        self.assertEqual(0, len(ports))
        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 47
0
    def _test_get_vif_port_by_id(self, iface_id, data):
        headings = ['external_ids', 'name', 'ofport']
        # Each element is a tuple of (expected mock call, return_value)
        expected_calls_and_values = [(mock.call([
            "ovs-vsctl", self.TO, "--format=json", "--",
            "--columns=external_ids,name,ofport", "find", "Interface",
            'external_ids:iface-id="%s"' % iface_id
        ],
                                                root_helper=self.root_helper),
                                      self._encode_ovs_json(headings, data))]

        tools.setup_mock_calls(self.execute, expected_calls_and_values)
        vif_port = self.br.get_vif_port_by_id(iface_id)

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
        return vif_port
Esempio n. 48
0
    def _test_get_vif_port_set(self, is_xen):
        if is_xen:
            id_key = 'xs-vif-uuid'
        else:
            id_key = 'iface-id'

        headings = ['name', 'external_ids']
        data = [
            # A vif port on this bridge:
            ['tap99', {
                id_key: 'tap99id',
                'attached-mac': 'tap99mac'
            }],
            # A vif port on another bridge:
            ['tap88', {
                id_key: 'tap88id',
                'attached-mac': 'tap88id'
            }],
            # Non-vif port on this bridge:
            ['tun22', {}],
        ]

        # Each element is a tuple of (expected mock call, return_value)
        expected_calls_and_values = [
            (mock.call(["ovs-vsctl", self.TO, "list-ports", self.BR_NAME],
                       root_helper=self.root_helper), 'tap99\ntun22'),
            (mock.call([
                "ovs-vsctl", self.TO, "--format=json", "--",
                "--columns=name,external_ids", "list", "Interface"
            ],
                       root_helper=self.root_helper),
             self._encode_ovs_json(headings, data)),
        ]
        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        if is_xen:
            get_xapi_iface_id = mock.patch.object(self.br,
                                                  'get_xapi_iface_id').start()
            get_xapi_iface_id.return_value = 'tap99id'

        port_set = self.br.get_vif_port_set()
        self.assertEqual(set(['tap99id']), port_set)
        tools.verify_mock_calls(self.execute, expected_calls_and_values)
        if is_xen:
            get_xapi_iface_id.assert_called_once_with('tap99id')
Esempio n. 49
0
    def test_add_patch_port(self):
        pname = "tap99"
        peer = "bar10"
        ofport = 6

        # Each element is a tuple of (expected mock call, return_value)
        command = ["--may-exist", "add-port", self.BR_NAME, pname]
        command.extend(["--", "set", "Interface", pname])
        command.extend(["type=patch", "options:peer=" + peer])
        expected_calls_and_values = [
            (self._vsctl_mock(*command), None),
            (self._vsctl_mock("--columns=ofport", "list", "Interface", pname),
             self._encode_ovs_json(['ofport'], [[ofport]]))
        ]
        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.assertEqual(self.br.add_patch_port(pname, peer), ofport)
        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 50
0
    def _test_get_vif_ports(self, is_xen=False):
        pname = "tap99"
        ofport = "6"
        vif_id = uuidutils.generate_uuid()
        mac = "ca:fe:de:ad:be:ef"

        if is_xen:
            external_ids = ('{xs-vif-uuid="%s", attached-mac="%s"}'
                            % (vif_id, mac))
        else:
            external_ids = ('{iface-id="%s", attached-mac="%s"}'
                            % (vif_id, mac))

        # Each element is a tuple of (expected mock call, return_value)
        expected_calls_and_values = [
            (mock.call(["ovs-vsctl", self.TO, "list-ports", self.BR_NAME],
                       root_helper=self.root_helper),
             "%s\n" % pname),
            (mock.call(["ovs-vsctl", self.TO, "get",
                        "Interface", pname, "external_ids"],
                       root_helper=self.root_helper),
             external_ids),
            (mock.call(["ovs-vsctl", self.TO, "get",
                        "Interface", pname, "ofport"],
                       root_helper=self.root_helper),
             ofport),
        ]
        if is_xen:
            expected_calls_and_values.append(
                (mock.call(["xe", "vif-param-get", "param-name=other-config",
                            "param-key=nicira-iface-id", "uuid=" + vif_id],
                           root_helper=self.root_helper),
                 vif_id)
            )
        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        ports = self.br.get_vif_ports()
        self.assertEqual(1, len(ports))
        self.assertEqual(ports[0].port_name, pname)
        self.assertEqual(ports[0].ofport, ofport)
        self.assertEqual(ports[0].vif_id, vif_id)
        self.assertEqual(ports[0].vif_mac, mac)
        self.assertEqual(ports[0].switch.br_name, self.BR_NAME)
        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 51
0
    def test_add_rule_exchanged_interface_and_ip(self):
        self.iptables = iptables_manager.IptablesManager(
            use_ipv6=False)
        self.execute = mock.patch.object(self.iptables, "execute").start()

        iptables_args = {}
        iptables_args.update(IPTABLES_ARG)
        filter_rules = ('-A %(bn)s-test-filter -d 192.168.0.2 -i tap-xxx '
                        '-j ACCEPT\n'
                        % iptables_args)
        iptables_args['filter_rules'] = filter_rules
        filter_dump_mod = FILTER_RESTORE_DUMP % iptables_args

        RESTORE_INPUT = ('# Generated by iptables_manager\n'
                         '*filter\n'
                         '-D run.py-test-filter 1\n'
                         '-I run.py-test-filter 1 '
                         '-i tap-xxx -d 192.168.0.2 -j ACCEPT\n'
                         'COMMIT\n'
                         '# Completed by iptables_manager\n'
                         % IPTABLES_ARG)

        expected_calls_and_values = [
            (mock.call(['iptables-save'],
                       run_as_root=True),
             (filter_dump_mod + MANGLE_RESTORE_DUMP +
              NAT_RESTORE_DUMP + RAW_RESTORE_DUMP)),
            (mock.call(['iptables-restore', '-n'],
                       process_input=RESTORE_INPUT,
                       run_as_root=True),
             None),
        ]

        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.iptables.ipv4['filter'].add_chain('test-filter')
        self.iptables.ipv4['filter'].add_rule('test-filter',
                                              '-i tap-xxx -d 192.168.0.2 '
                                              '-j ACCEPT')

        self.iptables.apply()

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 52
0
    def test_add_patch_port(self):
        pname = "tap99"
        peer = "bar10"
        ofport = "6"

        # Each element is a tuple of (expected mock call, return_value)
        command = ["ovs-vsctl", self.TO, "add-port", self.BR_NAME, pname]
        command.extend(["--", "set", "Interface", pname])
        command.extend(["type=patch", "options:peer=" + peer])
        expected_calls_and_values = [
            (mock.call(command, root_helper=self.root_helper), None),
            (mock.call(
                ["ovs-vsctl", self.TO, "get", "Interface", pname, "ofport"],
                root_helper=self.root_helper), ofport)
        ]
        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.assertEqual(self.br.add_patch_port(pname, peer), ofport)
        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 53
0
    def _test_get_vif_ports(self, is_xen=False):
        pname = "tap99"
        ofport = 6
        vif_id = uuidutils.generate_uuid()
        mac = "ca:fe:de:ad:be:ef"
        id_field = 'xs-vif-uuid' if is_xen else 'iface-id'
        external_ids = ('{"data":[[["map",[["attached-mac","%(mac)s"],'
                        '["%(id_field)s","%(vif)s"],'
                        '["iface-status","active"]]], '
                        '"%(name)s", %(ofport)s]],'
                        '"headings":["external_ids", "name", "ofport"]}' % {
                            'mac': mac,
                            'vif': vif_id,
                            'id_field': id_field,
                            'name': pname,
                            'ofport': ofport
                        })

        # Each element is a tuple of (expected mock call, return_value)
        expected_calls_and_values = [
            (self._vsctl_mock("list-ports", self.BR_NAME), "%s\n" % pname),
            (self._vsctl_mock("--columns=name,external_ids,ofport", "list",
                              "Interface"), external_ids),
        ]
        if is_xen:
            expected_calls_and_values.append(
                (mock.call([
                    "xe", "vif-param-get", "param-name=other-config",
                    "param-key=nicira-iface-id", "uuid=" + vif_id
                ],
                           run_as_root=True), vif_id))
        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        ports = self.br.get_vif_ports()
        self.assertEqual(1, len(ports))
        self.assertEqual(ports[0].port_name, pname)
        self.assertEqual(ports[0].ofport, ofport)
        self.assertEqual(ports[0].vif_id, vif_id)
        self.assertEqual(ports[0].vif_mac, mac)
        self.assertEqual(ports[0].switch.br_name, self.BR_NAME)
        tools.verify_mock_calls(self.execute, expected_calls_and_values)
    def _test_add_and_remove_chain_helper(self, use_ipv6):
        self.iptables = iptables_manager.IptablesManager(
            root_helper=self.root_helper,
            use_ipv6=use_ipv6)
        self.execute = mock.patch.object(self.iptables, "execute").start()

        filter_dump_mod = FILTER_WITH_RULES_TEMPLATE % IPTABLES_ARG

        expected_calls_and_values = [
            (mock.call(['iptables-save', '-c'],
                       root_helper=self.root_helper),
             ''),
            (mock.call(['iptables-restore', '-c'],
                       process_input=(RAW_DUMP + NAT_DUMP + MANGLE_DUMP +
                                      filter_dump_mod),
                       root_helper=self.root_helper),
             None),
            (mock.call(['iptables-save', '-c'],
                       root_helper=self.root_helper),
             ''),
            (mock.call(['iptables-restore', '-c'],
                       process_input=(RAW_DUMP + NAT_DUMP + MANGLE_DUMP +
                                      FILTER_DUMP),
                       root_helper=self.root_helper),
             None),
        ]
        if use_ipv6:
            self._extend_with_ip6tables_filter(expected_calls_and_values,
                                               FILTER_DUMP)

        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.iptables.ipv4['filter'].add_chain('filter')
        self.iptables.apply()

        self.iptables.ipv4['filter'].remove_chain('filter')
        self.iptables.apply()

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 55
0
    def _test_get_vif_port_by_id(self,
                                 iface_id,
                                 data,
                                 br_name=None,
                                 extra_calls_and_values=None):
        headings = ['external_ids', 'name', 'ofport']

        # Each element is a tuple of (expected mock call, return_value)
        expected_calls_and_values = [(mock.call([
            "ovs-vsctl", self.TO, "--format=json", "--",
            "--columns=external_ids,name,ofport", "find", "Interface",
            'external_ids:iface-id="%s"' % iface_id
        ],
                                                root_helper=self.root_helper),
                                      self._encode_ovs_json(headings, data))]
        if data:
            if not br_name:
                br_name = self.BR_NAME

            # Only the last information list in 'data' is used, so if more
            # than one vif is described in data, the rest must be declared
            # in the argument 'expected_calls_and_values'.
            if extra_calls_and_values:
                expected_calls_and_values.extend(extra_calls_and_values)

            expected_calls_and_values.append(
                (mock.call([
                    "ovs-vsctl", self.TO, "iface-to-br",
                    data[-1][headings.index('name')]
                ],
                           root_helper=self.root_helper), br_name))
        tools.setup_mock_calls(self.execute, expected_calls_and_values)
        vif_port = self.br.get_vif_port_by_id(iface_id)

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
        return vif_port
Esempio n. 56
0
    def test_add_tunnel_port(self):
        pname = "tap99"
        local_ip = "1.1.1.1"
        remote_ip = "9.9.9.9"
        ofport = 6
        command = ["--may-exist", "add-port", self.BR_NAME, pname]
        command.extend(["--", "set", "Interface", pname])
        command.extend([
            "type=gre", "options:df_default=true",
            "options:remote_ip=" + remote_ip, "options:local_ip=" + local_ip,
            "options:in_key=flow", "options:out_key=flow"
        ])
        # Each element is a tuple of (expected mock call, return_value)
        expected_calls_and_values = [
            (self._vsctl_mock(*command), None),
            (self._vsctl_mock("--columns=ofport", "list", "Interface", pname),
             self._encode_ovs_json(['ofport'], [[ofport]])),
        ]
        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.assertEqual(self.br.add_tunnel_port(pname, remote_ip, local_ip),
                         ofport)

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 57
0
    def test_add_and_remove_chain_custom_binary_name(self):
        bn = ("abcdef" * 5)

        self.iptables = (iptables_manager.
                         IptablesManager(root_helper=self.root_helper,
                                         binary_name=bn))
        self.execute = mock.patch.object(self.iptables, "execute").start()

        iptables_args = {'bn': bn[:16]}

        filter_dump = ('# Generated by iptables_manager\n'
                       '*filter\n'
                       ':neutron-filter-top - [0:0]\n'
                       ':%(bn)s-FORWARD - [0:0]\n'
                       ':%(bn)s-INPUT - [0:0]\n'
                       ':%(bn)s-local - [0:0]\n'
                       ':%(bn)s-filter - [0:0]\n'
                       ':%(bn)s-OUTPUT - [0:0]\n'
                       '[0:0] -A FORWARD -j neutron-filter-top\n'
                       '[0:0] -A OUTPUT -j neutron-filter-top\n'
                       '[0:0] -A neutron-filter-top -j %(bn)s-local\n'
                       '[0:0] -A INPUT -j %(bn)s-INPUT\n'
                       '[0:0] -A OUTPUT -j %(bn)s-OUTPUT\n'
                       '[0:0] -A FORWARD -j %(bn)s-FORWARD\n'
                       'COMMIT\n'
                       '# Completed by iptables_manager\n' % iptables_args)

        filter_dump_mod = ('# Generated by iptables_manager\n'
                           '*filter\n'
                           ':neutron-filter-top - [0:0]\n'
                           ':%(bn)s-FORWARD - [0:0]\n'
                           ':%(bn)s-INPUT - [0:0]\n'
                           ':%(bn)s-local - [0:0]\n'
                           ':%(bn)s-filter - [0:0]\n'
                           ':%(bn)s-OUTPUT - [0:0]\n'
                           '[0:0] -A FORWARD -j neutron-filter-top\n'
                           '[0:0] -A OUTPUT -j neutron-filter-top\n'
                           '[0:0] -A neutron-filter-top -j %(bn)s-local\n'
                           '[0:0] -A INPUT -j %(bn)s-INPUT\n'
                           '[0:0] -A OUTPUT -j %(bn)s-OUTPUT\n'
                           '[0:0] -A FORWARD -j %(bn)s-FORWARD\n'
                           'COMMIT\n'
                           '# Completed by iptables_manager\n'
                           % iptables_args)

        nat_dump = ('# Generated by iptables_manager\n'
                    '*nat\n'
                    ':neutron-postrouting-bottom - [0:0]\n'
                    ':%(bn)s-OUTPUT - [0:0]\n'
                    ':%(bn)s-snat - [0:0]\n'
                    ':%(bn)s-PREROUTING - [0:0]\n'
                    ':%(bn)s-float-snat - [0:0]\n'
                    ':%(bn)s-POSTROUTING - [0:0]\n'
                    '[0:0] -A PREROUTING -j %(bn)s-PREROUTING\n'
                    '[0:0] -A OUTPUT -j %(bn)s-OUTPUT\n'
                    '[0:0] -A POSTROUTING -j %(bn)s-POSTROUTING\n'
                    '[0:0] -A POSTROUTING -j neutron-postrouting-bottom\n'
                    '[0:0] -A neutron-postrouting-bottom -j %(bn)s-snat\n'
                    '[0:0] -A %(bn)s-snat -j '
                    '%(bn)s-float-snat\n'
                    'COMMIT\n'
                    '# Completed by iptables_manager\n' % iptables_args)

        expected_calls_and_values = [
            (mock.call(['iptables-save', '-c'],
                       root_helper=self.root_helper),
             ''),
            (mock.call(['iptables-restore', '-c'],
                       process_input=nat_dump + filter_dump_mod,
                       root_helper=self.root_helper),
             None),
            (mock.call(['iptables-save', '-c'],
                       root_helper=self.root_helper),
             ''),
            (mock.call(['iptables-restore', '-c'],
                       process_input=nat_dump + filter_dump,
                       root_helper=self.root_helper),
             None),
        ]
        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.iptables.ipv4['filter'].add_chain('filter')
        self.iptables.apply()

        self.iptables.ipv4['filter'].empty_chain('filter')
        self.iptables.apply()

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
    def _test_add_nat_rule_helper(self, use_ipv6):
        self.iptables = iptables_manager.IptablesManager(
            root_helper=self.root_helper,
            use_ipv6=use_ipv6)
        self.execute = mock.patch.object(self.iptables, "execute").start()

        nat_dump = NAT_TEMPLATE % IPTABLES_ARG

        nat_dump_mod = ('# Generated by iptables_manager\n'
                        '*nat\n'
                        ':neutron-postrouting-bottom - [0:0]\n'
                        ':%(bn)s-OUTPUT - [0:0]\n'
                        ':%(bn)s-POSTROUTING - [0:0]\n'
                        ':%(bn)s-PREROUTING - [0:0]\n'
                        ':%(bn)s-float-snat - [0:0]\n'
                        ':%(bn)s-nat - [0:0]\n'
                        ':%(bn)s-snat - [0:0]\n'
                        '[0:0] -A PREROUTING -j %(bn)s-PREROUTING\n'
                        '[0:0] -A OUTPUT -j %(bn)s-OUTPUT\n'
                        '[0:0] -A POSTROUTING -j %(bn)s-POSTROUTING\n'
                        '[0:0] -A POSTROUTING -j neutron-postrouting-bottom\n'
                        '[0:0] -A neutron-postrouting-bottom -j %(bn)s-snat\n'
                        '[0:0] -A %(bn)s-snat -j %(bn)s-float-snat\n'
                        '[0:0] -A %(bn)s-PREROUTING -d 192.168.0.3 -j '
                        '%(bn)s-nat\n'
                        '[0:0] -A %(bn)s-nat -p tcp --dport 8080 -j '
                        'REDIRECT --to-port 80\n'
                        'COMMIT\n'
                        '# Completed by iptables_manager\n'
                        % IPTABLES_ARG)

        expected_calls_and_values = [
            (mock.call(['iptables-save', '-c'],
                       root_helper=self.root_helper),
             ''),
            (mock.call(['iptables-restore', '-c'],
                       process_input=(RAW_DUMP + nat_dump_mod + MANGLE_DUMP +
                                      FILTER_DUMP),
                       root_helper=self.root_helper),
             None),
            (mock.call(['iptables-save', '-c'],
                       root_helper=self.root_helper),
             ''),
            (mock.call(['iptables-restore', '-c'],
                       process_input=(RAW_DUMP + nat_dump + MANGLE_DUMP +
                                      FILTER_DUMP),
                       root_helper=self.root_helper),
             None),
        ]
        if use_ipv6:
            self._extend_with_ip6tables_filter(expected_calls_and_values,
                                               FILTER_DUMP)

        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.iptables.ipv4['nat'].add_chain('nat')
        self.iptables.ipv4['nat'].add_rule('PREROUTING',
                                           '-d 192.168.0.3 -j '
                                           '%(bn)s-nat' % IPTABLES_ARG)
        self.iptables.ipv4['nat'].add_rule('nat',
                                           '-p tcp --dport 8080' +
                                           ' -j REDIRECT --to-port 80')

        self.iptables.apply()

        self.iptables.ipv4['nat'].remove_rule('nat',
                                              '-p tcp --dport 8080 -j'
                                              ' REDIRECT --to-port 80')
        self.iptables.ipv4['nat'].remove_rule('PREROUTING',
                                              '-d 192.168.0.3 -j '
                                              '%(bn)s-nat' % IPTABLES_ARG)
        self.iptables.ipv4['nat'].remove_chain('nat')

        self.iptables.apply()

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Esempio n. 59
0
    def _test_rule_with_wrap_target_helper(self, use_ipv6):
        self.iptables = iptables_manager.IptablesManager(use_ipv6=use_ipv6)
        self.execute = mock.patch.object(self.iptables, "execute").start()

        name = '0123456789' * 5
        wrap = "%s-%s" % (iptables_manager.binary_name,
                          iptables_manager.get_chain_name(name))

        iptables_args = {'bn': iptables_manager.binary_name, 'wrap': wrap}

        filter_dump_mod = ('# Generated by iptables_manager\n'
                           '*filter\n'
                           ':neutron-filter-top - [0:0]\n'
                           ':%(wrap)s - [0:0]\n'
                           ':%(bn)s-FORWARD - [0:0]\n'
                           ':%(bn)s-INPUT - [0:0]\n'
                           ':%(bn)s-OUTPUT - [0:0]\n'
                           ':%(bn)s-local - [0:0]\n'
                           '[0:0] -A FORWARD -j neutron-filter-top\n'
                           '[0:0] -A OUTPUT -j neutron-filter-top\n'
                           '[0:0] -A neutron-filter-top -j %(bn)s-local\n'
                           '[0:0] -A INPUT -j %(bn)s-INPUT\n'
                           '[0:0] -A OUTPUT -j %(bn)s-OUTPUT\n'
                           '[0:0] -A FORWARD -j %(bn)s-FORWARD\n'
                           '[0:0] -A %(bn)s-INPUT -s 0/0 -d 192.168.0.2 -j '
                           '%(wrap)s\n'
                           'COMMIT\n'
                           '# Completed by iptables_manager\n' % iptables_args)

        raw_dump = RAW_DUMP % IPTABLES_ARG

        expected_calls_and_values = [
            (mock.call(['iptables-save', '-c'], run_as_root=True), ''),
            (mock.call(['iptables-restore', '-c'],
                       process_input=(RAW_DUMP + NAT_DUMP + MANGLE_DUMP +
                                      filter_dump_mod),
                       run_as_root=True), None),
            (mock.call(['iptables-save', '-c'], run_as_root=True), ''),
            (mock.call(['iptables-restore', '-c'],
                       process_input=(RAW_DUMP + NAT_DUMP + MANGLE_DUMP +
                                      FILTER_DUMP),
                       run_as_root=True), None),
        ]
        if use_ipv6:
            self._extend_with_ip6tables_filter(expected_calls_and_values,
                                               raw_dump + FILTER_DUMP)

        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        self.iptables.ipv4['filter'].add_chain(name)
        self.iptables.ipv4['filter'].add_rule(
            'INPUT', '-s 0/0 -d 192.168.0.2 -j'
            ' $%s' % name)
        self.iptables.apply()

        self.iptables.ipv4['filter'].remove_rule(
            'INPUT', '-s 0/0 -d 192.168.0.2 -j'
            ' $%s' % name)
        self.iptables.ipv4['filter'].remove_chain(name)

        self.iptables.apply()

        tools.verify_mock_calls(self.execute, expected_calls_and_values)