blob: ed3a885bdf2f0bf88763b8eae829130c1205fd04 [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
67# aarch64 has no graphics
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050068DEFAULT_TEST_SUITES_remove_aarch64 = "xorg"
Brad Bishop316dfdd2018-06-25 12:45:53 -040069# musl doesn't support systemtap
70DEFAULT_TEST_SUITES_remove_libc-musl = "stap"
Patrick Williamsc124f4f2015-09-15 14:41:29 -050071
Patrick Williamsc0f7c042017-02-23 20:41:17 -060072# qemumips is quite slow and has reached the timeout limit several times on the YP build cluster,
73# mitigate this by removing build tests for qemumips machines.
Brad Bishopd7bf8c12018-02-25 22:55:05 -050074MIPSREMOVE ??= "buildcpio buildlzip buildgalculator"
Patrick Williamsc0f7c042017-02-23 20:41:17 -060075DEFAULT_TEST_SUITES_remove_qemumips = "${MIPSREMOVE}"
76DEFAULT_TEST_SUITES_remove_qemumips64 = "${MIPSREMOVE}"
Patrick Williamsc124f4f2015-09-15 14:41:29 -050077
78TEST_SUITES ?= "${DEFAULT_TEST_SUITES}"
79
80TEST_QEMUBOOT_TIMEOUT ?= "1000"
Andrew Geissler82c905d2020-04-13 13:39:40 -050081TEST_OVERALL_TIMEOUT ?= ""
Patrick Williamsc124f4f2015-09-15 14:41:29 -050082TEST_TARGET ?= "qemu"
Brad Bishop977dc1a2019-02-06 16:01:43 -050083TEST_QEMUPARAMS ?= ""
Brad Bishop19323692019-04-05 15:28:33 -040084TEST_RUNQEMUPARAMS ?= ""
Patrick Williamsc124f4f2015-09-15 14:41:29 -050085
Andrew Geissler82c905d2020-04-13 13:39:40 -050086TESTIMAGE_BOOT_PATTERNS ?= ""
87
Patrick Williamsc124f4f2015-09-15 14:41:29 -050088TESTIMAGEDEPENDS = ""
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080089TESTIMAGEDEPENDS_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 -060090TESTIMAGEDEPENDS += "${@bb.utils.contains('IMAGE_PKGTYPE', 'rpm', 'cpio-native:do_populate_sysroot', '', d)}"
Brad Bishop6e60e8b2018-02-01 10:27:11 -050091TESTIMAGEDEPENDS += "${@bb.utils.contains('IMAGE_PKGTYPE', 'rpm', 'dnf-native:do_populate_sysroot', '', d)}"
Brad Bishop977dc1a2019-02-06 16:01:43 -050092TESTIMAGEDEPENDS += "${@bb.utils.contains('IMAGE_PKGTYPE', 'rpm', 'createrepo-c-native:do_populate_sysroot', '', d)}"
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080093TESTIMAGEDEPENDS += "${@bb.utils.contains('IMAGE_PKGTYPE', 'ipk', 'opkg-utils-native:do_populate_sysroot package-index:do_package_index', '', d)}"
94TESTIMAGEDEPENDS += "${@bb.utils.contains('IMAGE_PKGTYPE', 'deb', 'apt-native:do_populate_sysroot package-index:do_package_index', '', d)}"
Patrick Williamsc124f4f2015-09-15 14:41:29 -050095
96TESTIMAGELOCK = "${TMPDIR}/testimage.lock"
97TESTIMAGELOCK_qemuall = ""
98
Brad Bishop977dc1a2019-02-06 16:01:43 -050099TESTIMAGE_DUMP_DIR ?= "${LOG_DIR}/runtime-hostdump/"
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500100
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500101TESTIMAGE_UPDATE_VARS ?= "DL_DIR WORKDIR DEPLOY_DIR"
102
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500103testimage_dump_target () {
104 top -bn1
105 ps
106 free
107 df
108 # The next command will export the default gateway IP
109 export DEFAULT_GATEWAY=$(ip route | awk '/default/ { print $3}')
110 ping -c3 $DEFAULT_GATEWAY
111 dmesg
112 netstat -an
113 ip address
114 # Next command will dump logs from /var/log/
115 find /var/log/ -type f 2>/dev/null -exec echo "====================" \; -exec echo {} \; -exec echo "====================" \; -exec cat {} \; -exec echo "" \;
116}
117
118testimage_dump_host () {
119 top -bn1
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500120 iostat -x -z -N -d -p ALL 20 2
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500121 ps -ef
122 free
123 df
124 memstat
125 dmesg
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500126 ip -s link
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500127 netstat -an
128}
129
Andrew Geisslerc926e172021-05-07 16:11:35 -0500130testimage_dump_monitor () {
131 query-status
132 query-block
Andrew Geissler5f350902021-07-23 13:09:54 -0400133 dump-guest-memory {"paging":false,"protocol":"file:%s.img"}
Andrew Geisslerc926e172021-05-07 16:11:35 -0500134}
135
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500136python do_testimage() {
137 testimage_main(d)
138}
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600139
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500140addtask testimage
141do_testimage[nostamp] = "1"
142do_testimage[depends] += "${TESTIMAGEDEPENDS}"
143do_testimage[lockfiles] += "${TESTIMAGELOCK}"
144
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500145def testimage_sanity(d):
146 if (d.getVar('TEST_TARGET') == 'simpleremote'
147 and (not d.getVar('TEST_TARGET_IP')
148 or not d.getVar('TEST_SERVER_IP'))):
149 bb.fatal('When TEST_TARGET is set to "simpleremote" '
150 'TEST_TARGET_IP and TEST_SERVER_IP are needed too.')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500151
Brad Bishopf86d0552018-12-04 14:18:15 -0800152def get_testimage_configuration(d, test_type, machine):
153 import platform
154 from oeqa.utils.metadata import get_layers
155 configuration = {'TEST_TYPE': test_type,
156 'MACHINE': machine,
157 'DISTRO': d.getVar("DISTRO"),
158 'IMAGE_BASENAME': d.getVar("IMAGE_BASENAME"),
159 'IMAGE_PKGTYPE': d.getVar("IMAGE_PKGTYPE"),
160 'STARTTIME': d.getVar("DATETIME"),
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800161 'HOST_DISTRO': oe.lsb.distro_identifier().replace(' ', '-'),
Brad Bishopf86d0552018-12-04 14:18:15 -0800162 'LAYERS': get_layers(d.getVar("BBLAYERS"))}
163 return configuration
164get_testimage_configuration[vardepsexclude] = "DATETIME"
165
166def get_testimage_json_result_dir(d):
167 json_result_dir = os.path.join(d.getVar("LOG_DIR"), 'oeqa')
168 custom_json_result_dir = d.getVar("OEQA_JSON_RESULT_DIR")
169 if custom_json_result_dir:
170 json_result_dir = custom_json_result_dir
171 return json_result_dir
172
173def get_testimage_result_id(configuration):
174 return '%s_%s_%s_%s' % (configuration['TEST_TYPE'], configuration['IMAGE_BASENAME'], configuration['MACHINE'], configuration['STARTTIME'])
175
Andrew Geissler82c905d2020-04-13 13:39:40 -0500176def get_testimage_boot_patterns(d):
177 from collections import defaultdict
178 boot_patterns = defaultdict(str)
179 # Only accept certain values
180 accepted_patterns = ['search_reached_prompt', 'send_login_user', 'search_login_succeeded', 'search_cmd_finished']
181 # Not all patterns need to be overriden, e.g. perhaps we only want to change the user
182 boot_patterns_flags = d.getVarFlags('TESTIMAGE_BOOT_PATTERNS') or {}
183 if boot_patterns_flags:
184 patterns_set = [p for p in boot_patterns_flags.items() if p[0] in d.getVar('TESTIMAGE_BOOT_PATTERNS').split()]
185 for flag, flagval in patterns_set:
186 if flag not in accepted_patterns:
187 bb.fatal('Testimage: The only accepted boot patterns are: search_reached_prompt,send_login_user, \
188 search_login_succeeded,search_cmd_finished\n Make sure your TESTIMAGE_BOOT_PATTERNS=%s \
189 contains an accepted flag.' % d.getVar('TESTIMAGE_BOOT_PATTERNS'))
190 return
191 # We know boot prompt is searched through in binary format, others might be expressions
192 if flag == 'search_reached_prompt':
193 boot_patterns[flag] = flagval.encode()
194 else:
195 boot_patterns[flag] = flagval.encode().decode('unicode-escape')
196 return boot_patterns
197
198
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500199def testimage_main(d):
200 import os
201 import json
202 import signal
203 import logging
204
205 from bb.utils import export_proxies
206 from oeqa.core.utils.misc import updateTestData
207 from oeqa.runtime.context import OERuntimeTestContext
208 from oeqa.runtime.context import OERuntimeTestContextExecutor
209 from oeqa.core.target.qemu import supported_fstypes
210 from oeqa.core.utils.test import getSuiteCases
211 from oeqa.utils import make_logger_bitbake_compatible
212
213 def sigterm_exception(signum, stackframe):
214 """
215 Catch SIGTERM from worker in order to stop qemu.
216 """
Andrew Geissler82c905d2020-04-13 13:39:40 -0500217 os.kill(os.getpid(), signal.SIGINT)
218
219 def handle_test_timeout(timeout):
220 bb.warn("Global test timeout reached (%s seconds), stopping the tests." %(timeout))
221 os.kill(os.getpid(), signal.SIGINT)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500222
Brad Bishopd5ae7d92018-06-14 09:52:03 -0700223 testimage_sanity(d)
224
225 if (d.getVar('IMAGE_PKGTYPE') == 'rpm'
226 and ('dnf' in d.getVar('TEST_SUITES') or 'auto' in d.getVar('TEST_SUITES'))):
227 create_rpm_index(d)
228
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500229 logger = make_logger_bitbake_compatible(logging.getLogger("BitBake"))
230 pn = d.getVar("PN")
231
232 bb.utils.mkdirhier(d.getVar("TEST_LOG_DIR"))
233
234 image_name = ("%s/%s" % (d.getVar('DEPLOY_DIR_IMAGE'),
235 d.getVar('IMAGE_LINK_NAME')))
236
237 tdname = "%s.testdata.json" % image_name
238 try:
239 td = json.load(open(tdname, "r"))
240 except (FileNotFoundError) as err:
241 bb.fatal('File %s Not Found. Have you built the image with INHERIT+="testimage" in the conf/local.conf?' % tdname)
242
243 # Some variables need to be updates (mostly paths) with the
244 # ones of the current environment because some tests require them.
245 updateTestData(d, td, d.getVar('TESTIMAGE_UPDATE_VARS').split())
246
247 image_manifest = "%s.manifest" % image_name
248 image_packages = OERuntimeTestContextExecutor.readPackagesManifest(image_manifest)
249
250 extract_dir = d.getVar("TEST_EXTRACTED_DIR")
251
252 # Get machine
253 machine = d.getVar("MACHINE")
254
255 # Get rootfs
Brad Bishop977dc1a2019-02-06 16:01:43 -0500256 fstypes = d.getVar('IMAGE_FSTYPES').split()
257 if d.getVar("TEST_TARGET") == "qemu":
258 fstypes = [fs for fs in fstypes if fs in supported_fstypes]
259 if not fstypes:
Andrew Geissler82c905d2020-04-13 13:39:40 -0500260 bb.fatal('Unsupported image type built. Add a compatible image to '
Brad Bishop977dc1a2019-02-06 16:01:43 -0500261 'IMAGE_FSTYPES. Supported types: %s' %
262 ', '.join(supported_fstypes))
Brad Bishop15ae2502019-06-18 21:44:24 -0400263 qfstype = fstypes[0]
264 qdeffstype = d.getVar("QB_DEFAULT_FSTYPE")
265 if qdeffstype:
266 qfstype = qdeffstype
267 rootfs = '%s.%s' % (image_name, qfstype)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500268
269 # Get tmpdir (not really used, just for compatibility)
270 tmpdir = d.getVar("TMPDIR")
271
272 # Get deploy_dir_image (not really used, just for compatibility)
273 dir_image = d.getVar("DEPLOY_DIR_IMAGE")
274
275 # Get bootlog
276 bootlog = os.path.join(d.getVar("TEST_LOG_DIR"),
277 'qemu_boot_log.%s' % d.getVar('DATETIME'))
278
279 # Get display
280 display = d.getVar("BB_ORIGENV").getVar("DISPLAY")
281
282 # Get kernel
283 kernel_name = ('%s-%s.bin' % (d.getVar("KERNEL_IMAGETYPE"), machine))
284 kernel = os.path.join(d.getVar("DEPLOY_DIR_IMAGE"), kernel_name)
285
286 # Get boottime
287 boottime = int(d.getVar("TEST_QEMUBOOT_TIMEOUT"))
288
289 # Get use_kvm
Brad Bishop977dc1a2019-02-06 16:01:43 -0500290 kvm = oe.types.qemu_use_kvm(d.getVar('QEMU_USE_KVM'), d.getVar('TARGET_ARCH'))
291
Andrew Geissler82c905d2020-04-13 13:39:40 -0500292 # Get OVMF
293 ovmf = d.getVar("QEMU_USE_OVMF")
294
Brad Bishop977dc1a2019-02-06 16:01:43 -0500295 slirp = False
296 if d.getVar("QEMU_USE_SLIRP"):
297 slirp = True
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500298
Andrew Geissler82c905d2020-04-13 13:39:40 -0500299 # TODO: We use the current implementation of qemu runner because of
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500300 # time constrains, qemu runner really needs a refactor too.
301 target_kwargs = { 'machine' : machine,
302 'rootfs' : rootfs,
303 'tmpdir' : tmpdir,
304 'dir_image' : dir_image,
305 'display' : display,
306 'kernel' : kernel,
307 'boottime' : boottime,
308 'bootlog' : bootlog,
309 'kvm' : kvm,
Brad Bishop977dc1a2019-02-06 16:01:43 -0500310 'slirp' : slirp,
311 'dump_dir' : d.getVar("TESTIMAGE_DUMP_DIR"),
Andrew Geissler82c905d2020-04-13 13:39:40 -0500312 'serial_ports': len(d.getVar("SERIAL_CONSOLES").split()),
313 'ovmf' : ovmf,
Andrew Geissler3b8a17c2021-04-15 15:55:55 -0500314 'tmpfsdir' : d.getVar("RUNQEMU_TMPFS_DIR"),
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500315 }
316
Andrew Geissler82c905d2020-04-13 13:39:40 -0500317 if d.getVar("TESTIMAGE_BOOT_PATTERNS"):
318 target_kwargs['boot_patterns'] = get_testimage_boot_patterns(d)
319
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500320 # TODO: Currently BBPATH is needed for custom loading of targets.
321 # It would be better to find these modules using instrospection.
322 target_kwargs['target_modules_path'] = d.getVar('BBPATH')
323
Brad Bishop64c979e2019-11-04 13:55:29 -0500324 # hardware controlled targets might need further access
325 target_kwargs['powercontrol_cmd'] = d.getVar("TEST_POWERCONTROL_CMD") or None
326 target_kwargs['powercontrol_extra_args'] = d.getVar("TEST_POWERCONTROL_EXTRA_ARGS") or ""
327 target_kwargs['serialcontrol_cmd'] = d.getVar("TEST_SERIALCONTROL_CMD") or None
328 target_kwargs['serialcontrol_extra_args'] = d.getVar("TEST_SERIALCONTROL_EXTRA_ARGS") or ""
Andrew Geisslerc926e172021-05-07 16:11:35 -0500329 target_kwargs['testimage_dump_monitor'] = d.getVar("testimage_dump_monitor") or ""
Andrew Geisslerc3d88e42020-10-02 09:45:00 -0500330 target_kwargs['testimage_dump_target'] = d.getVar("testimage_dump_target") or ""
Brad Bishop64c979e2019-11-04 13:55:29 -0500331
332 def export_ssh_agent(d):
333 import os
334
335 variables = ['SSH_AGENT_PID', 'SSH_AUTH_SOCK']
336 for v in variables:
337 if v not in os.environ.keys():
338 val = d.getVar(v)
339 if val is not None:
340 os.environ[v] = val
341
342 export_ssh_agent(d)
343
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500344 # runtime use network for download projects for build
345 export_proxies(d)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500346
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500347 # we need the host dumper in test context
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500348 host_dumper = OERuntimeTestContextExecutor.getHostDumper(
349 d.getVar("testimage_dump_host"),
350 d.getVar("TESTIMAGE_DUMP_DIR"))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500351
352 # the robot dance
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500353 target = OERuntimeTestContextExecutor.getTarget(
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500354 d.getVar("TEST_TARGET"), logger, d.getVar("TEST_TARGET_IP"),
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500355 d.getVar("TEST_SERVER_IP"), **target_kwargs)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500356
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500357 # test context
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500358 tc = OERuntimeTestContext(td, logger, target, host_dumper,
359 image_packages, extract_dir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500360
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500361 # Load tests before starting the target
362 test_paths = get_runtime_paths(d)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500363 test_modules = d.getVar('TEST_SUITES').split()
Brad Bishopd5ae7d92018-06-14 09:52:03 -0700364 if not test_modules:
365 bb.fatal('Empty test suite, please verify TEST_SUITES variable')
366
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500367 tc.loadTests(test_paths, modules=test_modules)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500368
Brad Bishopd5ae7d92018-06-14 09:52:03 -0700369 suitecases = getSuiteCases(tc.suites)
370 if not suitecases:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500371 bb.fatal('Empty test suite, please verify TEST_SUITES variable')
Brad Bishopd5ae7d92018-06-14 09:52:03 -0700372 else:
373 bb.debug(2, 'test suites:\n\t%s' % '\n\t'.join([str(c) for c in suitecases]))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500374
375 package_extraction(d, tc.suites)
376
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500377 results = None
Andrew Geissler6ce62a22020-11-30 19:58:47 -0600378 complete = False
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500379 orig_sigterm_handler = signal.signal(signal.SIGTERM, sigterm_exception)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600380 try:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500381 # We need to check if runqemu ends unexpectedly
382 # or if the worker send us a SIGTERM
Brad Bishop19323692019-04-05 15:28:33 -0400383 tc.target.start(params=d.getVar("TEST_QEMUPARAMS"), runqemuparams=d.getVar("TEST_RUNQEMUPARAMS"))
Andrew Geissler82c905d2020-04-13 13:39:40 -0500384 import threading
385 try:
386 threading.Timer(int(d.getVar("TEST_OVERALL_TIMEOUT")), handle_test_timeout, (int(d.getVar("TEST_OVERALL_TIMEOUT")),)).start()
387 except ValueError:
388 pass
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500389 results = tc.runTests()
Andrew Geissler6ce62a22020-11-30 19:58:47 -0600390 complete = True
Andrew Geissler82c905d2020-04-13 13:39:40 -0500391 except (KeyboardInterrupt, BlockingIOError) as err:
392 if isinstance(err, KeyboardInterrupt):
393 bb.error('testimage interrupted, shutting down...')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600394 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500395 bb.error('runqemu failed, shutting down...')
396 if results:
397 results.stop()
Andrew Geissler6ce62a22020-11-30 19:58:47 -0600398 results = tc.results
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600399 finally:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500400 signal.signal(signal.SIGTERM, orig_sigterm_handler)
401 tc.target.stop()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600402
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500403 # Show results (if we have them)
Andrew Geissler6ce62a22020-11-30 19:58:47 -0600404 if results:
405 configuration = get_testimage_configuration(d, 'runtime', machine)
406 results.logDetails(get_testimage_json_result_dir(d),
407 configuration,
408 get_testimage_result_id(configuration),
409 dump_streams=d.getVar('TESTREPORT_FULLLOGS'))
410 results.logSummary(pn)
411 if not results or not complete:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500412 bb.fatal('%s - FAILED - tests were interrupted during execution' % pn, forcelog=True)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500413 if not results.wasSuccessful():
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500414 bb.fatal('%s - FAILED - check the task log and the ssh log' % pn, forcelog=True)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600415
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500416def get_runtime_paths(d):
417 """
418 Returns a list of paths where runtime test must reside.
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500419
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500420 Runtime tests are expected in <LAYER_DIR>/lib/oeqa/runtime/cases/
421 """
422 paths = []
423
424 for layer in d.getVar('BBLAYERS').split():
425 path = os.path.join(layer, 'lib/oeqa/runtime/cases')
426 if os.path.isdir(path):
427 paths.append(path)
428 return paths
429
430def create_index(arg):
431 import subprocess
432
433 index_cmd = arg
434 try:
435 bb.note("Executing '%s' ..." % index_cmd)
436 result = subprocess.check_output(index_cmd,
437 stderr=subprocess.STDOUT,
438 shell=True)
439 result = result.decode('utf-8')
440 except subprocess.CalledProcessError as e:
441 return("Index creation command '%s' failed with return code "
442 '%d:\n%s' % (e.cmd, e.returncode, e.output.decode("utf-8")))
443 if result:
444 bb.note(result)
445 return None
446
447def create_rpm_index(d):
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800448 import glob
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500449 # Index RPMs
450 rpm_createrepo = bb.utils.which(os.getenv('PATH'), "createrepo_c")
451 index_cmds = []
452 archs = (d.getVar('ALL_MULTILIB_PACKAGE_ARCHS') or '').replace('-', '_')
453
454 for arch in archs.split():
455 rpm_dir = os.path.join(d.getVar('DEPLOY_DIR_RPM'), arch)
456 idx_path = os.path.join(d.getVar('WORKDIR'), 'oe-testimage-repo', arch)
457
458 if not os.path.isdir(rpm_dir):
459 continue
460
461 lockfilename = os.path.join(d.getVar('DEPLOY_DIR_RPM'), 'rpm.lock')
462 lf = bb.utils.lockfile(lockfilename, False)
463 oe.path.copyhardlinktree(rpm_dir, idx_path)
464 # Full indexes overload a 256MB image so reduce the number of rpms
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800465 # in the feed by filtering to specific packages needed by the tests.
466 package_list = glob.glob(idx_path + "*/*.rpm")
467
468 for pkg in package_list:
469 if not os.path.basename(pkg).startswith(("rpm", "run-postinsts", "busybox", "bash", "update-alternatives", "libc6", "curl", "musl")):
470 bb.utils.remove(pkg)
471
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500472 bb.utils.unlockfile(lf)
473 cmd = '%s --update -q %s' % (rpm_createrepo, idx_path)
474
475 # Create repodata
476 result = create_index(cmd)
477 if result:
478 bb.fatal('%s' % ('\n'.join(result)))
479
480def package_extraction(d, test_suites):
481 from oeqa.utils.package_manager import find_packages_to_extract
482 from oeqa.utils.package_manager import extract_packages
483
484 bb.utils.remove(d.getVar("TEST_NEEDED_PACKAGES_DIR"), recurse=True)
485 packages = find_packages_to_extract(test_suites)
486 if packages:
487 bb.utils.mkdirhier(d.getVar("TEST_INSTALL_TMP_DIR"))
488 bb.utils.mkdirhier(d.getVar("TEST_PACKAGED_DIR"))
489 bb.utils.mkdirhier(d.getVar("TEST_EXTRACTED_DIR"))
490 extract_packages(d, packages)
491
492testimage_main[vardepsexclude] += "BB_ORIGENV DATETIME"
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500493
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800494python () {
495 if oe.types.boolean(d.getVar("TESTIMAGE_AUTO") or "False"):
496 bb.build.addtask("testimage", "do_build", "do_image_complete", d)
497}
498
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500499inherit testsdk