HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

test/networkd-test.py

52,019 bytesGit mode 100755Download original fileLGPL-2.1-or-later

Git blob: 27619da6ff1ab18dd7edfbdf59045496c15c8751

Lines 1001–1383 of 1,383

        self.do_test(coldplug=None, extra_opts='IPv6AcceptRA=no', dhcp_mode='ipv4')
 
        try:
            # should have received the fixed IP above
            out = subprocess.check_output(['ip', '-4', 'a', 'show', 'dev', self.iface])
            self.assertRegex(out, b'inet 192.168.5.210/24 .* scope global dynamic')
            # static hostname wins over transient one, thus *not* applied
            self.assertEqual(socket.gethostname(), 'foobarqux')
        except AssertionError:
            self.show_journal('systemd-networkd.service')
            self.show_journal('systemd-hostnamed.service')
            self.print_server_log()
            raise
 
 
class NetworkdClientTest(ClientTestBase, unittest.TestCase):
    """Test networkd client against networkd server"""
 
    def setUp(self):
        super().setUp()
        self.dnsmasq = None
 
    def create_iface(self, ipv6=False, dhcpserver_opts=None):
        """Create test interface with DHCP server behind it"""
 
        # run "router-side" networkd in own mount namespace to shield it from
        # "client-side" configuration and networkd
        (fd, script) = tempfile.mkstemp(prefix='networkd-router.sh')
        self.addCleanup(os.remove, script)
        with os.fdopen(fd, 'w+') as f:
            f.write(
                '''\
#!/bin/sh
set -eu
mkdir -p /run/systemd/network
mkdir -p /run/systemd/netif
mkdir -p /run/systemd/report
mkdir -p /run/systemd/resolve.hook
mkdir -p /var/lib/systemd/network
mount -t tmpfs none /run/systemd/network
mount -t tmpfs none /run/systemd/netif
mount -t tmpfs none /run/systemd/report
mount -t tmpfs none /run/systemd/resolve.hook
mount -t tmpfs none /var/lib/systemd/network
[ ! -e /run/dbus ] || mount -t tmpfs none /run/dbus
# create router/client veth pair
cat <<EOF >/run/systemd/network/50-test.netdev
[NetDev]
Name={ifr}
Kind=veth
 
[Peer]
Name={ifc}
EOF
 
cat <<EOF >/run/systemd/network/50-test.network
[Match]
Name={ifr}
 
[Network]
IPv6AcceptRA=no
Address=192.168.5.1/24
{addr6}
DHCPServer=yes
 
[DHCPServer]
PoolOffset=10
PoolSize=50
DNS=192.168.5.1
{dhopts}
EOF
 
# For the networkd instance invoked below cannot support varlink connection.
# Hence, 'networkctl persistent-storage yes' cannot be used.
export SYSTEMD_NETWORK_PERSISTENT_STORAGE_READY=1
 
# Generate debugging logs.
export SYSTEMD_LOG_LEVEL=debug
 
# run networkd as in systemd-networkd.service
exec $(systemctl cat systemd-networkd.service | sed -n '/^ExecStart=/ {{ s/^.*=//; s/^[@+-]//; s/^!*//; p}}')
'''.format(
                    ifr=self.if_router,
                    ifc=self.iface,
                    addr6=('Address=2600::1/64' if ipv6 else ''),
                    dhopts=(dhcpserver_opts or ''),
                )
            )
 
            os.fchmod(fd, 0o755)
 
        subprocess.check_call(
            [
                'systemd-run',
                '--unit=networkd-test-router.service',
                '-p', 'InaccessibleDirectories=-/etc/systemd/network',
                '-p', 'InaccessibleDirectories=-/run/systemd/network',
                '-p', 'InaccessibleDirectories=-/run/systemd/netif',
                '-p', 'InaccessibleDirectories=-/run/systemd/report',
                '-p', 'InaccessibleDirectories=-/run/systemd/resolve.hook',
                '-p', 'InaccessibleDirectories=-/var/lib/systemd/network',
                '--service-type=notify',
                script,
            ]
        )  # fmt: skip
 
        # wait until devices got created
        for _ in range(50):
            if subprocess.run(
                    ['ip', 'link', 'show', 'dev', self.if_router],
                    stdout=subprocess.DEVNULL,
                    stderr=subprocess.DEVNULL,
            ).returncode == 0:  # fmt: skip
                break
            time.sleep(0.1)
        else:
            subprocess.call(['ip', 'link', 'show', 'dev', self.if_router])
            self.fail(f'Timed out waiting for {self.if_router} created.')
 
    def shutdown_iface(self):
        """Remove test interface and stop DHCP server"""
 
        if self.if_router:
            subprocess.check_call(['systemctl', 'stop', 'networkd-test-router.service'])
            # ensure failed transient unit does not stay around
            subprocess.call(['systemctl', 'reset-failed', 'networkd-test-router.service'])
            subprocess.call(['ip', 'link', 'del', 'dev', self.if_router])
            self.if_router = None
 
    def print_server_log(self):
        """Print DHCP server log for debugging failures"""
 
        self.show_journal('networkd-test-router.service')
 
    @unittest.skip('networkd does not have DHCPv6 server support')
    def test_hotplug_dhcp_ip6(self):
        pass
 
    @unittest.skip('networkd does not have DHCPv6 server support')
    def test_coldplug_dhcp_ip6(self):
        pass
 
    def test_search_domains(self):
 
        # we don't use this interface for this test
        self.if_router = None
 
        self.write_network(
            '50-test.netdev',
            '''\
[NetDev]
Name=dummy0
Kind=dummy
MACAddress=12:34:56:78:9a:bc
''',
        )
        self.write_network(
            '50-test.network',
            '''\
[Match]
Name=dummy0
[Network]
IPv6AcceptRA=no
Address=192.168.42.100/24
DNS=192.168.42.1
Domains= one two three four five six seven eight nine ten
''',
        )
 
        self.start_unit('systemd-networkd')
 
        for timeout in range(50):
            with open(RESOLV_CONF) as f:
                contents = f.read()
            if ' one' in contents:
                break
            time.sleep(0.1)
        self.assertRegex(contents, 'search .*one two three four five six seven eight nine ten')
 
    def test_dropin(self):
        # we don't use this interface for this test
        self.if_router = None
 
        self.write_network(
            '50-test.netdev',
            '''\
[NetDev]
Name=dummy0
Kind=dummy
MACAddress=12:34:56:78:9a:bc
''',
        )
        self.write_network(
            '50-test.network',
            '''\
[Match]
Name=dummy0
[Network]
IPv6AcceptRA=no
Address=192.168.42.100/24
DNS=192.168.42.1
''',
        )
        self.write_network_dropin(
            '50-test.network',
            'dns',
            '''\
[Network]
DNS=127.0.0.1
''',
        )
 
        self.start_unit('systemd-resolved')
        self.start_unit('systemd-networkd')
 
        subprocess.check_call([NETWORKD_WAIT_ONLINE, '--interface', 'dummy0', '--timeout=10'])
 
        out = subprocess.check_output(['networkctl', 'status', 'dummy0'])
        self.assertIn(b'50-test.netdev', out)
        self.assertIn(b'50-test.network.d/dns.conf', out)
 
        for _ in range(50):
            with open(RESOLV_CONF) as f:
                contents = f.read()
            if 'nameserver 127.0.0.1\n' in contents and 'nameserver 192.168.42.1\n' in contents:
                break
            time.sleep(0.1)
        else:
            self.fail(f'Expected DNS servers not found in resolv.conf: {contents}')
 
    def test_dhcp_timezone(self):
        """networkd sets time zone from DHCP"""
 
        def get_tz():
            out = subprocess.check_output(
                [
                    'busctl',
                    'get-property',
                    'org.freedesktop.timedate1',
                    '/org/freedesktop/timedate1',
                    'org.freedesktop.timedate1',
                    'Timezone',
                ]
            )
            assert out.startswith(b's "')
            out = out.strip()
            assert out.endswith(b'"')
            return out[3:-1].decode()
 
        orig_timezone = get_tz()
        self.addCleanup(subprocess.call, ['timedatectl', 'set-timezone', orig_timezone])
 
        self.create_iface(dhcpserver_opts='EmitTimezone=yes\nTimezone=Pacific/Honolulu')
        self.do_test(
            coldplug=None, extra_opts='IPv6AcceptRA=false\n[DHCP]\nUseTimezone=true', dhcp_mode='ipv4'
        )
 
        # Should have applied the received timezone. This is asynchronous, so we need to wait for a while:
        for _ in range(20):
            tz = get_tz()
            if tz == 'Pacific/Honolulu':
                break
            time.sleep(0.5)
        else:
            self.show_journal('systemd-networkd.service')
            self.show_journal('systemd-timedated.service')
            self.fail(f'Timezone: {tz}, expected: Pacific/Honolulu')
 
 
