blob: 5cc408b0c47b64620ced7f929700429cf60a8cad [file] [log] [blame]
Patrick Williams92b42cb2022-09-03 06:53:57 -05001# Copyright (C) 2013 Intel Corporation
2#
3# SPDX-License-Identifier: MIT
4
5inherit metadata_scm
6inherit image-artifact-names
7
8# testimage.bbclass enables testing of qemu images using python unittests.
9# Most of the tests are commands run on target image over ssh.
10# To use it add testimage to global inherit and call your target image with -c testimage
11# You can try it out like this:
12# - first add IMAGE_CLASSES += "testimage" in local.conf
13# - build a qemu core-image-sato
14# - then bitbake core-image-sato -c testimage. That will run a standard suite of tests.
15#
16# The tests can be run automatically each time an image is built if you set
17# TESTIMAGE_AUTO = "1"
18
19TESTIMAGE_AUTO ??= "0"
20
21# You can set (or append to) TEST_SUITES in local.conf to select the tests
22# which you want to run for your target.
23# The test names are the module names in meta/lib/oeqa/runtime/cases.
24# Each name in TEST_SUITES represents a required test for the image. (no skipping allowed)
25# Appending "auto" means that it will try to run all tests that are suitable for the image (each test decides that on it's own).
26# Note that order in TEST_SUITES is relevant: tests are run in an order such that
27# tests mentioned in @skipUnlessPassed run before the tests that depend on them,
28# but without such dependencies, tests run in the order in which they are listed
29# in TEST_SUITES.
30#
31# A layer can add its own tests in lib/oeqa/runtime, provided it extends BBPATH as normal in its layer.conf.
32
33# TEST_LOG_DIR contains a command ssh log and may contain infromation about what command is running, output and return codes and for qemu a boot log till login.
34# Booting is handled by this class, and it's not a test in itself.
35# TEST_QEMUBOOT_TIMEOUT can be used to set the maximum time in seconds the launch code will wait for the login prompt.
36# TEST_OVERALL_TIMEOUT can be used to set the maximum time in seconds the tests will be allowed to run (defaults to no limit).
37# TEST_QEMUPARAMS can be used to pass extra parameters to qemu, e.g. "-m 1024" for setting the amount of ram to 1 GB.
38# TEST_RUNQEMUPARAMS can be used to pass extra parameters to runqemu, e.g. "gl" to enable OpenGL acceleration.
39# QEMU_USE_KVM can be set to "" to disable the use of kvm (by default it is enabled if target_arch == build_arch or both of them are x86 archs)
40
41# TESTIMAGE_BOOT_PATTERNS can be used to override certain patterns used to communicate with the target when booting,
42# if a pattern is not specifically present on this variable a default will be used when booting the target.
43# TESTIMAGE_BOOT_PATTERNS[<flag>] overrides the pattern used for that specific flag, where flag comes from a list of accepted flags
44# e.g. normally the system boots and waits for a login prompt (login:), after that it sends the command: "root\n" to log as the root user
45# if we wanted to log in as the hypothetical "webserver" user for example we could set the following:
46# TESTIMAGE_BOOT_PATTERNS = "send_login_user search_login_succeeded"
47# TESTIMAGE_BOOT_PATTERNS[send_login_user] = "webserver\n"
48# TESTIMAGE_BOOT_PATTERNS[search_login_succeeded] = "webserver@[a-zA-Z0-9\-]+:~#"
49# The accepted flags are the following: search_reached_prompt, send_login_user, search_login_succeeded, search_cmd_finished.
50# They are prefixed with either search/send, to differentiate if the pattern is meant to be sent or searched to/from the target terminal
51
52TEST_LOG_DIR ?= "${WORKDIR}/testimage"
53
54TEST_EXPORT_DIR ?= "${TMPDIR}/testimage/${PN}"
55TEST_INSTALL_TMP_DIR ?= "${WORKDIR}/testimage/install_tmp"
56TEST_NEEDED_PACKAGES_DIR ?= "${WORKDIR}/testimage/packages"
57TEST_EXTRACTED_DIR ?= "${TEST_NEEDED_PACKAGES_DIR}/extracted"
58TEST_PACKAGED_DIR ?= "${TEST_NEEDED_PACKAGES_DIR}/packaged"
59
60BASICTESTSUITE = "\
61 ping date df ssh scp python perl gi ptest parselogs \
62 logrotate connman systemd oe_syslog pam stap ldd xorg \
63 kernelmodule gcc buildcpio buildlzip buildgalculator \
64 dnf rpm opkg apt weston go rust"
65
66DEFAULT_TEST_SUITES = "${BASICTESTSUITE}"
67
68# musl doesn't support systemtap
69DEFAULT_TEST_SUITES:remove:libc-musl = "stap"
70
71# qemumips is quite slow and has reached the timeout limit several times on the YP build cluster,
72# mitigate this by removing build tests for qemumips machines.
73MIPSREMOVE ??= "buildcpio buildlzip buildgalculator"
74DEFAULT_TEST_SUITES:remove:qemumips = "${MIPSREMOVE}"
75DEFAULT_TEST_SUITES:remove:qemumips64 = "${MIPSREMOVE}"
76
77TEST_SUITES ?= "${DEFAULT_TEST_SUITES}"
78
79QEMU_USE_KVM ?= "1"
80TEST_QEMUBOOT_TIMEOUT ?= "1000"
81TEST_OVERALL_TIMEOUT ?= ""
82TEST_TARGET ?= "qemu"
83TEST_QEMUPARAMS ?= ""
84TEST_RUNQEMUPARAMS ?= ""
85
86TESTIMAGE_BOOT_PATTERNS ?= ""
87
88TESTIMAGEDEPENDS = ""
89TESTIMAGEDEPENDS:append:qemuall = " qemu-native:do_populate_sysroot qemu-helper-native:do_populate_sysroot qemu-helper-native:do_addto_recipe_sysroot"
90TESTIMAGEDEPENDS += "${@bb.utils.contains('IMAGE_PKGTYPE', 'rpm', 'cpio-native:do_populate_sysroot', '', d)}"
91TESTIMAGEDEPENDS += "${@bb.utils.contains('IMAGE_PKGTYPE', 'rpm', 'dnf-native:do_populate_sysroot', '', d)}"
92TESTIMAGEDEPENDS += "${@bb.utils.contains('IMAGE_PKGTYPE', 'rpm', 'createrepo-c-native:do_populate_sysroot', '', d)}"
93TESTIMAGEDEPENDS += "${@bb.utils.contains('IMAGE_PKGTYPE', 'ipk', 'opkg-utils-native:do_populate_sysroot package-index:do_package_index', '', d)}"
94TESTIMAGEDEPENDS += "${@bb.utils.contains('IMAGE_PKGTYPE', 'deb', 'apt-native:do_populate_sysroot package-index:do_package_index', '', d)}"
95
96TESTIMAGELOCK = "${TMPDIR}/testimage.lock"
97TESTIMAGELOCK:qemuall = ""
98
99TESTIMAGE_DUMP_DIR ?= "${LOG_DIR}/runtime-hostdump/"
100
101TESTIMAGE_UPDATE_VARS ?= "DL_DIR WORKDIR DEPLOY_DIR"
102
103testimage_dump_target () {
104 top -bn1
105 ps
106 free
107 df
108 # The next command will export the default gateway IP
109 export DEFAULT_GATEWAY=$(ip route | awk '/default/ { print $3}')
110 ping -c3 $DEFAULT_GATEWAY
111 dmesg
112 netstat -an
113 ip address
114 # Next command will dump logs from /var/log/
115 find /var/log/ -type f 2>/dev/null -exec echo "====================" \; -exec echo {} \; -exec echo "====================" \; -exec cat {} \; -exec echo "" \;
116}
117
118testimage_dump_host () {
119 top -bn1
120 iostat -x -z -N -d -p ALL 20 2
121 ps -ef
122 free
123 df
124 memstat
125 dmesg
126 ip -s link
127 netstat -an
128}
129
130testimage_dump_monitor () {
131 query-status
132 query-block
133 dump-guest-memory {"paging":false,"protocol":"file:%s.img"}
134}
135
136python do_testimage() {
137 testimage_main(d)
138}
139
140addtask testimage
141do_testimage[nostamp] = "1"
142do_testimage[network] = "1"
143do_testimage[depends] += "${TESTIMAGEDEPENDS}"
144do_testimage[lockfiles] += "${TESTIMAGELOCK}"
145
146def testimage_sanity(d):
147 if (d.getVar('TEST_TARGET') == 'simpleremote'
148 and (not d.getVar('TEST_TARGET_IP')
149 or not d.getVar('TEST_SERVER_IP'))):
150 bb.fatal('When TEST_TARGET is set to "simpleremote" '
151 'TEST_TARGET_IP and TEST_SERVER_IP are needed too.')
152
153def get_testimage_configuration(d, test_type, machine):
154 import platform
155 from oeqa.utils.metadata import get_layers
156 configuration = {'TEST_TYPE': test_type,
157 'MACHINE': machine,
158 'DISTRO': d.getVar("DISTRO"),
159 'IMAGE_BASENAME': d.getVar("IMAGE_BASENAME"),
160 'IMAGE_PKGTYPE': d.getVar("IMAGE_PKGTYPE"),
161 'STARTTIME': d.getVar("DATETIME"),
162 'HOST_DISTRO': oe.lsb.distro_identifier().replace(' ', '-'),
163 'LAYERS': get_layers(d.getVar("BBLAYERS"))}
164 return configuration
165get_testimage_configuration[vardepsexclude] = "DATETIME"
166
167def get_testimage_json_result_dir(d):
168 json_result_dir = os.path.join(d.getVar("LOG_DIR"), 'oeqa')
169 custom_json_result_dir = d.getVar("OEQA_JSON_RESULT_DIR")
170 if custom_json_result_dir:
171 json_result_dir = custom_json_result_dir
172 return json_result_dir
173
174def get_testimage_result_id(configuration):
175 return '%s_%s_%s_%s' % (configuration['TEST_TYPE'], configuration['IMAGE_BASENAME'], configuration['MACHINE'], configuration['STARTTIME'])
176
177def get_testimage_boot_patterns(d):
178 from collections import defaultdict
179 boot_patterns = defaultdict(str)
180 # Only accept certain values
181 accepted_patterns = ['search_reached_prompt', 'send_login_user', 'search_login_succeeded', 'search_cmd_finished']
182 # Not all patterns need to be overriden, e.g. perhaps we only want to change the user
183 boot_patterns_flags = d.getVarFlags('TESTIMAGE_BOOT_PATTERNS') or {}
184 if boot_patterns_flags:
185 patterns_set = [p for p in boot_patterns_flags.items() if p[0] in d.getVar('TESTIMAGE_BOOT_PATTERNS').split()]
186 for flag, flagval in patterns_set:
187 if flag not in accepted_patterns:
188 bb.fatal('Testimage: The only accepted boot patterns are: search_reached_prompt,send_login_user, \
189 search_login_succeeded,search_cmd_finished\n Make sure your TESTIMAGE_BOOT_PATTERNS=%s \
190 contains an accepted flag.' % d.getVar('TESTIMAGE_BOOT_PATTERNS'))
191 return
Andrew Geissler87f5cff2022-09-30 13:13:31 -0500192 boot_patterns[flag] = flagval.encode().decode('unicode-escape')
Patrick Williams92b42cb2022-09-03 06:53:57 -0500193 return boot_patterns
194
195
196def testimage_main(d):
197 import os
198 import json
199 import signal
200 import logging
201 import shutil
202
203 from bb.utils import export_proxies
204 from oeqa.runtime.context import OERuntimeTestContext
205 from oeqa.runtime.context import OERuntimeTestContextExecutor
206 from oeqa.core.target.qemu import supported_fstypes
207 from oeqa.core.utils.test import getSuiteCases
208 from oeqa.utils import make_logger_bitbake_compatible
209
210 def sigterm_exception(signum, stackframe):
211 """
212 Catch SIGTERM from worker in order to stop qemu.
213 """
214 os.kill(os.getpid(), signal.SIGINT)
215
216 def handle_test_timeout(timeout):
217 bb.warn("Global test timeout reached (%s seconds), stopping the tests." %(timeout))
218 os.kill(os.getpid(), signal.SIGINT)
219
220 testimage_sanity(d)
221
222 if (d.getVar('IMAGE_PKGTYPE') == 'rpm'
223 and ('dnf' in d.getVar('TEST_SUITES') or 'auto' in d.getVar('TEST_SUITES'))):
224 create_rpm_index(d)
225
226 logger = make_logger_bitbake_compatible(logging.getLogger("BitBake"))
227 pn = d.getVar("PN")
228
229 bb.utils.mkdirhier(d.getVar("TEST_LOG_DIR"))
230
231 image_name = ("%s/%s" % (d.getVar('DEPLOY_DIR_IMAGE'),
232 d.getVar('IMAGE_LINK_NAME')))
233
234 tdname = "%s.testdata.json" % image_name
235 try:
236 with open(tdname, "r") as f:
237 td = json.load(f)
238 except FileNotFoundError as err:
239 bb.fatal('File %s not found (%s).\nHave you built the image with INHERIT += "testimage" in the conf/local.conf?' % (tdname, err))
240
241 # Some variables need to be updates (mostly paths) with the
242 # ones of the current environment because some tests require them.
243 for var in d.getVar('TESTIMAGE_UPDATE_VARS').split():
244 td[var] = d.getVar(var)
245
246 image_manifest = "%s.manifest" % image_name
247 image_packages = OERuntimeTestContextExecutor.readPackagesManifest(image_manifest)
248
249 extract_dir = d.getVar("TEST_EXTRACTED_DIR")
250
251 # Get machine
252 machine = d.getVar("MACHINE")
253
254 # Get rootfs
255 fstypes = d.getVar('IMAGE_FSTYPES').split()
256 if d.getVar("TEST_TARGET") == "qemu":
257 fstypes = [fs for fs in fstypes if fs in supported_fstypes]
258 if not fstypes:
259 bb.fatal('Unsupported image type built. Add a compatible image to '
260 'IMAGE_FSTYPES. Supported types: %s' %
261 ', '.join(supported_fstypes))
262 qfstype = fstypes[0]
263 qdeffstype = d.getVar("QB_DEFAULT_FSTYPE")
264 if qdeffstype:
265 qfstype = qdeffstype
266 rootfs = '%s.%s' % (image_name, qfstype)
267
268 # Get tmpdir (not really used, just for compatibility)
269 tmpdir = d.getVar("TMPDIR")
270
271 # Get deploy_dir_image (not really used, just for compatibility)
272 dir_image = d.getVar("DEPLOY_DIR_IMAGE")
273
274 # Get bootlog
275 bootlog = os.path.join(d.getVar("TEST_LOG_DIR"),
276 'qemu_boot_log.%s' % d.getVar('DATETIME'))
277
278 # Get display
279 display = d.getVar("BB_ORIGENV").getVar("DISPLAY")
280
281 # Get kernel
282 kernel_name = ('%s-%s.bin' % (d.getVar("KERNEL_IMAGETYPE"), machine))
283 kernel = os.path.join(d.getVar("DEPLOY_DIR_IMAGE"), kernel_name)
284
285 # Get boottime
286 boottime = int(d.getVar("TEST_QEMUBOOT_TIMEOUT"))
287
288 # Get use_kvm
289 kvm = oe.types.qemu_use_kvm(d.getVar('QEMU_USE_KVM'), d.getVar('TARGET_ARCH'))
290
291 # Get OVMF
292 ovmf = d.getVar("QEMU_USE_OVMF")
293
294 slirp = False
295 if d.getVar("QEMU_USE_SLIRP"):
296 slirp = True
297
298 # TODO: We use the current implementation of qemu runner because of
299 # time constrains, qemu runner really needs a refactor too.
300 target_kwargs = { 'machine' : machine,
301 'rootfs' : rootfs,
302 'tmpdir' : tmpdir,
303 'dir_image' : dir_image,
304 'display' : display,
305 'kernel' : kernel,
306 'boottime' : boottime,
307 'bootlog' : bootlog,
308 'kvm' : kvm,
309 'slirp' : slirp,
310 'dump_dir' : d.getVar("TESTIMAGE_DUMP_DIR"),
311 'serial_ports': len(d.getVar("SERIAL_CONSOLES").split()),
312 'ovmf' : ovmf,
313 'tmpfsdir' : d.getVar("RUNQEMU_TMPFS_DIR"),
314 }
315
316 if d.getVar("TESTIMAGE_BOOT_PATTERNS"):
317 target_kwargs['boot_patterns'] = get_testimage_boot_patterns(d)
318
319 # hardware controlled targets might need further access
320 target_kwargs['powercontrol_cmd'] = d.getVar("TEST_POWERCONTROL_CMD") or None
321 target_kwargs['powercontrol_extra_args'] = d.getVar("TEST_POWERCONTROL_EXTRA_ARGS") or ""
322 target_kwargs['serialcontrol_cmd'] = d.getVar("TEST_SERIALCONTROL_CMD") or None
323 target_kwargs['serialcontrol_extra_args'] = d.getVar("TEST_SERIALCONTROL_EXTRA_ARGS") or ""
324 target_kwargs['testimage_dump_monitor'] = d.getVar("testimage_dump_monitor") or ""
325 target_kwargs['testimage_dump_target'] = d.getVar("testimage_dump_target") or ""
326
327 def export_ssh_agent(d):
328 import os
329
330 variables = ['SSH_AGENT_PID', 'SSH_AUTH_SOCK']
331 for v in variables:
332 if v not in os.environ.keys():
333 val = d.getVar(v)
334 if val is not None:
335 os.environ[v] = val
336
337 export_ssh_agent(d)
338
339 # runtime use network for download projects for build
340 export_proxies(d)
341
342 # we need the host dumper in test context
343 host_dumper = OERuntimeTestContextExecutor.getHostDumper(
344 d.getVar("testimage_dump_host"),
345 d.getVar("TESTIMAGE_DUMP_DIR"))
346
347 # the robot dance
348 target = OERuntimeTestContextExecutor.getTarget(
349 d.getVar("TEST_TARGET"), logger, d.getVar("TEST_TARGET_IP"),
350 d.getVar("TEST_SERVER_IP"), **target_kwargs)
351
352 # test context
353 tc = OERuntimeTestContext(td, logger, target, host_dumper,
354 image_packages, extract_dir)
355
356 # Load tests before starting the target
357 test_paths = get_runtime_paths(d)
358 test_modules = d.getVar('TEST_SUITES').split()
359 if not test_modules:
360 bb.fatal('Empty test suite, please verify TEST_SUITES variable')
361
362 tc.loadTests(test_paths, modules=test_modules)
363
364 suitecases = getSuiteCases(tc.suites)
365 if not suitecases:
366 bb.fatal('Empty test suite, please verify TEST_SUITES variable')
367 else:
368 bb.debug(2, 'test suites:\n\t%s' % '\n\t'.join([str(c) for c in suitecases]))
369
370 package_extraction(d, tc.suites)
371
372 results = None
373 complete = False
374 orig_sigterm_handler = signal.signal(signal.SIGTERM, sigterm_exception)
375 try:
376 # We need to check if runqemu ends unexpectedly
377 # or if the worker send us a SIGTERM
378 tc.target.start(params=d.getVar("TEST_QEMUPARAMS"), runqemuparams=d.getVar("TEST_RUNQEMUPARAMS"))
379 import threading
380 try:
381 threading.Timer(int(d.getVar("TEST_OVERALL_TIMEOUT")), handle_test_timeout, (int(d.getVar("TEST_OVERALL_TIMEOUT")),)).start()
382 except ValueError:
383 pass
384 results = tc.runTests()
385 complete = True
386 except (KeyboardInterrupt, BlockingIOError) as err:
387 if isinstance(err, KeyboardInterrupt):
388 bb.error('testimage interrupted, shutting down...')
389 else:
390 bb.error('runqemu failed, shutting down...')
391 if results:
392 results.stop()
393 results = tc.results
394 finally:
395 signal.signal(signal.SIGTERM, orig_sigterm_handler)
396 tc.target.stop()
397
398 # Show results (if we have them)
399 if results:
400 configuration = get_testimage_configuration(d, 'runtime', machine)
401 results.logDetails(get_testimage_json_result_dir(d),
402 configuration,
403 get_testimage_result_id(configuration),
404 dump_streams=d.getVar('TESTREPORT_FULLLOGS'))
405 results.logSummary(pn)
406
407 # Copy additional logs to tmp/log/oeqa so it's easier to find them
408 targetdir = os.path.join(get_testimage_json_result_dir(d), d.getVar("PN"))
409 os.makedirs(targetdir, exist_ok=True)
410 os.symlink(bootlog, os.path.join(targetdir, os.path.basename(bootlog)))
411 os.symlink(d.getVar("BB_LOGFILE"), os.path.join(targetdir, os.path.basename(d.getVar("BB_LOGFILE") + "." + d.getVar('DATETIME'))))
412
413 if not results or not complete:
414 bb.fatal('%s - FAILED - tests were interrupted during execution, check the logs in %s' % (pn, d.getVar("LOG_DIR")), forcelog=True)
415 if not results.wasSuccessful():
416 bb.fatal('%s - FAILED - also check the logs in %s' % (pn, d.getVar("LOG_DIR")), forcelog=True)
417
418def get_runtime_paths(d):
419 """
420 Returns a list of paths where runtime test must reside.
421
422 Runtime tests are expected in <LAYER_DIR>/lib/oeqa/runtime/cases/
423 """
424 paths = []
425
426 for layer in d.getVar('BBLAYERS').split():
427 path = os.path.join(layer, 'lib/oeqa/runtime/cases')
428 if os.path.isdir(path):
429 paths.append(path)
430 return paths
431
432def create_index(arg):
433 import subprocess
434
435 index_cmd = arg
436 try:
437 bb.note("Executing '%s' ..." % index_cmd)
438 result = subprocess.check_output(index_cmd,
439 stderr=subprocess.STDOUT,
440 shell=True)
441 result = result.decode('utf-8')
442 except subprocess.CalledProcessError as e:
443 return("Index creation command '%s' failed with return code "
444 '%d:\n%s' % (e.cmd, e.returncode, e.output.decode("utf-8")))
445 if result:
446 bb.note(result)
447 return None
448
449def create_rpm_index(d):
450 import glob
451 # Index RPMs
452 rpm_createrepo = bb.utils.which(os.getenv('PATH'), "createrepo_c")
453 index_cmds = []
454 archs = (d.getVar('ALL_MULTILIB_PACKAGE_ARCHS') or '').replace('-', '_')
455
456 for arch in archs.split():
457 rpm_dir = os.path.join(d.getVar('DEPLOY_DIR_RPM'), arch)
458 idx_path = os.path.join(d.getVar('WORKDIR'), 'oe-testimage-repo', arch)
459
460 if not os.path.isdir(rpm_dir):
461 continue
462
463 lockfilename = os.path.join(d.getVar('DEPLOY_DIR_RPM'), 'rpm.lock')
464 lf = bb.utils.lockfile(lockfilename, False)
465 oe.path.copyhardlinktree(rpm_dir, idx_path)
466 # Full indexes overload a 256MB image so reduce the number of rpms
467 # in the feed by filtering to specific packages needed by the tests.
468 package_list = glob.glob(idx_path + "*/*.rpm")
469
470 for pkg in package_list:
Andrew Geissler87f5cff2022-09-30 13:13:31 -0500471 if not os.path.basename(pkg).startswith(("dnf-test-", "busybox", "update-alternatives", "libc6", "musl")):
Patrick Williams92b42cb2022-09-03 06:53:57 -0500472 bb.utils.remove(pkg)
473
474 bb.utils.unlockfile(lf)
475 cmd = '%s --update -q %s' % (rpm_createrepo, idx_path)
476
477 # Create repodata
478 result = create_index(cmd)
479 if result:
480 bb.fatal('%s' % ('\n'.join(result)))
481
482def package_extraction(d, test_suites):
483 from oeqa.utils.package_manager import find_packages_to_extract
484 from oeqa.utils.package_manager import extract_packages
485
486 bb.utils.remove(d.getVar("TEST_NEEDED_PACKAGES_DIR"), recurse=True)
487 packages = find_packages_to_extract(test_suites)
488 if packages:
489 bb.utils.mkdirhier(d.getVar("TEST_INSTALL_TMP_DIR"))
490 bb.utils.mkdirhier(d.getVar("TEST_PACKAGED_DIR"))
491 bb.utils.mkdirhier(d.getVar("TEST_EXTRACTED_DIR"))
492 extract_packages(d, packages)
493
494testimage_main[vardepsexclude] += "BB_ORIGENV DATETIME"
495
496python () {
497 if oe.types.boolean(d.getVar("TESTIMAGE_AUTO") or "False"):
498 bb.build.addtask("testimage", "do_build", "do_image_complete", d)
499}
500
501inherit testsdk