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    ${sysconfdir}/version \
28    ${sysconfdir}/os-release"
29
30# If some ptests are run and fail, retrieve corresponding directories
31TESTIMAGE_FAILED_QA_ARTIFACTS += "${@bb.utils.contains('DISTRO_FEATURES', 'ptest', '${libdir}/${MCNAME}/ptest', '', d)}"
32
33# You can set (or append to) TEST_SUITES in local.conf to select the tests
34# which you want to run for your target.
35# The test names are the module names in meta/lib/oeqa/runtime/cases.
36# Each name in TEST_SUITES represents a required test for the image. (no skipping allowed)
37# 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).
38# Note that order in TEST_SUITES is relevant: tests are run in an order such that
39# tests mentioned in @skipUnlessPassed run before the tests that depend on them,
40# but without such dependencies, tests run in the order in which they are listed
41# in TEST_SUITES.
42#
43# A layer can add its own tests in lib/oeqa/runtime, provided it extends BBPATH as normal in its layer.conf.
44
45# 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.
46# Booting is handled by this class, and it's not a test in itself.
47# TEST_QEMUBOOT_TIMEOUT can be used to set the maximum time in seconds the launch code will wait for the login prompt.
48# TEST_OVERALL_TIMEOUT can be used to set the maximum time in seconds the tests will be allowed to run (defaults to no limit).
49# TEST_QEMUPARAMS can be used to pass extra parameters to qemu, e.g. "-m 1024" for setting the amount of ram to 1 GB.
50# TEST_RUNQEMUPARAMS can be used to pass extra parameters to runqemu, e.g. "gl" to enable OpenGL acceleration.
51# 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)
52
53# TESTIMAGE_BOOT_PATTERNS can be used to override certain patterns used to communicate with the target when booting,
54# if a pattern is not specifically present on this variable a default will be used when booting the target.
55# TESTIMAGE_BOOT_PATTERNS[<flag>] overrides the pattern used for that specific flag, where flag comes from a list of accepted flags
56# 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
57# if we wanted to log in as the hypothetical "webserver" user for example we could set the following:
58# TESTIMAGE_BOOT_PATTERNS = "send_login_user search_login_succeeded"
59# TESTIMAGE_BOOT_PATTERNS[send_login_user] = "webserver\n"
60# TESTIMAGE_BOOT_PATTERNS[search_login_succeeded] = "webserver@[a-zA-Z0-9\-]+:~#"
61# The accepted flags are the following: search_reached_prompt, send_login_user, search_login_succeeded, search_cmd_finished.
62# They are prefixed with either search/send, to differentiate if the pattern is meant to be sent or searched to/from the target terminal
63
64TEST_LOG_DIR ?= "${WORKDIR}/testimage"
65
66TEST_EXPORT_DIR ?= "${TMPDIR}/testimage/${PN}"
67TEST_INSTALL_TMP_DIR ?= "${WORKDIR}/testimage/install_tmp"
68TEST_NEEDED_PACKAGES_DIR ?= "${WORKDIR}/testimage/packages"
69TEST_EXTRACTED_DIR ?= "${TEST_NEEDED_PACKAGES_DIR}/extracted"
70TEST_PACKAGED_DIR ?= "${TEST_NEEDED_PACKAGES_DIR}/packaged"
71
72BASICTESTSUITE = "\
73    ping date df ssh scp python perl gi ptest parselogs \
74    logrotate connman systemd oe_syslog pam stap ldd xorg \
75    kernelmodule gcc buildcpio buildlzip buildgalculator \
76    dnf rpm opkg apt weston go rust"
77
78DEFAULT_TEST_SUITES = "${BASICTESTSUITE}"
79
80# musl doesn't support systemtap
81DEFAULT_TEST_SUITES:remove:libc-musl = "stap"
82
83# qemumips is quite slow and has reached the timeout limit several times on the YP build cluster,
84# mitigate this by removing build tests for qemumips machines.
85MIPSREMOVE ??= "buildcpio buildlzip buildgalculator"
86DEFAULT_TEST_SUITES:remove:qemumips = "${MIPSREMOVE}"
87DEFAULT_TEST_SUITES:remove:qemumips64 = "${MIPSREMOVE}"
88
89TEST_SUITES ?= "${DEFAULT_TEST_SUITES}"
90
91QEMU_USE_KVM ?= "1"
92TEST_QEMUBOOT_TIMEOUT ?= "1000"
93TEST_OVERALL_TIMEOUT ?= ""
94TEST_TARGET ?= "qemu"
95TEST_QEMUPARAMS ?= ""
96TEST_RUNQEMUPARAMS ?= ""
97
98TESTIMAGE_BOOT_PATTERNS ?= ""
99
100TESTIMAGEDEPENDS = ""
101TESTIMAGEDEPENDS:append:qemuall = " qemu-native:do_populate_sysroot qemu-helper-native:do_populate_sysroot qemu-helper-native:do_addto_recipe_sysroot"
102TESTIMAGEDEPENDS += "${@bb.utils.contains('IMAGE_PKGTYPE', 'rpm', 'cpio-native:do_populate_sysroot', '', d)}"
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"
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')))
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    qfstype = fstypes[0]
243    qdeffstype = d.getVar("QB_DEFAULT_FSTYPE")
244    if qdeffstype:
245        qfstype = qdeffstype
246    rootfs = '%s.%s' % (image_name, qfstype)
247
248    # Get tmpdir (not really used, just for compatibility)
249    tmpdir = d.getVar("TMPDIR")
250
251    # Get deploy_dir_image (not really used, just for compatibility)
252    dir_image = d.getVar("DEPLOY_DIR_IMAGE")
253
254    # Get bootlog
255    bootlog = os.path.join(d.getVar("TEST_LOG_DIR"),
256                           'qemu_boot_log.%s' % d.getVar('DATETIME'))
257
258    # Get display
259    display = d.getVar("BB_ORIGENV").getVar("DISPLAY")
260
261    # Get kernel
262    kernel_name = ('%s-%s.bin' % (d.getVar("KERNEL_IMAGETYPE"), machine))
263    kernel = os.path.join(d.getVar("DEPLOY_DIR_IMAGE"), kernel_name)
264
265    # Get boottime
266    boottime = int(d.getVar("TEST_QEMUBOOT_TIMEOUT"))
267
268    # Get use_kvm
269    kvm = oe.types.qemu_use_kvm(d.getVar('QEMU_USE_KVM'), d.getVar('TARGET_ARCH'))
270
271    # Get OVMF
272    ovmf = d.getVar("QEMU_USE_OVMF")
273
274    slirp = False
275    if bb.utils.contains('TEST_RUNQEMUPARAMS', 'slirp', True, False, d):
276        slirp = True
277
278    # TODO: We use the current implementation of qemu runner because of
279    # time constrains, qemu runner really needs a refactor too.
280    target_kwargs = { 'machine'     : machine,
281                      'rootfs'      : rootfs,
282                      'tmpdir'      : tmpdir,
283                      'dir_image'   : dir_image,
284                      'display'     : display,
285                      'kernel'      : kernel,
286                      'boottime'    : boottime,
287                      'bootlog'     : bootlog,
288                      'kvm'         : kvm,
289                      'slirp'       : slirp,
290                      'dump_dir'    : d.getVar("TESTIMAGE_DUMP_DIR"),
291                      'serial_ports': len(d.getVar("SERIAL_CONSOLES").split()),
292                      'ovmf'        : ovmf,
293                      'tmpfsdir'    : d.getVar("RUNQEMU_TMPFS_DIR"),
294                    }
295
296    if d.getVar("TESTIMAGE_BOOT_PATTERNS"):
297        target_kwargs['boot_patterns'] = get_testimage_boot_patterns(d)
298
299    # hardware controlled targets might need further access
300    target_kwargs['powercontrol_cmd'] = d.getVar("TEST_POWERCONTROL_CMD") or None
301    target_kwargs['powercontrol_extra_args'] = d.getVar("TEST_POWERCONTROL_EXTRA_ARGS") or ""
302    target_kwargs['serialcontrol_cmd'] = d.getVar("TEST_SERIALCONTROL_CMD") or None
303    target_kwargs['serialcontrol_extra_args'] = d.getVar("TEST_SERIALCONTROL_EXTRA_ARGS") or ""
304    target_kwargs['testimage_dump_monitor'] = d.getVar("testimage_dump_monitor") or ""
305
306    def export_ssh_agent(d):
307        import os
308
309        variables = ['SSH_AGENT_PID', 'SSH_AUTH_SOCK']
310        for v in variables:
311            if v not in os.environ.keys():
312                val = d.getVar(v)
313                if val is not None:
314                    os.environ[v] = val
315
316    export_ssh_agent(d)
317
318    # runtime use network for download projects for build
319    export_proxies(d)
320
321    if slirp:
322        # Default to 127.0.0.1 and let the runner identify the port forwarding
323        # (as OEQemuTarget does), but allow overriding.
324        target_ip = d.getVar("TEST_TARGET_IP") or "127.0.0.1"
325        # Default to 10.0.2.2 as this is the IP that the guest has with the
326        # default qemu slirp networking configuration, but allow overriding.
327        server_ip = d.getVar("TEST_SERVER_IP") or "10.0.2.2"
328    else:
329        target_ip = d.getVar("TEST_TARGET_IP")
330        server_ip = d.getVar("TEST_SERVER_IP")
331
332    # the robot dance
333    target = OERuntimeTestContextExecutor.getTarget(
334        d.getVar("TEST_TARGET"), logger, target_ip,
335        server_ip, **target_kwargs)
336
337    # test context
338    tc = OERuntimeTestContext(td, logger, target, image_packages, extract_dir)
339
340    # Load tests before starting the target
341    test_paths = get_runtime_paths(d)
342    test_modules = d.getVar('TEST_SUITES').split()
343    if not test_modules:
344        bb.fatal('Empty test suite, please verify TEST_SUITES variable')
345
346    tc.loadTests(test_paths, modules=test_modules)
347
348    suitecases = getSuiteCases(tc.suites)
349    if not suitecases:
350        bb.fatal('Empty test suite, please verify TEST_SUITES variable')
351    else:
352        bb.debug(2, 'test suites:\n\t%s' % '\n\t'.join([str(c) for c in suitecases]))
353
354    package_extraction(d, tc.suites)
355
356    results = None
357    complete = False
358    orig_sigterm_handler = signal.signal(signal.SIGTERM, sigterm_exception)
359    try:
360        # We need to check if runqemu ends unexpectedly
361        # or if the worker send us a SIGTERM
362        tc.target.start(params=d.getVar("TEST_QEMUPARAMS"), runqemuparams=d.getVar("TEST_RUNQEMUPARAMS"))
363        import threading
364        try:
365            threading.Timer(int(d.getVar("TEST_OVERALL_TIMEOUT")), handle_test_timeout, (int(d.getVar("TEST_OVERALL_TIMEOUT")),)).start()
366        except ValueError:
367            pass
368        results = tc.runTests()
369        complete = True
370        if results.hasAnyFailingTest():
371            run_failed_tests_post_actions(d, tc)
372    except (KeyboardInterrupt, BlockingIOError) as err:
373        if isinstance(err, KeyboardInterrupt):
374            bb.error('testimage interrupted, shutting down...')
375        else:
376            bb.error('runqemu failed, shutting down...')
377        if results:
378            results.stop()
379        results = tc.results
380    finally:
381        signal.signal(signal.SIGTERM, orig_sigterm_handler)
382        tc.target.stop()
383
384    # Show results (if we have them)
385    if results:
386        configuration = get_testimage_configuration(d, 'runtime', machine)
387        results.logDetails(get_json_result_dir(d),
388                        configuration,
389                        get_testimage_result_id(configuration),
390                        dump_streams=d.getVar('TESTREPORT_FULLLOGS'))
391        results.logSummary(pn)
392
393    # Copy additional logs to tmp/log/oeqa so it's easier to find them
394    targetdir = os.path.join(get_json_result_dir(d), d.getVar("PN"))
395    os.makedirs(targetdir, exist_ok=True)
396    os.symlink(bootlog, os.path.join(targetdir, os.path.basename(bootlog)))
397    os.symlink(d.getVar("BB_LOGFILE"), os.path.join(targetdir, os.path.basename(d.getVar("BB_LOGFILE") + "." + d.getVar('DATETIME'))))
398
399    if not results or not complete:
400        bb.fatal('%s - FAILED - tests were interrupted during execution, check the logs in %s' % (pn, d.getVar("LOG_DIR")), forcelog=True)
401    if not results.wasSuccessful():
402        bb.fatal('%s - FAILED - also check the logs in %s' % (pn, d.getVar("LOG_DIR")), forcelog=True)
403
404def get_runtime_paths(d):
405    """
406    Returns a list of paths where runtime test must reside.
407
408    Runtime tests are expected in <LAYER_DIR>/lib/oeqa/runtime/cases/
409    """
410    paths = []
411
412    for layer in d.getVar('BBLAYERS').split():
413        path = os.path.join(layer, 'lib/oeqa/runtime/cases')
414        if os.path.isdir(path):
415            paths.append(path)
416    return paths
417
418def create_index(arg):
419    import subprocess
420
421    index_cmd = arg
422    try:
423        bb.note("Executing '%s' ..." % index_cmd)
424        result = subprocess.check_output(index_cmd,
425                                        stderr=subprocess.STDOUT,
426                                        shell=True)
427        result = result.decode('utf-8')
428    except subprocess.CalledProcessError as e:
429        return("Index creation command '%s' failed with return code "
430               '%d:\n%s' % (e.cmd, e.returncode, e.output.decode("utf-8")))
431    if result:
432        bb.note(result)
433    return None
434
435def create_rpm_index(d):
436    import glob
437    # Index RPMs
438    rpm_createrepo = bb.utils.which(os.getenv('PATH'), "createrepo_c")
439    index_cmds = []
440    archs = (d.getVar('ALL_MULTILIB_PACKAGE_ARCHS') or '').replace('-', '_')
441
442    for arch in archs.split():
443        rpm_dir = os.path.join(d.getVar('DEPLOY_DIR_RPM'), arch)
444        idx_path = os.path.join(d.getVar('WORKDIR'), 'oe-testimage-repo', arch)
445
446        if not os.path.isdir(rpm_dir):
447            continue
448
449        lockfilename = os.path.join(d.getVar('DEPLOY_DIR_RPM'), 'rpm.lock')
450        lf = bb.utils.lockfile(lockfilename, False)
451        oe.path.copyhardlinktree(rpm_dir, idx_path)
452        # Full indexes overload a 256MB image so reduce the number of rpms
453        # in the feed by filtering to specific packages needed by the tests.
454        package_list = glob.glob(idx_path + "*/*.rpm")
455
456        for pkg in package_list:
457            if not os.path.basename(pkg).startswith(("dnf-test-", "busybox", "update-alternatives", "libc6", "musl")):
458                bb.utils.remove(pkg)
459
460        bb.utils.unlockfile(lf)
461        cmd = '%s --update -q %s' % (rpm_createrepo, idx_path)
462
463        # Create repodata
464        result = create_index(cmd)
465        if result:
466            bb.fatal('%s' % ('\n'.join(result)))
467
468def package_extraction(d, test_suites):
469    from oeqa.utils.package_manager import find_packages_to_extract
470    from oeqa.utils.package_manager import extract_packages
471
472    bb.utils.remove(d.getVar("TEST_NEEDED_PACKAGES_DIR"), recurse=True)
473    packages = find_packages_to_extract(test_suites)
474    if packages:
475        bb.utils.mkdirhier(d.getVar("TEST_INSTALL_TMP_DIR"))
476        bb.utils.mkdirhier(d.getVar("TEST_PACKAGED_DIR"))
477        bb.utils.mkdirhier(d.getVar("TEST_EXTRACTED_DIR"))
478        extract_packages(d, packages)
479
480testimage_main[vardepsexclude] += "BB_ORIGENV DATETIME"
481
482python () {
483    if oe.types.boolean(d.getVar("TESTIMAGE_AUTO") or "False"):
484        bb.build.addtask("testimage", "do_build", "do_image_complete", d)
485}
486
487inherit testsdk
488