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
225    image_manifest = "%s.manifest" % image_name
226    image_packages = OERuntimeTestContextExecutor.readPackagesManifest(image_manifest)
227
228    extract_dir = d.getVar("TEST_EXTRACTED_DIR")
229
230    # Get machine
231    machine = d.getVar("MACHINE")
232
233    # Get rootfs
234    fstypes = d.getVar('IMAGE_FSTYPES').split()
235    if d.getVar("TEST_TARGET") == "qemu":
236        fstypes = [fs for fs in fstypes if fs in supported_fstypes]
237        if not fstypes:
238            bb.fatal('Unsupported image type built. Add a compatible image to '
239                     'IMAGE_FSTYPES. Supported types: %s' %
240                     ', '.join(supported_fstypes))
241    qfstype = fstypes[0]
242    qdeffstype = d.getVar("QB_DEFAULT_FSTYPE")
243    if qdeffstype:
244        qfstype = qdeffstype
245    rootfs = '%s.%s' % (image_name, qfstype)
246
247    # Get tmpdir (not really used, just for compatibility)
248    tmpdir = d.getVar("TMPDIR")
249
250    # Get deploy_dir_image (not really used, just for compatibility)
251    dir_image = d.getVar("DEPLOY_DIR_IMAGE")
252
253    # Get bootlog
254    bootlog = os.path.join(d.getVar("TEST_LOG_DIR"),
255                           'qemu_boot_log.%s' % d.getVar('DATETIME'))
256
257    # Get display
258    display = d.getVar("BB_ORIGENV").getVar("DISPLAY")
259
260    # Get kernel
261    kernel_name = ('%s-%s.bin' % (d.getVar("KERNEL_IMAGETYPE"), machine))
262    kernel = os.path.join(d.getVar("DEPLOY_DIR_IMAGE"), kernel_name)
263
264    # Get boottime
265    boottime = int(d.getVar("TEST_QEMUBOOT_TIMEOUT"))
266
267    # Get use_kvm
268    kvm = oe.types.qemu_use_kvm(d.getVar('QEMU_USE_KVM'), d.getVar('TARGET_ARCH'))
269
270    # Get OVMF
271    ovmf = d.getVar("QEMU_USE_OVMF")
272
273    slirp = False
274    if bb.utils.contains('TEST_RUNQEMUPARAMS', 'slirp', True, False, d):
275        slirp = True
276
277    # TODO: We use the current implementation of qemu runner because of
278    # time constrains, qemu runner really needs a refactor too.
279    target_kwargs = { 'machine'     : machine,
280                      'rootfs'      : rootfs,
281                      'tmpdir'      : tmpdir,
282                      'dir_image'   : dir_image,
283                      'display'     : display,
284                      'kernel'      : kernel,
285                      'boottime'    : boottime,
286                      'bootlog'     : bootlog,
287                      'kvm'         : kvm,
288                      'slirp'       : slirp,
289                      'dump_dir'    : d.getVar("TESTIMAGE_DUMP_DIR"),
290                      'serial_ports': len(d.getVar("SERIAL_CONSOLES").split()),
291                      'ovmf'        : ovmf,
292                      'tmpfsdir'    : d.getVar("RUNQEMU_TMPFS_DIR"),
293                    }
294
295    if d.getVar("TESTIMAGE_BOOT_PATTERNS"):
296        target_kwargs['boot_patterns'] = get_testimage_boot_patterns(d)
297
298    # hardware controlled targets might need further access
299    target_kwargs['powercontrol_cmd'] = d.getVar("TEST_POWERCONTROL_CMD") or None
300    target_kwargs['powercontrol_extra_args'] = d.getVar("TEST_POWERCONTROL_EXTRA_ARGS") or ""
301    target_kwargs['serialcontrol_cmd'] = d.getVar("TEST_SERIALCONTROL_CMD") or None
302    target_kwargs['serialcontrol_extra_args'] = d.getVar("TEST_SERIALCONTROL_EXTRA_ARGS") or ""
303    target_kwargs['testimage_dump_monitor'] = d.getVar("testimage_dump_monitor") or ""
304
305    def export_ssh_agent(d):
306        import os
307
308        variables = ['SSH_AGENT_PID', 'SSH_AUTH_SOCK']
309        for v in variables:
310            if v not in os.environ.keys():
311                val = d.getVar(v)
312                if val is not None:
313                    os.environ[v] = val
314
315    export_ssh_agent(d)
316
317    # runtime use network for download projects for build
318    export_proxies(d)
319
320    if slirp:
321        # Default to 127.0.0.1 and let the runner identify the port forwarding
322        # (as OEQemuTarget does), but allow overriding.
323        target_ip = d.getVar("TEST_TARGET_IP") or "127.0.0.1"
324        # Default to 10.0.2.2 as this is the IP that the guest has with the
325        # default qemu slirp networking configuration, but allow overriding.
326        server_ip = d.getVar("TEST_SERVER_IP") or "10.0.2.2"
327    else:
328        target_ip = d.getVar("TEST_TARGET_IP")
329        server_ip = d.getVar("TEST_SERVER_IP")
330
331    # the robot dance
332    target = OERuntimeTestContextExecutor.getTarget(
333        d.getVar("TEST_TARGET"), logger, target_ip,
334        server_ip, **target_kwargs)
335
336    # test context
337    tc = OERuntimeTestContext(td, logger, target, image_packages, extract_dir)
338
339    # Load tests before starting the target
340    test_paths = get_runtime_paths(d)
341    test_modules = d.getVar('TEST_SUITES').split()
342    if not test_modules:
343        bb.fatal('Empty test suite, please verify TEST_SUITES variable')
344
345    tc.loadTests(test_paths, modules=test_modules)
346
347    suitecases = getSuiteCases(tc.suites)
348    if not suitecases:
349        bb.fatal('Empty test suite, please verify TEST_SUITES variable')
350    else:
351        bb.debug(2, 'test suites:\n\t%s' % '\n\t'.join([str(c) for c in suitecases]))
352
353    package_extraction(d, tc.suites)
354
355    results = None
356    complete = False
357    orig_sigterm_handler = signal.signal(signal.SIGTERM, sigterm_exception)
358    try:
359        # We need to check if runqemu ends unexpectedly
360        # or if the worker send us a SIGTERM
361        tc.target.start(params=d.getVar("TEST_QEMUPARAMS"), runqemuparams=d.getVar("TEST_RUNQEMUPARAMS"))
362        import threading
363        try:
364            threading.Timer(int(d.getVar("TEST_OVERALL_TIMEOUT")), handle_test_timeout, (int(d.getVar("TEST_OVERALL_TIMEOUT")),)).start()
365        except ValueError:
366            pass
367        results = tc.runTests()
368        complete = True
369        if results.hasAnyFailingTest():
370            run_failed_tests_post_actions(d, tc)
371    except (KeyboardInterrupt, BlockingIOError) as err:
372        if isinstance(err, KeyboardInterrupt):
373            bb.error('testimage interrupted, shutting down...')
374        else:
375            bb.error('runqemu failed, shutting down...')
376        if results:
377            results.stop()
378        results = tc.results
379    finally:
380        signal.signal(signal.SIGTERM, orig_sigterm_handler)
381        tc.target.stop()
382
383    # Show results (if we have them)
384    if results:
385        configuration = get_testimage_configuration(d, 'runtime', machine)
386        results.logDetails(get_json_result_dir(d),
387                        configuration,
388                        get_testimage_result_id(configuration),
389                        dump_streams=d.getVar('TESTREPORT_FULLLOGS'))
390        results.logSummary(pn)
391
392    # Copy additional logs to tmp/log/oeqa so it's easier to find them
393    targetdir = os.path.join(get_json_result_dir(d), d.getVar("PN"))
394    os.makedirs(targetdir, exist_ok=True)
395    os.symlink(bootlog, os.path.join(targetdir, os.path.basename(bootlog)))
396    os.symlink(d.getVar("BB_LOGFILE"), os.path.join(targetdir, os.path.basename(d.getVar("BB_LOGFILE") + "." + d.getVar('DATETIME'))))
397
398    if not results or not complete:
399        bb.fatal('%s - FAILED - tests were interrupted during execution, check the logs in %s' % (pn, d.getVar("LOG_DIR")), forcelog=True)
400    if not results.wasSuccessful():
401        bb.fatal('%s - FAILED - also check the logs in %s' % (pn, d.getVar("LOG_DIR")), forcelog=True)
402
403def get_runtime_paths(d):
404    """
405    Returns a list of paths where runtime test must reside.
406
407    Runtime tests are expected in <LAYER_DIR>/lib/oeqa/runtime/cases/
408    """
409    paths = []
410
411    for layer in d.getVar('BBLAYERS').split():
412        path = os.path.join(layer, 'lib/oeqa/runtime/cases')
413        if os.path.isdir(path):
414            paths.append(path)
415    return paths
416
417def create_index(arg):
418    import subprocess
419
420    index_cmd = arg
421    try:
422        bb.note("Executing '%s' ..." % index_cmd)
423        result = subprocess.check_output(index_cmd,
424                                        stderr=subprocess.STDOUT,
425                                        shell=True)
426        result = result.decode('utf-8')
427    except subprocess.CalledProcessError as e:
428        return("Index creation command '%s' failed with return code "
429               '%d:\n%s' % (e.cmd, e.returncode, e.output.decode("utf-8")))
430    if result:
431        bb.note(result)
432    return None
433
434def create_rpm_index(d):
435    import glob
436    # Index RPMs
437    rpm_createrepo = bb.utils.which(os.getenv('PATH'), "createrepo_c")
438    index_cmds = []
439    archs = (d.getVar('ALL_MULTILIB_PACKAGE_ARCHS') or '').replace('-', '_')
440
441    for arch in archs.split():
442        rpm_dir = os.path.join(d.getVar('DEPLOY_DIR_RPM'), arch)
443        idx_path = os.path.join(d.getVar('WORKDIR'), 'oe-testimage-repo', arch)
444
445        if not os.path.isdir(rpm_dir):
446            continue
447
448        lockfilename = os.path.join(d.getVar('DEPLOY_DIR_RPM'), 'rpm.lock')
449        lf = bb.utils.lockfile(lockfilename, False)
450        oe.path.copyhardlinktree(rpm_dir, idx_path)
451        # Full indexes overload a 256MB image so reduce the number of rpms
452        # in the feed by filtering to specific packages needed by the tests.
453        package_list = glob.glob(idx_path + "*/*.rpm")
454
455        for pkg in package_list:
456            if not os.path.basename(pkg).startswith(("dnf-test-", "busybox", "update-alternatives", "libc6", "musl")):
457                bb.utils.remove(pkg)
458
459        bb.utils.unlockfile(lf)
460        cmd = '%s --update -q %s' % (rpm_createrepo, idx_path)
461
462        # Create repodata
463        result = create_index(cmd)
464        if result:
465            bb.fatal('%s' % ('\n'.join(result)))
466
467def package_extraction(d, test_suites):
468    from oeqa.utils.package_manager import find_packages_to_extract
469    from oeqa.utils.package_manager import extract_packages
470
471    bb.utils.remove(d.getVar("TEST_NEEDED_PACKAGES_DIR"), recurse=True)
472    packages = find_packages_to_extract(test_suites)
473    if packages:
474        bb.utils.mkdirhier(d.getVar("TEST_INSTALL_TMP_DIR"))
475        bb.utils.mkdirhier(d.getVar("TEST_PACKAGED_DIR"))
476        bb.utils.mkdirhier(d.getVar("TEST_EXTRACTED_DIR"))
477        extract_packages(d, packages)
478
479testimage_main[vardepsexclude] += "BB_ORIGENV DATETIME"
480
481python () {
482    if oe.types.boolean(d.getVar("TESTIMAGE_AUTO") or "False"):
483        bb.build.addtask("testimage", "do_build", "do_image_complete", d)
484}
485
486inherit testsdk
487