]>
git.ipfire.org Git - thirdparty/systemd.git/blob - test/networkd-test.py
2 # SPDX-License-Identifier: LGPL-2.1+
4 # networkd integration test
5 # This uses temporary configuration in /run and temporary veth devices, and
6 # does not write anything on disk or change any system configuration;
7 # but it assumes (and checks at the beginning) that networkd is not currently
10 # This can be run on a normal installation, in QEMU, nspawn (with
11 # --private-network), LXD (with "--config raw.lxc=lxc.aa_profile=unconfined"),
12 # or LXC system containers. You need at least the "ip" tool from the iproute
13 # package; it is recommended to install dnsmasq too to get full test coverage.
15 # ATTENTION: This uses the *installed* networkd, not the one from the built
18 # © 2015 Canonical Ltd.
19 # Author: Martin Pitt <martin.pitt@ubuntu.com>
31 HAVE_DNSMASQ
= shutil
.which('dnsmasq') is not None
33 NETWORK_UNITDIR
= '/run/systemd/network'
35 NETWORKD_WAIT_ONLINE
= shutil
.which('systemd-networkd-wait-online',
36 path
='/usr/lib/systemd:/lib/systemd')
38 RESOLV_CONF
= '/run/systemd/resolve/resolv.conf'
42 """Initialize the environment, and perform sanity checks on it."""
43 if NETWORKD_WAIT_ONLINE
is None:
44 raise OSError(errno
.ENOENT
, 'systemd-networkd-wait-online not found')
46 # Do not run any tests if the system is using networkd already.
47 if subprocess
.call(['systemctl', 'is-active', '--quiet',
48 'systemd-networkd.service']) == 0:
49 raise unittest
.SkipTest('networkd is already active')
51 # Avoid "Failed to open /dev/tty" errors in containers.
52 os
.environ
['SYSTEMD_LOG_TARGET'] = 'journal'
54 # Ensure the unit directory exists so tests can dump files into it.
55 os
.makedirs(NETWORK_UNITDIR
, exist_ok
=True)
57 # create static systemd-network user for networkd-test-router.service (it
58 # needs to do some stuff as root and can't start as user; but networkd
59 # still insists on the user)
60 subprocess
.check_call(['adduser', '--system', '--no-create-home', 'systemd-network'])
63 class NetworkdTestingUtilities
:
64 """Provide a set of utility functions to facilitate networkd tests.
66 This class must be inherited along with unittest.TestCase to define
67 some required methods.
70 def add_veth_pair(self
, veth
, peer
, veth_options
=(), peer_options
=()):
71 """Add a veth interface pair, and queue them to be removed."""
72 subprocess
.check_call(['ip', 'link', 'add', 'name', veth
] +
74 ['type', 'veth', 'peer', 'name', peer
] +
76 self
.addCleanup(subprocess
.call
, ['ip', 'link', 'del', 'dev', peer
])
78 def write_network(self
, unit_name
, contents
):
79 """Write a network unit file, and queue it to be removed."""
80 unit_path
= os
.path
.join(NETWORK_UNITDIR
, unit_name
)
82 with
open(unit_path
, 'w') as unit
:
84 self
.addCleanup(os
.remove
, unit_path
)
86 def write_network_dropin(self
, unit_name
, dropin_name
, contents
):
87 """Write a network unit drop-in, and queue it to be removed."""
88 dropin_dir
= os
.path
.join(NETWORK_UNITDIR
, "{}.d".format(unit_name
))
89 dropin_path
= os
.path
.join(dropin_dir
, "{}.conf".format(dropin_name
))
91 os
.makedirs(dropin_dir
, exist_ok
=True)
92 self
.addCleanup(os
.rmdir
, dropin_dir
)
93 with
open(dropin_path
, 'w') as dropin
:
94 dropin
.write(contents
)
95 self
.addCleanup(os
.remove
, dropin_path
)
97 def read_attr(self
, link
, attribute
):
98 """Read a link attributed from the sysfs."""
99 # Note we we don't want to check if interface `link' is managed, we
100 # want to evaluate link variable and pass the value of the link to
101 # assert_link_states e.g. eth0=managed.
102 self
.assert_link_states(**{link
:'managed'})
103 with
open(os
.path
.join('/sys/class/net', link
, attribute
)) as f
:
104 return f
.readline().strip()
106 def assert_link_states(self
, **kwargs
):
107 """Match networkctl link states to the given ones.
109 Each keyword argument should be the name of a network interface
110 with its expected value of the "SETUP" column in output from
111 networkctl. The interfaces have five seconds to come online
112 before the check is performed. Every specified interface must
113 be present in the output, and any other interfaces found in the
116 A special interface state "managed" is supported, which matches
117 any value in the "SETUP" column other than "unmanaged".
121 interfaces
= set(kwargs
)
123 # Wait for the requested interfaces, but don't fail for them.
124 subprocess
.call([NETWORKD_WAIT_ONLINE
, '--timeout=5'] +
125 ['--interface={}'.format(iface
) for iface
in kwargs
])
127 # Validate each link state found in the networkctl output.
128 out
= subprocess
.check_output(['networkctl', '--no-legend']).rstrip()
129 for line
in out
.decode('utf-8').split('\n'):
130 fields
= line
.split()
131 if len(fields
) >= 5 and fields
[1] in kwargs
:
133 expected
= kwargs
[iface
]
135 if (actual
!= expected
and
136 not (expected
== 'managed' and actual
!= 'unmanaged')):
137 self
.fail("Link {} expects state {}, found {}".format(iface
, expected
, actual
))
138 interfaces
.remove(iface
)
140 # Ensure that all requested interfaces have been covered.
142 self
.fail("Missing links in status output: {}".format(interfaces
))
145 class BridgeTest(NetworkdTestingUtilities
, unittest
.TestCase
):
146 """Provide common methods for testing networkd against servers."""
149 self
.write_network('port1.netdev', '''\
153 MACAddress=12:34:56:78:9a:bc''')
154 self
.write_network('port2.netdev', '''\
158 MACAddress=12:34:56:78:9a:bd''')
159 self
.write_network('mybridge.netdev', '''\
163 self
.write_network('port1.network', '''\
168 self
.write_network('port2.network', '''\
173 self
.write_network('mybridge.network', '''\
178 Address=192.168.250.33/24
179 Gateway=192.168.250.1''')
180 subprocess
.check_call(['systemctl', 'reset-failed', 'systemd-networkd'])
181 subprocess
.check_call(['systemctl', 'start', 'systemd-networkd'])
184 subprocess
.check_call(['systemctl', 'stop', 'systemd-networkd'])
185 subprocess
.check_call(['ip', 'link', 'del', 'mybridge'])
186 subprocess
.check_call(['ip', 'link', 'del', 'port1'])
187 subprocess
.check_call(['ip', 'link', 'del', 'port2'])
189 def test_bridge_init(self
):
190 self
.assert_link_states(
195 def test_bridge_port_priority(self
):
196 self
.assertEqual(self
.read_attr('port1', 'brport/priority'), '32')
197 self
.write_network_dropin('port1.network', 'priority', '''\
201 subprocess
.check_call(['systemctl', 'restart', 'systemd-networkd'])
202 self
.assertEqual(self
.read_attr('port1', 'brport/priority'), '28')
204 def test_bridge_port_priority_set_zero(self
):
205 """It should be possible to set the bridge port priority to 0"""
206 self
.assertEqual(self
.read_attr('port2', 'brport/priority'), '32')
207 self
.write_network_dropin('port2.network', 'priority', '''\
211 subprocess
.check_call(['systemctl', 'restart', 'systemd-networkd'])
212 self
.assertEqual(self
.read_attr('port2', 'brport/priority'), '0')
214 def test_bridge_port_property(self
):
215 """Test the "[Bridge]" section keys"""
216 self
.assertEqual(self
.read_attr('port2', 'brport/priority'), '32')
217 self
.write_network_dropin('port2.network', 'property', '''\
223 AllowPortToBeRoot=true
227 subprocess
.check_call(['systemctl', 'restart', 'systemd-networkd'])
229 self
.assertEqual(self
.read_attr('port2', 'brport/priority'), '23')
230 self
.assertEqual(self
.read_attr('port2', 'brport/hairpin_mode'), '1')
231 self
.assertEqual(self
.read_attr('port2', 'brport/path_cost'), '555')
232 self
.assertEqual(self
.read_attr('port2', 'brport/multicast_fast_leave'), '1')
233 self
.assertEqual(self
.read_attr('port2', 'brport/unicast_flood'), '1')
234 self
.assertEqual(self
.read_attr('port2', 'brport/bpdu_guard'), '1')
235 self
.assertEqual(self
.read_attr('port2', 'brport/root_block'), '1')
237 class ClientTestBase(NetworkdTestingUtilities
):
238 """Provide common methods for testing networkd against servers."""
241 def setUpClass(klass
):
242 klass
.orig_log_level
= subprocess
.check_output(
243 ['systemctl', 'show', '--value', '--property', 'LogLevel'],
244 universal_newlines
=True).strip()
245 subprocess
.check_call(['systemd-analyze', 'set-log-level', 'debug'])
248 def tearDownClass(klass
):
249 subprocess
.check_call(['systemd-analyze', 'set-log-level', klass
.orig_log_level
])
252 self
.iface
= 'test_eth42'
253 self
.if_router
= 'router_eth42'
254 self
.workdir_obj
= tempfile
.TemporaryDirectory()
255 self
.workdir
= self
.workdir_obj
.name
256 self
.config
= 'test_eth42.network'
258 # get current journal cursor
259 subprocess
.check_output(['journalctl', '--sync'])
260 out
= subprocess
.check_output(['journalctl', '-b', '--quiet',
261 '--no-pager', '-n0', '--show-cursor'],
262 universal_newlines
=True)
263 self
.assertTrue(out
.startswith('-- cursor:'))
264 self
.journal_cursor
= out
.split()[-1]
266 subprocess
.check_call(['systemctl', 'reset-failed', 'systemd-networkd'])
269 self
.shutdown_iface()
270 subprocess
.call(['systemctl', 'stop', 'systemd-networkd'])
271 subprocess
.call(['ip', 'link', 'del', 'dummy0'],
272 stderr
=subprocess
.DEVNULL
)
274 def show_journal(self
, unit
):
275 '''Show journal of given unit since start of the test'''
277 print('---- {} ----'.format(unit
))
278 subprocess
.check_output(['journalctl', '--sync'])
280 subprocess
.call(['journalctl', '-b', '--no-pager', '--quiet',
281 '--cursor', self
.journal_cursor
, '-u', unit
])
283 def create_iface(self
, ipv6
=False):
284 '''Create test interface with DHCP server behind it'''
286 raise NotImplementedError('must be implemented by a subclass')
288 def shutdown_iface(self
):
289 '''Remove test interface and stop DHCP server'''
291 raise NotImplementedError('must be implemented by a subclass')
293 def print_server_log(self
):
294 '''Print DHCP server log for debugging failures'''
296 raise NotImplementedError('must be implemented by a subclass')
298 def do_test(self
, coldplug
=True, ipv6
=False, extra_opts
='',
299 online_timeout
=10, dhcp_mode
='yes'):
301 subprocess
.check_call(['systemctl', 'start', 'systemd-resolved'])
302 except subprocess
.CalledProcessError
:
303 self
.show_journal('systemd-resolved.service')
305 self
.write_network(self
.config
, '''\
310 {}'''.format(self
.iface
, dhcp_mode
, extra_opts
))
313 # create interface first, then start networkd
314 self
.create_iface(ipv6
=ipv6
)
315 subprocess
.check_call(['systemctl', 'start', 'systemd-networkd'])
316 elif coldplug
is not None:
317 # start networkd first, then create interface
318 subprocess
.check_call(['systemctl', 'start', 'systemd-networkd'])
319 self
.create_iface(ipv6
=ipv6
)
321 # "None" means test sets up interface by itself
322 subprocess
.check_call(['systemctl', 'start', 'systemd-networkd'])
325 subprocess
.check_call([NETWORKD_WAIT_ONLINE
, '--interface',
326 self
.iface
, '--timeout=%i' % online_timeout
])
329 # check iface state and IP 6 address; FIXME: we need to wait a bit
330 # longer, as the iface is "configured" already with IPv4 *or*
331 # IPv6, but we want to wait for both
333 out
= subprocess
.check_output(['ip', 'a', 'show', 'dev', self
.iface
])
334 if b
'state UP' in out
and b
'inet6 2600' in out
and b
'inet 192.168' in out
:
338 self
.fail('timed out waiting for IPv6 configuration')
340 self
.assertRegex(out
, b
'inet6 2600::.* scope global .*dynamic')
341 self
.assertRegex(out
, b
'inet6 fe80::.* scope link')
343 # should have link-local address on IPv6 only
344 out
= subprocess
.check_output(['ip', '-6', 'a', 'show', 'dev', self
.iface
])
345 self
.assertRegex(out
, br
'inet6 fe80::.* scope link')
346 self
.assertNotIn(b
'scope global', out
)
348 # should have IPv4 address
349 out
= subprocess
.check_output(['ip', '-4', 'a', 'show', 'dev', self
.iface
])
350 self
.assertIn(b
'state UP', out
)
351 self
.assertRegex(out
, br
'inet 192.168.5.\d+/.* scope global dynamic')
353 # check networkctl state
354 out
= subprocess
.check_output(['networkctl'])
355 self
.assertRegex(out
, (r
'{}\s+ether\s+[a-z-]+\s+unmanaged'.format(self
.if_router
)).encode())
356 self
.assertRegex(out
, (r
'{}\s+ether\s+routable\s+configured'.format(self
.iface
)).encode())
358 out
= subprocess
.check_output(['networkctl', 'status', self
.iface
])
359 self
.assertRegex(out
, br
'Type:\s+ether')
360 self
.assertRegex(out
, br
'State:\s+routable.*configured')
361 self
.assertRegex(out
, br
'Address:\s+192.168.5.\d+')
363 self
.assertRegex(out
, br
'2600::')
365 self
.assertNotIn(br
'2600::', out
)
366 self
.assertRegex(out
, br
'fe80::')
367 self
.assertRegex(out
, br
'Gateway:\s+192.168.5.1')
368 self
.assertRegex(out
, br
'DNS:\s+192.168.5.1')
369 except (AssertionError, subprocess
.CalledProcessError
):
370 # show networkd status, journal, and DHCP server log on failure
371 with
open(os
.path
.join(NETWORK_UNITDIR
, self
.config
)) as f
:
372 print('\n---- {} ----\n{}'.format(self
.config
, f
.read()))
373 print('---- interface status ----')
375 subprocess
.call(['ip', 'a', 'show', 'dev', self
.iface
])
376 print('---- networkctl status {} ----'.format(self
.iface
))
378 subprocess
.call(['networkctl', 'status', self
.iface
])
379 self
.show_journal('systemd-networkd.service')
380 self
.print_server_log()
383 for timeout
in range(50):
384 with
open(RESOLV_CONF
) as f
:
386 if 'nameserver 192.168.5.1\n' in contents
:
390 self
.fail('nameserver 192.168.5.1 not found in ' + RESOLV_CONF
)
392 if coldplug
is False:
393 # check post-down.d hook
394 self
.shutdown_iface()
396 def test_coldplug_dhcp_yes_ip4(self
):
397 # we have a 12s timeout on RA, so we need to wait longer
398 self
.do_test(coldplug
=True, ipv6
=False, online_timeout
=15)
400 def test_coldplug_dhcp_yes_ip4_no_ra(self
):
401 # with disabling RA explicitly things should be fast
402 self
.do_test(coldplug
=True, ipv6
=False,
403 extra_opts
='IPv6AcceptRA=False')
405 def test_coldplug_dhcp_ip4_only(self
):
406 # we have a 12s timeout on RA, so we need to wait longer
407 self
.do_test(coldplug
=True, ipv6
=False, dhcp_mode
='ipv4',
410 def test_coldplug_dhcp_ip4_only_no_ra(self
):
411 # with disabling RA explicitly things should be fast
412 self
.do_test(coldplug
=True, ipv6
=False, dhcp_mode
='ipv4',
413 extra_opts
='IPv6AcceptRA=False')
415 def test_coldplug_dhcp_ip6(self
):
416 self
.do_test(coldplug
=True, ipv6
=True)
418 def test_hotplug_dhcp_ip4(self
):
419 # With IPv4 only we have a 12s timeout on RA, so we need to wait longer
420 self
.do_test(coldplug
=False, ipv6
=False, online_timeout
=15)
422 def test_hotplug_dhcp_ip6(self
):
423 self
.do_test(coldplug
=False, ipv6
=True)
425 def test_route_only_dns(self
):
426 self
.write_network('myvpn.netdev', '''\
430 MACAddress=12:34:56:78:9a:bc''')
431 self
.write_network('myvpn.network', '''\
435 Address=192.168.42.100
437 Domains= ~company''')
439 self
.do_test(coldplug
=True, ipv6
=False,
440 extra_opts
='IPv6AcceptRouterAdvertisements=False')
442 with
open(RESOLV_CONF
) as f
:
444 # ~company is not a search domain, only a routing domain
445 self
.assertNotRegex(contents
, 'search.*company')
446 # our global server should appear
447 self
.assertIn('nameserver 192.168.5.1\n', contents
)
448 # should not have domain-restricted server as global server
449 self
.assertNotIn('nameserver 192.168.42.1\n', contents
)
451 def test_route_only_dns_all_domains(self
):
452 self
.write_network('myvpn.netdev', '''[NetDev]
455 MACAddress=12:34:56:78:9a:bc''')
456 self
.write_network('myvpn.network', '''[Match]
459 Address=192.168.42.100
461 Domains= ~company ~.''')
463 self
.do_test(coldplug
=True, ipv6
=False,
464 extra_opts
='IPv6AcceptRouterAdvertisements=False')
466 with
open(RESOLV_CONF
) as f
:
469 # ~company is not a search domain, only a routing domain
470 self
.assertNotRegex(contents
, 'search.*company')
472 # our global server should appear
473 self
.assertIn('nameserver 192.168.5.1\n', contents
)
474 # should have company server as global server due to ~.
475 self
.assertIn('nameserver 192.168.42.1\n', contents
)
478 @unittest.skipUnless(HAVE_DNSMASQ
, 'dnsmasq not installed')
479 class DnsmasqClientTest(ClientTestBase
, unittest
.TestCase
):
480 '''Test networkd client against dnsmasq'''
485 self
.iface_mac
= 'de:ad:be:ef:47:11'
487 def create_iface(self
, ipv6
=False, dnsmasq_opts
=None):
488 '''Create test interface with DHCP server behind it'''
491 subprocess
.check_call(['ip', 'link', 'add', 'name', self
.iface
,
492 'address', self
.iface_mac
,
493 'type', 'veth', 'peer', 'name', self
.if_router
])
495 # give our router an IP
496 subprocess
.check_call(['ip', 'a', 'flush', 'dev', self
.if_router
])
497 subprocess
.check_call(['ip', 'a', 'add', '192.168.5.1/24', 'dev', self
.if_router
])
499 subprocess
.check_call(['ip', 'a', 'add', '2600::1/64', 'dev', self
.if_router
])
500 subprocess
.check_call(['ip', 'link', 'set', self
.if_router
, 'up'])
503 self
.dnsmasq_log
= os
.path
.join(self
.workdir
, 'dnsmasq.log')
504 lease_file
= os
.path
.join(self
.workdir
, 'dnsmasq.leases')
506 extra_opts
= ['--enable-ra', '--dhcp-range=2600::10,2600::20']
510 extra_opts
+= dnsmasq_opts
511 self
.dnsmasq
= subprocess
.Popen(
512 ['dnsmasq', '--keep-in-foreground', '--log-queries',
513 '--log-facility=' + self
.dnsmasq_log
, '--conf-file=/dev/null',
514 '--dhcp-leasefile=' + lease_file
, '--bind-interfaces',
515 '--interface=' + self
.if_router
, '--except-interface=lo',
516 '--dhcp-range=192.168.5.10,192.168.5.200'] + extra_opts
)
518 def shutdown_iface(self
):
519 '''Remove test interface and stop DHCP server'''
522 subprocess
.check_call(['ip', 'link', 'del', 'dev', self
.if_router
])
523 self
.if_router
= None
529 def print_server_log(self
):
530 '''Print DHCP server log for debugging failures'''
532 with
open(self
.dnsmasq_log
) as f
:
533 sys
.stdout
.write('\n\n---- dnsmasq log ----\n{}\n------\n\n'.format(f
.read()))
535 def test_resolved_domain_restricted_dns(self
):
536 '''resolved: domain-restricted DNS servers'''
538 # create interface for generic connections; this will map all DNS names
540 self
.create_iface(dnsmasq_opts
=['--address=/#/192.168.42.1'])
541 self
.write_network('general.network', '''\
546 IPv6AcceptRA=False'''.format(self
.iface
))
548 # create second device/dnsmasq for a .company/.lab VPN interface
549 # static IPs for simplicity
550 self
.add_veth_pair('testvpnclient', 'testvpnrouter')
551 subprocess
.check_call(['ip', 'a', 'flush', 'dev', 'testvpnrouter'])
552 subprocess
.check_call(['ip', 'a', 'add', '10.241.3.1/24', 'dev', 'testvpnrouter'])
553 subprocess
.check_call(['ip', 'link', 'set', 'testvpnrouter', 'up'])
555 vpn_dnsmasq_log
= os
.path
.join(self
.workdir
, 'dnsmasq-vpn.log')
556 vpn_dnsmasq
= subprocess
.Popen(
557 ['dnsmasq', '--keep-in-foreground', '--log-queries',
558 '--log-facility=' + vpn_dnsmasq_log
, '--conf-file=/dev/null',
559 '--dhcp-leasefile=/dev/null', '--bind-interfaces',
560 '--interface=testvpnrouter', '--except-interface=lo',
561 '--address=/math.lab/10.241.3.3', '--address=/cantina.company/10.241.4.4'])
562 self
.addCleanup(vpn_dnsmasq
.wait
)
563 self
.addCleanup(vpn_dnsmasq
.kill
)
565 self
.write_network('vpn.network', '''\
570 Address=10.241.3.2/24
572 Domains= ~company ~lab''')
574 subprocess
.check_call(['systemctl', 'start', 'systemd-networkd'])
575 subprocess
.check_call([NETWORKD_WAIT_ONLINE
, '--interface', self
.iface
,
576 '--interface=testvpnclient', '--timeout=20'])
578 # ensure we start fresh with every test
579 subprocess
.check_call(['systemctl', 'restart', 'systemd-resolved'])
581 # test vpnclient specific domains; these should *not* be answered by
583 out
= subprocess
.check_output(['systemd-resolve', 'math.lab'])
584 self
.assertIn(b
'math.lab: 10.241.3.3', out
)
585 out
= subprocess
.check_output(['systemd-resolve', 'kettle.cantina.company'])
586 self
.assertIn(b
'kettle.cantina.company: 10.241.4.4', out
)
588 # test general domains
589 out
= subprocess
.check_output(['systemd-resolve', 'megasearch.net'])
590 self
.assertIn(b
'megasearch.net: 192.168.42.1', out
)
592 with
open(self
.dnsmasq_log
) as f
:
593 general_log
= f
.read()
594 with
open(vpn_dnsmasq_log
) as f
:
597 # VPN domains should only be sent to VPN DNS
598 self
.assertRegex(vpn_log
, 'query.*math.lab')
599 self
.assertRegex(vpn_log
, 'query.*cantina.company')
600 self
.assertNotIn('.lab', general_log
)
601 self
.assertNotIn('.company', general_log
)
603 # general domains should not be sent to the VPN DNS
604 self
.assertRegex(general_log
, 'query.*megasearch.net')
605 self
.assertNotIn('megasearch.net', vpn_log
)
607 def test_resolved_etc_hosts(self
):
608 '''resolved queries to /etc/hosts'''
610 # FIXME: -t MX query fails with enabled DNSSEC (even when using
611 # the known negative trust anchor .internal instead of .example)
612 conf
= '/run/systemd/resolved.conf.d/test-disable-dnssec.conf'
613 os
.makedirs(os
.path
.dirname(conf
), exist_ok
=True)
614 with
open(conf
, 'w') as f
:
615 f
.write('[Resolve]\nDNSSEC=no')
616 self
.addCleanup(os
.remove
, conf
)
618 # create /etc/hosts bind mount which resolves my.example for IPv4
619 hosts
= os
.path
.join(self
.workdir
, 'hosts')
620 with
open(hosts
, 'w') as f
:
621 f
.write('172.16.99.99 my.example\n')
622 subprocess
.check_call(['mount', '--bind', hosts
, '/etc/hosts'])
623 self
.addCleanup(subprocess
.call
, ['umount', '/etc/hosts'])
624 subprocess
.check_call(['systemctl', 'stop', 'systemd-resolved.service'])
626 # note: different IPv4 address here, so that it's easy to tell apart
627 # what resolved the query
628 self
.create_iface(dnsmasq_opts
=['--host-record=my.example,172.16.99.1,2600::99:99',
629 '--host-record=other.example,172.16.0.42,2600::42',
630 '--mx-host=example,mail.example'],
632 self
.do_test(coldplug
=None, ipv6
=True)
635 # family specific queries
636 out
= subprocess
.check_output(['systemd-resolve', '-4', 'my.example'])
637 self
.assertIn(b
'my.example: 172.16.99.99', out
)
638 # we don't expect an IPv6 answer; if /etc/hosts has any IP address,
639 # it's considered a sufficient source
640 self
.assertNotEqual(subprocess
.call(['systemd-resolve', '-6', 'my.example']), 0)
641 # "any family" query; IPv4 should come from /etc/hosts
642 out
= subprocess
.check_output(['systemd-resolve', 'my.example'])
643 self
.assertIn(b
'my.example: 172.16.99.99', out
)
644 # IP → name lookup; again, takes the /etc/hosts one
645 out
= subprocess
.check_output(['systemd-resolve', '172.16.99.99'])
646 self
.assertIn(b
'172.16.99.99: my.example', out
)
648 # non-address RRs should fall back to DNS
649 out
= subprocess
.check_output(['systemd-resolve', '--type=MX', 'example'])
650 self
.assertIn(b
'example IN MX 1 mail.example', out
)
652 # other domains query DNS
653 out
= subprocess
.check_output(['systemd-resolve', 'other.example'])
654 self
.assertIn(b
'172.16.0.42', out
)
655 out
= subprocess
.check_output(['systemd-resolve', '172.16.0.42'])
656 self
.assertIn(b
'172.16.0.42: other.example', out
)
657 except (AssertionError, subprocess
.CalledProcessError
):
658 self
.show_journal('systemd-resolved.service')
659 self
.print_server_log()
662 def test_transient_hostname(self
):
663 '''networkd sets transient hostname from DHCP'''
665 orig_hostname
= socket
.gethostname()
666 self
.addCleanup(socket
.sethostname
, orig_hostname
)
667 # temporarily move /etc/hostname away; restart hostnamed to pick it up
668 if os
.path
.exists('/etc/hostname'):
669 subprocess
.check_call(['mount', '--bind', '/dev/null', '/etc/hostname'])
670 self
.addCleanup(subprocess
.call
, ['umount', '/etc/hostname'])
671 subprocess
.check_call(['systemctl', 'stop', 'systemd-hostnamed.service'])
673 self
.create_iface(dnsmasq_opts
=['--dhcp-host={},192.168.5.210,testgreen'.format(self
.iface_mac
)])
674 self
.do_test(coldplug
=None, extra_opts
='IPv6AcceptRA=False', dhcp_mode
='ipv4')
677 # should have received the fixed IP above
678 out
= subprocess
.check_output(['ip', '-4', 'a', 'show', 'dev', self
.iface
])
679 self
.assertRegex(out
, b
'inet 192.168.5.210/24 .* scope global dynamic')
680 # should have set transient hostname in hostnamed; this is
681 # sometimes a bit lagging (issue #4753), so retry a few times
682 for retry
in range(1, 6):
683 out
= subprocess
.check_output(['hostnamectl'])
684 if b
'testgreen' in out
:
687 sys
.stdout
.write('[retry %i] ' % retry
)
690 self
.fail('Transient hostname not found in hostnamectl:\n{}'.format(out
.decode()))
691 # and also applied to the system
692 self
.assertEqual(socket
.gethostname(), 'testgreen')
693 except AssertionError:
694 self
.show_journal('systemd-networkd.service')
695 self
.show_journal('systemd-hostnamed.service')
696 self
.print_server_log()
699 def test_transient_hostname_with_static(self
):
700 '''transient hostname is not applied if static hostname exists'''
702 orig_hostname
= socket
.gethostname()
703 self
.addCleanup(socket
.sethostname
, orig_hostname
)
704 if not os
.path
.exists('/etc/hostname'):
705 self
.writeConfig('/etc/hostname', orig_hostname
)
706 subprocess
.check_call(['systemctl', 'stop', 'systemd-hostnamed.service'])
708 self
.create_iface(dnsmasq_opts
=['--dhcp-host={},192.168.5.210,testgreen'.format(self
.iface_mac
)])
709 self
.do_test(coldplug
=None, extra_opts
='IPv6AcceptRA=False', dhcp_mode
='ipv4')
712 # should have received the fixed IP above
713 out
= subprocess
.check_output(['ip', '-4', 'a', 'show', 'dev', self
.iface
])
714 self
.assertRegex(out
, b
'inet 192.168.5.210/24 .* scope global dynamic')
715 # static hostname wins over transient one, thus *not* applied
716 self
.assertEqual(socket
.gethostname(), orig_hostname
)
717 except AssertionError:
718 self
.show_journal('systemd-networkd.service')
719 self
.show_journal('systemd-hostnamed.service')
720 self
.print_server_log()
724 class NetworkdClientTest(ClientTestBase
, unittest
.TestCase
):
725 '''Test networkd client against networkd server'''
731 def create_iface(self
, ipv6
=False, dhcpserver_opts
=None):
732 '''Create test interface with DHCP server behind it'''
734 # run "router-side" networkd in own mount namespace to shield it from
735 # "client-side" configuration and networkd
736 (fd
, script
) = tempfile
.mkstemp(prefix
='networkd-router.sh')
737 self
.addCleanup(os
.remove
, script
)
738 with os
.fdopen(fd
, 'w+') as f
:
742 mkdir -p /run/systemd/network
743 mkdir -p /run/systemd/netif
744 mount -t tmpfs none /run/systemd/network
745 mount -t tmpfs none /run/systemd/netif
746 [ ! -e /run/dbus ] || mount -t tmpfs none /run/dbus
747 # create router/client veth pair
748 cat << EOF > /run/systemd/network/test.netdev
757 cat << EOF > /run/systemd/network/test.network
762 Address=192.168.5.1/24
773 # run networkd as in systemd-networkd.service
774 exec $(systemctl cat systemd-networkd.service | sed -n '/^ExecStart=/ { s/^.*=//; s/^[@+-]//; s/^!*//; p}')
775 ''' % {'ifr': self
.if_router
, 'ifc': self
.iface
, 'addr6': ipv6
and 'Address=2600::1/64' or '',
776 'dhopts': dhcpserver_opts
or ''})
780 subprocess
.check_call(['systemd-run', '--unit=networkd-test-router.service',
781 '-p', 'InaccessibleDirectories=-/etc/systemd/network',
782 '-p', 'InaccessibleDirectories=-/run/systemd/network',
783 '-p', 'InaccessibleDirectories=-/run/systemd/netif',
784 '--service-type=notify', script
])
786 # wait until devices got created
788 out
= subprocess
.check_output(['ip', 'a', 'show', 'dev', self
.if_router
])
789 if b
'state UP' in out
and b
'scope global' in out
:
793 def shutdown_iface(self
):
794 '''Remove test interface and stop DHCP server'''
797 subprocess
.check_call(['systemctl', 'stop', 'networkd-test-router.service'])
798 # ensure failed transient unit does not stay around
799 subprocess
.call(['systemctl', 'reset-failed', 'networkd-test-router.service'])
800 subprocess
.call(['ip', 'link', 'del', 'dev', self
.if_router
])
801 self
.if_router
= None
803 def print_server_log(self
):
804 '''Print DHCP server log for debugging failures'''
806 self
.show_journal('networkd-test-router.service')
808 @unittest.skip('networkd does not have DHCPv6 server support')
809 def test_hotplug_dhcp_ip6(self
):
812 @unittest.skip('networkd does not have DHCPv6 server support')
813 def test_coldplug_dhcp_ip6(self
):
816 def test_search_domains(self
):
818 # we don't use this interface for this test
819 self
.if_router
= None
821 self
.write_network('test.netdev', '''\
825 MACAddress=12:34:56:78:9a:bc''')
826 self
.write_network('test.network', '''\
830 Address=192.168.42.100
832 Domains= one two three four five six seven eight nine ten''')
834 subprocess
.check_call(['systemctl', 'start', 'systemd-networkd'])
836 for timeout
in range(50):
837 with
open(RESOLV_CONF
) as f
:
839 if ' one' in contents
:
842 self
.assertRegex(contents
, 'search .*one two three four')
843 self
.assertNotIn('seven\n', contents
)
844 self
.assertIn('# Too many search domains configured, remaining ones ignored.\n', contents
)
846 def test_search_domains_too_long(self
):
848 # we don't use this interface for this test
849 self
.if_router
= None
851 name_prefix
= 'a' * 60
853 self
.write_network('test.netdev', '''\
857 MACAddress=12:34:56:78:9a:bc''')
858 self
.write_network('test.network', '''\
862 Address=192.168.42.100
864 Domains={p}0 {p}1 {p}2 {p}3 {p}4'''.format(p
=name_prefix
))
866 subprocess
.check_call(['systemctl', 'start', 'systemd-networkd'])
868 for timeout
in range(50):
869 with
open(RESOLV_CONF
) as f
:
871 if ' one' in contents
:
874 self
.assertRegex(contents
, 'search .*{p}0 {p}1 {p}2'.format(p
=name_prefix
))
875 self
.assertIn('# Total length of all search domains is too long, remaining ones ignored.', contents
)
877 def test_dropin(self
):
878 # we don't use this interface for this test
879 self
.if_router
= None
881 self
.write_network('test.netdev', '''\
885 MACAddress=12:34:56:78:9a:bc''')
886 self
.write_network('test.network', '''\
890 Address=192.168.42.100
892 self
.write_network_dropin('test.network', 'dns', '''\
896 subprocess
.check_call(['systemctl', 'start', 'systemd-networkd'])
898 for timeout
in range(50):
899 with
open(RESOLV_CONF
) as f
:
901 if ' 127.0.0.1' in contents
:
904 self
.assertIn('nameserver 192.168.42.1\n', contents
)
905 self
.assertIn('nameserver 127.0.0.1\n', contents
)
907 def test_dhcp_timezone(self
):
908 '''networkd sets time zone from DHCP'''
911 out
= subprocess
.check_output(['busctl', 'get-property', 'org.freedesktop.timedate1',
912 '/org/freedesktop/timedate1', 'org.freedesktop.timedate1', 'Timezone'])
913 assert out
.startswith(b
's "')
915 assert out
.endswith(b
'"')
916 return out
[3:-1].decode()
918 orig_timezone
= get_tz()
919 self
.addCleanup(subprocess
.call
, ['timedatectl', 'set-timezone', orig_timezone
])
921 self
.create_iface(dhcpserver_opts
='EmitTimezone=yes\nTimezone=Pacific/Honolulu')
922 self
.do_test(coldplug
=None, extra_opts
='IPv6AcceptRA=false\n[DHCP]\nUseTimezone=true', dhcp_mode
='ipv4')
924 # should have applied the received timezone
926 self
.assertEqual(get_tz(), 'Pacific/Honolulu')
927 except AssertionError:
928 self
.show_journal('systemd-networkd.service')
929 self
.show_journal('systemd-hostnamed.service')
933 class MatchClientTest(unittest
.TestCase
, NetworkdTestingUtilities
):
934 """Test [Match] sections in .network files.
936 Be aware that matching the test host's interfaces will wipe their
937 configuration, so as a precaution, all network files should have a
938 restrictive [Match] section to only ever interfere with the
939 temporary veth interfaces created here.
944 subprocess
.call(['systemctl', 'stop', 'systemd-networkd'])
946 def test_basic_matching(self
):
947 """Verify the Name= line works throughout this class."""
948 self
.add_veth_pair('test_if1', 'fake_if2')
949 self
.write_network('test.network', "[Match]\nName=test_*\n[Network]")
950 subprocess
.check_call(['systemctl', 'start', 'systemd-networkd'])
951 self
.assert_link_states(test_if1
='managed', fake_if2
='unmanaged')
953 def test_inverted_matching(self
):
954 """Verify that a '!'-prefixed value inverts the match."""
955 # Use a MAC address as the interfaces' common matching attribute
956 # to avoid depending on udev, to support testing in containers.
957 mac
= '00:01:02:03:98:99'
958 self
.add_veth_pair('test_veth', 'test_peer',
959 ['addr', mac
], ['addr', mac
])
960 self
.write_network('no-veth.network', """\
963 Name=!nonexistent *peer*
964 [Network]""".format(mac
))
965 subprocess
.check_call(['systemctl', 'start', 'systemd-networkd'])
966 self
.assert_link_states(test_veth
='managed', test_peer
='unmanaged')
969 class UnmanagedClientTest(unittest
.TestCase
, NetworkdTestingUtilities
):
970 """Test if networkd manages the correct interfaces."""
973 """Write .network files to match the named veth devices."""
974 # Define the veth+peer pairs to be created.
975 # Their pairing doesn't actually matter, only their names do.
981 # Define the contents of .network files to be read in order.
983 "[Match]\nName=m1def\n",
984 "[Match]\nName=m1unm\n[Link]\nUnmanaged=yes\n",
985 "[Match]\nName=m1*\n[Link]\nUnmanaged=no\n",
988 # Write out the .network files to be cleaned up automatically.
989 for i
, config
in enumerate(self
.configs
):
990 self
.write_network("%02d-test.network" % i
, config
)
994 subprocess
.call(['systemctl', 'stop', 'systemd-networkd'])
996 def create_iface(self
):
997 """Create temporary veth pairs for interface matching."""
998 for veth
, peer
in self
.veths
.items():
999 self
.add_veth_pair(veth
, peer
)
1001 def test_unmanaged_setting(self
):
1002 """Verify link states with Unmanaged= settings, hot-plug."""
1003 subprocess
.check_call(['systemctl', 'start', 'systemd-networkd'])
1005 self
.assert_link_states(m1def
='managed',
1010 def test_unmanaged_setting_coldplug(self
):
1011 """Verify link states with Unmanaged= settings, cold-plug."""
1013 subprocess
.check_call(['systemctl', 'start', 'systemd-networkd'])
1014 self
.assert_link_states(m1def
='managed',
1019 def test_catchall_config(self
):
1020 """Verify link states with a catch-all config, hot-plug."""
1021 # Don't actually catch ALL interfaces. It messes up the host.
1022 self
.write_network('all.network', "[Match]\nName=m[01]???\n")
1023 subprocess
.check_call(['systemctl', 'start', 'systemd-networkd'])
1025 self
.assert_link_states(m1def
='managed',
1030 def test_catchall_config_coldplug(self
):
1031 """Verify link states with a catch-all config, cold-plug."""
1032 # Don't actually catch ALL interfaces. It messes up the host.
1033 self
.write_network('all.network', "[Match]\nName=m[01]???\n")
1035 subprocess
.check_call(['systemctl', 'start', 'systemd-networkd'])
1036 self
.assert_link_states(m1def
='managed',
1042 if __name__
== '__main__':
1043 unittest
.main(testRunner
=unittest
.TextTestRunner(stream
=sys
.stdout
,