]>
Commit | Line | Data |
---|---|---|
4ddb85b1 | 1 | #!/usr/bin/env python3 |
35df7443 | 2 | # SPDX-License-Identifier: LGPL-2.1+ |
4ddb85b1 MP |
3 | # |
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 | |
8 | # running. | |
daad34df MP |
9 | # |
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. | |
14 | # | |
4ddb85b1 MP |
15 | # ATTENTION: This uses the *installed* networkd, not the one from the built |
16 | # source tree. | |
17 | # | |
810adae9 | 18 | # © 2015 Canonical Ltd. |
4ddb85b1 | 19 | # Author: Martin Pitt <martin.pitt@ubuntu.com> |
4ddb85b1 | 20 | |
ec89276c | 21 | import errno |
4ddb85b1 | 22 | import os |
278391c2 BOT |
23 | import shutil |
24 | import socket | |
25 | import subprocess | |
4ddb85b1 | 26 | import sys |
278391c2 | 27 | import tempfile |
4ddb85b1 MP |
28 | import time |
29 | import unittest | |
4ddb85b1 | 30 | |
ec89276c DM |
31 | HAVE_DNSMASQ = shutil.which('dnsmasq') is not None |
32 | ||
33 | NETWORK_UNITDIR = '/run/systemd/network' | |
34 | ||
35 | NETWORKD_WAIT_ONLINE = shutil.which('systemd-networkd-wait-online', | |
36 | path='/usr/lib/systemd:/lib/systemd') | |
4ddb85b1 | 37 | |
30b42a9a MP |
38 | RESOLV_CONF = '/run/systemd/resolve/resolv.conf' |
39 | ||
4ddb85b1 | 40 | |
ec89276c DM |
41 | def setUpModule(): |
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') | |
45 | ||
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') | |
50 | ||
51 | # Avoid "Failed to open /dev/tty" errors in containers. | |
52 | os.environ['SYSTEMD_LOG_TARGET'] = 'journal' | |
53 | ||
54 | # Ensure the unit directory exists so tests can dump files into it. | |
55 | os.makedirs(NETWORK_UNITDIR, exist_ok=True) | |
56 | ||
c44c1b8a MP |
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']) | |
61 | ||
ec89276c DM |
62 | |
63 | class NetworkdTestingUtilities: | |
64 | """Provide a set of utility functions to facilitate networkd tests. | |
65 | ||
66 | This class must be inherited along with unittest.TestCase to define | |
67 | some required methods. | |
68 | """ | |
69 | ||
618b196e DM |
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] + | |
73 | list(veth_options) + | |
74 | ['type', 'veth', 'peer', 'name', peer] + | |
75 | list(peer_options)) | |
76 | self.addCleanup(subprocess.call, ['ip', 'link', 'del', 'dev', peer]) | |
77 | ||
ec89276c DM |
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) | |
81 | ||
82 | with open(unit_path, 'w') as unit: | |
83 | unit.write(contents) | |
84 | self.addCleanup(os.remove, unit_path) | |
85 | ||
86 | def write_network_dropin(self, unit_name, dropin_name, contents): | |
87 | """Write a network unit drop-in, and queue it to be removed.""" | |
278391c2 BOT |
88 | dropin_dir = os.path.join(NETWORK_UNITDIR, "{}.d".format(unit_name)) |
89 | dropin_path = os.path.join(dropin_dir, "{}.conf".format(dropin_name)) | |
ec89276c DM |
90 | |
91 | os.makedirs(dropin_dir, exist_ok=True) | |
b56be296 | 92 | self.addCleanup(os.rmdir, dropin_dir) |
ec89276c DM |
93 | with open(dropin_path, 'w') as dropin: |
94 | dropin.write(contents) | |
95 | self.addCleanup(os.remove, dropin_path) | |
96 | ||
b56be296 DJL |
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() | |
105 | ||
a09dc546 DM |
106 | def assert_link_states(self, **kwargs): |
107 | """Match networkctl link states to the given ones. | |
108 | ||
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 | |
114 | output are ignored. | |
115 | ||
116 | A special interface state "managed" is supported, which matches | |
117 | any value in the "SETUP" column other than "unmanaged". | |
118 | """ | |
119 | if not kwargs: | |
120 | return | |
121 | interfaces = set(kwargs) | |
122 | ||
123 | # Wait for the requested interfaces, but don't fail for them. | |
124 | subprocess.call([NETWORKD_WAIT_ONLINE, '--timeout=5'] + | |
278391c2 | 125 | ['--interface={}'.format(iface) for iface in kwargs]) |
a09dc546 DM |
126 | |
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: | |
132 | iface = fields[1] | |
133 | expected = kwargs[iface] | |
134 | actual = fields[-1] | |
135 | if (actual != expected and | |
136 | not (expected == 'managed' and actual != 'unmanaged')): | |
278391c2 | 137 | self.fail("Link {} expects state {}, found {}".format(iface, expected, actual)) |
a09dc546 DM |
138 | interfaces.remove(iface) |
139 | ||
140 | # Ensure that all requested interfaces have been covered. | |
141 | if interfaces: | |
278391c2 | 142 | self.fail("Missing links in status output: {}".format(interfaces)) |
a09dc546 | 143 | |
ec89276c | 144 | |
b56be296 DJL |
145 | class BridgeTest(NetworkdTestingUtilities, unittest.TestCase): |
146 | """Provide common methods for testing networkd against servers.""" | |
147 | ||
148 | def setUp(self): | |
149 | self.write_network('port1.netdev', '''\ | |
150 | [NetDev] | |
151 | Name=port1 | |
152 | Kind=dummy | |
153 | MACAddress=12:34:56:78:9a:bc''') | |
154 | self.write_network('port2.netdev', '''\ | |
155 | [NetDev] | |
156 | Name=port2 | |
157 | Kind=dummy | |
158 | MACAddress=12:34:56:78:9a:bd''') | |
159 | self.write_network('mybridge.netdev', '''\ | |
160 | [NetDev] | |
161 | Name=mybridge | |
162 | Kind=bridge''') | |
163 | self.write_network('port1.network', '''\ | |
164 | [Match] | |
165 | Name=port1 | |
166 | [Network] | |
167 | Bridge=mybridge''') | |
168 | self.write_network('port2.network', '''\ | |
169 | [Match] | |
170 | Name=port2 | |
171 | [Network] | |
172 | Bridge=mybridge''') | |
173 | self.write_network('mybridge.network', '''\ | |
174 | [Match] | |
175 | Name=mybridge | |
176 | [Network] | |
177 | DNS=192.168.250.1 | |
178 | Address=192.168.250.33/24 | |
179 | Gateway=192.168.250.1''') | |
c44c1b8a | 180 | subprocess.check_call(['systemctl', 'reset-failed', 'systemd-networkd']) |
b56be296 DJL |
181 | subprocess.check_call(['systemctl', 'start', 'systemd-networkd']) |
182 | ||
183 | def tearDown(self): | |
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']) | |
188 | ||
189 | def test_bridge_init(self): | |
190 | self.assert_link_states( | |
191 | port1='managed', | |
192 | port2='managed', | |
193 | mybridge='managed') | |
194 | ||
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', '''\ | |
198 | [Bridge] | |
199 | Priority=28 | |
200 | ''') | |
201 | subprocess.check_call(['systemctl', 'restart', 'systemd-networkd']) | |
202 | self.assertEqual(self.read_attr('port1', 'brport/priority'), '28') | |
203 | ||
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', '''\ | |
208 | [Bridge] | |
209 | Priority=0 | |
210 | ''') | |
211 | subprocess.check_call(['systemctl', 'restart', 'systemd-networkd']) | |
212 | self.assertEqual(self.read_attr('port2', 'brport/priority'), '0') | |
213 | ||
4319c181 SS |
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', '''\ | |
218 | [Bridge] | |
219 | UnicastFlood=true | |
220 | HairPin=true | |
221 | UseBPDU=true | |
222 | FastLeave=true | |
223 | AllowPortToBeRoot=true | |
224 | Cost=555 | |
225 | Priority=23 | |
226 | ''') | |
227 | subprocess.check_call(['systemctl', 'restart', 'systemd-networkd']) | |
228 | ||
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') | |
236 | ||
ec89276c DM |
237 | class ClientTestBase(NetworkdTestingUtilities): |
238 | """Provide common methods for testing networkd against servers.""" | |
239 | ||
fd0cec03 MP |
240 | @classmethod |
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']) | |
246 | ||
247 | @classmethod | |
248 | def tearDownClass(klass): | |
249 | subprocess.check_call(['systemd-analyze', 'set-log-level', klass.orig_log_level]) | |
250 | ||
4ddb85b1 MP |
251 | def setUp(self): |
252 | self.iface = 'test_eth42' | |
253 | self.if_router = 'router_eth42' | |
254 | self.workdir_obj = tempfile.TemporaryDirectory() | |
255 | self.workdir = self.workdir_obj.name | |
ec89276c | 256 | self.config = 'test_eth42.network' |
4ddb85b1 MP |
257 | |
258 | # get current journal cursor | |
fd0cec03 | 259 | subprocess.check_output(['journalctl', '--sync']) |
4ddb85b1 MP |
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] | |
265 | ||
c44c1b8a MP |
266 | subprocess.check_call(['systemctl', 'reset-failed', 'systemd-networkd']) |
267 | ||
4ddb85b1 MP |
268 | def tearDown(self): |
269 | self.shutdown_iface() | |
4ddb85b1 | 270 | subprocess.call(['systemctl', 'stop', 'systemd-networkd']) |
9e0c296a MP |
271 | subprocess.call(['ip', 'link', 'del', 'dummy0'], |
272 | stderr=subprocess.DEVNULL) | |
4ddb85b1 MP |
273 | |
274 | def show_journal(self, unit): | |
275 | '''Show journal of given unit since start of the test''' | |
276 | ||
278391c2 | 277 | print('---- {} ----'.format(unit)) |
fd0cec03 | 278 | subprocess.check_output(['journalctl', '--sync']) |
4ddb85b1 MP |
279 | sys.stdout.flush() |
280 | subprocess.call(['journalctl', '-b', '--no-pager', '--quiet', | |
281 | '--cursor', self.journal_cursor, '-u', unit]) | |
282 | ||
283 | def create_iface(self, ipv6=False): | |
284 | '''Create test interface with DHCP server behind it''' | |
285 | ||
286 | raise NotImplementedError('must be implemented by a subclass') | |
287 | ||
288 | def shutdown_iface(self): | |
289 | '''Remove test interface and stop DHCP server''' | |
290 | ||
291 | raise NotImplementedError('must be implemented by a subclass') | |
292 | ||
293 | def print_server_log(self): | |
294 | '''Print DHCP server log for debugging failures''' | |
295 | ||
296 | raise NotImplementedError('must be implemented by a subclass') | |
297 | ||
298 | def do_test(self, coldplug=True, ipv6=False, extra_opts='', | |
299 | online_timeout=10, dhcp_mode='yes'): | |
d26fdaa2 MP |
300 | try: |
301 | subprocess.check_call(['systemctl', 'start', 'systemd-resolved']) | |
302 | except subprocess.CalledProcessError: | |
303 | self.show_journal('systemd-resolved.service') | |
304 | raise | |
ec89276c | 305 | self.write_network(self.config, '''\ |
38d78d1e | 306 | [Match] |
278391c2 | 307 | Name={} |
4ddb85b1 | 308 | [Network] |
278391c2 BOT |
309 | DHCP={} |
310 | {}'''.format(self.iface, dhcp_mode, extra_opts)) | |
4ddb85b1 MP |
311 | |
312 | if coldplug: | |
313 | # create interface first, then start networkd | |
314 | self.create_iface(ipv6=ipv6) | |
315 | subprocess.check_call(['systemctl', 'start', 'systemd-networkd']) | |
e8c0de91 | 316 | elif coldplug is not None: |
4ddb85b1 MP |
317 | # start networkd first, then create interface |
318 | subprocess.check_call(['systemctl', 'start', 'systemd-networkd']) | |
319 | self.create_iface(ipv6=ipv6) | |
e8c0de91 MP |
320 | else: |
321 | # "None" means test sets up interface by itself | |
322 | subprocess.check_call(['systemctl', 'start', 'systemd-networkd']) | |
4ddb85b1 MP |
323 | |
324 | try: | |
ec89276c | 325 | subprocess.check_call([NETWORKD_WAIT_ONLINE, '--interface', |
4ddb85b1 MP |
326 | self.iface, '--timeout=%i' % online_timeout]) |
327 | ||
328 | if ipv6: | |
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 | |
00d5eaaf | 332 | for _ in range(10): |
4ddb85b1 MP |
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: | |
335 | break | |
336 | time.sleep(1) | |
337 | else: | |
338 | self.fail('timed out waiting for IPv6 configuration') | |
339 | ||
340 | self.assertRegex(out, b'inet6 2600::.* scope global .*dynamic') | |
341 | self.assertRegex(out, b'inet6 fe80::.* scope link') | |
342 | else: | |
343 | # should have link-local address on IPv6 only | |
344 | out = subprocess.check_output(['ip', '-6', 'a', 'show', 'dev', self.iface]) | |
cda39975 | 345 | self.assertRegex(out, br'inet6 fe80::.* scope link') |
4ddb85b1 MP |
346 | self.assertNotIn(b'scope global', out) |
347 | ||
348 | # should have IPv4 address | |
349 | out = subprocess.check_output(['ip', '-4', 'a', 'show', 'dev', self.iface]) | |
350 | self.assertIn(b'state UP', out) | |
cda39975 | 351 | self.assertRegex(out, br'inet 192.168.5.\d+/.* scope global dynamic') |
4ddb85b1 MP |
352 | |
353 | # check networkctl state | |
354 | out = subprocess.check_output(['networkctl']) | |
278391c2 BOT |
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()) | |
4ddb85b1 MP |
357 | |
358 | out = subprocess.check_output(['networkctl', 'status', self.iface]) | |
cda39975 ZJS |
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+') | |
4ddb85b1 | 362 | if ipv6: |
cda39975 | 363 | self.assertRegex(out, br'2600::') |
4ddb85b1 | 364 | else: |
cda39975 ZJS |
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') | |
4ddb85b1 MP |
369 | except (AssertionError, subprocess.CalledProcessError): |
370 | # show networkd status, journal, and DHCP server log on failure | |
ec89276c | 371 | with open(os.path.join(NETWORK_UNITDIR, self.config)) as f: |
278391c2 | 372 | print('\n---- {} ----\n{}'.format(self.config, f.read())) |
4ddb85b1 MP |
373 | print('---- interface status ----') |
374 | sys.stdout.flush() | |
375 | subprocess.call(['ip', 'a', 'show', 'dev', self.iface]) | |
278391c2 | 376 | print('---- networkctl status {} ----'.format(self.iface)) |
4ddb85b1 MP |
377 | sys.stdout.flush() |
378 | subprocess.call(['networkctl', 'status', self.iface]) | |
379 | self.show_journal('systemd-networkd.service') | |
380 | self.print_server_log() | |
381 | raise | |
382 | ||
30b42a9a MP |
383 | for timeout in range(50): |
384 | with open(RESOLV_CONF) as f: | |
385 | contents = f.read() | |
386 | if 'nameserver 192.168.5.1\n' in contents: | |
387 | break | |
388 | time.sleep(0.1) | |
389 | else: | |
390 | self.fail('nameserver 192.168.5.1 not found in ' + RESOLV_CONF) | |
4ddb85b1 | 391 | |
e8c0de91 | 392 | if coldplug is False: |
4ddb85b1 MP |
393 | # check post-down.d hook |
394 | self.shutdown_iface() | |
395 | ||
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) | |
399 | ||
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, | |
f921f573 | 403 | extra_opts='IPv6AcceptRA=False') |
4ddb85b1 MP |
404 | |
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', | |
408 | online_timeout=15) | |
409 | ||
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', | |
f921f573 | 413 | extra_opts='IPv6AcceptRA=False') |
4ddb85b1 MP |
414 | |
415 | def test_coldplug_dhcp_ip6(self): | |
416 | self.do_test(coldplug=True, ipv6=True) | |
417 | ||
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) | |
421 | ||
422 | def test_hotplug_dhcp_ip6(self): | |
423 | self.do_test(coldplug=False, ipv6=True) | |
424 | ||
94363cbb | 425 | def test_route_only_dns(self): |
ec89276c | 426 | self.write_network('myvpn.netdev', '''\ |
38d78d1e | 427 | [NetDev] |
94363cbb MP |
428 | Name=dummy0 |
429 | Kind=dummy | |
430 | MACAddress=12:34:56:78:9a:bc''') | |
ec89276c | 431 | self.write_network('myvpn.network', '''\ |
38d78d1e | 432 | [Match] |
94363cbb MP |
433 | Name=dummy0 |
434 | [Network] | |
435 | Address=192.168.42.100 | |
436 | DNS=192.168.42.1 | |
437 | Domains= ~company''') | |
94363cbb MP |
438 | |
439 | self.do_test(coldplug=True, ipv6=False, | |
440 | extra_opts='IPv6AcceptRouterAdvertisements=False') | |
441 | ||
30b42a9a MP |
442 | with open(RESOLV_CONF) as f: |
443 | contents = f.read() | |
94363cbb MP |
444 | # ~company is not a search domain, only a routing domain |
445 | self.assertNotRegex(contents, 'search.*company') | |
30b42a9a MP |
446 | # our global server should appear |
447 | self.assertIn('nameserver 192.168.5.1\n', contents) | |
b9fe94ca MP |
448 | # should not have domain-restricted server as global server |
449 | self.assertNotIn('nameserver 192.168.42.1\n', contents) | |
450 | ||
451 | def test_route_only_dns_all_domains(self): | |
ec89276c | 452 | self.write_network('myvpn.netdev', '''[NetDev] |
b9fe94ca MP |
453 | Name=dummy0 |
454 | Kind=dummy | |
455 | MACAddress=12:34:56:78:9a:bc''') | |
ec89276c | 456 | self.write_network('myvpn.network', '''[Match] |
b9fe94ca MP |
457 | Name=dummy0 |
458 | [Network] | |
459 | Address=192.168.42.100 | |
460 | DNS=192.168.42.1 | |
461 | Domains= ~company ~.''') | |
b9fe94ca MP |
462 | |
463 | self.do_test(coldplug=True, ipv6=False, | |
464 | extra_opts='IPv6AcceptRouterAdvertisements=False') | |
465 | ||
466 | with open(RESOLV_CONF) as f: | |
467 | contents = f.read() | |
468 | ||
469 | # ~company is not a search domain, only a routing domain | |
470 | self.assertNotRegex(contents, 'search.*company') | |
471 | ||
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) | |
94363cbb | 476 | |
4ddb85b1 | 477 | |
ec89276c | 478 | @unittest.skipUnless(HAVE_DNSMASQ, 'dnsmasq not installed') |
4ddb85b1 MP |
479 | class DnsmasqClientTest(ClientTestBase, unittest.TestCase): |
480 | '''Test networkd client against dnsmasq''' | |
481 | ||
482 | def setUp(self): | |
483 | super().setUp() | |
484 | self.dnsmasq = None | |
e8c0de91 | 485 | self.iface_mac = 'de:ad:be:ef:47:11' |
4ddb85b1 | 486 | |
b9fe94ca | 487 | def create_iface(self, ipv6=False, dnsmasq_opts=None): |
4ddb85b1 MP |
488 | '''Create test interface with DHCP server behind it''' |
489 | ||
490 | # add veth pair | |
e8c0de91 MP |
491 | subprocess.check_call(['ip', 'link', 'add', 'name', self.iface, |
492 | 'address', self.iface_mac, | |
493 | 'type', 'veth', 'peer', 'name', self.if_router]) | |
4ddb85b1 MP |
494 | |
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]) | |
498 | if ipv6: | |
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']) | |
501 | ||
502 | # add DHCP server | |
503 | self.dnsmasq_log = os.path.join(self.workdir, 'dnsmasq.log') | |
504 | lease_file = os.path.join(self.workdir, 'dnsmasq.leases') | |
505 | if ipv6: | |
506 | extra_opts = ['--enable-ra', '--dhcp-range=2600::10,2600::20'] | |
507 | else: | |
508 | extra_opts = [] | |
b9fe94ca MP |
509 | if dnsmasq_opts: |
510 | extra_opts += dnsmasq_opts | |
4ddb85b1 MP |
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) | |
517 | ||
518 | def shutdown_iface(self): | |
519 | '''Remove test interface and stop DHCP server''' | |
520 | ||
521 | if self.if_router: | |
522 | subprocess.check_call(['ip', 'link', 'del', 'dev', self.if_router]) | |
523 | self.if_router = None | |
524 | if self.dnsmasq: | |
525 | self.dnsmasq.kill() | |
526 | self.dnsmasq.wait() | |
527 | self.dnsmasq = None | |
528 | ||
529 | def print_server_log(self): | |
530 | '''Print DHCP server log for debugging failures''' | |
531 | ||
532 | with open(self.dnsmasq_log) as f: | |
278391c2 | 533 | sys.stdout.write('\n\n---- dnsmasq log ----\n{}\n------\n\n'.format(f.read())) |
4ddb85b1 | 534 | |
b9fe94ca MP |
535 | def test_resolved_domain_restricted_dns(self): |
536 | '''resolved: domain-restricted DNS servers''' | |
537 | ||
538 | # create interface for generic connections; this will map all DNS names | |
539 | # to 192.168.42.1 | |
540 | self.create_iface(dnsmasq_opts=['--address=/#/192.168.42.1']) | |
ec89276c | 541 | self.write_network('general.network', '''\ |
b9fe94ca | 542 | [Match] |
278391c2 | 543 | Name={} |
b9fe94ca MP |
544 | [Network] |
545 | DHCP=ipv4 | |
278391c2 | 546 | IPv6AcceptRA=False'''.format(self.iface)) |
b9fe94ca MP |
547 | |
548 | # create second device/dnsmasq for a .company/.lab VPN interface | |
549 | # static IPs for simplicity | |
618b196e | 550 | self.add_veth_pair('testvpnclient', 'testvpnrouter') |
b9fe94ca MP |
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']) | |
554 | ||
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) | |
564 | ||
ec89276c | 565 | self.write_network('vpn.network', '''\ |
b9fe94ca MP |
566 | [Match] |
567 | Name=testvpnclient | |
568 | [Network] | |
569 | IPv6AcceptRA=False | |
570 | Address=10.241.3.2/24 | |
571 | DNS=10.241.3.1 | |
572 | Domains= ~company ~lab''') | |
573 | ||
574 | subprocess.check_call(['systemctl', 'start', 'systemd-networkd']) | |
ec89276c | 575 | subprocess.check_call([NETWORKD_WAIT_ONLINE, '--interface', self.iface, |
b9fe94ca MP |
576 | '--interface=testvpnclient', '--timeout=20']) |
577 | ||
578 | # ensure we start fresh with every test | |
579 | subprocess.check_call(['systemctl', 'restart', 'systemd-resolved']) | |
580 | ||
581 | # test vpnclient specific domains; these should *not* be answered by | |
582 | # the general DNS | |
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) | |
587 | ||
588 | # test general domains | |
589 | out = subprocess.check_output(['systemd-resolve', 'megasearch.net']) | |
590 | self.assertIn(b'megasearch.net: 192.168.42.1', out) | |
591 | ||
592 | with open(self.dnsmasq_log) as f: | |
593 | general_log = f.read() | |
594 | with open(vpn_dnsmasq_log) as f: | |
595 | vpn_log = f.read() | |
596 | ||
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') | |
27e2e323 MP |
600 | self.assertNotIn('.lab', general_log) |
601 | self.assertNotIn('.company', general_log) | |
b9fe94ca MP |
602 | |
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) | |
606 | ||
4050e04b MP |
607 | def test_resolved_etc_hosts(self): |
608 | '''resolved queries to /etc/hosts''' | |
609 | ||
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) | |
617 | ||
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']) | |
625 | ||
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'], | |
631 | ipv6=True) | |
632 | self.do_test(coldplug=None, ipv6=True) | |
633 | ||
634 | try: | |
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) | |
647 | ||
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) | |
651 | ||
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() | |
660 | raise | |
661 | ||
e8c0de91 MP |
662 | def test_transient_hostname(self): |
663 | '''networkd sets transient hostname from DHCP''' | |
664 | ||
89748b0a MP |
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']) | |
672 | ||
278391c2 | 673 | self.create_iface(dnsmasq_opts=['--dhcp-host={},192.168.5.210,testgreen'.format(self.iface_mac)]) |
e8c0de91 MP |
674 | self.do_test(coldplug=None, extra_opts='IPv6AcceptRA=False', dhcp_mode='ipv4') |
675 | ||
fd0cec03 MP |
676 | try: |
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') | |
2926b130 MP |
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: | |
685 | break | |
686 | time.sleep(5) | |
687 | sys.stdout.write('[retry %i] ' % retry) | |
688 | sys.stdout.flush() | |
689 | else: | |
278391c2 | 690 | self.fail('Transient hostname not found in hostnamectl:\n{}'.format(out.decode())) |
fd0cec03 MP |
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() | |
697 | raise | |
89748b0a MP |
698 | |
699 | def test_transient_hostname_with_static(self): | |
700 | '''transient hostname is not applied if static hostname exists''' | |
701 | ||
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']) | |
707 | ||
278391c2 | 708 | self.create_iface(dnsmasq_opts=['--dhcp-host={},192.168.5.210,testgreen'.format(self.iface_mac)]) |
89748b0a MP |
709 | self.do_test(coldplug=None, extra_opts='IPv6AcceptRA=False', dhcp_mode='ipv4') |
710 | ||
fd0cec03 MP |
711 | try: |
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() | |
721 | raise | |
e8c0de91 | 722 | |
4ddb85b1 MP |
723 | |
724 | class NetworkdClientTest(ClientTestBase, unittest.TestCase): | |
725 | '''Test networkd client against networkd server''' | |
726 | ||
727 | def setUp(self): | |
728 | super().setUp() | |
729 | self.dnsmasq = None | |
730 | ||
2c99aba7 | 731 | def create_iface(self, ipv6=False, dhcpserver_opts=None): |
4ddb85b1 MP |
732 | '''Create test interface with DHCP server behind it''' |
733 | ||
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: | |
38d78d1e | 739 | f.write('''\ |
7629744a | 740 | #!/bin/sh |
741 | set -eu | |
4ddb85b1 MP |
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 | |
749 | [NetDev] | |
750 | Name=%(ifr)s | |
751 | Kind=veth | |
752 | ||
753 | [Peer] | |
754 | Name=%(ifc)s | |
755 | EOF | |
756 | ||
757 | cat << EOF > /run/systemd/network/test.network | |
758 | [Match] | |
759 | Name=%(ifr)s | |
760 | ||
761 | [Network] | |
762 | Address=192.168.5.1/24 | |
763 | %(addr6)s | |
764 | DHCPServer=yes | |
765 | ||
766 | [DHCPServer] | |
767 | PoolOffset=10 | |
768 | PoolSize=50 | |
769 | DNS=192.168.5.1 | |
2c99aba7 | 770 | %(dhopts)s |
4ddb85b1 MP |
771 | EOF |
772 | ||
773 | # run networkd as in systemd-networkd.service | |
5ed0dcf4 | 774 | exec $(systemctl cat systemd-networkd.service | sed -n '/^ExecStart=/ { s/^.*=//; s/^[@+-]//; s/^!*//; p}') |
2c99aba7 MP |
775 | ''' % {'ifr': self.if_router, 'ifc': self.iface, 'addr6': ipv6 and 'Address=2600::1/64' or '', |
776 | 'dhopts': dhcpserver_opts or ''}) | |
4ddb85b1 MP |
777 | |
778 | os.fchmod(fd, 0o755) | |
779 | ||
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]) | |
785 | ||
786 | # wait until devices got created | |
00d5eaaf | 787 | for _ in range(50): |
4ddb85b1 MP |
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: | |
790 | break | |
791 | time.sleep(0.1) | |
792 | ||
793 | def shutdown_iface(self): | |
794 | '''Remove test interface and stop DHCP server''' | |
795 | ||
796 | if self.if_router: | |
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 | |
802 | ||
803 | def print_server_log(self): | |
804 | '''Print DHCP server log for debugging failures''' | |
805 | ||
806 | self.show_journal('networkd-test-router.service') | |
807 | ||
808 | @unittest.skip('networkd does not have DHCPv6 server support') | |
809 | def test_hotplug_dhcp_ip6(self): | |
810 | pass | |
811 | ||
812 | @unittest.skip('networkd does not have DHCPv6 server support') | |
813 | def test_coldplug_dhcp_ip6(self): | |
814 | pass | |
815 | ||
d2bc1251 MP |
816 | def test_search_domains(self): |
817 | ||
818 | # we don't use this interface for this test | |
819 | self.if_router = None | |
820 | ||
ec89276c | 821 | self.write_network('test.netdev', '''\ |
38d78d1e | 822 | [NetDev] |
d2bc1251 MP |
823 | Name=dummy0 |
824 | Kind=dummy | |
825 | MACAddress=12:34:56:78:9a:bc''') | |
ec89276c | 826 | self.write_network('test.network', '''\ |
38d78d1e | 827 | [Match] |
d2bc1251 MP |
828 | Name=dummy0 |
829 | [Network] | |
830 | Address=192.168.42.100 | |
831 | DNS=192.168.42.1 | |
832 | Domains= one two three four five six seven eight nine ten''') | |
d2bc1251 MP |
833 | |
834 | subprocess.check_call(['systemctl', 'start', 'systemd-networkd']) | |
835 | ||
30b42a9a MP |
836 | for timeout in range(50): |
837 | with open(RESOLV_CONF) as f: | |
838 | contents = f.read() | |
839 | if ' one' in contents: | |
840 | break | |
841 | time.sleep(0.1) | |
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) | |
d2bc1251 MP |
845 | |
846 | def test_search_domains_too_long(self): | |
847 | ||
848 | # we don't use this interface for this test | |
849 | self.if_router = None | |
850 | ||
851 | name_prefix = 'a' * 60 | |
852 | ||
ec89276c | 853 | self.write_network('test.netdev', '''\ |
38d78d1e | 854 | [NetDev] |
d2bc1251 MP |
855 | Name=dummy0 |
856 | Kind=dummy | |
857 | MACAddress=12:34:56:78:9a:bc''') | |
ec89276c | 858 | self.write_network('test.network', '''\ |
38d78d1e | 859 | [Match] |
d2bc1251 MP |
860 | Name=dummy0 |
861 | [Network] | |
862 | Address=192.168.42.100 | |
863 | DNS=192.168.42.1 | |
38d78d1e | 864 | Domains={p}0 {p}1 {p}2 {p}3 {p}4'''.format(p=name_prefix)) |
d2bc1251 MP |
865 | |
866 | subprocess.check_call(['systemctl', 'start', 'systemd-networkd']) | |
867 | ||
30b42a9a MP |
868 | for timeout in range(50): |
869 | with open(RESOLV_CONF) as f: | |
870 | contents = f.read() | |
871 | if ' one' in contents: | |
872 | break | |
873 | time.sleep(0.1) | |
38d78d1e | 874 | self.assertRegex(contents, 'search .*{p}0 {p}1 {p}2'.format(p=name_prefix)) |
30b42a9a | 875 | self.assertIn('# Total length of all search domains is too long, remaining ones ignored.', contents) |
d2bc1251 | 876 | |
047a0dac JSB |
877 | def test_dropin(self): |
878 | # we don't use this interface for this test | |
879 | self.if_router = None | |
880 | ||
ec89276c | 881 | self.write_network('test.netdev', '''\ |
047a0dac JSB |
882 | [NetDev] |
883 | Name=dummy0 | |
884 | Kind=dummy | |
885 | MACAddress=12:34:56:78:9a:bc''') | |
ec89276c | 886 | self.write_network('test.network', '''\ |
047a0dac JSB |
887 | [Match] |
888 | Name=dummy0 | |
889 | [Network] | |
890 | Address=192.168.42.100 | |
891 | DNS=192.168.42.1''') | |
ec89276c | 892 | self.write_network_dropin('test.network', 'dns', '''\ |
047a0dac JSB |
893 | [Network] |
894 | DNS=127.0.0.1''') | |
895 | ||
896 | subprocess.check_call(['systemctl', 'start', 'systemd-networkd']) | |
897 | ||
898 | for timeout in range(50): | |
899 | with open(RESOLV_CONF) as f: | |
900 | contents = f.read() | |
901 | if ' 127.0.0.1' in contents: | |
902 | break | |
903 | time.sleep(0.1) | |
904 | self.assertIn('nameserver 192.168.42.1\n', contents) | |
905 | self.assertIn('nameserver 127.0.0.1\n', contents) | |
906 | ||
2c99aba7 MP |
907 | def test_dhcp_timezone(self): |
908 | '''networkd sets time zone from DHCP''' | |
909 | ||
910 | def get_tz(): | |
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 "') | |
914 | out = out.strip() | |
915 | assert out.endswith(b'"') | |
916 | return out[3:-1].decode() | |
917 | ||
918 | orig_timezone = get_tz() | |
919 | self.addCleanup(subprocess.call, ['timedatectl', 'set-timezone', orig_timezone]) | |
920 | ||
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') | |
923 | ||
924 | # should have applied the received timezone | |
925 | try: | |
926 | self.assertEqual(get_tz(), 'Pacific/Honolulu') | |
927 | except AssertionError: | |
928 | self.show_journal('systemd-networkd.service') | |
929 | self.show_journal('systemd-hostnamed.service') | |
930 | raise | |
931 | ||
932 | ||
618b196e DM |
933 | class MatchClientTest(unittest.TestCase, NetworkdTestingUtilities): |
934 | """Test [Match] sections in .network files. | |
935 | ||
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. | |
940 | """ | |
941 | ||
942 | def tearDown(self): | |
943 | """Stop networkd.""" | |
944 | subprocess.call(['systemctl', 'stop', 'systemd-networkd']) | |
945 | ||
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') | |
952 | ||
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', """\ | |
961 | [Match] | |
278391c2 | 962 | MACAddress={} |
618b196e | 963 | Name=!nonexistent *peer* |
278391c2 | 964 | [Network]""".format(mac)) |
618b196e DM |
965 | subprocess.check_call(['systemctl', 'start', 'systemd-networkd']) |
966 | self.assert_link_states(test_veth='managed', test_peer='unmanaged') | |
967 | ||
968 | ||
a09dc546 DM |
969 | class UnmanagedClientTest(unittest.TestCase, NetworkdTestingUtilities): |
970 | """Test if networkd manages the correct interfaces.""" | |
971 | ||
972 | def setUp(self): | |
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. | |
976 | self.veths = { | |
977 | 'm1def': 'm0unm', | |
978 | 'm1man': 'm1unm', | |
979 | } | |
980 | ||
981 | # Define the contents of .network files to be read in order. | |
982 | self.configs = ( | |
983 | "[Match]\nName=m1def\n", | |
984 | "[Match]\nName=m1unm\n[Link]\nUnmanaged=yes\n", | |
985 | "[Match]\nName=m1*\n[Link]\nUnmanaged=no\n", | |
986 | ) | |
987 | ||
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) | |
991 | ||
992 | def tearDown(self): | |
993 | """Stop networkd.""" | |
994 | subprocess.call(['systemctl', 'stop', 'systemd-networkd']) | |
995 | ||
996 | def create_iface(self): | |
997 | """Create temporary veth pairs for interface matching.""" | |
998 | for veth, peer in self.veths.items(): | |
618b196e | 999 | self.add_veth_pair(veth, peer) |
a09dc546 DM |
1000 | |
1001 | def test_unmanaged_setting(self): | |
1002 | """Verify link states with Unmanaged= settings, hot-plug.""" | |
1003 | subprocess.check_call(['systemctl', 'start', 'systemd-networkd']) | |
1004 | self.create_iface() | |
1005 | self.assert_link_states(m1def='managed', | |
1006 | m1man='managed', | |
1007 | m1unm='unmanaged', | |
1008 | m0unm='unmanaged') | |
1009 | ||
1010 | def test_unmanaged_setting_coldplug(self): | |
1011 | """Verify link states with Unmanaged= settings, cold-plug.""" | |
1012 | self.create_iface() | |
1013 | subprocess.check_call(['systemctl', 'start', 'systemd-networkd']) | |
1014 | self.assert_link_states(m1def='managed', | |
1015 | m1man='managed', | |
1016 | m1unm='unmanaged', | |
1017 | m0unm='unmanaged') | |
1018 | ||
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']) | |
1024 | self.create_iface() | |
1025 | self.assert_link_states(m1def='managed', | |
1026 | m1man='managed', | |
1027 | m1unm='unmanaged', | |
1028 | m0unm='managed') | |
1029 | ||
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") | |
1034 | self.create_iface() | |
1035 | subprocess.check_call(['systemctl', 'start', 'systemd-networkd']) | |
1036 | self.assert_link_states(m1def='managed', | |
1037 | m1man='managed', | |
1038 | m1unm='unmanaged', | |
1039 | m0unm='managed') | |
1040 | ||
1041 | ||
4ddb85b1 MP |
1042 | if __name__ == '__main__': |
1043 | unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, | |
1044 | verbosity=2)) |