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