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