diff options
Diffstat (limited to 'meta/classes/testimage.bbclass')
-rw-r--r-- | meta/classes/testimage.bbclass | 250 |
1 files changed, 180 insertions, 70 deletions
diff --git a/meta/classes/testimage.bbclass b/meta/classes/testimage.bbclass index 39de191a73..898248992c 100644 --- a/meta/classes/testimage.bbclass +++ b/meta/classes/testimage.bbclass @@ -2,6 +2,8 @@ # # Released under the MIT license (see COPYING.MIT) +inherit metadata_scm +inherit image-artifact-names # testimage.bbclass enables testing of qemu images using python unittests. # Most of the tests are commands run on target image over ssh. @@ -31,6 +33,21 @@ TESTIMAGE_AUTO ??= "0" # 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. # Booting is handled by this class, and it's not a test in itself. # TEST_QEMUBOOT_TIMEOUT can be used to set the maximum time in seconds the launch code will wait for the login prompt. +# TEST_OVERALL_TIMEOUT can be used to set the maximum time in seconds the tests will be allowed to run (defaults to no limit). +# TEST_QEMUPARAMS can be used to pass extra parameters to qemu, e.g. "-m 1024" for setting the amount of ram to 1 GB. +# TEST_RUNQEMUPARAMS can be used to pass extra parameters to runqemu, e.g. "gl" to enable OpenGL acceleration. +# 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) + +# TESTIMAGE_BOOT_PATTERNS can be used to override certain patterns used to communicate with the target when booting, +# if a pattern is not specifically present on this variable a default will be used when booting the target. +# TESTIMAGE_BOOT_PATTERNS[<flag>] overrides the pattern used for that specific flag, where flag comes from a list of accepted flags +# 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 +# if we wanted to log in as the hypothetical "webserver" user for example we could set the following: +# TESTIMAGE_BOOT_PATTERNS = "send_login_user search_login_succeeded" +# TESTIMAGE_BOOT_PATTERNS[send_login_user] = "webserver\n" +# TESTIMAGE_BOOT_PATTERNS[search_login_succeeded] = "webserver@[a-zA-Z0-9\-]+:~#" +# The accepted flags are the following: search_reached_prompt, send_login_user, search_login_succeeded, search_cmd_finished. +# They are prefixed with either search/send, to differentiate if the pattern is meant to be sent or searched to/from the target terminal TEST_LOG_DIR ?= "${WORKDIR}/testimage" @@ -40,57 +57,46 @@ TEST_NEEDED_PACKAGES_DIR ?= "${WORKDIR}/testimage/packages" TEST_EXTRACTED_DIR ?= "${TEST_NEEDED_PACKAGES_DIR}/extracted" TEST_PACKAGED_DIR ?= "${TEST_NEEDED_PACKAGES_DIR}/packaged" -RPMTESTSUITE = "${@bb.utils.contains('IMAGE_PKGTYPE', 'rpm', 'dnf rpm', '', d)}" -SYSTEMDSUITE = "${@bb.utils.filter('DISTRO_FEATURES', 'systemd', d)}" -MINTESTSUITE = "ping" -NETTESTSUITE = "${MINTESTSUITE} ssh df date scp oe_syslog ${SYSTEMDSUITE}" -DEVTESTSUITE = "gcc kernelmodule ldd" - -DEFAULT_TEST_SUITES = "${MINTESTSUITE} auto" -DEFAULT_TEST_SUITES_pn-core-image-minimal = "${MINTESTSUITE}" -DEFAULT_TEST_SUITES_pn-core-image-minimal-dev = "${MINTESTSUITE}" -DEFAULT_TEST_SUITES_pn-core-image-full-cmdline = "${NETTESTSUITE} perl python logrotate ptest" -DEFAULT_TEST_SUITES_pn-core-image-x11 = "${MINTESTSUITE}" -DEFAULT_TEST_SUITES_pn-core-image-lsb = "${NETTESTSUITE} pam parselogs ${RPMTESTSUITE} ptest" -DEFAULT_TEST_SUITES_pn-core-image-sato = "${NETTESTSUITE} connman xorg parselogs ${RPMTESTSUITE} \ - ${@bb.utils.contains('IMAGE_PKGTYPE', 'rpm', 'python', '', d)} ptest gi" -DEFAULT_TEST_SUITES_pn-core-image-sato-sdk = "${NETTESTSUITE} buildcpio buildlzip buildgalculator \ - connman ${DEVTESTSUITE} logrotate perl parselogs python ${RPMTESTSUITE} xorg ptest gi stap" -DEFAULT_TEST_SUITES_pn-core-image-lsb-dev = "${NETTESTSUITE} pam perl python parselogs ${RPMTESTSUITE} ptest gi" -DEFAULT_TEST_SUITES_pn-core-image-lsb-sdk = "${NETTESTSUITE} buildcpio buildlzip buildgalculator \ - connman ${DEVTESTSUITE} logrotate pam parselogs perl python ${RPMTESTSUITE} ptest gi stap" -DEFAULT_TEST_SUITES_pn-meta-toolchain = "auto" - -# aarch64 has no graphics -DEFAULT_TEST_SUITES_remove_aarch64 = "xorg" +BASICTESTSUITE = "\ + ping date df ssh scp python perl gi ptest parselogs \ + logrotate connman systemd oe_syslog pam stap ldd xorg \ + kernelmodule gcc buildcpio buildlzip buildgalculator \ + dnf rpm opkg apt weston go rust" + +DEFAULT_TEST_SUITES = "${BASICTESTSUITE}" + # musl doesn't support systemtap -DEFAULT_TEST_SUITES_remove_libc-musl = "stap" +DEFAULT_TEST_SUITES:remove:libc-musl = "stap" # qemumips is quite slow and has reached the timeout limit several times on the YP build cluster, # mitigate this by removing build tests for qemumips machines. MIPSREMOVE ??= "buildcpio buildlzip buildgalculator" -DEFAULT_TEST_SUITES_remove_qemumips = "${MIPSREMOVE}" -DEFAULT_TEST_SUITES_remove_qemumips64 = "${MIPSREMOVE}" +DEFAULT_TEST_SUITES:remove:qemumips = "${MIPSREMOVE}" +DEFAULT_TEST_SUITES:remove:qemumips64 = "${MIPSREMOVE}" TEST_SUITES ?= "${DEFAULT_TEST_SUITES}" +QEMU_USE_KVM ?= "1" TEST_QEMUBOOT_TIMEOUT ?= "1000" +TEST_OVERALL_TIMEOUT ?= "" TEST_TARGET ?= "qemu" +TEST_QEMUPARAMS ?= "" +TEST_RUNQEMUPARAMS ?= "" + +TESTIMAGE_BOOT_PATTERNS ?= "" TESTIMAGEDEPENDS = "" -TESTIMAGEDEPENDS_qemuall = "qemu-native:do_populate_sysroot qemu-helper-native:do_populate_sysroot qemu-helper-native:do_addto_recipe_sysroot" +TESTIMAGEDEPENDS:append:qemuall = " qemu-native:do_populate_sysroot qemu-helper-native:do_populate_sysroot qemu-helper-native:do_addto_recipe_sysroot" TESTIMAGEDEPENDS += "${@bb.utils.contains('IMAGE_PKGTYPE', 'rpm', 'cpio-native:do_populate_sysroot', '', d)}" -TESTIMAGEDEPENDS_qemuall += "${@bb.utils.contains('IMAGE_PKGTYPE', 'rpm', 'cpio-native:do_populate_sysroot', '', d)}" -TESTIMAGEDEPENDS_qemuall += "${@bb.utils.contains('IMAGE_PKGTYPE', 'rpm', 'createrepo-c-native:do_populate_sysroot', '', d)}" TESTIMAGEDEPENDS += "${@bb.utils.contains('IMAGE_PKGTYPE', 'rpm', 'dnf-native:do_populate_sysroot', '', d)}" -TESTIMAGEDEPENDS += "${@bb.utils.contains('IMAGE_PKGTYPE', 'ipk', 'opkg-utils-native:do_populate_sysroot', '', d)}" -TESTIMAGEDEPENDS += "${@bb.utils.contains('IMAGE_PKGTYPE', 'deb', 'apt-native:do_populate_sysroot', '', d)}" TESTIMAGEDEPENDS += "${@bb.utils.contains('IMAGE_PKGTYPE', 'rpm', 'createrepo-c-native:do_populate_sysroot', '', d)}" +TESTIMAGEDEPENDS += "${@bb.utils.contains('IMAGE_PKGTYPE', 'ipk', 'opkg-utils-native:do_populate_sysroot package-index:do_package_index', '', d)}" +TESTIMAGEDEPENDS += "${@bb.utils.contains('IMAGE_PKGTYPE', 'deb', 'apt-native:do_populate_sysroot package-index:do_package_index', '', d)}" TESTIMAGELOCK = "${TMPDIR}/testimage.lock" -TESTIMAGELOCK_qemuall = "" +TESTIMAGELOCK:qemuall = "" -TESTIMAGE_DUMP_DIR ?= "/tmp/oe-saved-tests/" +TESTIMAGE_DUMP_DIR ?= "${LOG_DIR}/runtime-hostdump/" TESTIMAGE_UPDATE_VARS ?= "DL_DIR WORKDIR DEPLOY_DIR" @@ -121,12 +127,19 @@ testimage_dump_host () { netstat -an } +testimage_dump_monitor () { + query-status + query-block + dump-guest-memory {"paging":false,"protocol":"file:%s.img"} +} + python do_testimage() { testimage_main(d) } addtask testimage do_testimage[nostamp] = "1" +do_testimage[network] = "1" do_testimage[depends] += "${TESTIMAGEDEPENDS}" do_testimage[lockfiles] += "${TESTIMAGELOCK}" @@ -137,11 +150,59 @@ def testimage_sanity(d): bb.fatal('When TEST_TARGET is set to "simpleremote" ' 'TEST_TARGET_IP and TEST_SERVER_IP are needed too.') +def get_testimage_configuration(d, test_type, machine): + import platform + from oeqa.utils.metadata import get_layers + configuration = {'TEST_TYPE': test_type, + 'MACHINE': machine, + 'DISTRO': d.getVar("DISTRO"), + 'IMAGE_BASENAME': d.getVar("IMAGE_BASENAME"), + 'IMAGE_PKGTYPE': d.getVar("IMAGE_PKGTYPE"), + 'STARTTIME': d.getVar("DATETIME"), + 'HOST_DISTRO': oe.lsb.distro_identifier().replace(' ', '-'), + 'LAYERS': get_layers(d.getVar("BBLAYERS"))} + return configuration +get_testimage_configuration[vardepsexclude] = "DATETIME" + +def get_testimage_json_result_dir(d): + json_result_dir = os.path.join(d.getVar("LOG_DIR"), 'oeqa') + custom_json_result_dir = d.getVar("OEQA_JSON_RESULT_DIR") + if custom_json_result_dir: + json_result_dir = custom_json_result_dir + return json_result_dir + +def get_testimage_result_id(configuration): + return '%s_%s_%s_%s' % (configuration['TEST_TYPE'], configuration['IMAGE_BASENAME'], configuration['MACHINE'], configuration['STARTTIME']) + +def get_testimage_boot_patterns(d): + from collections import defaultdict + boot_patterns = defaultdict(str) + # Only accept certain values + accepted_patterns = ['search_reached_prompt', 'send_login_user', 'search_login_succeeded', 'search_cmd_finished'] + # Not all patterns need to be overriden, e.g. perhaps we only want to change the user + boot_patterns_flags = d.getVarFlags('TESTIMAGE_BOOT_PATTERNS') or {} + if boot_patterns_flags: + patterns_set = [p for p in boot_patterns_flags.items() if p[0] in d.getVar('TESTIMAGE_BOOT_PATTERNS').split()] + for flag, flagval in patterns_set: + if flag not in accepted_patterns: + bb.fatal('Testimage: The only accepted boot patterns are: search_reached_prompt,send_login_user, \ + search_login_succeeded,search_cmd_finished\n Make sure your TESTIMAGE_BOOT_PATTERNS=%s \ + contains an accepted flag.' % d.getVar('TESTIMAGE_BOOT_PATTERNS')) + return + # We know boot prompt is searched through in binary format, others might be expressions + if flag == 'search_reached_prompt': + boot_patterns[flag] = flagval.encode() + else: + boot_patterns[flag] = flagval.encode().decode('unicode-escape') + return boot_patterns + + def testimage_main(d): import os import json import signal import logging + import shutil from bb.utils import export_proxies from oeqa.core.utils.misc import updateTestData @@ -155,7 +216,11 @@ def testimage_main(d): """ Catch SIGTERM from worker in order to stop qemu. """ - raise RuntimeError + os.kill(os.getpid(), signal.SIGINT) + + def handle_test_timeout(timeout): + bb.warn("Global test timeout reached (%s seconds), stopping the tests." %(timeout)) + os.kill(os.getpid(), signal.SIGINT) testimage_sanity(d) @@ -173,9 +238,10 @@ def testimage_main(d): tdname = "%s.testdata.json" % image_name try: - td = json.load(open(tdname, "r")) - except (FileNotFoundError) as err: - bb.fatal('File %s Not Found. Have you built the image with INHERIT+="testimage" in the conf/local.conf?' % tdname) + with open(tdname, "r") as f: + td = json.load(f) + except FileNotFoundError as err: + bb.fatal('File %s not found (%s).\nHave you built the image with INHERIT += "testimage" in the conf/local.conf?' % (tdname, err)) # Some variables need to be updates (mostly paths) with the # ones of the current environment because some tests require them. @@ -190,13 +256,18 @@ def testimage_main(d): machine = d.getVar("MACHINE") # Get rootfs - fstypes = [fs for fs in d.getVar('IMAGE_FSTYPES').split(' ') - if fs in supported_fstypes] - if not fstypes: - bb.fatal('Unsupported image type built. Add a comptible image to ' - 'IMAGE_FSTYPES. Supported types: %s' % - ', '.join(supported_fstypes)) - rootfs = '%s.%s' % (image_name, fstypes[0]) + fstypes = d.getVar('IMAGE_FSTYPES').split() + if d.getVar("TEST_TARGET") == "qemu": + fstypes = [fs for fs in fstypes if fs in supported_fstypes] + if not fstypes: + bb.fatal('Unsupported image type built. Add a compatible image to ' + 'IMAGE_FSTYPES. Supported types: %s' % + ', '.join(supported_fstypes)) + qfstype = fstypes[0] + qdeffstype = d.getVar("QB_DEFAULT_FSTYPE") + if qdeffstype: + qfstype = qdeffstype + rootfs = '%s.%s' % (image_name, qfstype) # Get tmpdir (not really used, just for compatibility) tmpdir = d.getVar("TMPDIR") @@ -219,15 +290,16 @@ def testimage_main(d): boottime = int(d.getVar("TEST_QEMUBOOT_TIMEOUT")) # Get use_kvm - qemu_use_kvm = d.getVar("QEMU_USE_KVM") - if qemu_use_kvm and \ - (d.getVar('MACHINE') in qemu_use_kvm.split() or \ - oe.types.boolean(qemu_use_kvm) and 'x86' in machine): - kvm = True - else: - kvm = False + kvm = oe.types.qemu_use_kvm(d.getVar('QEMU_USE_KVM'), d.getVar('TARGET_ARCH')) + + # Get OVMF + ovmf = d.getVar("QEMU_USE_OVMF") - # TODO: We use the current implementatin of qemu runner because of + slirp = False + if d.getVar("QEMU_USE_SLIRP"): + slirp = True + + # TODO: We use the current implementation of qemu runner because of # time constrains, qemu runner really needs a refactor too. target_kwargs = { 'machine' : machine, 'rootfs' : rootfs, @@ -238,11 +310,35 @@ def testimage_main(d): 'boottime' : boottime, 'bootlog' : bootlog, 'kvm' : kvm, + 'slirp' : slirp, + 'dump_dir' : d.getVar("TESTIMAGE_DUMP_DIR"), + 'serial_ports': len(d.getVar("SERIAL_CONSOLES").split()), + 'ovmf' : ovmf, + 'tmpfsdir' : d.getVar("RUNQEMU_TMPFS_DIR"), } - # TODO: Currently BBPATH is needed for custom loading of targets. - # It would be better to find these modules using instrospection. - target_kwargs['target_modules_path'] = d.getVar('BBPATH') + if d.getVar("TESTIMAGE_BOOT_PATTERNS"): + target_kwargs['boot_patterns'] = get_testimage_boot_patterns(d) + + # hardware controlled targets might need further access + target_kwargs['powercontrol_cmd'] = d.getVar("TEST_POWERCONTROL_CMD") or None + target_kwargs['powercontrol_extra_args'] = d.getVar("TEST_POWERCONTROL_EXTRA_ARGS") or "" + target_kwargs['serialcontrol_cmd'] = d.getVar("TEST_SERIALCONTROL_CMD") or None + target_kwargs['serialcontrol_extra_args'] = d.getVar("TEST_SERIALCONTROL_EXTRA_ARGS") or "" + target_kwargs['testimage_dump_monitor'] = d.getVar("testimage_dump_monitor") or "" + target_kwargs['testimage_dump_target'] = d.getVar("testimage_dump_target") or "" + + def export_ssh_agent(d): + import os + + variables = ['SSH_AGENT_PID', 'SSH_AUTH_SOCK'] + for v in variables: + if v not in os.environ.keys(): + val = d.getVar(v) + if val is not None: + os.environ[v] = val + + export_ssh_agent(d) # runtime use network for download projects for build export_proxies(d) @@ -277,37 +373,51 @@ def testimage_main(d): package_extraction(d, tc.suites) - bootparams = None - if d.getVar('VIRTUAL-RUNTIME_init_manager', '') == 'systemd': - # Add systemd.log_level=debug to enable systemd debug logging - bootparams = 'systemd.log_target=console' - results = None + complete = False orig_sigterm_handler = signal.signal(signal.SIGTERM, sigterm_exception) try: # We need to check if runqemu ends unexpectedly # or if the worker send us a SIGTERM - tc.target.start(extra_bootparams=bootparams) + tc.target.start(params=d.getVar("TEST_QEMUPARAMS"), runqemuparams=d.getVar("TEST_RUNQEMUPARAMS")) + import threading + try: + threading.Timer(int(d.getVar("TEST_OVERALL_TIMEOUT")), handle_test_timeout, (int(d.getVar("TEST_OVERALL_TIMEOUT")),)).start() + except ValueError: + pass results = tc.runTests() - except (RuntimeError, BlockingIOError) as err: - if isinstance(err, RuntimeError): - bb.error('testimage received SIGTERM, shutting down...') + complete = True + except (KeyboardInterrupt, BlockingIOError) as err: + if isinstance(err, KeyboardInterrupt): + bb.error('testimage interrupted, shutting down...') else: bb.error('runqemu failed, shutting down...') if results: results.stop() - results = None + results = tc.results finally: signal.signal(signal.SIGTERM, orig_sigterm_handler) tc.target.stop() # Show results (if we have them) - if not results: - bb.fatal('%s - FAILED - tests were interrupted during execution' % pn, forcelog=True) - results.logDetails() - results.logSummary(pn) + if results: + configuration = get_testimage_configuration(d, 'runtime', machine) + results.logDetails(get_testimage_json_result_dir(d), + configuration, + get_testimage_result_id(configuration), + dump_streams=d.getVar('TESTREPORT_FULLLOGS')) + results.logSummary(pn) + + # Copy additional logs to tmp/log/oeqa so it's easier to find them + targetdir = os.path.join(get_testimage_json_result_dir(d), d.getVar("PN")) + os.makedirs(targetdir, exist_ok=True) + os.symlink(bootlog, os.path.join(targetdir, os.path.basename(bootlog))) + os.symlink(d.getVar("BB_LOGFILE"), os.path.join(targetdir, os.path.basename(d.getVar("BB_LOGFILE") + "." + d.getVar('DATETIME')))) + + if not results or not complete: + bb.fatal('%s - FAILED - tests were interrupted during execution, check the logs in %s' % (pn, d.getVar("LOG_DIR")), forcelog=True) if not results.wasSuccessful(): - bb.fatal('%s - FAILED - check the task log and the ssh log' % pn, forcelog=True) + bb.fatal('%s - FAILED - also check the logs in %s' % (pn, d.getVar("LOG_DIR")), forcelog=True) def get_runtime_paths(d): """ |