blob: fd386ef5a20a5215d36b53f52ebcaf837068a0b1 [file] [log] [blame]
Brad Bishopc342db32019-05-15 21:57:59 -04001#
Patrick Williamsc124f4f2015-09-15 14:41:29 -05002# Copyright (C) 2013 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# This module provides a class for starting qemu images using runqemu.
8# It's used by testimage.bbclass.
9
10import subprocess
11import os
Brad Bishop6e60e8b2018-02-01 10:27:11 -050012import sys
Patrick Williamsc124f4f2015-09-15 14:41:29 -050013import time
14import signal
15import re
16import socket
17import select
18import errno
Patrick Williamsf1e5d692016-03-30 15:21:19 -050019import string
Patrick Williamsc124f4f2015-09-15 14:41:29 -050020import threading
Patrick Williamsf1e5d692016-03-30 15:21:19 -050021import codecs
Patrick Williamsc124f4f2015-09-15 14:41:29 -050022import logging
Brad Bishopd7bf8c12018-02-25 22:55:05 -050023from oeqa.utils.dump import HostDumper
Patrick Williamsc124f4f2015-09-15 14:41:29 -050024
Patrick Williamsf1e5d692016-03-30 15:21:19 -050025# Get Unicode non printable control chars
Patrick Williamsc0f7c042017-02-23 20:41:17 -060026control_range = list(range(0,32))+list(range(127,160))
27control_chars = [chr(x) for x in control_range
28 if chr(x) not in string.printable]
Patrick Williamsf1e5d692016-03-30 15:21:19 -050029re_control_char = re.compile('[%s]' % re.escape("".join(control_chars)))
30
Patrick Williamsc124f4f2015-09-15 14:41:29 -050031class QemuRunner:
32
Brad Bishop19323692019-04-05 15:28:33 -040033 def __init__(self, machine, rootfs, display, tmpdir, deploy_dir_image, logfile, boottime, dump_dir, dump_host_cmds,
34 use_kvm, logger, use_slirp=False):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050035
36 # Popen object for runqemu
37 self.runqemu = None
38 # pid of the qemu process that runqemu will start
39 self.qemupid = None
Brad Bishop6e60e8b2018-02-01 10:27:11 -050040 # target ip - from the command line or runqemu output
Patrick Williamsc124f4f2015-09-15 14:41:29 -050041 self.ip = None
42 # host ip - where qemu is running
43 self.server_ip = None
Brad Bishop6e60e8b2018-02-01 10:27:11 -050044 # target ip netmask
45 self.netmask = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -050046
47 self.machine = machine
48 self.rootfs = rootfs
49 self.display = display
50 self.tmpdir = tmpdir
51 self.deploy_dir_image = deploy_dir_image
52 self.logfile = logfile
53 self.boottime = boottime
54 self.logged = False
55 self.thread = None
Patrick Williamsc0f7c042017-02-23 20:41:17 -060056 self.use_kvm = use_kvm
Brad Bishop19323692019-04-05 15:28:33 -040057 self.use_slirp = use_slirp
Brad Bishopd7bf8c12018-02-25 22:55:05 -050058 self.msg = ''
Patrick Williamsc124f4f2015-09-15 14:41:29 -050059
Brad Bishopd7bf8c12018-02-25 22:55:05 -050060 self.runqemutime = 120
61 self.qemu_pidfile = 'pidfile_'+str(os.getpid())
Patrick Williamsc124f4f2015-09-15 14:41:29 -050062 self.host_dumper = HostDumper(dump_host_cmds, dump_dir)
63
Brad Bishopd7bf8c12018-02-25 22:55:05 -050064 self.logger = logger
65
Patrick Williamsc124f4f2015-09-15 14:41:29 -050066 def create_socket(self):
67 try:
68 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
69 sock.setblocking(0)
70 sock.bind(("127.0.0.1",0))
71 sock.listen(2)
72 port = sock.getsockname()[1]
Brad Bishopd7bf8c12018-02-25 22:55:05 -050073 self.logger.debug("Created listening socket for qemu serial console on: 127.0.0.1:%s" % port)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050074 return (sock, port)
75
76 except socket.error:
77 sock.close()
78 raise
79
80 def log(self, msg):
81 if self.logfile:
Patrick Williamsf1e5d692016-03-30 15:21:19 -050082 # It is needed to sanitize the data received from qemu
83 # because is possible to have control characters
Brad Bishop6e60e8b2018-02-01 10:27:11 -050084 msg = msg.decode("utf-8", errors='ignore')
Patrick Williamsc0f7c042017-02-23 20:41:17 -060085 msg = re_control_char.sub('', msg)
Brad Bishopd7bf8c12018-02-25 22:55:05 -050086 self.msg += msg
Patrick Williamsf1e5d692016-03-30 15:21:19 -050087 with codecs.open(self.logfile, "a", encoding="utf-8") as f:
Patrick Williamsc124f4f2015-09-15 14:41:29 -050088 f.write("%s" % msg)
89
90 def getOutput(self, o):
91 import fcntl
92 fl = fcntl.fcntl(o, fcntl.F_GETFL)
93 fcntl.fcntl(o, fcntl.F_SETFL, fl | os.O_NONBLOCK)
Patrick Williamsc0f7c042017-02-23 20:41:17 -060094 return os.read(o.fileno(), 1000000).decode("utf-8")
Patrick Williamsc124f4f2015-09-15 14:41:29 -050095
96
97 def handleSIGCHLD(self, signum, frame):
98 if self.runqemu and self.runqemu.poll():
99 if self.runqemu.returncode:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500100 self.logger.debug('runqemu exited with code %d' % self.runqemu.returncode)
101 self.logger.debug("Output from runqemu:\n%s" % self.getOutput(self.runqemu.stdout))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500102 self.stop()
103 self._dump_host()
104 raise SystemExit
105
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500106 def start(self, qemuparams = None, get_ip = True, extra_bootparams = None, runqemuparams='', launch_cmd=None, discard_writes=True):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500107 env = os.environ.copy()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500108 if self.display:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500109 env["DISPLAY"] = self.display
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500110 # Set this flag so that Qemu doesn't do any grabs as SDL grabs
111 # interact badly with screensavers.
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500112 env["QEMU_DONT_GRAB"] = "1"
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500113 if not os.path.exists(self.rootfs):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500114 self.logger.error("Invalid rootfs %s" % self.rootfs)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500115 return False
116 if not os.path.exists(self.tmpdir):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500117 self.logger.error("Invalid TMPDIR path %s" % self.tmpdir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500118 return False
119 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500120 env["OE_TMPDIR"] = self.tmpdir
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500121 if not os.path.exists(self.deploy_dir_image):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500122 self.logger.error("Invalid DEPLOY_DIR_IMAGE path %s" % self.deploy_dir_image)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500123 return False
124 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500125 env["DEPLOY_DIR_IMAGE"] = self.deploy_dir_image
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500126
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500127 if not launch_cmd:
128 launch_cmd = 'runqemu %s %s ' % ('snapshot' if discard_writes else '', runqemuparams)
129 if self.use_kvm:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500130 self.logger.debug('Using kvm for runqemu')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500131 launch_cmd += ' kvm'
132 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500133 self.logger.debug('Not using kvm for runqemu')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500134 if not self.display:
135 launch_cmd += ' nographic'
Brad Bishop19323692019-04-05 15:28:33 -0400136 if self.use_slirp:
137 launch_cmd += ' slirp'
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500138 launch_cmd += ' %s %s' % (self.machine, self.rootfs)
139
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500140 return self.launch(launch_cmd, qemuparams=qemuparams, get_ip=get_ip, extra_bootparams=extra_bootparams, env=env)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500141
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500142 def launch(self, launch_cmd, get_ip = True, qemuparams = None, extra_bootparams = None, env = None):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500143 try:
Brad Bishopf86d0552018-12-04 14:18:15 -0800144 self.threadsock, threadport = self.create_socket()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500145 self.server_socket, self.serverport = self.create_socket()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600146 except socket.error as msg:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500147 self.logger.error("Failed to create listening socket: %s" % msg[1])
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500148 return False
149
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600150 bootparams = 'console=tty1 console=ttyS0,115200n8 printk.time=1'
151 if extra_bootparams:
152 bootparams = bootparams + ' ' + extra_bootparams
153
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500154 # Ask QEMU to store the QEMU process PID in file, this way we don't have to parse running processes
155 # and analyze descendents in order to determine it.
156 if os.path.exists(self.qemu_pidfile):
157 os.remove(self.qemu_pidfile)
158 self.qemuparams = 'bootparams="{0}" qemuparams="-serial tcp:127.0.0.1:{1} -pidfile {2}"'.format(bootparams, threadport, self.qemu_pidfile)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500159 if qemuparams:
160 self.qemuparams = self.qemuparams[:-1] + " " + qemuparams + " " + '\"'
161
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500162 launch_cmd += ' tcpserial=%s %s' % (self.serverport, self.qemuparams)
163
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500164 self.origchldhandler = signal.getsignal(signal.SIGCHLD)
165 signal.signal(signal.SIGCHLD, self.handleSIGCHLD)
166
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500167 self.logger.debug('launchcmd=%s'%(launch_cmd))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600168
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500169 # FIXME: We pass in stdin=subprocess.PIPE here to work around stty
170 # blocking at the end of the runqemu script when using this within
171 # oe-selftest (this makes stty error out immediately). There ought
172 # to be a proper fix but this will suffice for now.
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500173 self.runqemu = subprocess.Popen(launch_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, preexec_fn=os.setpgrp, env=env)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500174 output = self.runqemu.stdout
175
176 #
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600177 # We need the preexec_fn above so that all runqemu processes can easily be killed
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500178 # (by killing their process group). This presents a problem if this controlling
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600179 # process itself is killed however since those processes don't notice the death
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500180 # of the parent and merrily continue on.
181 #
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600182 # Rather than hack runqemu to deal with this, we add something here instead.
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500183 # Basically we fork off another process which holds an open pipe to the parent
184 # and also is setpgrp. If/when the pipe sees EOF from the parent dieing, it kills
185 # the process group. This is like pctrl's PDEATHSIG but for a process group
186 # rather than a single process.
187 #
188 r, w = os.pipe()
189 self.monitorpid = os.fork()
190 if self.monitorpid:
191 os.close(r)
192 self.monitorpipe = os.fdopen(w, "w")
193 else:
194 # child process
195 os.setpgrp()
196 os.close(w)
197 r = os.fdopen(r)
198 x = r.read()
199 os.killpg(os.getpgid(self.runqemu.pid), signal.SIGTERM)
200 sys.exit(0)
201
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500202 self.logger.debug("runqemu started, pid is %s" % self.runqemu.pid)
Brad Bishop316dfdd2018-06-25 12:45:53 -0400203 self.logger.debug("waiting at most %s seconds for qemu pid (%s)" %
204 (self.runqemutime, time.strftime("%D %H:%M:%S")))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500205 endtime = time.time() + self.runqemutime
206 while not self.is_alive() and time.time() < endtime:
207 if self.runqemu.poll():
208 if self.runqemu.returncode:
209 # No point waiting any longer
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500210 self.logger.debug('runqemu exited with code %d' % self.runqemu.returncode)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500211 self._dump_host()
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500212 self.logger.debug("Output from runqemu:\n%s" % self.getOutput(output))
Brad Bishopf86d0552018-12-04 14:18:15 -0800213 self.stop()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500214 return False
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500215 time.sleep(0.5)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500216
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500217 if not self.is_alive():
Brad Bishop316dfdd2018-06-25 12:45:53 -0400218 self.logger.error("Qemu pid didn't appear in %s seconds (%s)" %
219 (self.runqemutime, time.strftime("%D %H:%M:%S")))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500220 # Dump all processes to help us to figure out what is going on...
221 ps = subprocess.Popen(['ps', 'axww', '-o', 'pid,ppid,command '], stdout=subprocess.PIPE).communicate()[0]
222 processes = ps.decode("utf-8")
223 self.logger.debug("Running processes:\n%s" % processes)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500224 self._dump_host()
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500225 op = self.getOutput(output)
Brad Bishopf86d0552018-12-04 14:18:15 -0800226 self.stop()
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500227 if op:
228 self.logger.error("Output from runqemu:\n%s" % op)
229 else:
230 self.logger.error("No output from runqemu.\n")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500231 return False
232
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500233 # We are alive: qemu is running
234 out = self.getOutput(output)
235 netconf = False # network configuration is not required by default
Brad Bishop316dfdd2018-06-25 12:45:53 -0400236 self.logger.debug("qemu started in %s seconds - qemu procces pid is %s (%s)" %
237 (time.time() - (endtime - self.runqemutime),
238 self.qemupid, time.strftime("%D %H:%M:%S")))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500239 if get_ip:
240 cmdline = ''
241 with open('/proc/%s/cmdline' % self.qemupid) as p:
242 cmdline = p.read()
243 # It is needed to sanitize the data received
244 # because is possible to have control characters
245 cmdline = re_control_char.sub(' ', cmdline)
246 try:
Brad Bishop19323692019-04-05 15:28:33 -0400247 if self.use_slirp:
248 tcp_ports = cmdline.split("hostfwd=tcp::")[1]
249 host_port = tcp_ports[:tcp_ports.find('-')]
250 self.ip = "localhost:%s" % host_port
251 else:
252 ips = re.findall(r"((?:[0-9]{1,3}\.){3}[0-9]{1,3})", cmdline.split("ip=")[1])
253 self.ip = ips[0]
254 self.server_ip = ips[1]
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500255 self.logger.debug("qemu cmdline used:\n{}".format(cmdline))
256 except (IndexError, ValueError):
257 # Try to get network configuration from runqemu output
Brad Bishopf86d0552018-12-04 14:18:15 -0800258 match = re.match(r'.*Network configuration: ([0-9.]+)::([0-9.]+):([0-9.]+)$.*',
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500259 out, re.MULTILINE|re.DOTALL)
260 if match:
261 self.ip, self.server_ip, self.netmask = match.groups()
262 # network configuration is required as we couldn't get it
263 # from the runqemu command line, so qemu doesn't run kernel
264 # and guest networking is not configured
265 netconf = True
266 else:
267 self.logger.error("Couldn't get ip from qemu command line and runqemu output! "
268 "Here is the qemu command line used:\n%s\n"
269 "and output from runqemu:\n%s" % (cmdline, out))
270 self._dump_host()
271 self.stop()
272 return False
273
274 self.logger.debug("Target IP: %s" % self.ip)
275 self.logger.debug("Server IP: %s" % self.server_ip)
276
Brad Bishopf86d0552018-12-04 14:18:15 -0800277 self.thread = LoggingThread(self.log, self.threadsock, self.logger)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500278 self.thread.start()
279 if not self.thread.connection_established.wait(self.boottime):
280 self.logger.error("Didn't receive a console connection from qemu. "
281 "Here is the qemu command line used:\n%s\nand "
282 "output from runqemu:\n%s" % (cmdline, out))
283 self.stop_thread()
284 return False
285
286 self.logger.debug("Output from runqemu:\n%s", out)
Brad Bishop316dfdd2018-06-25 12:45:53 -0400287 self.logger.debug("Waiting at most %d seconds for login banner (%s)" %
288 (self.boottime, time.strftime("%D %H:%M:%S")))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500289 endtime = time.time() + self.boottime
290 socklist = [self.server_socket]
291 reachedlogin = False
292 stopread = False
293 qemusock = None
294 bootlog = b''
295 data = b''
296 while time.time() < endtime and not stopread:
297 try:
298 sread, swrite, serror = select.select(socklist, [], [], 5)
299 except InterruptedError:
300 continue
301 for sock in sread:
302 if sock is self.server_socket:
303 qemusock, addr = self.server_socket.accept()
304 qemusock.setblocking(0)
305 socklist.append(qemusock)
306 socklist.remove(self.server_socket)
307 self.logger.debug("Connection from %s:%s" % addr)
308 else:
309 data = data + sock.recv(1024)
310 if data:
311 bootlog += data
312 data = b''
313 if b' login:' in bootlog:
314 self.server_socket = qemusock
315 stopread = True
316 reachedlogin = True
Brad Bishop316dfdd2018-06-25 12:45:53 -0400317 self.logger.debug("Reached login banner in %s seconds (%s)" %
318 (time.time() - (endtime - self.boottime),
319 time.strftime("%D %H:%M:%S")))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500320 else:
Brad Bishop316dfdd2018-06-25 12:45:53 -0400321 # no need to check if reachedlogin unless we support multiple connections
322 self.logger.debug("QEMU socket disconnected before login banner reached. (%s)" %
323 time.strftime("%D %H:%M:%S"))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500324 socklist.remove(sock)
325 sock.close()
326 stopread = True
327
328
329 if not reachedlogin:
Brad Bishop316dfdd2018-06-25 12:45:53 -0400330 if time.time() >= endtime:
331 self.logger.debug("Target didn't reach login banner in %d seconds (%s)" %
332 (self.boottime, time.strftime("%D %H:%M:%S")))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500333 tail = lambda l: "\n".join(l.splitlines()[-25:])
Brad Bishopd89cb5f2019-04-10 09:02:41 -0400334 bootlog = bootlog.decode("utf-8")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500335 # in case bootlog is empty, use tail qemu log store at self.msg
336 lines = tail(bootlog if bootlog else self.msg)
337 self.logger.debug("Last 25 lines of text:\n%s" % lines)
338 self.logger.debug("Check full boot log: %s" % self.logfile)
339 self._dump_host()
340 self.stop()
341 return False
342
343 # If we are not able to login the tests can continue
344 try:
345 (status, output) = self.run_serial("root\n", raw=True)
Brad Bishopf86d0552018-12-04 14:18:15 -0800346 if re.search(r"root@[a-zA-Z0-9\-]+:~#", output):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500347 self.logged = True
348 self.logger.debug("Logged as root in serial console")
349 if netconf:
350 # configure guest networking
351 cmd = "ifconfig eth0 %s netmask %s up\n" % (self.ip, self.netmask)
352 output = self.run_serial(cmd, raw=True)[1]
Brad Bishopf86d0552018-12-04 14:18:15 -0800353 if re.search(r"root@[a-zA-Z0-9\-]+:~#", output):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500354 self.logger.debug("configured ip address %s", self.ip)
355 else:
356 self.logger.debug("Couldn't configure guest networking")
357 else:
358 self.logger.debug("Couldn't login into serial console"
359 " as root using blank password")
Brad Bishop977dc1a2019-02-06 16:01:43 -0500360 self.logger.debug("The output:\n%s" % output)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500361 except:
362 self.logger.debug("Serial console failed while trying to login")
363 return True
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500364
365 def stop(self):
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500366 if hasattr(self, "origchldhandler"):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500367 signal.signal(signal.SIGCHLD, self.origchldhandler)
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800368 self.stop_thread()
369 self.stop_qemu_system()
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500370 if self.runqemu:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600371 if hasattr(self, "monitorpid"):
372 os.kill(self.monitorpid, signal.SIGKILL)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500373 self.logger.debug("Sending SIGTERM to runqemu")
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600374 try:
375 os.killpg(os.getpgid(self.runqemu.pid), signal.SIGTERM)
376 except OSError as e:
377 if e.errno != errno.ESRCH:
378 raise
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500379 endtime = time.time() + self.runqemutime
380 while self.runqemu.poll() is None and time.time() < endtime:
381 time.sleep(1)
382 if self.runqemu.poll() is None:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500383 self.logger.debug("Sending SIGKILL to runqemu")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500384 os.killpg(os.getpgid(self.runqemu.pid), signal.SIGKILL)
Brad Bishopf86d0552018-12-04 14:18:15 -0800385 self.runqemu.stdin.close()
386 self.runqemu.stdout.close()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500387 self.runqemu = None
Brad Bishopf86d0552018-12-04 14:18:15 -0800388
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500389 if hasattr(self, 'server_socket') and self.server_socket:
390 self.server_socket.close()
391 self.server_socket = None
Brad Bishopf86d0552018-12-04 14:18:15 -0800392 if hasattr(self, 'threadsock') and self.threadsock:
393 self.threadsock.close()
394 self.threadsock = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500395 self.qemupid = None
396 self.ip = None
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500397 if os.path.exists(self.qemu_pidfile):
398 os.remove(self.qemu_pidfile)
Brad Bishopf86d0552018-12-04 14:18:15 -0800399 if self.monitorpipe:
400 self.monitorpipe.close()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500401
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500402 def stop_qemu_system(self):
403 if self.qemupid:
404 try:
405 # qemu-system behaves well and a SIGTERM is enough
406 os.kill(self.qemupid, signal.SIGTERM)
407 except ProcessLookupError as e:
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800408 self.logger.warning('qemu-system ended unexpectedly')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500409
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500410 def stop_thread(self):
411 if self.thread and self.thread.is_alive():
412 self.thread.stop()
413 self.thread.join()
414
415 def restart(self, qemuparams = None):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500416 self.logger.debug("Restarting qemu process")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500417 if self.runqemu.poll() is None:
418 self.stop()
419 if self.start(qemuparams):
420 return True
421 return False
422
423 def is_alive(self):
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800424 if not self.runqemu or self.runqemu.poll() is not None:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500425 return False
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500426 if os.path.isfile(self.qemu_pidfile):
427 f = open(self.qemu_pidfile, 'r')
428 qemu_pid = f.read()
429 f.close()
430 qemupid = int(qemu_pid)
431 if os.path.exists("/proc/" + str(qemupid)):
432 self.qemupid = qemupid
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500433 return True
434 return False
435
Brad Bishop977dc1a2019-02-06 16:01:43 -0500436 def run_serial(self, command, raw=False, timeout=60):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500437 # We assume target system have echo to get command status
438 if not raw:
439 command = "%s; echo $?\n" % command
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500440
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500441 data = ''
442 status = 0
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600443 self.server_socket.sendall(command.encode('utf-8'))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500444 start = time.time()
445 end = start + timeout
446 while True:
447 now = time.time()
448 if now >= end:
449 data += "<<< run_serial(): command timed out after %d seconds without output >>>\r\n\r\n" % timeout
450 break
451 try:
452 sread, _, _ = select.select([self.server_socket],[],[], end - now)
453 except InterruptedError:
454 continue
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500455 if sread:
456 answer = self.server_socket.recv(1024)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500457 if answer:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600458 data += answer.decode('utf-8')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500459 # Search the prompt to stop
Brad Bishopf86d0552018-12-04 14:18:15 -0800460 if re.search(r"[a-zA-Z0-9]+@[a-zA-Z0-9\-]+:~#", data):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500461 break
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500462 else:
463 raise Exception("No data on serial console socket")
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500464
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500465 if data:
466 if raw:
467 status = 1
468 else:
469 # Remove first line (command line) and last line (prompt)
470 data = data[data.find('$?\r\n')+4:data.rfind('\r\n')]
471 index = data.rfind('\r\n')
472 if index == -1:
473 status_cmd = data
474 data = ""
475 else:
476 status_cmd = data[index+2:]
477 data = data[:index]
478 if (status_cmd == "0"):
479 status = 1
480 return (status, str(data))
481
482
483 def _dump_host(self):
484 self.host_dumper.create_dir("qemu")
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800485 self.logger.warning("Qemu ended unexpectedly, dump data from host"
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500486 " is in %s" % self.host_dumper.dump_dir)
487 self.host_dumper.dump_host()
488
489# This class is for reading data from a socket and passing it to logfunc
490# to be processed. It's completely event driven and has a straightforward
491# event loop. The mechanism for stopping the thread is a simple pipe which
492# will wake up the poll and allow for tearing everything down.
493class LoggingThread(threading.Thread):
494 def __init__(self, logfunc, sock, logger):
495 self.connection_established = threading.Event()
496 self.serversock = sock
497 self.logfunc = logfunc
498 self.logger = logger
499 self.readsock = None
500 self.running = False
501
502 self.errorevents = select.POLLERR | select.POLLHUP | select.POLLNVAL
503 self.readevents = select.POLLIN | select.POLLPRI
504
505 threading.Thread.__init__(self, target=self.threadtarget)
506
507 def threadtarget(self):
508 try:
509 self.eventloop()
510 finally:
511 self.teardown()
512
513 def run(self):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500514 self.logger.debug("Starting logging thread")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500515 self.readpipe, self.writepipe = os.pipe()
516 threading.Thread.run(self)
517
518 def stop(self):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500519 self.logger.debug("Stopping logging thread")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500520 if self.running:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600521 os.write(self.writepipe, bytes("stop", "utf-8"))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500522
523 def teardown(self):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500524 self.logger.debug("Tearing down logging thread")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500525 self.close_socket(self.serversock)
526
527 if self.readsock is not None:
528 self.close_socket(self.readsock)
529
530 self.close_ignore_error(self.readpipe)
531 self.close_ignore_error(self.writepipe)
532 self.running = False
533
534 def eventloop(self):
535 poll = select.poll()
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500536 event_read_mask = self.errorevents | self.readevents
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500537 poll.register(self.serversock.fileno())
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500538 poll.register(self.readpipe, event_read_mask)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500539
540 breakout = False
541 self.running = True
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500542 self.logger.debug("Starting thread event loop")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500543 while not breakout:
544 events = poll.poll()
545 for event in events:
546 # An error occurred, bail out
547 if event[1] & self.errorevents:
548 raise Exception(self.stringify_event(event[1]))
549
550 # Event to stop the thread
551 if self.readpipe == event[0]:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500552 self.logger.debug("Stop event received")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500553 breakout = True
554 break
555
556 # A connection request was received
557 elif self.serversock.fileno() == event[0]:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500558 self.logger.debug("Connection request received")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500559 self.readsock, _ = self.serversock.accept()
560 self.readsock.setblocking(0)
561 poll.unregister(self.serversock.fileno())
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500562 poll.register(self.readsock.fileno(), event_read_mask)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500563
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500564 self.logger.debug("Setting connection established event")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500565 self.connection_established.set()
566
567 # Actual data to be logged
568 elif self.readsock.fileno() == event[0]:
569 data = self.recv(1024)
570 self.logfunc(data)
571
572 # Since the socket is non-blocking make sure to honor EAGAIN
573 # and EWOULDBLOCK.
574 def recv(self, count):
575 try:
576 data = self.readsock.recv(count)
577 except socket.error as e:
578 if e.errno == errno.EAGAIN or e.errno == errno.EWOULDBLOCK:
579 return ''
580 else:
581 raise
582
583 if data is None:
584 raise Exception("No data on read ready socket")
585 elif not data:
586 # This actually means an orderly shutdown
587 # happened. But for this code it counts as an
588 # error since the connection shouldn't go away
589 # until qemu exits.
590 raise Exception("Console connection closed unexpectedly")
591
592 return data
593
594 def stringify_event(self, event):
595 val = ''
596 if select.POLLERR == event:
597 val = 'POLLER'
598 elif select.POLLHUP == event:
599 val = 'POLLHUP'
600 elif select.POLLNVAL == event:
601 val = 'POLLNVAL'
602 return val
603
604 def close_socket(self, sock):
605 sock.shutdown(socket.SHUT_RDWR)
606 sock.close()
607
608 def close_ignore_error(self, fd):
609 try:
610 os.close(fd)
611 except OSError:
612 pass