blob: 281de4784f319d7de3f2f20405f1e59181f165c2 [file] [log] [blame]
Patrick Williams92b42cb2022-09-03 06:53:57 -05001# 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
Patrick Williams520786c2023-06-25 16:20:36 -050021# 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
Patrick Williams73bd93f2024-02-20 08:07:48 -060025TESTIMAGE_FAILED_QA_ARTIFACTS = "\
Patrick Williams520786c2023-06-25 16:20:36 -050026 ${localstatedir}/log \
27 ${sysconfdir}/version \
28 ${sysconfdir}/os-release"
29
Patrick Williams73bd93f2024-02-20 08:07:48 -060030# 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
Patrick Williams92b42cb2022-09-03 06:53:57 -050033# 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
Patrick Williams8e7b46e2023-05-01 14:19:06 -0500113TESTIMAGE_UPDATE_VARS ?= "DL_DIR WORKDIR DEPLOY_DIR_IMAGE IMAGE_LINK_NAME"
Patrick Williams92b42cb2022-09-03 06:53:57 -0500114
Patrick Williams92b42cb2022-09-03 06:53:57 -0500115testimage_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_json_result_dir(d):
153 json_result_dir = os.path.join(d.getVar("LOG_DIR"), 'oeqa')
154 custom_json_result_dir = d.getVar("OEQA_JSON_RESULT_DIR")
155 if custom_json_result_dir:
156 json_result_dir = custom_json_result_dir
157 return json_result_dir
158
159def get_testimage_result_id(configuration):
160 return '%s_%s_%s_%s' % (configuration['TEST_TYPE'], configuration['IMAGE_BASENAME'], configuration['MACHINE'], configuration['STARTTIME'])
161
162def get_testimage_boot_patterns(d):
163 from collections import defaultdict
164 boot_patterns = defaultdict(str)
165 # Only accept certain values
166 accepted_patterns = ['search_reached_prompt', 'send_login_user', 'search_login_succeeded', 'search_cmd_finished']
167 # Not all patterns need to be overriden, e.g. perhaps we only want to change the user
168 boot_patterns_flags = d.getVarFlags('TESTIMAGE_BOOT_PATTERNS') or {}
169 if boot_patterns_flags:
170 patterns_set = [p for p in boot_patterns_flags.items() if p[0] in d.getVar('TESTIMAGE_BOOT_PATTERNS').split()]
171 for flag, flagval in patterns_set:
172 if flag not in accepted_patterns:
173 bb.fatal('Testimage: The only accepted boot patterns are: search_reached_prompt,send_login_user, \
174 search_login_succeeded,search_cmd_finished\n Make sure your TESTIMAGE_BOOT_PATTERNS=%s \
175 contains an accepted flag.' % d.getVar('TESTIMAGE_BOOT_PATTERNS'))
176 return
Andrew Geissler87f5cff2022-09-30 13:13:31 -0500177 boot_patterns[flag] = flagval.encode().decode('unicode-escape')
Patrick Williams92b42cb2022-09-03 06:53:57 -0500178 return boot_patterns
179
Patrick Williams520786c2023-06-25 16:20:36 -0500180def get_artifacts_list(target, raw_list):
181 result = []
182 # Passed list may contains patterns in paths, expand them directly on target
183 for raw_path in raw_list.split():
184 cmd = f"for p in {raw_path}; do if [ -e $p ]; then echo $p; fi; done"
185 try:
186 status, output = target.run(cmd)
187 if status != 0 or not output:
188 raise Exception()
189 result += output.split()
190 except:
191 bb.note(f"No file/directory matching path {raw_path}")
192
193 return result
194
195def retrieve_test_artifacts(target, artifacts_list, target_dir):
196 import shutil
197
198 local_artifacts_dir = os.path.join(target_dir, "artifacts")
199 if os.path.isdir(local_artifacts_dir):
200 shutil.rmtree(local_artifacts_dir)
201
202 os.makedirs(local_artifacts_dir)
203 for artifact_path in artifacts_list:
204 if not os.path.isabs(artifact_path):
205 bb.warn(f"{artifact_path} is not an absolute path")
206 continue
207 try:
208 dest_dir = os.path.join(local_artifacts_dir, os.path.dirname(artifact_path[1:]))
209 os.makedirs(dest_dir, exist_ok=True)
210 target.copyFrom(artifact_path, dest_dir)
211 except:
212 bb.warn(f"Can not retrieve {artifact_path} from test target")
Patrick Williams92b42cb2022-09-03 06:53:57 -0500213
214def testimage_main(d):
215 import os
216 import json
217 import signal
218 import logging
219 import shutil
220
221 from bb.utils import export_proxies
222 from oeqa.runtime.context import OERuntimeTestContext
223 from oeqa.runtime.context import OERuntimeTestContextExecutor
224 from oeqa.core.target.qemu import supported_fstypes
225 from oeqa.core.utils.test import getSuiteCases
226 from oeqa.utils import make_logger_bitbake_compatible
227
228 def sigterm_exception(signum, stackframe):
229 """
230 Catch SIGTERM from worker in order to stop qemu.
231 """
232 os.kill(os.getpid(), signal.SIGINT)
233
234 def handle_test_timeout(timeout):
235 bb.warn("Global test timeout reached (%s seconds), stopping the tests." %(timeout))
236 os.kill(os.getpid(), signal.SIGINT)
237
238 testimage_sanity(d)
239
240 if (d.getVar('IMAGE_PKGTYPE') == 'rpm'
241 and ('dnf' in d.getVar('TEST_SUITES') or 'auto' in d.getVar('TEST_SUITES'))):
242 create_rpm_index(d)
243
244 logger = make_logger_bitbake_compatible(logging.getLogger("BitBake"))
245 pn = d.getVar("PN")
246
247 bb.utils.mkdirhier(d.getVar("TEST_LOG_DIR"))
248
249 image_name = ("%s/%s" % (d.getVar('DEPLOY_DIR_IMAGE'),
250 d.getVar('IMAGE_LINK_NAME')))
251
252 tdname = "%s.testdata.json" % image_name
253 try:
254 with open(tdname, "r") as f:
255 td = json.load(f)
256 except FileNotFoundError as err:
Patrick Williams864cc432023-02-09 14:54:44 -0600257 bb.fatal('File %s not found (%s).\nHave you built the image with IMAGE_CLASSES += "testimage" in the conf/local.conf?' % (tdname, err))
Patrick Williams92b42cb2022-09-03 06:53:57 -0500258
259 # Some variables need to be updates (mostly paths) with the
260 # ones of the current environment because some tests require them.
261 for var in d.getVar('TESTIMAGE_UPDATE_VARS').split():
262 td[var] = d.getVar(var)
263
264 image_manifest = "%s.manifest" % image_name
265 image_packages = OERuntimeTestContextExecutor.readPackagesManifest(image_manifest)
266
267 extract_dir = d.getVar("TEST_EXTRACTED_DIR")
268
269 # Get machine
270 machine = d.getVar("MACHINE")
271
272 # Get rootfs
273 fstypes = d.getVar('IMAGE_FSTYPES').split()
274 if d.getVar("TEST_TARGET") == "qemu":
275 fstypes = [fs for fs in fstypes if fs in supported_fstypes]
276 if not fstypes:
277 bb.fatal('Unsupported image type built. Add a compatible image to '
278 'IMAGE_FSTYPES. Supported types: %s' %
279 ', '.join(supported_fstypes))
280 qfstype = fstypes[0]
281 qdeffstype = d.getVar("QB_DEFAULT_FSTYPE")
282 if qdeffstype:
283 qfstype = qdeffstype
284 rootfs = '%s.%s' % (image_name, qfstype)
285
286 # Get tmpdir (not really used, just for compatibility)
287 tmpdir = d.getVar("TMPDIR")
288
289 # Get deploy_dir_image (not really used, just for compatibility)
290 dir_image = d.getVar("DEPLOY_DIR_IMAGE")
291
292 # Get bootlog
293 bootlog = os.path.join(d.getVar("TEST_LOG_DIR"),
294 'qemu_boot_log.%s' % d.getVar('DATETIME'))
295
296 # Get display
297 display = d.getVar("BB_ORIGENV").getVar("DISPLAY")
298
299 # Get kernel
300 kernel_name = ('%s-%s.bin' % (d.getVar("KERNEL_IMAGETYPE"), machine))
301 kernel = os.path.join(d.getVar("DEPLOY_DIR_IMAGE"), kernel_name)
302
303 # Get boottime
304 boottime = int(d.getVar("TEST_QEMUBOOT_TIMEOUT"))
305
306 # Get use_kvm
307 kvm = oe.types.qemu_use_kvm(d.getVar('QEMU_USE_KVM'), d.getVar('TARGET_ARCH'))
308
309 # Get OVMF
310 ovmf = d.getVar("QEMU_USE_OVMF")
311
312 slirp = False
Andrew Geissler220dafd2023-10-04 10:18:08 -0500313 if bb.utils.contains('TEST_RUNQEMUPARAMS', 'slirp', True, False, d):
Patrick Williams92b42cb2022-09-03 06:53:57 -0500314 slirp = True
315
316 # TODO: We use the current implementation of qemu runner because of
317 # time constrains, qemu runner really needs a refactor too.
318 target_kwargs = { 'machine' : machine,
319 'rootfs' : rootfs,
320 'tmpdir' : tmpdir,
321 'dir_image' : dir_image,
322 'display' : display,
323 'kernel' : kernel,
324 'boottime' : boottime,
325 'bootlog' : bootlog,
326 'kvm' : kvm,
327 'slirp' : slirp,
328 'dump_dir' : d.getVar("TESTIMAGE_DUMP_DIR"),
329 'serial_ports': len(d.getVar("SERIAL_CONSOLES").split()),
330 'ovmf' : ovmf,
331 'tmpfsdir' : d.getVar("RUNQEMU_TMPFS_DIR"),
332 }
333
334 if d.getVar("TESTIMAGE_BOOT_PATTERNS"):
335 target_kwargs['boot_patterns'] = get_testimage_boot_patterns(d)
336
337 # hardware controlled targets might need further access
338 target_kwargs['powercontrol_cmd'] = d.getVar("TEST_POWERCONTROL_CMD") or None
339 target_kwargs['powercontrol_extra_args'] = d.getVar("TEST_POWERCONTROL_EXTRA_ARGS") or ""
340 target_kwargs['serialcontrol_cmd'] = d.getVar("TEST_SERIALCONTROL_CMD") or None
341 target_kwargs['serialcontrol_extra_args'] = d.getVar("TEST_SERIALCONTROL_EXTRA_ARGS") or ""
342 target_kwargs['testimage_dump_monitor'] = d.getVar("testimage_dump_monitor") or ""
Patrick Williams92b42cb2022-09-03 06:53:57 -0500343
344 def export_ssh_agent(d):
345 import os
346
347 variables = ['SSH_AGENT_PID', 'SSH_AUTH_SOCK']
348 for v in variables:
349 if v not in os.environ.keys():
350 val = d.getVar(v)
351 if val is not None:
352 os.environ[v] = val
353
354 export_ssh_agent(d)
355
356 # runtime use network for download projects for build
357 export_proxies(d)
358
Andrew Geissler220dafd2023-10-04 10:18:08 -0500359 if slirp:
360 # Default to 127.0.0.1 and let the runner identify the port forwarding
361 # (as OEQemuTarget does), but allow overriding.
362 target_ip = d.getVar("TEST_TARGET_IP") or "127.0.0.1"
363 # Default to 10.0.2.2 as this is the IP that the guest has with the
364 # default qemu slirp networking configuration, but allow overriding.
365 server_ip = d.getVar("TEST_SERVER_IP") or "10.0.2.2"
366 else:
367 target_ip = d.getVar("TEST_TARGET_IP")
368 server_ip = d.getVar("TEST_SERVER_IP")
369
Patrick Williams92b42cb2022-09-03 06:53:57 -0500370 # the robot dance
371 target = OERuntimeTestContextExecutor.getTarget(
Andrew Geissler220dafd2023-10-04 10:18:08 -0500372 d.getVar("TEST_TARGET"), logger, target_ip,
373 server_ip, **target_kwargs)
Patrick Williams92b42cb2022-09-03 06:53:57 -0500374
375 # test context
Andrew Geissler8f840682023-07-21 09:09:43 -0500376 tc = OERuntimeTestContext(td, logger, target, image_packages, extract_dir)
Patrick Williams92b42cb2022-09-03 06:53:57 -0500377
378 # Load tests before starting the target
379 test_paths = get_runtime_paths(d)
380 test_modules = d.getVar('TEST_SUITES').split()
381 if not test_modules:
382 bb.fatal('Empty test suite, please verify TEST_SUITES variable')
383
384 tc.loadTests(test_paths, modules=test_modules)
385
386 suitecases = getSuiteCases(tc.suites)
387 if not suitecases:
388 bb.fatal('Empty test suite, please verify TEST_SUITES variable')
389 else:
390 bb.debug(2, 'test suites:\n\t%s' % '\n\t'.join([str(c) for c in suitecases]))
391
392 package_extraction(d, tc.suites)
393
394 results = None
395 complete = False
396 orig_sigterm_handler = signal.signal(signal.SIGTERM, sigterm_exception)
397 try:
398 # We need to check if runqemu ends unexpectedly
399 # or if the worker send us a SIGTERM
400 tc.target.start(params=d.getVar("TEST_QEMUPARAMS"), runqemuparams=d.getVar("TEST_RUNQEMUPARAMS"))
401 import threading
402 try:
403 threading.Timer(int(d.getVar("TEST_OVERALL_TIMEOUT")), handle_test_timeout, (int(d.getVar("TEST_OVERALL_TIMEOUT")),)).start()
404 except ValueError:
405 pass
406 results = tc.runTests()
407 complete = True
Patrick Williams520786c2023-06-25 16:20:36 -0500408 if results.hasAnyFailingTest():
409 artifacts_list = get_artifacts_list(tc.target, d.getVar("TESTIMAGE_FAILED_QA_ARTIFACTS"))
410 if not artifacts_list:
411 bb.warn("Could not load artifacts list, skip artifacts retrieval")
412 else:
413 retrieve_test_artifacts(tc.target, artifacts_list, get_testimage_json_result_dir(d))
Patrick Williams92b42cb2022-09-03 06:53:57 -0500414 except (KeyboardInterrupt, BlockingIOError) as err:
415 if isinstance(err, KeyboardInterrupt):
416 bb.error('testimage interrupted, shutting down...')
417 else:
418 bb.error('runqemu failed, shutting down...')
419 if results:
420 results.stop()
421 results = tc.results
422 finally:
423 signal.signal(signal.SIGTERM, orig_sigterm_handler)
424 tc.target.stop()
425
426 # Show results (if we have them)
427 if results:
428 configuration = get_testimage_configuration(d, 'runtime', machine)
429 results.logDetails(get_testimage_json_result_dir(d),
430 configuration,
431 get_testimage_result_id(configuration),
432 dump_streams=d.getVar('TESTREPORT_FULLLOGS'))
433 results.logSummary(pn)
434
435 # Copy additional logs to tmp/log/oeqa so it's easier to find them
436 targetdir = os.path.join(get_testimage_json_result_dir(d), d.getVar("PN"))
437 os.makedirs(targetdir, exist_ok=True)
438 os.symlink(bootlog, os.path.join(targetdir, os.path.basename(bootlog)))
439 os.symlink(d.getVar("BB_LOGFILE"), os.path.join(targetdir, os.path.basename(d.getVar("BB_LOGFILE") + "." + d.getVar('DATETIME'))))
440
441 if not results or not complete:
442 bb.fatal('%s - FAILED - tests were interrupted during execution, check the logs in %s' % (pn, d.getVar("LOG_DIR")), forcelog=True)
443 if not results.wasSuccessful():
444 bb.fatal('%s - FAILED - also check the logs in %s' % (pn, d.getVar("LOG_DIR")), forcelog=True)
445
446def get_runtime_paths(d):
447 """
448 Returns a list of paths where runtime test must reside.
449
450 Runtime tests are expected in <LAYER_DIR>/lib/oeqa/runtime/cases/
451 """
452 paths = []
453
454 for layer in d.getVar('BBLAYERS').split():
455 path = os.path.join(layer, 'lib/oeqa/runtime/cases')
456 if os.path.isdir(path):
457 paths.append(path)
458 return paths
459
460def create_index(arg):
461 import subprocess
462
463 index_cmd = arg
464 try:
465 bb.note("Executing '%s' ..." % index_cmd)
466 result = subprocess.check_output(index_cmd,
467 stderr=subprocess.STDOUT,
468 shell=True)
469 result = result.decode('utf-8')
470 except subprocess.CalledProcessError as e:
471 return("Index creation command '%s' failed with return code "
472 '%d:\n%s' % (e.cmd, e.returncode, e.output.decode("utf-8")))
473 if result:
474 bb.note(result)
475 return None
476
477def create_rpm_index(d):
478 import glob
479 # Index RPMs
480 rpm_createrepo = bb.utils.which(os.getenv('PATH'), "createrepo_c")
481 index_cmds = []
482 archs = (d.getVar('ALL_MULTILIB_PACKAGE_ARCHS') or '').replace('-', '_')
483
484 for arch in archs.split():
485 rpm_dir = os.path.join(d.getVar('DEPLOY_DIR_RPM'), arch)
486 idx_path = os.path.join(d.getVar('WORKDIR'), 'oe-testimage-repo', arch)
487
488 if not os.path.isdir(rpm_dir):
489 continue
490
491 lockfilename = os.path.join(d.getVar('DEPLOY_DIR_RPM'), 'rpm.lock')
492 lf = bb.utils.lockfile(lockfilename, False)
493 oe.path.copyhardlinktree(rpm_dir, idx_path)
494 # Full indexes overload a 256MB image so reduce the number of rpms
495 # in the feed by filtering to specific packages needed by the tests.
496 package_list = glob.glob(idx_path + "*/*.rpm")
497
498 for pkg in package_list:
Andrew Geissler87f5cff2022-09-30 13:13:31 -0500499 if not os.path.basename(pkg).startswith(("dnf-test-", "busybox", "update-alternatives", "libc6", "musl")):
Patrick Williams92b42cb2022-09-03 06:53:57 -0500500 bb.utils.remove(pkg)
501
502 bb.utils.unlockfile(lf)
503 cmd = '%s --update -q %s' % (rpm_createrepo, idx_path)
504
505 # Create repodata
506 result = create_index(cmd)
507 if result:
508 bb.fatal('%s' % ('\n'.join(result)))
509
510def package_extraction(d, test_suites):
511 from oeqa.utils.package_manager import find_packages_to_extract
512 from oeqa.utils.package_manager import extract_packages
513
514 bb.utils.remove(d.getVar("TEST_NEEDED_PACKAGES_DIR"), recurse=True)
515 packages = find_packages_to_extract(test_suites)
516 if packages:
517 bb.utils.mkdirhier(d.getVar("TEST_INSTALL_TMP_DIR"))
518 bb.utils.mkdirhier(d.getVar("TEST_PACKAGED_DIR"))
519 bb.utils.mkdirhier(d.getVar("TEST_EXTRACTED_DIR"))
520 extract_packages(d, packages)
521
522testimage_main[vardepsexclude] += "BB_ORIGENV DATETIME"
523
524python () {
525 if oe.types.boolean(d.getVar("TESTIMAGE_AUTO") or "False"):
526 bb.build.addtask("testimage", "do_build", "do_image_complete", d)
527}
528
529inherit testsdk