blob: a76e77385354e5aed3a2a46699e2b19f6addf700 [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001# Copyright (C) 2013 Intel Corporation
2#
3# Released under the MIT license (see COPYING.MIT)
4
Brad Bishopf86d0552018-12-04 14:18:15 -08005inherit metadata_scm
Andrew Geisslerc9f78652020-09-18 14:11:35 -05006inherit image-artifact-names
7
Patrick Williamsc124f4f2015-09-15 14:41:29 -05008# 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:
Brad Bishopd7bf8c12018-02-25 22:55:05 -050012# - first add IMAGE_CLASSES += "testimage" in local.conf
13# - build a qemu core-image-sato
Patrick Williamsc124f4f2015-09-15 14:41:29 -050014# - then bitbake core-image-sato -c testimage. That will run a standard suite of tests.
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080015#
16# The tests can be run automatically each time an image is built if you set
17# TESTIMAGE_AUTO = "1"
18
19TESTIMAGE_AUTO ??= "0"
Patrick Williamsc124f4f2015-09-15 14:41:29 -050020
21# You can set (or append to) TEST_SUITES in local.conf to select the tests
22# which you want to run for your target.
Brad Bishopd7bf8c12018-02-25 22:55:05 -050023# The test names are the module names in meta/lib/oeqa/runtime/cases.
Patrick Williamsc124f4f2015-09-15 14:41:29 -050024# Each name in TEST_SUITES represents a required test for the image. (no skipping allowed)
25# 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# Note that order in TEST_SUITES is relevant: tests are run in an order such that
27# tests mentioned in @skipUnlessPassed run before the tests that depend on them,
28# but without such dependencies, tests run in the order in which they are listed
29# in TEST_SUITES.
30#
31# A layer can add its own tests in lib/oeqa/runtime, provided it extends BBPATH as normal in its layer.conf.
32
33# 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# Booting is handled by this class, and it's not a test in itself.
35# TEST_QEMUBOOT_TIMEOUT can be used to set the maximum time in seconds the launch code will wait for the login prompt.
Andrew Geissler82c905d2020-04-13 13:39:40 -050036# TEST_OVERALL_TIMEOUT can be used to set the maximum time in seconds the tests will be allowed to run (defaults to no limit).
Brad Bishop977dc1a2019-02-06 16:01:43 -050037# TEST_QEMUPARAMS can be used to pass extra parameters to qemu, e.g. "-m 1024" for setting the amount of ram to 1 GB.
Brad Bishop19323692019-04-05 15:28:33 -040038# TEST_RUNQEMUPARAMS can be used to pass extra parameters to runqemu, e.g. "gl" to enable OpenGL acceleration.
Patrick Williamsc124f4f2015-09-15 14:41:29 -050039
Andrew Geissler82c905d2020-04-13 13:39:40 -050040# TESTIMAGE_BOOT_PATTERNS can be used to override certain patterns used to communicate with the target when booting,
41# if a pattern is not specifically present on this variable a default will be used when booting the target.
42# TESTIMAGE_BOOT_PATTERNS[<flag>] overrides the pattern used for that specific flag, where flag comes from a list of accepted flags
43# 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
44# if we wanted to log in as the hypothetical "webserver" user for example we could set the following:
45# TESTIMAGE_BOOT_PATTERNS = "send_login_user search_login_succeeded"
46# TESTIMAGE_BOOT_PATTERNS[send_login_user] = "webserver\n"
47# TESTIMAGE_BOOT_PATTERNS[search_login_succeeded] = "webserver@[a-zA-Z0-9\-]+:~#"
48# The accepted flags are the following: search_reached_prompt, send_login_user, search_login_succeeded, search_cmd_finished.
49# They are prefixed with either search/send, to differentiate if the pattern is meant to be sent or searched to/from the target terminal
50
Patrick Williamsc124f4f2015-09-15 14:41:29 -050051TEST_LOG_DIR ?= "${WORKDIR}/testimage"
52
53TEST_EXPORT_DIR ?= "${TMPDIR}/testimage/${PN}"
Patrick Williamsc0f7c042017-02-23 20:41:17 -060054TEST_INSTALL_TMP_DIR ?= "${WORKDIR}/testimage/install_tmp"
55TEST_NEEDED_PACKAGES_DIR ?= "${WORKDIR}/testimage/packages"
56TEST_EXTRACTED_DIR ?= "${TEST_NEEDED_PACKAGES_DIR}/extracted"
57TEST_PACKAGED_DIR ?= "${TEST_NEEDED_PACKAGES_DIR}/packaged"
Patrick Williamsc124f4f2015-09-15 14:41:29 -050058
Brad Bishop977dc1a2019-02-06 16:01:43 -050059BASICTESTSUITE = "\
60 ping date df ssh scp python perl gi ptest parselogs \
61 logrotate connman systemd oe_syslog pam stap ldd xorg \
62 kernelmodule gcc buildcpio buildlzip buildgalculator \
Andrew Geissler82c905d2020-04-13 13:39:40 -050063 dnf rpm opkg apt weston"
Patrick Williamsc124f4f2015-09-15 14:41:29 -050064
Brad Bishop977dc1a2019-02-06 16:01:43 -050065DEFAULT_TEST_SUITES = "${BASICTESTSUITE}"
Patrick Williamsc124f4f2015-09-15 14:41:29 -050066
Brad Bishop316dfdd2018-06-25 12:45:53 -040067# musl doesn't support systemtap
Patrick Williams213cb262021-08-07 19:21:33 -050068DEFAULT_TEST_SUITES:remove:libc-musl = "stap"
Patrick Williamsc124f4f2015-09-15 14:41:29 -050069
Patrick Williamsc0f7c042017-02-23 20:41:17 -060070# qemumips is quite slow and has reached the timeout limit several times on the YP build cluster,
71# mitigate this by removing build tests for qemumips machines.
Brad Bishopd7bf8c12018-02-25 22:55:05 -050072MIPSREMOVE ??= "buildcpio buildlzip buildgalculator"
Patrick Williams213cb262021-08-07 19:21:33 -050073DEFAULT_TEST_SUITES:remove:qemumips = "${MIPSREMOVE}"
74DEFAULT_TEST_SUITES:remove:qemumips64 = "${MIPSREMOVE}"
Patrick Williamsc124f4f2015-09-15 14:41:29 -050075
76TEST_SUITES ?= "${DEFAULT_TEST_SUITES}"
77
78TEST_QEMUBOOT_TIMEOUT ?= "1000"
Andrew Geissler82c905d2020-04-13 13:39:40 -050079TEST_OVERALL_TIMEOUT ?= ""
Patrick Williamsc124f4f2015-09-15 14:41:29 -050080TEST_TARGET ?= "qemu"
Brad Bishop977dc1a2019-02-06 16:01:43 -050081TEST_QEMUPARAMS ?= ""
Brad Bishop19323692019-04-05 15:28:33 -040082TEST_RUNQEMUPARAMS ?= ""
Patrick Williamsc124f4f2015-09-15 14:41:29 -050083
Andrew Geissler82c905d2020-04-13 13:39:40 -050084TESTIMAGE_BOOT_PATTERNS ?= ""
85
Patrick Williamsc124f4f2015-09-15 14:41:29 -050086TESTIMAGEDEPENDS = ""
Patrick Williams213cb262021-08-07 19:21:33 -050087TESTIMAGEDEPENDS:append:qemuall = " qemu-native:do_populate_sysroot qemu-helper-native:do_populate_sysroot qemu-helper-native:do_addto_recipe_sysroot"
Patrick Williamsc0f7c042017-02-23 20:41:17 -060088TESTIMAGEDEPENDS += "${@bb.utils.contains('IMAGE_PKGTYPE', 'rpm', 'cpio-native:do_populate_sysroot', '', d)}"
Brad Bishop6e60e8b2018-02-01 10:27:11 -050089TESTIMAGEDEPENDS += "${@bb.utils.contains('IMAGE_PKGTYPE', 'rpm', 'dnf-native:do_populate_sysroot', '', d)}"
Brad Bishop977dc1a2019-02-06 16:01:43 -050090TESTIMAGEDEPENDS += "${@bb.utils.contains('IMAGE_PKGTYPE', 'rpm', 'createrepo-c-native:do_populate_sysroot', '', d)}"
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080091TESTIMAGEDEPENDS += "${@bb.utils.contains('IMAGE_PKGTYPE', 'ipk', 'opkg-utils-native:do_populate_sysroot package-index:do_package_index', '', d)}"
92TESTIMAGEDEPENDS += "${@bb.utils.contains('IMAGE_PKGTYPE', 'deb', 'apt-native:do_populate_sysroot package-index:do_package_index', '', d)}"
Patrick Williamsc124f4f2015-09-15 14:41:29 -050093
94TESTIMAGELOCK = "${TMPDIR}/testimage.lock"
Patrick Williams213cb262021-08-07 19:21:33 -050095TESTIMAGELOCK:qemuall = ""
Patrick Williamsc124f4f2015-09-15 14:41:29 -050096
Brad Bishop977dc1a2019-02-06 16:01:43 -050097TESTIMAGE_DUMP_DIR ?= "${LOG_DIR}/runtime-hostdump/"
Patrick Williamsc124f4f2015-09-15 14:41:29 -050098
Brad Bishop6e60e8b2018-02-01 10:27:11 -050099TESTIMAGE_UPDATE_VARS ?= "DL_DIR WORKDIR DEPLOY_DIR"
100
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500101testimage_dump_target () {
102 top -bn1
103 ps
104 free
105 df
106 # The next command will export the default gateway IP
107 export DEFAULT_GATEWAY=$(ip route | awk '/default/ { print $3}')
108 ping -c3 $DEFAULT_GATEWAY
109 dmesg
110 netstat -an
111 ip address
112 # Next command will dump logs from /var/log/
113 find /var/log/ -type f 2>/dev/null -exec echo "====================" \; -exec echo {} \; -exec echo "====================" \; -exec cat {} \; -exec echo "" \;
114}
115
116testimage_dump_host () {
117 top -bn1
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500118 iostat -x -z -N -d -p ALL 20 2
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500119 ps -ef
120 free
121 df
122 memstat
123 dmesg
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500124 ip -s link
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500125 netstat -an
126}
127
Andrew Geisslerc926e172021-05-07 16:11:35 -0500128testimage_dump_monitor () {
129 query-status
130 query-block
Andrew Geissler5f350902021-07-23 13:09:54 -0400131 dump-guest-memory {"paging":false,"protocol":"file:%s.img"}
Andrew Geisslerc926e172021-05-07 16:11:35 -0500132}
133
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500134python do_testimage() {
135 testimage_main(d)
136}
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600137
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500138addtask testimage
139do_testimage[nostamp] = "1"
140do_testimage[depends] += "${TESTIMAGEDEPENDS}"
141do_testimage[lockfiles] += "${TESTIMAGELOCK}"
142
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500143def testimage_sanity(d):
144 if (d.getVar('TEST_TARGET') == 'simpleremote'
145 and (not d.getVar('TEST_TARGET_IP')
146 or not d.getVar('TEST_SERVER_IP'))):
147 bb.fatal('When TEST_TARGET is set to "simpleremote" '
148 'TEST_TARGET_IP and TEST_SERVER_IP are needed too.')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500149
Brad Bishopf86d0552018-12-04 14:18:15 -0800150def get_testimage_configuration(d, test_type, machine):
151 import platform
152 from oeqa.utils.metadata import get_layers
153 configuration = {'TEST_TYPE': test_type,
154 'MACHINE': machine,
155 'DISTRO': d.getVar("DISTRO"),
156 'IMAGE_BASENAME': d.getVar("IMAGE_BASENAME"),
157 'IMAGE_PKGTYPE': d.getVar("IMAGE_PKGTYPE"),
158 'STARTTIME': d.getVar("DATETIME"),
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800159 'HOST_DISTRO': oe.lsb.distro_identifier().replace(' ', '-'),
Brad Bishopf86d0552018-12-04 14:18:15 -0800160 'LAYERS': get_layers(d.getVar("BBLAYERS"))}
161 return configuration
162get_testimage_configuration[vardepsexclude] = "DATETIME"
163
164def get_testimage_json_result_dir(d):
165 json_result_dir = os.path.join(d.getVar("LOG_DIR"), 'oeqa')
166 custom_json_result_dir = d.getVar("OEQA_JSON_RESULT_DIR")
167 if custom_json_result_dir:
168 json_result_dir = custom_json_result_dir
169 return json_result_dir
170
171def get_testimage_result_id(configuration):
172 return '%s_%s_%s_%s' % (configuration['TEST_TYPE'], configuration['IMAGE_BASENAME'], configuration['MACHINE'], configuration['STARTTIME'])
173
Andrew Geissler82c905d2020-04-13 13:39:40 -0500174def get_testimage_boot_patterns(d):
175 from collections import defaultdict
176 boot_patterns = defaultdict(str)
177 # Only accept certain values
178 accepted_patterns = ['search_reached_prompt', 'send_login_user', 'search_login_succeeded', 'search_cmd_finished']
179 # Not all patterns need to be overriden, e.g. perhaps we only want to change the user
180 boot_patterns_flags = d.getVarFlags('TESTIMAGE_BOOT_PATTERNS') or {}
181 if boot_patterns_flags:
182 patterns_set = [p for p in boot_patterns_flags.items() if p[0] in d.getVar('TESTIMAGE_BOOT_PATTERNS').split()]
183 for flag, flagval in patterns_set:
184 if flag not in accepted_patterns:
185 bb.fatal('Testimage: The only accepted boot patterns are: search_reached_prompt,send_login_user, \
186 search_login_succeeded,search_cmd_finished\n Make sure your TESTIMAGE_BOOT_PATTERNS=%s \
187 contains an accepted flag.' % d.getVar('TESTIMAGE_BOOT_PATTERNS'))
188 return
189 # We know boot prompt is searched through in binary format, others might be expressions
190 if flag == 'search_reached_prompt':
191 boot_patterns[flag] = flagval.encode()
192 else:
193 boot_patterns[flag] = flagval.encode().decode('unicode-escape')
194 return boot_patterns
195
196
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500197def testimage_main(d):
198 import os
199 import json
200 import signal
201 import logging
Andrew Geissler5199d832021-09-24 16:47:35 -0500202 import shutil
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500203
204 from bb.utils import export_proxies
205 from oeqa.core.utils.misc import updateTestData
206 from oeqa.runtime.context import OERuntimeTestContext
207 from oeqa.runtime.context import OERuntimeTestContextExecutor
208 from oeqa.core.target.qemu import supported_fstypes
209 from oeqa.core.utils.test import getSuiteCases
210 from oeqa.utils import make_logger_bitbake_compatible
211
212 def sigterm_exception(signum, stackframe):
213 """
214 Catch SIGTERM from worker in order to stop qemu.
215 """
Andrew Geissler82c905d2020-04-13 13:39:40 -0500216 os.kill(os.getpid(), signal.SIGINT)
217
218 def handle_test_timeout(timeout):
219 bb.warn("Global test timeout reached (%s seconds), stopping the tests." %(timeout))
220 os.kill(os.getpid(), signal.SIGINT)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500221
Brad Bishopd5ae7d92018-06-14 09:52:03 -0700222 testimage_sanity(d)
223
224 if (d.getVar('IMAGE_PKGTYPE') == 'rpm'
225 and ('dnf' in d.getVar('TEST_SUITES') or 'auto' in d.getVar('TEST_SUITES'))):
226 create_rpm_index(d)
227
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500228 logger = make_logger_bitbake_compatible(logging.getLogger("BitBake"))
229 pn = d.getVar("PN")
230
231 bb.utils.mkdirhier(d.getVar("TEST_LOG_DIR"))
232
233 image_name = ("%s/%s" % (d.getVar('DEPLOY_DIR_IMAGE'),
234 d.getVar('IMAGE_LINK_NAME')))
235
236 tdname = "%s.testdata.json" % image_name
237 try:
238 td = json.load(open(tdname, "r"))
239 except (FileNotFoundError) as err:
240 bb.fatal('File %s Not Found. Have you built the image with INHERIT+="testimage" in the conf/local.conf?' % tdname)
241
242 # Some variables need to be updates (mostly paths) with the
243 # ones of the current environment because some tests require them.
244 updateTestData(d, td, d.getVar('TESTIMAGE_UPDATE_VARS').split())
245
246 image_manifest = "%s.manifest" % image_name
247 image_packages = OERuntimeTestContextExecutor.readPackagesManifest(image_manifest)
248
249 extract_dir = d.getVar("TEST_EXTRACTED_DIR")
250
251 # Get machine
252 machine = d.getVar("MACHINE")
253
254 # Get rootfs
Brad Bishop977dc1a2019-02-06 16:01:43 -0500255 fstypes = d.getVar('IMAGE_FSTYPES').split()
256 if d.getVar("TEST_TARGET") == "qemu":
257 fstypes = [fs for fs in fstypes if fs in supported_fstypes]
258 if not fstypes:
Andrew Geissler82c905d2020-04-13 13:39:40 -0500259 bb.fatal('Unsupported image type built. Add a compatible image to '
Brad Bishop977dc1a2019-02-06 16:01:43 -0500260 'IMAGE_FSTYPES. Supported types: %s' %
261 ', '.join(supported_fstypes))
Brad Bishop15ae2502019-06-18 21:44:24 -0400262 qfstype = fstypes[0]
263 qdeffstype = d.getVar("QB_DEFAULT_FSTYPE")
264 if qdeffstype:
265 qfstype = qdeffstype
266 rootfs = '%s.%s' % (image_name, qfstype)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500267
268 # Get tmpdir (not really used, just for compatibility)
269 tmpdir = d.getVar("TMPDIR")
270
271 # Get deploy_dir_image (not really used, just for compatibility)
272 dir_image = d.getVar("DEPLOY_DIR_IMAGE")
273
274 # Get bootlog
275 bootlog = os.path.join(d.getVar("TEST_LOG_DIR"),
276 'qemu_boot_log.%s' % d.getVar('DATETIME'))
277
278 # Get display
279 display = d.getVar("BB_ORIGENV").getVar("DISPLAY")
280
281 # Get kernel
282 kernel_name = ('%s-%s.bin' % (d.getVar("KERNEL_IMAGETYPE"), machine))
283 kernel = os.path.join(d.getVar("DEPLOY_DIR_IMAGE"), kernel_name)
284
285 # Get boottime
286 boottime = int(d.getVar("TEST_QEMUBOOT_TIMEOUT"))
287
288 # Get use_kvm
Brad Bishop977dc1a2019-02-06 16:01:43 -0500289 kvm = oe.types.qemu_use_kvm(d.getVar('QEMU_USE_KVM'), d.getVar('TARGET_ARCH'))
290
Andrew Geissler82c905d2020-04-13 13:39:40 -0500291 # Get OVMF
292 ovmf = d.getVar("QEMU_USE_OVMF")
293
Brad Bishop977dc1a2019-02-06 16:01:43 -0500294 slirp = False
295 if d.getVar("QEMU_USE_SLIRP"):
296 slirp = True
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500297
Andrew Geissler82c905d2020-04-13 13:39:40 -0500298 # TODO: We use the current implementation of qemu runner because of
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500299 # time constrains, qemu runner really needs a refactor too.
300 target_kwargs = { 'machine' : machine,
301 'rootfs' : rootfs,
302 'tmpdir' : tmpdir,
303 'dir_image' : dir_image,
304 'display' : display,
305 'kernel' : kernel,
306 'boottime' : boottime,
307 'bootlog' : bootlog,
308 'kvm' : kvm,
Brad Bishop977dc1a2019-02-06 16:01:43 -0500309 'slirp' : slirp,
310 'dump_dir' : d.getVar("TESTIMAGE_DUMP_DIR"),
Andrew Geissler82c905d2020-04-13 13:39:40 -0500311 'serial_ports': len(d.getVar("SERIAL_CONSOLES").split()),
312 'ovmf' : ovmf,
Andrew Geissler3b8a17c2021-04-15 15:55:55 -0500313 'tmpfsdir' : d.getVar("RUNQEMU_TMPFS_DIR"),
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500314 }
315
Andrew Geissler82c905d2020-04-13 13:39:40 -0500316 if d.getVar("TESTIMAGE_BOOT_PATTERNS"):
317 target_kwargs['boot_patterns'] = get_testimage_boot_patterns(d)
318
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500319 # TODO: Currently BBPATH is needed for custom loading of targets.
320 # It would be better to find these modules using instrospection.
321 target_kwargs['target_modules_path'] = d.getVar('BBPATH')
322
Brad Bishop64c979e2019-11-04 13:55:29 -0500323 # hardware controlled targets might need further access
324 target_kwargs['powercontrol_cmd'] = d.getVar("TEST_POWERCONTROL_CMD") or None
325 target_kwargs['powercontrol_extra_args'] = d.getVar("TEST_POWERCONTROL_EXTRA_ARGS") or ""
326 target_kwargs['serialcontrol_cmd'] = d.getVar("TEST_SERIALCONTROL_CMD") or None
327 target_kwargs['serialcontrol_extra_args'] = d.getVar("TEST_SERIALCONTROL_EXTRA_ARGS") or ""
Andrew Geisslerc926e172021-05-07 16:11:35 -0500328 target_kwargs['testimage_dump_monitor'] = d.getVar("testimage_dump_monitor") or ""
Andrew Geisslerc3d88e42020-10-02 09:45:00 -0500329 target_kwargs['testimage_dump_target'] = d.getVar("testimage_dump_target") or ""
Brad Bishop64c979e2019-11-04 13:55:29 -0500330
331 def export_ssh_agent(d):
332 import os
333
334 variables = ['SSH_AGENT_PID', 'SSH_AUTH_SOCK']
335 for v in variables:
336 if v not in os.environ.keys():
337 val = d.getVar(v)
338 if val is not None:
339 os.environ[v] = val
340
341 export_ssh_agent(d)
342
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500343 # runtime use network for download projects for build
344 export_proxies(d)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500345
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500346 # we need the host dumper in test context
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500347 host_dumper = OERuntimeTestContextExecutor.getHostDumper(
348 d.getVar("testimage_dump_host"),
349 d.getVar("TESTIMAGE_DUMP_DIR"))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500350
351 # the robot dance
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500352 target = OERuntimeTestContextExecutor.getTarget(
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500353 d.getVar("TEST_TARGET"), logger, d.getVar("TEST_TARGET_IP"),
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500354 d.getVar("TEST_SERVER_IP"), **target_kwargs)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500355
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500356 # test context
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500357 tc = OERuntimeTestContext(td, logger, target, host_dumper,
358 image_packages, extract_dir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500359
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500360 # Load tests before starting the target
361 test_paths = get_runtime_paths(d)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500362 test_modules = d.getVar('TEST_SUITES').split()
Brad Bishopd5ae7d92018-06-14 09:52:03 -0700363 if not test_modules:
364 bb.fatal('Empty test suite, please verify TEST_SUITES variable')
365
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500366 tc.loadTests(test_paths, modules=test_modules)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500367
Brad Bishopd5ae7d92018-06-14 09:52:03 -0700368 suitecases = getSuiteCases(tc.suites)
369 if not suitecases:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500370 bb.fatal('Empty test suite, please verify TEST_SUITES variable')
Brad Bishopd5ae7d92018-06-14 09:52:03 -0700371 else:
372 bb.debug(2, 'test suites:\n\t%s' % '\n\t'.join([str(c) for c in suitecases]))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500373
374 package_extraction(d, tc.suites)
375
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500376 results = None
Andrew Geissler6ce62a22020-11-30 19:58:47 -0600377 complete = False
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500378 orig_sigterm_handler = signal.signal(signal.SIGTERM, sigterm_exception)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600379 try:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500380 # We need to check if runqemu ends unexpectedly
381 # or if the worker send us a SIGTERM
Brad Bishop19323692019-04-05 15:28:33 -0400382 tc.target.start(params=d.getVar("TEST_QEMUPARAMS"), runqemuparams=d.getVar("TEST_RUNQEMUPARAMS"))
Andrew Geissler82c905d2020-04-13 13:39:40 -0500383 import threading
384 try:
385 threading.Timer(int(d.getVar("TEST_OVERALL_TIMEOUT")), handle_test_timeout, (int(d.getVar("TEST_OVERALL_TIMEOUT")),)).start()
386 except ValueError:
387 pass
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500388 results = tc.runTests()
Andrew Geissler6ce62a22020-11-30 19:58:47 -0600389 complete = True
Andrew Geissler82c905d2020-04-13 13:39:40 -0500390 except (KeyboardInterrupt, BlockingIOError) as err:
391 if isinstance(err, KeyboardInterrupt):
392 bb.error('testimage interrupted, shutting down...')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600393 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500394 bb.error('runqemu failed, shutting down...')
395 if results:
396 results.stop()
Andrew Geissler6ce62a22020-11-30 19:58:47 -0600397 results = tc.results
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600398 finally:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500399 signal.signal(signal.SIGTERM, orig_sigterm_handler)
400 tc.target.stop()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600401
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500402 # Show results (if we have them)
Andrew Geissler6ce62a22020-11-30 19:58:47 -0600403 if results:
404 configuration = get_testimage_configuration(d, 'runtime', machine)
405 results.logDetails(get_testimage_json_result_dir(d),
406 configuration,
407 get_testimage_result_id(configuration),
408 dump_streams=d.getVar('TESTREPORT_FULLLOGS'))
409 results.logSummary(pn)
Andrew Geissler5199d832021-09-24 16:47:35 -0500410
411 # Copy additional logs to tmp/log/oeqa so it's easier to find them
412 targetdir = os.path.join(get_testimage_json_result_dir(d), d.getVar("PN"))
413 os.makedirs(targetdir, exist_ok=True)
414 os.symlink(bootlog, os.path.join(targetdir, os.path.basename(bootlog)))
415 os.symlink(d.getVar("BB_LOGFILE"), os.path.join(targetdir, os.path.basename(d.getVar("BB_LOGFILE") + "." + d.getVar('DATETIME'))))
416
Andrew Geissler6ce62a22020-11-30 19:58:47 -0600417 if not results or not complete:
Andrew Geissler5199d832021-09-24 16:47:35 -0500418 bb.fatal('%s - FAILED - tests were interrupted during execution, check the logs in %s' % (pn, d.getVar("LOG_DIR")), forcelog=True)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500419 if not results.wasSuccessful():
Andrew Geissler5199d832021-09-24 16:47:35 -0500420 bb.fatal('%s - FAILED - also check the logs in %s' % (pn, d.getVar("LOG_DIR")), forcelog=True)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600421
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500422def get_runtime_paths(d):
423 """
424 Returns a list of paths where runtime test must reside.
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500425
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500426 Runtime tests are expected in <LAYER_DIR>/lib/oeqa/runtime/cases/
427 """
428 paths = []
429
430 for layer in d.getVar('BBLAYERS').split():
431 path = os.path.join(layer, 'lib/oeqa/runtime/cases')
432 if os.path.isdir(path):
433 paths.append(path)
434 return paths
435
436def create_index(arg):
437 import subprocess
438
439 index_cmd = arg
440 try:
441 bb.note("Executing '%s' ..." % index_cmd)
442 result = subprocess.check_output(index_cmd,
443 stderr=subprocess.STDOUT,
444 shell=True)
445 result = result.decode('utf-8')
446 except subprocess.CalledProcessError as e:
447 return("Index creation command '%s' failed with return code "
448 '%d:\n%s' % (e.cmd, e.returncode, e.output.decode("utf-8")))
449 if result:
450 bb.note(result)
451 return None
452
453def create_rpm_index(d):
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800454 import glob
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500455 # Index RPMs
456 rpm_createrepo = bb.utils.which(os.getenv('PATH'), "createrepo_c")
457 index_cmds = []
458 archs = (d.getVar('ALL_MULTILIB_PACKAGE_ARCHS') or '').replace('-', '_')
459
460 for arch in archs.split():
461 rpm_dir = os.path.join(d.getVar('DEPLOY_DIR_RPM'), arch)
462 idx_path = os.path.join(d.getVar('WORKDIR'), 'oe-testimage-repo', arch)
463
464 if not os.path.isdir(rpm_dir):
465 continue
466
467 lockfilename = os.path.join(d.getVar('DEPLOY_DIR_RPM'), 'rpm.lock')
468 lf = bb.utils.lockfile(lockfilename, False)
469 oe.path.copyhardlinktree(rpm_dir, idx_path)
470 # Full indexes overload a 256MB image so reduce the number of rpms
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800471 # in the feed by filtering to specific packages needed by the tests.
472 package_list = glob.glob(idx_path + "*/*.rpm")
473
474 for pkg in package_list:
475 if not os.path.basename(pkg).startswith(("rpm", "run-postinsts", "busybox", "bash", "update-alternatives", "libc6", "curl", "musl")):
476 bb.utils.remove(pkg)
477
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500478 bb.utils.unlockfile(lf)
479 cmd = '%s --update -q %s' % (rpm_createrepo, idx_path)
480
481 # Create repodata
482 result = create_index(cmd)
483 if result:
484 bb.fatal('%s' % ('\n'.join(result)))
485
486def package_extraction(d, test_suites):
487 from oeqa.utils.package_manager import find_packages_to_extract
488 from oeqa.utils.package_manager import extract_packages
489
490 bb.utils.remove(d.getVar("TEST_NEEDED_PACKAGES_DIR"), recurse=True)
491 packages = find_packages_to_extract(test_suites)
492 if packages:
493 bb.utils.mkdirhier(d.getVar("TEST_INSTALL_TMP_DIR"))
494 bb.utils.mkdirhier(d.getVar("TEST_PACKAGED_DIR"))
495 bb.utils.mkdirhier(d.getVar("TEST_EXTRACTED_DIR"))
496 extract_packages(d, packages)
497
498testimage_main[vardepsexclude] += "BB_ORIGENV DATETIME"
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500499
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800500python () {
501 if oe.types.boolean(d.getVar("TESTIMAGE_AUTO") or "False"):
502 bb.build.addtask("testimage", "do_build", "do_image_complete", d)
503}
504
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500505inherit testsdk