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