Debian Codegraph @

debian/tests/boot-and-services

raw
1 #!/usr/bin/python3
2 # autopkgtest check: Boot with systemd and check critical desktop services
3 # (C) 2014 Canonical Ltd.
4 # Author: Martin Pitt <[email protected]>
5
6 import platform
7 import sys
8 import os
9 import unittest
10 import subprocess
11 import tempfile
12 import shutil
13 import time
14 import re
15 from glob import glob
16
17 is_container = subprocess.call(['systemd-detect-virt', '--container']) == 0
18
19
20 def wait_unit_stop(unit, timeout=10):
21 '''Wait until given unit is not running any more
22
23 Raise RuntimeError on timeout.
24 '''
25 for i in range(timeout):
26 if subprocess.call(['systemctl', 'is-active', '--quiet', unit]) != 0:
27 return
28 time.sleep(1)
29
30 raise RuntimeError('Timed out waiting for %s to stop' % unit)
31
32
33 class ServicesTest(unittest.TestCase):
34 '''Check that expected services are running'''
35
36 def test_0_init(self):
37 '''Verify that init is systemd'''
38
39 self.assertIn('systemd', os.readlink('/proc/1/exe'))
40
41 @unittest.skipUnless(shutil.which('gdm3') is not None, 'gdm3 not found')
42 def test_gdm3(self):
43 if 'lxc' in subprocess.run(['systemd-detect-virt', '--container'], check=False, stdout=subprocess.PIPE).stdout.decode():
44 # this test often fails in tests-in-lxd
45 self.skipTest('gdm3 is flaky under lxd')
46 subprocess.check_call(['pgrep', '-af', '/gdm[-3]'])
47 self.active_unit('gdm')
48
49 def test_dbus(self):
50 out = subprocess.check_output(
51 ['dbus-send', '--print-reply', '--system',
52 '--dest=org.freedesktop.DBus', '/', 'org.freedesktop.DBus.GetId'])
53 self.assertIn(b'string "', out)
54 self.active_unit('dbus')
55
56 def test_network_manager(self):
57 # 0.9.10 changed the command name
58 _help = subprocess.check_output(['nmcli', '--help'],
59 stderr=subprocess.STDOUT)
60 if b' g[eneral]' in _help:
61 out = subprocess.check_output(['nmcli', 'general'])
62 else:
63 out = subprocess.check_output(['nmcli', 'nm'])
64 self.assertIn(b'enabled', out)
65 self.active_unit('NetworkManager')
66
67 def test_cron(self):
68 pid = subprocess.check_output(['pidof', 'cron'], universal_newlines=True).strip()
69 out = subprocess.check_output(['ps', 'u', pid], universal_newlines=True)
70 self.assertIn('root', out)
71 self.active_unit('cron')
72
73 def test_logind(self):
74 out = subprocess.check_output(['loginctl'])
75 self.assertNotEqual(b'', out)
76 self.active_unit('systemd-logind')
77
78 @unittest.skipIf('pkg.systemd.upstream' in os.environ.get('DEB_BUILD_PROFILES', ''),
79 'Forwarding to rsyslog is a Debian patch')
80 def test_rsyslog(self):
81 pid = subprocess.check_output(['pidof', 'rsyslogd'], universal_newlines=True).strip()
82 out = subprocess.check_output(['ps', 'u', pid], universal_newlines=True)
83 self.assertIn('bin/rsyslogd', out)
84 self.active_unit('rsyslog')
85
86 subprocess.check_call(
87 ['systemd-run',
88 '--quiet',
89 '--wait',
90 '--unit',
91 'test-boot-and-services-rsyslog.service',
92 '--',
93 'echo',
94 'hello rsyslog'
95 ]
96 )
97 subprocess.check_call(['journalctl', '--sync'])
98
99 with open('/var/log/syslog') as f:
100 log = f.read()
101 if not is_container:
102 # has kernel messages
103 self.assertRegex(log, 'kernel:.*')
104 # has init messages
105 self.assertRegex(log, 'systemd.*Reached target')
106 # has other services
107 self.assertRegex(log, 'echo.*: hello rsyslog')
108 self.assertRegex(log, 'test-boot-and-services-rsyslog.service.*:')
109
110 @unittest.skipIf(is_container, 'udev does not work in containers')
111 def test_udev(self):
112 out = subprocess.check_output(['udevadm', 'info', '--export-db'])
113 self.assertIn(b'\nP: /devices/', out)
114 self.active_unit('systemd-udevd')
115
116 @unittest.skipIf('pkg.systemd.upstream' in os.environ.get('DEB_BUILD_PROFILES', ''),
117 'Debian specific configuration, N/A for upstream')
118 def test_tmp_cleanup(self):
119 # autopkgtest overrides tmp.mount with empty /etc/systemd/system/tmp.mount
120 # as a workaround for issues where /tmp is filled up too easily. LP: #2069834
121 try:
122 if os.stat('/etc/systemd/system/tmp.mount').st_size == 0:
123 self.skipTest('autopkgtest environment has overridden tmp.mount')
124 except FileNotFoundError:
125 pass
126
127 # systemd-tmpfiles-clean.timer only runs 15 mins after boot, shortcut
128 # it
129 self.assertEqual(subprocess.call(
130 ['systemctl', 'status', 'systemd-tmpfiles-clean.timer'],
131 stdout=subprocess.PIPE), 0)
132 subprocess.check_call(['systemctl', 'start', 'systemd-tmpfiles-clean'])
133 if not is_container:
134 # all files in /tmp/ should get cleaned up on boot
135 self.assertFalse(os.path.exists('/tmp/oldfile.test'))
136 self.assertFalse(os.path.exists('/tmp/newfile.test'))
137 # files in /var/tmp/ older than 30d should get cleaned up, unless legacy
138 # compat tmpfiles.d is installed
139 if not is_container and not os.path.exists('/etc/tmpfiles.d/tmp.conf'):
140 self.assertFalse(os.path.exists('/var/tmp/oldfile.test'))
141 self.assertTrue(os.path.exists('/var/tmp/newfile.test'))
142
143 # next run should leave the recent ones
144 os.close(os.open('/tmp/newfile.test',
145 os.O_CREAT | os.O_EXCL | os.O_WRONLY))
146 subprocess.check_call(['systemctl', 'start', 'systemd-tmpfiles-clean'])
147 self.assertTrue(os.path.exists('/tmp/newfile.test'))
148
149 # Helper methods
150
151 def active_unit(self, unit):
152 '''Check that given unit is active'''
153
154 out = subprocess.check_output(['systemctl', 'status', unit])
155 self.assertIn(b'active (running)', out)
156
157
158 class JournalTest(unittest.TestCase):
159 '''Check journal functionality'''
160
161 def test_no_options(self):
162 out = subprocess.check_output(['journalctl'])
163 if not is_container:
164 # has kernel messages
165 self.assertRegex(out, b'kernel:.*')
166 # has init messages
167 self.assertRegex(out, b'systemd.*Reached target(?: graphical.target -)? Graphical Interface')
168 # has other services
169 self.assertRegex(out, b'NetworkManager.*:.*starting')
170
171 def test_log_for_service(self):
172 out = subprocess.check_output(
173 ['journalctl', '_SYSTEMD_UNIT=NetworkManager.service'])
174 self.assertRegex(out, b'NetworkManager.*:.*starting')
175 self.assertNotIn(b'kernel:', out)
176 self.assertNotIn(b'systemd:', out)
177
178
179 @unittest.skipIf(is_container, 'nspawn does not work in most containers')
180 class NspawnTest(unittest.TestCase):
181 '''Check nspawn'''
182
183 @classmethod
184 def setUpClass(kls):
185 '''Build a bootable busybox mini-container'''
186
187 kls.td_c_busybox = tempfile.TemporaryDirectory(prefix='c_busybox.')
188 kls.c_busybox = kls.td_c_busybox.name
189 for d in ['etc/init.d', 'bin', 'sbin']:
190 os.makedirs(os.path.join(kls.c_busybox, d))
191 shutil.copy('/bin/busybox', os.path.join(kls.c_busybox, 'bin'))
192 shutil.copy('/etc/os-release', os.path.join(kls.c_busybox, 'etc'))
193 os.symlink('busybox', os.path.join(kls.c_busybox, 'bin', 'sh'))
194 os.symlink('../bin/busybox', os.path.join(kls.c_busybox, 'sbin/init'))
195 with open(os.path.join(kls.c_busybox, 'etc/init.d/rcS'), 'w') as f:
196 f.write('''#!/bin/sh
197 echo fake container started
198 ps aux
199 poweroff\n''')
200 os.fchmod(f.fileno(), 0o755)
201 subprocess.check_call(['systemd-machine-id-setup', '--root',
202 kls.c_busybox], stderr=subprocess.PIPE)
203
204 def setUp(self):
205 self.workdir = tempfile.TemporaryDirectory()
206
207 def test_boot(self):
208 cont = os.path.join(self.workdir.name, 'c1')
209 shutil.copytree(self.c_busybox, cont, symlinks=True)
210 os.sync()
211 nspawn = subprocess.Popen(['systemd-nspawn', '-D', cont, '-b'],
212 stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
213 out = nspawn.communicate(timeout=60)[0]
214 self.assertIn(b'Spawning container c1', out)
215 self.assertIn(b'fake container started', out)
216 self.assertRegex(out, rb'\n\s+1\s+0\s+init[\r\n]')
217 self.assertRegex(out, rb'\n\s+2+\s+0\s.*rcS[\r\n]')
218 self.assertRegex(out, b'Container c1.*shut down')
219 self.assertEqual(nspawn.returncode, 0)
220
221 def test_service(self):
222 self.assertTrue(os.path.isdir('/var/lib/machines'))
223 cont = '/var/lib/machines/c1'
224 shutil.copytree(self.c_busybox, cont, symlinks=True)
225 self.addCleanup(shutil.rmtree, cont)
226 os.sync()
227 subprocess.check_call(['systemctl', 'start', 'systemd-nspawn@c1'])
228 wait_unit_stop('systemd-nspawn@c1')
229
230 subprocess.call(['journalctl', '--sync'])
231 systemctl = subprocess.Popen(
232 ['systemctl', 'status', '-overbose', '-l', 'systemd-nspawn@c1'],
233 stdout=subprocess.PIPE)
234 out = systemctl.communicate()[0].decode('UTF-8', 'replace')
235 self.assertEqual(systemctl.returncode, 3, out)
236 self.assertNotIn('failed', out)
237
238
239 @unittest.skipUnless(os.path.exists('/sys/kernel/security/apparmor'),
240 'AppArmor not enabled')
241 @unittest.skipIf(is_container and platform.machine().startswith('arm'), 'fails on armhf testbeds, see LP: #1842352')
242 class AppArmorTest(unittest.TestCase):
243 def test_profile(self):
244 '''AppArmor confined unit'''
245
246 # create AppArmor profile
247 aa_profile = tempfile.NamedTemporaryFile(prefix='aa_violator.')
248 aa_profile.write(b'''#include <tunables/global>
249
250 profile "violator-test" {
251 #include <abstractions/base>
252
253 /{usr/,}bin/** rix,
254 file @{coreutil_dirs}* ix,
255 /etc/machine-id r,
256 }
257 ''')
258 aa_profile.flush()
259 subprocess.check_call(['apparmor_parser', '-r', '-v', aa_profile.name])
260
261 # create confined unit
262 with open('/run/systemd/system/violator.service', 'w') as f:
263 f.write('''[Unit]
264 Description=AppArmor test
265
266 [Service]
267 ExecStart=/bin/sh -euc 'echo CP1; cat /etc/machine-id; echo CP2; if cat /etc/passwd; then exit 1; fi; echo CP3'
268 AppArmorProfile=violator-test
269 ''')
270 self.addCleanup(os.unlink, '/run/systemd/system/violator.service')
271
272 # launch
273 subprocess.check_call(['systemctl', 'daemon-reload'])
274 subprocess.check_call(['systemctl', 'start', 'violator.service'])
275 wait_unit_stop('violator.service')
276
277 # check status
278 st = subprocess.Popen(['systemctl', 'status', '-l',
279 'violator.service'], stdout=subprocess.PIPE,
280 universal_newlines=True)
281 out = st.communicate()[0]
282 # unit should be stopped
283 self.assertEqual(st.returncode, 3)
284
285 self.assertIn('inactive', out)
286 self.assertIn('CP1', out)
287 self.assertIn('CP2', out)
288 self.assertIn('CP3', out)
289 with open('/etc/machine-id') as f:
290 self.assertIn(f.read().strip(), out)
291 self.assertNotIn('root:x', out, 'unit can read /etc/passwd')
292
293
294 @unittest.skipIf(os.path.exists('/sys/fs/cgroup/cgroup.controllers'),
295 'test needs to be reworked on unified cgroup hierarchy')
296 class CgroupsTest(unittest.TestCase):
297 '''Check cgroup setup'''
298
299 @classmethod
300 def setUpClass(kls):
301 kls.controllers = []
302 for controller in glob('/sys/fs/cgroup/*'):
303 if not os.path.islink(controller):
304 kls.controllers.append(controller)
305
306 def setUp(self):
307 self.service = 'testsrv.service'
308 self.service_file = '/run/systemd/system/' + self.service
309
310 def tearDown(self):
311 subprocess.call(['systemctl', 'stop', self.service],
312 stderr=subprocess.PIPE)
313 try:
314 os.unlink(self.service_file)
315 except OSError:
316 pass
317 subprocess.check_call(['systemctl', 'daemon-reload'])
318
319 def create_service(self, extra_service=''):
320 '''Create test service unit'''
321
322 with open(self.service_file, 'w') as f:
323 f.write('''[Unit]
324 Description=test service
325 [Service]
326 ExecStart=/bin/sleep 500
327 %s
328 ''' % extra_service)
329 subprocess.check_call(['systemctl', 'daemon-reload'])
330
331 def assertNoControllers(self):
332 '''Assert that no cgroup controllers exist for test service'''
333
334 cs = glob('/sys/fs/cgroup/*/system.slice/%s' % self.service)
335 self.assertEqual(cs, [])
336
337 def assertController(self, name):
338 '''Assert that cgroup controller exists for test service'''
339
340 c = '/sys/fs/cgroup/%s/system.slice/%s' % (name, self.service)
341 self.assertTrue(os.path.isdir(c))
342
343 def assertNoController(self, name):
344 '''Assert that cgroup controller does not exist for test service'''
345
346 c = '/sys/fs/cgroup/%s/system.slice/%s' % (name, self.service)
347 self.assertFalse(os.path.isdir(c))
348
349 def test_simple(self):
350 '''simple service'''
351
352 self.create_service()
353 self.assertNoControllers()
354 subprocess.check_call(['systemctl', 'start', self.service])
355 self.assertController('systemd')
356 subprocess.check_call(['systemctl', 'stop', self.service])
357 self.assertNoControllers()
358
359 def test_cpushares(self):
360 '''service with CPUShares'''
361
362 self.create_service('CPUShares=1000')
363 self.assertNoControllers()
364 subprocess.check_call(['systemctl', 'start', self.service])
365 self.assertController('systemd')
366 self.assertController('cpu,cpuacct')
367 subprocess.check_call(['systemctl', 'stop', self.service])
368 self.assertNoControllers()
369
370
371 class SeccompTest(unittest.TestCase):
372 '''Check seccomp syscall filtering'''
373
374 def test_failing(self):
375 with open('/run/systemd/system/scfail.service', 'w') as f:
376 f.write('''[Unit]
377 Description=seccomp test
378 [Service]
379 ExecStart=/bin/cat /etc/machine-id
380 SystemCallFilter=access
381 ''')
382 self.addCleanup(os.unlink, '/run/systemd/system/scfail.service')
383
384 # launch
385 subprocess.check_call(['systemctl', 'daemon-reload'])
386 subprocess.check_call(['systemctl', 'start', 'scfail.service'])
387 wait_unit_stop('scfail.service')
388
389 # check status
390 st = subprocess.Popen(['systemctl', 'status', '-l',
391 'scfail.service'], stdout=subprocess.PIPE)
392 out = st.communicate()[0]
393 # unit should be stopped
394 self.assertEqual(st.returncode, 3)
395
396 subprocess.check_call(['systemctl', 'reset-failed', 'scfail.service'])
397
398 self.assertIn(b'failed', out)
399 self.assertRegex(out, b'code=(killed|dumped), signal=SYS')
400 with open('/etc/machine-id') as f:
401 self.assertNotIn(f.read().strip().encode('ASCII'), out)
402
403
404 @unittest.skipIf(is_container, 'systemd-coredump does not work in containers')
405 class CoredumpTest(unittest.TestCase):
406 '''Check systemd-coredump'''
407
408 def test_bash_crash(self):
409 subprocess.call("ulimit -c unlimited; bash -c 'kill -SEGV $$'", shell=True,
410 cwd='/tmp', stderr=subprocess.DEVNULL)
411
412 # with systemd-coredump installed we should get the core dumps in
413 # systemd's dir
414 for timeout in range(50):
415 cores = glob('/var/lib/systemd/coredump/core.bash.*')
416 if cores:
417 break
418 time.sleep(1)
419 self.assertNotEqual(cores, [])
420 self.assertEqual(glob('/tmp/core*'), [])
421
422 # we should also get a message and stack trace in journal
423 for timeout in range(10):
424 subprocess.call(['journalctl', '--sync'])
425 journal = subprocess.check_output(['journalctl', '-t', 'systemd-coredump'])
426 if re.search(b'Process.*bash.*dumped core', journal):
427 break
428 time.sleep(1)
429 self.assertRegex(journal, b'Process.*bash.*dumped core')
430 self.assertIn(b'Stack trace', journal)
431
432
433 class CLITest(unittest.TestCase):
434 def setUp(self):
435 self.programs = []
436 for line in subprocess.check_output(['dpkg', '-L', 'systemd', 'systemd-container', 'systemd-coredump', 'udev'],
437 universal_newlines=True).splitlines():
438 if '/bin/' in line:
439 self.programs.append(line.strip())
440
441 def test_help(self):
442 '--help works and succeeds'''
443
444 for program in self.programs:
445 p = subprocess.Popen([program, '--help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
446 (out, err) = p.communicate()
447 try:
448 self.assertEqual(err, '')
449 self.assertEqual(p.returncode, 0)
450 self.assertIn(os.path.basename(program), out)
451 self.assertTrue('--help' in out or 'Usage' in out, out)
452 except AssertionError:
453 print('Failed program: %s' % program)
454 raise
455
456 def test_version(self):
457 '--version works and succeeds'''
458
459 version = subprocess.check_output(['pkg-config', '--modversion', 'systemd'],
460 universal_newlines=True).strip()
461
462 for program in self.programs:
463 # known to not respond to --version
464 if os.path.basename(program) in ['kernel-install', 'systemd-ask-password', 'systemd-stdio-bridge']:
465 continue
466 p = subprocess.Popen([program, '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
467 (out, err) = p.communicate()
468 try:
469 self.assertEqual(err, '')
470 self.assertEqual(p.returncode, 0)
471 self.assertIn(version, out)
472 except AssertionError:
473 print('Failed program: %s' % program)
474 raise
475
476 def test_invalid_option(self):
477 '''Calling with invalid option fails'''
478
479 for program in self.programs:
480 p = subprocess.Popen([program, '--invalid-option'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
481 (out, err) = p.communicate()
482 try:
483 # kernel-install is an unique snowflake
484 if not program.endswith('/kernel-install'):
485 self.assertIn('--invalid-option', err)
486 self.assertNotEqual(p.returncode, 0)
487 except AssertionError:
488 print('Failed program: %s' % program)
489 raise
490
491
492 def pre_boot_setup():
493 '''Test setup before rebooting testbed'''
494
495 subprocess.check_call(['systemctl', 'set-default', 'graphical.target'],
496 stderr=subprocess.STDOUT)
497
498 # This test installs network-manager, which seems to cause
499 # systemd-networkd-wait-online to be stuck as they conflict,
500 # so systemctl start network-online.target ran by autopkgtest
501 # gets stuck, at least in Debian Bullseye images.
502 # https://salsa.debian.org/ci-team/autopkgtest/-/blob/debian/5.21/virt/autopkgtest-virt-lxc#L131
503 subprocess.check_call(['systemctl', 'disable', 'systemd-networkd.service'],
504 stderr=subprocess.STDOUT)
505
506 # create a few temporary files to ensure that they get cleaned up on boot
507 os.close(os.open('/tmp/newfile.test',
508 os.O_CREAT | os.O_EXCL | os.O_WRONLY))
509 os.close(os.open('/var/tmp/newfile.test',
510 os.O_CREAT | os.O_EXCL | os.O_WRONLY))
511 # we can't use utime() here, as systemd looks for ctime
512 if not is_container:
513 cur_time = time.clock_gettime(time.CLOCK_REALTIME)
514 time.clock_settime(time.CLOCK_REALTIME, cur_time - 2 * 30 * 86400)
515 try:
516 os.close(os.open('/tmp/oldfile.test',
517 os.O_CREAT | os.O_EXCL | os.O_WRONLY))
518 os.close(os.open('/var/tmp/oldfile.test',
519 os.O_CREAT | os.O_EXCL | os.O_WRONLY))
520 finally:
521 time.clock_settime(time.CLOCK_REALTIME, cur_time)
522
523 # allow X to start even on headless machines
524 os.makedirs('/etc/X11/xorg.conf.d/', exist_ok=True)
525 with open('/etc/X11/xorg.conf.d/dummy.conf', 'w') as f:
526 f.write('''Section "Device"
527 Identifier "test"
528 Driver "dummy"
529 EndSection''')
530
531 # accounts-daemon.service fails if /usr/share/accountsservice/interfaces does not exist.
532 # FIXME: remove this workaround again when
533 # https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=1038137 is fixed
534 os.makedirs('/usr/share/accountsservice/interfaces', exist_ok=True)
535
536
537 if __name__ == '__main__':
538 if not os.getenv('AUTOPKGTEST_REBOOT_MARK'):
539 pre_boot_setup()
540 print('Rebooting...')
541 subprocess.check_call(['/tmp/autopkgtest-reboot', 'boot1'])
542
543 unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout,
544 verbosity=2))