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)
Beispiel #2
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)
Beispiel #3
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)
Beispiel #4
0
    def _test_get_vif_port_by_id(self, ofport=None):
        expected_output = ('external_ids : {attached-mac="aa:bb:cc:dd:ee:ff", '
                           'iface-id="tap99id",'
                           'iface-status=active, '
                           'vm-uuid="tap99vm"}'
                           '\nname : "tap99"\nofport : %(ofport)s\n')

        # Each element is a tuple of (expected mock call, return_value)
        expected_calls_and_values = [
            (mock.call([
                "ovs-vsctl", self.TO, "--",
                "--columns=external_ids,name,ofport", "find", "Interface",
                'external_ids:iface-id="tap99id"'
            ],
                       root_helper=self.root_helper), expected_output % {
                           'ofport': ofport or '[]'
                       }),
        ]
        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        vif_port = self.br.get_vif_port_by_id('tap99id')
        self.assertEqual(vif_port.vif_id, 'tap99id')
        self.assertEqual(vif_port.vif_mac, 'aa:bb:cc:dd:ee:ff')
        self.assertEqual(vif_port.port_name, 'tap99')
        tools.verify_mock_calls(self.execute, expected_calls_and_values)
        return vif_port
    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)
    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)
Beispiel #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)
Beispiel #8
0
    def _test_get_vif_port_by_id(self, iface_id, data, br_name=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

            expected_calls_and_values.append(
                (mock.call([
                    "ovs-vsctl", self.TO, "iface-to-br",
                    data[0][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
Beispiel #9
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)
Beispiel #10
0
    def test_add_vxlan_csum_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 = True
        tunnel_csum = True
        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=true",
            "options:remote_ip=" + remote_ip, "options:local_ip=" + local_ip,
            "options:in_key=flow", "options:out_key=flow", "options:csum=true"
        ])
        # 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, tunnel_csum), ofport)

        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)
Beispiel #12
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)
Beispiel #13
0
    def test_get_port_tag_dict(self):
        headings = ["name", "tag"]
        data = [
            ["int-br-eth2", set()],
            ["patch-tun", set()],
            ["qr-76d9e6b6-21", 1],
            ["tapce5318ff-78", 1],
            ["tape1400310-e6", 1],
        ]

        # 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),
                "\n".join((iface for iface, tag in data)),
            ),
            (
                mock.call(
                    ["ovs-vsctl", self.TO, "--format=json", "--", "--columns=name,tag", "list", "Port"],
                    root_helper=self.root_helper,
                ),
                self._encode_ovs_json(headings, data),
            ),
        ]
        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        port_tags = self.br.get_port_tag_dict()
        self.assertEqual(
            port_tags,
            {u"int-br-eth2": [], u"patch-tun": [], u"qr-76d9e6b6-21": 1, u"tapce5318ff-78": 1, u"tape1400310-e6": 1},
        )
Beispiel #14
0
    def test_get_port_tag_dict(self):
        headings = ['name', 'tag']
        data = [
            ['int-br-eth2', set()],
            ['patch-tun', set()],
            ['qr-76d9e6b6-21', 1],
            ['tapce5318ff-78', 1],
            ['tape1400310-e6', 1],
        ]

        # 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), '\n'.join(
                           (iface for iface, tag in data))),
            (mock.call([
                "ovs-vsctl", self.TO, "--format=json", "--",
                "--columns=name,tag", "list", "Port"
            ],
                       root_helper=self.root_helper),
             self._encode_ovs_json(headings, data)),
        ]
        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        port_tags = self.br.get_port_tag_dict()
        self.assertEqual(
            port_tags, {
                u'int-br-eth2': [],
                u'patch-tun': [],
                u'qr-76d9e6b6-21': 1,
                u'tapce5318ff-78': 1,
                u'tape1400310-e6': 1
            })
    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)
Beispiel #16
0
    def test_get_port_tag_dict(self):
        headings = ['name', 'tag']
        data = [
            ['int-br-eth2', set()],
            ['patch-tun', set()],
            ['qr-76d9e6b6-21', 1],
            ['tapce5318ff-78', 1],
            ['tape1400310-e6', 1],
        ]

        # 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),
             '\n'.join((iface for iface, tag in data))),
            (mock.call(["ovs-vsctl", self.TO, "--format=json",
                        "--", "--columns=name,tag",
                        "list", "Port"],
                       root_helper=self.root_helper),
             self._encode_ovs_json(headings, data)),
        ]
        tools.setup_mock_calls(self.execute, expected_calls_and_values)

        port_tags = self.br.get_port_tag_dict()
        self.assertEqual(
            port_tags,
            {u'int-br-eth2': [],
             u'patch-tun': [],
             u'qr-76d9e6b6-21': 1,
             u'tapce5318ff-78': 1,
             u'tape1400310-e6': 1}
        )
    def _test_add_and_remove_chain_helper(self, use_ipv6):
        self.iptables = iptables_manager.IptablesManager(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'], 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.apply()

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

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Beispiel #18
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)
Beispiel #19
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
Beispiel #20
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)
    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)
Beispiel #22
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)
Beispiel #23
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
Beispiel #24
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 = [
            "ovs-vsctl", self.TO, '--', "--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 = [
            (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,
                                    constants.TYPE_VXLAN, vxlan_udp_port,
                                    dont_fragment), ofport)

        tools.verify_mock_calls(self.execute, expected_calls_and_values)
Beispiel #25
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)
    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)
    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)
Beispiel #28
0
    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)
Beispiel #29
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)
Beispiel #30
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_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)
    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)
Beispiel #33
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')
    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)
Beispiel #35
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)
    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)
    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_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)
    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)
Beispiel #40
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)
Beispiel #41
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)
Beispiel #42
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_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)
Beispiel #44
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)
Beispiel #45
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_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)
Beispiel #47
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)
Beispiel #48
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)
Beispiel #49
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)
Beispiel #50
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")
    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)
    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)
    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)
Beispiel #54
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)
Beispiel #56
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)
Beispiel #57
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)
Beispiel #58
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)