blob: f4daea250751fa7b9d536f163f5fd368c12828b0 [file] [log] [blame]
Brad Bishopc342db32019-05-15 21:57:59 -04001#
Patrick Williamsc124f4f2015-09-15 14:41:29 -05002# Copyright (c) 2013-2014 Intel Corporation
3#
Brad Bishopc342db32019-05-15 21:57:59 -04004# SPDX-License-Identifier: MIT
5#
Patrick Williamsc124f4f2015-09-15 14:41:29 -05006
7# DESCRIPTION
8# This module is mainly used by scripts/oe-selftest and modules under meta/oeqa/selftest
9# It provides a class and methods for running commands on the host in a convienent way for tests.
10
11
12
13import os
14import sys
15import signal
16import subprocess
17import threading
Brad Bishopd7bf8c12018-02-25 22:55:05 -050018import time
Patrick Williamsc124f4f2015-09-15 14:41:29 -050019import logging
20from oeqa.utils import CommandError
21from oeqa.utils import ftools
22import re
23import contextlib
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050024# Export test doesn't require bb
25try:
26 import bb
27except ImportError:
28 pass
Patrick Williamsc124f4f2015-09-15 14:41:29 -050029
30class Command(object):
Brad Bishopd7bf8c12018-02-25 22:55:05 -050031 def __init__(self, command, bg=False, timeout=None, data=None, output_log=None, **options):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050032
33 self.defaultopts = {
34 "stdout": subprocess.PIPE,
35 "stderr": subprocess.STDOUT,
36 "stdin": None,
37 "shell": False,
38 "bufsize": -1,
39 }
40
41 self.cmd = command
42 self.bg = bg
43 self.timeout = timeout
44 self.data = data
45
46 self.options = dict(self.defaultopts)
Patrick Williamsc0f7c042017-02-23 20:41:17 -060047 if isinstance(self.cmd, str):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050048 self.options["shell"] = True
49 if self.data:
50 self.options['stdin'] = subprocess.PIPE
51 self.options.update(options)
52
53 self.status = None
Brad Bishopd7bf8c12018-02-25 22:55:05 -050054 # We collect chunks of output before joining them at the end.
55 self._output_chunks = []
56 self._error_chunks = []
Patrick Williamsc124f4f2015-09-15 14:41:29 -050057 self.output = None
58 self.error = None
Brad Bishopd7bf8c12018-02-25 22:55:05 -050059 self.threads = []
Patrick Williamsc124f4f2015-09-15 14:41:29 -050060
Brad Bishopd7bf8c12018-02-25 22:55:05 -050061 self.output_log = output_log
Patrick Williamsc124f4f2015-09-15 14:41:29 -050062 self.log = logging.getLogger("utils.commands")
63
64 def run(self):
65 self.process = subprocess.Popen(self.cmd, **self.options)
66
Brad Bishopd7bf8c12018-02-25 22:55:05 -050067 def readThread(output, stream, logfunc):
68 if logfunc:
69 for line in stream:
70 output.append(line)
71 logfunc(line.decode("utf-8", errors='replace').rstrip())
72 else:
73 output.append(stream.read())
Patrick Williamsc124f4f2015-09-15 14:41:29 -050074
Brad Bishopd7bf8c12018-02-25 22:55:05 -050075 def readStderrThread():
76 readThread(self._error_chunks, self.process.stderr, self.output_log.error if self.output_log else None)
77
78 def readStdoutThread():
79 readThread(self._output_chunks, self.process.stdout, self.output_log.info if self.output_log else None)
80
81 def writeThread():
82 try:
83 self.process.stdin.write(self.data)
84 self.process.stdin.close()
85 except OSError as ex:
86 # It's not an error when the command does not consume all
87 # of our data. subprocess.communicate() also ignores that.
88 if ex.errno != EPIPE:
89 raise
90
91 # We write in a separate thread because then we can read
92 # without worrying about deadlocks. The additional thread is
93 # expected to terminate by itself and we mark it as a daemon,
94 # so even it should happen to not terminate for whatever
95 # reason, the main process will still exit, which will then
96 # kill the write thread.
97 if self.data:
Andrew Geisslerd25ed322020-06-27 00:28:28 -050098 thread = threading.Thread(target=writeThread, daemon=True)
99 thread.start()
100 self.threads.append(thread)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500101 if self.process.stderr:
102 thread = threading.Thread(target=readStderrThread)
103 thread.start()
104 self.threads.append(thread)
105 if self.output_log:
106 self.output_log.info('Running: %s' % self.cmd)
107 thread = threading.Thread(target=readStdoutThread)
108 thread.start()
109 self.threads.append(thread)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500110
111 self.log.debug("Running command '%s'" % self.cmd)
112
113 if not self.bg:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500114 if self.timeout is None:
115 for thread in self.threads:
116 thread.join()
117 else:
118 deadline = time.time() + self.timeout
119 for thread in self.threads:
120 timeout = deadline - time.time()
121 if timeout < 0:
122 timeout = 0
123 thread.join(timeout)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500124 self.stop()
125
126 def stop(self):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500127 for thread in self.threads:
Andrew Geissler6ce62a22020-11-30 19:58:47 -0600128 if thread.is_alive():
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500129 self.process.terminate()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500130 # let's give it more time to terminate gracefully before killing it
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500131 thread.join(5)
Andrew Geissler6ce62a22020-11-30 19:58:47 -0600132 if thread.is_alive():
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500133 self.process.kill()
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500134 thread.join()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500135
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500136 def finalize_output(data):
137 if not data:
138 data = ""
139 else:
140 data = b"".join(data)
141 data = data.decode("utf-8", errors='replace').rstrip()
142 return data
143
144 self.output = finalize_output(self._output_chunks)
145 self._output_chunks = None
146 # self.error used to be a byte string earlier, probably unintentionally.
147 # Now it is a normal string, just like self.output.
148 self.error = finalize_output(self._error_chunks)
149 self._error_chunks = None
150 # At this point we know that the process has closed stdout/stderr, so
151 # it is safe and necessary to wait for the actual process completion.
152 self.status = self.process.wait()
Brad Bishopf86d0552018-12-04 14:18:15 -0800153 self.process.stdout.close()
154 if self.process.stderr:
155 self.process.stderr.close()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500156
157 self.log.debug("Command '%s' returned %d as exit code." % (self.cmd, self.status))
158 # logging the complete output is insane
159 # bitbake -e output is really big
160 # and makes the log file useless
161 if self.status:
162 lout = "\n".join(self.output.splitlines()[-20:])
163 self.log.debug("Last 20 lines:\n%s" % lout)
164
165
166class Result(object):
167 pass
168
169
Andrew Geissler4c19ea12020-10-27 13:52:24 -0500170def runCmd(command, ignore_status=False, timeout=None, assert_error=True, sync=True,
Patrick Williams92b42cb2022-09-03 06:53:57 -0500171 native_sysroot=None, target_sys=None, limit_exc_output=0, output_log=None, **options):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500172 result = Result()
173
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500174 if native_sysroot:
Patrick Williams92b42cb2022-09-03 06:53:57 -0500175 new_env = dict(options.get('env', os.environ))
176 paths = new_env["PATH"].split(":")
177 paths = [
178 os.path.join(native_sysroot, "bin"),
179 os.path.join(native_sysroot, "sbin"),
180 os.path.join(native_sysroot, "usr", "bin"),
181 os.path.join(native_sysroot, "usr", "sbin"),
182 ] + paths
183 if target_sys:
184 paths = [os.path.join(native_sysroot, "usr", "bin", target_sys)] + paths
185 new_env["PATH"] = ":".join(paths)
186 options['env'] = new_env
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500187
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500188 cmd = Command(command, timeout=timeout, output_log=output_log, **options)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500189 cmd.run()
190
Andrew Geissler4c19ea12020-10-27 13:52:24 -0500191 # tests can be heavy on IO and if bitbake can't write out its caches, we see timeouts.
192 # call sync around the tests to ensure the IO queue doesn't get too large, taking any IO
193 # hit here rather than in bitbake shutdown.
194 if sync:
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600195 p = os.environ['PATH']
196 os.environ['PATH'] = "/usr/bin:/bin:/usr/sbin:/sbin:" + p
Andrew Geissler4c19ea12020-10-27 13:52:24 -0500197 os.system("sync")
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600198 os.environ['PATH'] = p
Andrew Geissler4c19ea12020-10-27 13:52:24 -0500199
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500200 result.command = command
201 result.status = cmd.status
202 result.output = cmd.output
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600203 result.error = cmd.error
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500204 result.pid = cmd.process.pid
205
206 if result.status and not ignore_status:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500207 exc_output = result.output
208 if limit_exc_output > 0:
209 split = result.output.splitlines()
210 if len(split) > limit_exc_output:
211 exc_output = "\n... (last %d lines of output)\n" % limit_exc_output + \
212 '\n'.join(split[-limit_exc_output:])
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500213 if assert_error:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500214 raise AssertionError("Command '%s' returned non-zero exit status %d:\n%s" % (command, result.status, exc_output))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500215 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500216 raise CommandError(result.status, command, exc_output)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500217
218 return result
219
220
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500221def bitbake(command, ignore_status=False, timeout=None, postconfig=None, output_log=None, **options):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500222
223 if postconfig:
224 postconfig_file = os.path.join(os.environ.get('BUILDDIR'), 'oeqa-post.conf')
225 ftools.write_file(postconfig_file, postconfig)
226 extra_args = "-R %s" % postconfig_file
227 else:
228 extra_args = ""
229
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600230 if isinstance(command, str):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500231 cmd = "bitbake " + extra_args + " " + command
232 else:
233 cmd = [ "bitbake" ] + [a for a in (command + extra_args.split(" ")) if a not in [""]]
234
235 try:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500236 return runCmd(cmd, ignore_status, timeout, output_log=output_log, **options)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500237 finally:
238 if postconfig:
239 os.remove(postconfig_file)
240
241
242def get_bb_env(target=None, postconfig=None):
243 if target:
244 return bitbake("-e %s" % target, postconfig=postconfig).output
245 else:
246 return bitbake("-e", postconfig=postconfig).output
247
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600248def get_bb_vars(variables=None, target=None, postconfig=None):
249 """Get values of multiple bitbake variables"""
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500250 bbenv = get_bb_env(target, postconfig=postconfig)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600251
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500252 if variables is not None:
Brad Bishop316dfdd2018-06-25 12:45:53 -0400253 variables = list(variables)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500254 var_re = re.compile(r'^(export )?(?P<var>\w+(_.*)?)="(?P<value>.*)"$')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600255 unset_re = re.compile(r'^unset (?P<var>\w+)$')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500256 lastline = None
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600257 values = {}
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500258 for line in bbenv.splitlines():
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600259 match = var_re.match(line)
260 val = None
261 if match:
262 val = match.group('value')
263 else:
264 match = unset_re.match(line)
265 if match:
266 # Handle [unexport] variables
267 if lastline.startswith('# "'):
268 val = lastline.split('"')[1]
269 if val:
270 var = match.group('var')
271 if variables is None:
272 values[var] = val
273 else:
274 if var in variables:
275 values[var] = val
276 variables.remove(var)
277 # Stop after all required variables have been found
278 if not variables:
279 break
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500280 lastline = line
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600281 if variables:
282 # Fill in missing values
283 for var in variables:
284 values[var] = None
285 return values
286
287def get_bb_var(var, target=None, postconfig=None):
288 return get_bb_vars([var], target, postconfig)[var]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500289
290def get_test_layer():
291 layers = get_bb_var("BBLAYERS").split()
292 testlayer = None
293 for l in layers:
294 if '~' in l:
295 l = os.path.expanduser(l)
296 if "/meta-selftest" in l and os.path.isdir(l):
297 testlayer = l
298 break
299 return testlayer
300
301def create_temp_layer(templayerdir, templayername, priority=999, recipepathspec='recipes-*/*'):
302 os.makedirs(os.path.join(templayerdir, 'conf'))
Andrew Geissler517393d2023-01-13 08:55:19 -0600303 corenames = get_bb_var('LAYERSERIES_CORENAMES')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500304 with open(os.path.join(templayerdir, 'conf', 'layer.conf'), 'w') as f:
305 f.write('BBPATH .= ":${LAYERDIR}"\n')
306 f.write('BBFILES += "${LAYERDIR}/%s/*.bb \\' % recipepathspec)
307 f.write(' ${LAYERDIR}/%s/*.bbappend"\n' % recipepathspec)
308 f.write('BBFILE_COLLECTIONS += "%s"\n' % templayername)
309 f.write('BBFILE_PATTERN_%s = "^${LAYERDIR}/"\n' % templayername)
310 f.write('BBFILE_PRIORITY_%s = "%d"\n' % (templayername, priority))
311 f.write('BBFILE_PATTERN_IGNORE_EMPTY_%s = "1"\n' % templayername)
Andrew Geissler517393d2023-01-13 08:55:19 -0600312 f.write('LAYERSERIES_COMPAT_%s = "%s"\n' % (templayername, corenames))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500313
314@contextlib.contextmanager
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500315def runqemu(pn, ssh=True, runqemuparams='', image_fstype=None, launch_cmd=None, qemuparams=None, overrides={}, discard_writes=True):
316 """
317 launch_cmd means directly run the command, don't need set rootfs or env vars.
318 """
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500319
320 import bb.tinfoil
321 import bb.build
322
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500323 # Need a non-'BitBake' logger to capture the runner output
324 targetlogger = logging.getLogger('TargetRunner')
325 targetlogger.setLevel(logging.DEBUG)
326 handler = logging.StreamHandler(sys.stdout)
327 targetlogger.addHandler(handler)
328
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500329 tinfoil = bb.tinfoil.Tinfoil()
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500330 tinfoil.prepare(config_only=False, quiet=True)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500331 try:
332 tinfoil.logger.setLevel(logging.WARNING)
333 import oeqa.targetcontrol
Andrew Geissler82c905d2020-04-13 13:39:40 -0500334 recipedata = tinfoil.parse_recipe(pn)
335 recipedata.setVar("TEST_LOG_DIR", "${WORKDIR}/testimage")
336 recipedata.setVar("TEST_QEMUBOOT_TIMEOUT", "1000")
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500337 # Tell QemuTarget() whether need find rootfs/kernel or not
338 if launch_cmd:
Andrew Geissler82c905d2020-04-13 13:39:40 -0500339 recipedata.setVar("FIND_ROOTFS", '0')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500340 else:
Andrew Geissler82c905d2020-04-13 13:39:40 -0500341 recipedata.setVar("FIND_ROOTFS", '1')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500342
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500343 for key, value in overrides.items():
344 recipedata.setVar(key, value)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500345
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500346 logdir = recipedata.getVar("TEST_LOG_DIR")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500347
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500348 qemu = oeqa.targetcontrol.QemuTarget(recipedata, targetlogger, image_fstype)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500349 finally:
350 # We need to shut down tinfoil early here in case we actually want
351 # to run tinfoil-using utilities with the running QEMU instance.
352 # Luckily QemuTarget doesn't need it after the constructor.
353 tinfoil.shutdown()
354
355 try:
356 qemu.deploy()
357 try:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500358 qemu.start(params=qemuparams, ssh=ssh, runqemuparams=runqemuparams, launch_cmd=launch_cmd, discard_writes=discard_writes)
Brad Bishop79641f22019-09-10 07:20:22 -0400359 except Exception as e:
Brad Bishop08902b02019-08-20 09:16:51 -0400360 msg = str(e) + '\nFailed to start QEMU - see the logs in %s' % logdir
Brad Bishopf86d0552018-12-04 14:18:15 -0800361 if os.path.exists(qemu.qemurunnerlog):
362 with open(qemu.qemurunnerlog, 'r') as f:
363 msg = msg + "Qemurunner log output from %s:\n%s" % (qemu.qemurunnerlog, f.read())
364 raise Exception(msg)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500365
366 yield qemu
367
368 finally:
Brad Bishopf86d0552018-12-04 14:18:15 -0800369 targetlogger.removeHandler(handler)
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500370 qemu.stop()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600371
372def updateEnv(env_file):
373 """
374 Source a file and update environment.
375 """
376
377 cmd = ". %s; env -0" % env_file
378 result = runCmd(cmd)
379
380 for line in result.output.split("\0"):
381 (key, _, value) = line.partition("=")
382 os.environ[key] = value