class MatchClientTest(unittest.TestCase, NetworkdTestingUtilities):
    """Test [Match] sections in .network files.
 
    Be aware that matching the test host's interfaces will wipe their
    configuration, so as a precaution, all network files should have a
    restrictive [Match] section to only ever interfere with the
    temporary veth interfaces created here.
    """
 
    def tearDown(self):
        """Stop networkd."""
        subprocess.call(['systemctl', 'stop', 'systemd-networkd.socket'])
        subprocess.call(['systemctl', 'stop', 'systemd-networkd.service'])
 
    def test_basic_matching(self):
        """Verify the Name= line works throughout this class."""
        self.add_veth_pair('test_if1', 'fake_if2')
        self.write_network(
            '50-test.network',
            '''\
[Match]
Name=test_*
[Network]
IPv6AcceptRA=no
''',
        )
        subprocess.check_call(['systemctl', 'restart', 'systemd-networkd'])
        self.assert_link_states(test_if1='managed', fake_if2='unmanaged')
 
    def test_inverted_matching(self):
        """Verify that a '!'-prefixed value inverts the match."""
        # Use a MAC address as the interfaces' common matching attribute
        # to avoid depending on udev, to support testing in containers.
        mac = '00:01:02:03:98:99'
        self.add_veth_pair('test_veth', 'test_peer', ['addr', mac], ['addr', mac])
        self.write_network(
            '50-no-veth.network',
            f'''\
[Match]
MACAddress={mac}
Name=!nonexistent *peer*
[Network]
IPv6AcceptRA=no
''',
        )
        subprocess.check_call(['systemctl', 'restart', 'systemd-networkd'])
        self.assert_link_states(test_veth='managed', test_peer='unmanaged')
 
 
