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