blob: 2e6a2289cd988a78ee4c77171d136ce42ad35a1e [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001# Copyright (c) 2013-2014 Intel Corporation
2#
3# Released under the MIT license (see COPYING.MIT)
4
5# DESCRIPTION
6# This module is mainly used by scripts/oe-selftest and modules under meta/oeqa/selftest
7# It provides a class and methods for running commands on the host in a convienent way for tests.
8
9
10
11import os
12import sys
13import signal
14import subprocess
15import threading
Brad Bishopd7bf8c12018-02-25 22:55:05 -050016import time
Patrick Williamsc124f4f2015-09-15 14:41:29 -050017import logging
18from oeqa.utils import CommandError
19from oeqa.utils import ftools
20import re
21import contextlib
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050022# Export test doesn't require bb
23try:
24 import bb
25except ImportError:
26 pass
Patrick Williamsc124f4f2015-09-15 14:41:29 -050027
28class Command(object):
Brad Bishopd7bf8c12018-02-25 22:55:05 -050029 def __init__(self, command, bg=False, timeout=None, data=None, output_log=None, **options):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050030
31 self.defaultopts = {
32 "stdout": subprocess.PIPE,
33 "stderr": subprocess.STDOUT,
34 "stdin": None,
35 "shell": False,
36 "bufsize": -1,
37 }
38
39 self.cmd = command
40 self.bg = bg
41 self.timeout = timeout
42 self.data = data
43
44 self.options = dict(self.defaultopts)
Patrick Williamsc0f7c042017-02-23 20:41:17 -060045 if isinstance(self.cmd, str):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050046 self.options["shell"] = True
47 if self.data:
48 self.options['stdin'] = subprocess.PIPE
49 self.options.update(options)
50
51 self.status = None
Brad Bishopd7bf8c12018-02-25 22:55:05 -050052 # We collect chunks of output before joining them at the end.
53 self._output_chunks = []
54 self._error_chunks = []
Patrick Williamsc124f4f2015-09-15 14:41:29 -050055 self.output = None
56 self.error = None
Brad Bishopd7bf8c12018-02-25 22:55:05 -050057 self.threads = []
Patrick Williamsc124f4f2015-09-15 14:41:29 -050058
Brad Bishopd7bf8c12018-02-25 22:55:05 -050059 self.output_log = output_log
Patrick Williamsc124f4f2015-09-15 14:41:29 -050060 self.log = logging.getLogger("utils.commands")
61
62 def run(self):
63 self.process = subprocess.Popen(self.cmd, **self.options)
64
Brad Bishopd7bf8c12018-02-25 22:55:05 -050065 def readThread(output, stream, logfunc):
66 if logfunc:
67 for line in stream:
68 output.append(line)
69 logfunc(line.decode("utf-8", errors='replace').rstrip())
70 else:
71 output.append(stream.read())
Patrick Williamsc124f4f2015-09-15 14:41:29 -050072
Brad Bishopd7bf8c12018-02-25 22:55:05 -050073 def readStderrThread():
74 readThread(self._error_chunks, self.process.stderr, self.output_log.error if self.output_log else None)
75
76 def readStdoutThread():
77 readThread(self._output_chunks, self.process.stdout, self.output_log.info if self.output_log else None)
78
79 def writeThread():
80 try:
81 self.process.stdin.write(self.data)
82 self.process.stdin.close()
83 except OSError as ex:
84 # It's not an error when the command does not consume all
85 # of our data. subprocess.communicate() also ignores that.
86 if ex.errno != EPIPE:
87 raise
88
89 # We write in a separate thread because then we can read
90 # without worrying about deadlocks. The additional thread is
91 # expected to terminate by itself and we mark it as a daemon,
92 # so even it should happen to not terminate for whatever
93 # reason, the main process will still exit, which will then
94 # kill the write thread.
95 if self.data:
96 threading.Thread(target=writeThread, daemon=True).start()
97 if self.process.stderr:
98 thread = threading.Thread(target=readStderrThread)
99 thread.start()
100 self.threads.append(thread)
101 if self.output_log:
102 self.output_log.info('Running: %s' % self.cmd)
103 thread = threading.Thread(target=readStdoutThread)
104 thread.start()
105 self.threads.append(thread)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500106
107 self.log.debug("Running command '%s'" % self.cmd)
108
109 if not self.bg:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500110 if self.timeout is None:
111 for thread in self.threads:
112 thread.join()
113 else:
114 deadline = time.time() + self.timeout
115 for thread in self.threads:
116 timeout = deadline - time.time()
117 if timeout < 0:
118 timeout = 0
119 thread.join(timeout)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500120 self.stop()
121
122 def stop(self):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500123 for thread in self.threads:
124 if thread.isAlive():
125 self.process.terminate()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500126 # let's give it more time to terminate gracefully before killing it
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500127 thread.join(5)
128 if thread.isAlive():
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500129 self.process.kill()
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500130 thread.join()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500131
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500132 def finalize_output(data):
133 if not data:
134 data = ""
135 else:
136 data = b"".join(data)
137 data = data.decode("utf-8", errors='replace').rstrip()
138 return data
139
140 self.output = finalize_output(self._output_chunks)
141 self._output_chunks = None
142 # self.error used to be a byte string earlier, probably unintentionally.
143 # Now it is a normal string, just like self.output.
144 self.error = finalize_output(self._error_chunks)
145 self._error_chunks = None
146 # At this point we know that the process has closed stdout/stderr, so
147 # it is safe and necessary to wait for the actual process completion.
148 self.status = self.process.wait()
Brad Bishopf86d0552018-12-04 14:18:15 -0800149 self.process.stdout.close()
150 if self.process.stderr:
151 self.process.stderr.close()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500152
153 self.log.debug("Command '%s' returned %d as exit code." % (self.cmd, self.status))
154 # logging the complete output is insane
155 # bitbake -e output is really big
156 # and makes the log file useless
157 if self.status:
158 lout = "\n".join(self.output.splitlines()[-20:])
159 self.log.debug("Last 20 lines:\n%s" % lout)
160
161
162class Result(object):
163 pass
164
165
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500166def runCmd(command, ignore_status=False, timeout=None, assert_error=True,
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500167 native_sysroot=None, limit_exc_output=0, output_log=None, **options):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500168 result = Result()
169
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500170 if native_sysroot:
171 extra_paths = "%s/sbin:%s/usr/sbin:%s/usr/bin" % \
172 (native_sysroot, native_sysroot, native_sysroot)
173 nenv = dict(options.get('env', os.environ))
174 nenv['PATH'] = extra_paths + ':' + nenv.get('PATH', '')
175 options['env'] = nenv
176
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500177 cmd = Command(command, timeout=timeout, output_log=output_log, **options)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500178 cmd.run()
179
180 result.command = command
181 result.status = cmd.status
182 result.output = cmd.output
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600183 result.error = cmd.error
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500184 result.pid = cmd.process.pid
185
186 if result.status and not ignore_status:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500187 exc_output = result.output
188 if limit_exc_output > 0:
189 split = result.output.splitlines()
190 if len(split) > limit_exc_output:
191 exc_output = "\n... (last %d lines of output)\n" % limit_exc_output + \
192 '\n'.join(split[-limit_exc_output:])
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500193 if assert_error:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500194 raise AssertionError("Command '%s' returned non-zero exit status %d:\n%s" % (command, result.status, exc_output))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500195 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500196 raise CommandError(result.status, command, exc_output)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500197
198 return result
199
200
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500201def bitbake(command, ignore_status=False, timeout=None, postconfig=None, output_log=None, **options):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500202
203 if postconfig:
204 postconfig_file = os.path.join(os.environ.get('BUILDDIR'), 'oeqa-post.conf')
205 ftools.write_file(postconfig_file, postconfig)
206 extra_args = "-R %s" % postconfig_file
207 else:
208 extra_args = ""
209
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600210 if isinstance(command, str):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500211 cmd = "bitbake " + extra_args + " " + command
212 else:
213 cmd = [ "bitbake" ] + [a for a in (command + extra_args.split(" ")) if a not in [""]]
214
215 try:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500216 return runCmd(cmd, ignore_status, timeout, output_log=output_log, **options)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500217 finally:
218 if postconfig:
219 os.remove(postconfig_file)
220
221
222def get_bb_env(target=None, postconfig=None):
223 if target:
224 return bitbake("-e %s" % target, postconfig=postconfig).output
225 else:
226 return bitbake("-e", postconfig=postconfig).output
227
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600228def get_bb_vars(variables=None, target=None, postconfig=None):
229 """Get values of multiple bitbake variables"""
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500230 bbenv = get_bb_env(target, postconfig=postconfig)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600231
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500232 if variables is not None:
Brad Bishop316dfdd2018-06-25 12:45:53 -0400233 variables = list(variables)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500234 var_re = re.compile(r'^(export )?(?P<var>\w+(_.*)?)="(?P<value>.*)"$')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600235 unset_re = re.compile(r'^unset (?P<var>\w+)$')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500236 lastline = None
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600237 values = {}
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500238 for line in bbenv.splitlines():
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600239 match = var_re.match(line)
240 val = None
241 if match:
242 val = match.group('value')
243 else:
244 match = unset_re.match(line)
245 if match:
246 # Handle [unexport] variables
247 if lastline.startswith('# "'):
248 val = lastline.split('"')[1]
249 if val:
250 var = match.group('var')
251 if variables is None:
252 values[var] = val
253 else:
254 if var in variables:
255 values[var] = val
256 variables.remove(var)
257 # Stop after all required variables have been found
258 if not variables:
259 break
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500260 lastline = line
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600261 if variables:
262 # Fill in missing values
263 for var in variables:
264 values[var] = None
265 return values
266
267def get_bb_var(var, target=None, postconfig=None):
268 return get_bb_vars([var], target, postconfig)[var]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500269
270def get_test_layer():
271 layers = get_bb_var("BBLAYERS").split()
272 testlayer = None
273 for l in layers:
274 if '~' in l:
275 l = os.path.expanduser(l)
276 if "/meta-selftest" in l and os.path.isdir(l):
277 testlayer = l
278 break
279 return testlayer
280
281def create_temp_layer(templayerdir, templayername, priority=999, recipepathspec='recipes-*/*'):
282 os.makedirs(os.path.join(templayerdir, 'conf'))
283 with open(os.path.join(templayerdir, 'conf', 'layer.conf'), 'w') as f:
284 f.write('BBPATH .= ":${LAYERDIR}"\n')
285 f.write('BBFILES += "${LAYERDIR}/%s/*.bb \\' % recipepathspec)
286 f.write(' ${LAYERDIR}/%s/*.bbappend"\n' % recipepathspec)
287 f.write('BBFILE_COLLECTIONS += "%s"\n' % templayername)
288 f.write('BBFILE_PATTERN_%s = "^${LAYERDIR}/"\n' % templayername)
289 f.write('BBFILE_PRIORITY_%s = "%d"\n' % (templayername, priority))
290 f.write('BBFILE_PATTERN_IGNORE_EMPTY_%s = "1"\n' % templayername)
Brad Bishop316dfdd2018-06-25 12:45:53 -0400291 f.write('LAYERSERIES_COMPAT_%s = "${LAYERSERIES_COMPAT_core}"\n' % templayername)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500292
293@contextlib.contextmanager
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500294def runqemu(pn, ssh=True, runqemuparams='', image_fstype=None, launch_cmd=None, qemuparams=None, overrides={}, discard_writes=True):
295 """
296 launch_cmd means directly run the command, don't need set rootfs or env vars.
297 """
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500298
299 import bb.tinfoil
300 import bb.build
301
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500302 # Need a non-'BitBake' logger to capture the runner output
303 targetlogger = logging.getLogger('TargetRunner')
304 targetlogger.setLevel(logging.DEBUG)
305 handler = logging.StreamHandler(sys.stdout)
306 targetlogger.addHandler(handler)
307
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500308 tinfoil = bb.tinfoil.Tinfoil()
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500309 tinfoil.prepare(config_only=False, quiet=True)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500310 try:
311 tinfoil.logger.setLevel(logging.WARNING)
312 import oeqa.targetcontrol
313 tinfoil.config_data.setVar("TEST_LOG_DIR", "${WORKDIR}/testimage")
314 tinfoil.config_data.setVar("TEST_QEMUBOOT_TIMEOUT", "1000")
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500315 # Tell QemuTarget() whether need find rootfs/kernel or not
316 if launch_cmd:
317 tinfoil.config_data.setVar("FIND_ROOTFS", '0')
318 else:
319 tinfoil.config_data.setVar("FIND_ROOTFS", '1')
320
321 recipedata = tinfoil.parse_recipe(pn)
322 for key, value in overrides.items():
323 recipedata.setVar(key, value)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500324
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500325 logdir = recipedata.getVar("TEST_LOG_DIR")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500326
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500327 qemu = oeqa.targetcontrol.QemuTarget(recipedata, targetlogger, image_fstype)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500328 finally:
329 # We need to shut down tinfoil early here in case we actually want
330 # to run tinfoil-using utilities with the running QEMU instance.
331 # Luckily QemuTarget doesn't need it after the constructor.
332 tinfoil.shutdown()
333
334 try:
335 qemu.deploy()
336 try:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500337 qemu.start(params=qemuparams, ssh=ssh, runqemuparams=runqemuparams, launch_cmd=launch_cmd, discard_writes=discard_writes)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500338 except bb.build.FuncFailed:
Brad Bishopf86d0552018-12-04 14:18:15 -0800339 msg = 'Failed to start QEMU - see the logs in %s' % logdir
340 if os.path.exists(qemu.qemurunnerlog):
341 with open(qemu.qemurunnerlog, 'r') as f:
342 msg = msg + "Qemurunner log output from %s:\n%s" % (qemu.qemurunnerlog, f.read())
343 raise Exception(msg)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500344
345 yield qemu
346
347 finally:
Brad Bishopf86d0552018-12-04 14:18:15 -0800348 targetlogger.removeHandler(handler)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500349 try:
350 qemu.stop()
351 except:
352 pass
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600353
354def updateEnv(env_file):
355 """
356 Source a file and update environment.
357 """
358
359 cmd = ". %s; env -0" % env_file
360 result = runCmd(cmd)
361
362 for line in result.output.split("\0"):
363 (key, _, value) = line.partition("=")
364 os.environ[key] = value