class UnmanagedClientTest(unittest.TestCase, NetworkdTestingUtilities):
    """Test if networkd manages the correct interfaces."""
 
    def setUp(self):
        """Write .network files to match the named veth devices."""
        # Define the veth+peer pairs to be created.
        # Their pairing doesn't actually matter, only their names do.
        self.veths = {
            'm1def': 'm0unm',
            'm1man': 'm1unm',
        }
 
        # Define the contents of .network files to be read in order.
        self.configs = (
            '[Match]\nName=m1def\n',
            '[Match]\nName=m1unm\n[Link]\nUnmanaged=yes\n',
            '[Match]\nName=m1*\n[Link]\nUnmanaged=no\n',
        )
 
        # Write out the .network files to be cleaned up automatically.
        for i, config in enumerate(self.configs):
            self.write_network(f'{i:02d}-test.network', config)
 
    def tearDown(self):
        """Stop networkd."""
        subprocess.call(['systemctl', 'stop', 'systemd-networkd.socket'])
        subprocess.call(['systemctl', 'stop', 'systemd-networkd.service'])
 
    def create_iface(self):
        """Create temporary veth pairs for interface matching."""
        for veth, peer in self.veths.items():
            self.add_veth_pair(veth, peer)
 
    def test_unmanaged_setting(self):
        """Verify link states with Unmanaged= settings, hot-plug."""
        subprocess.check_call(['systemctl', 'restart', 'systemd-networkd'])
        self.create_iface()
        self.assert_link_states(m1def='managed', m1man='managed', m1unm='unmanaged', m0unm='unmanaged')
 
    def test_unmanaged_setting_coldplug(self):
        """Verify link states with Unmanaged= settings, cold-plug."""
        self.create_iface()
        subprocess.check_call(['systemctl', 'restart', 'systemd-networkd'])
        self.assert_link_states(m1def='managed', m1man='managed', m1unm='unmanaged', m0unm='unmanaged')
 
    def test_catchall_config(self):
        """Verify link states with a catch-all config, hot-plug."""
        # Don't actually catch ALL interfaces.  It messes up the host.
        self.write_network('50-all.network', '[Match]\nName=m[01]???\n')
        subprocess.check_call(['systemctl', 'restart', 'systemd-networkd'])
        self.create_iface()
        self.assert_link_states(m1def='managed', m1man='managed', m1unm='unmanaged', m0unm='managed')
 
    def test_catchall_config_coldplug(self):
        """Verify link states with a catch-all config, cold-plug."""
        # Don't actually catch ALL interfaces.  It messes up the host.
        self.write_network('50-all.network', '[Match]\nName=m[01]???\n')
        self.create_iface()
        subprocess.check_call(['systemctl', 'restart', 'systemd-networkd'])
        self.assert_link_states(m1def='managed', m1man='managed', m1unm='unmanaged', m0unm='managed')
 
 
if __name__ == '__main__':
    unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, verbosity=2))