blob: 0631d43218f7ea0b06e3fa4f8970617c05fa3703 [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001# Copyright (C) 2013 Intel Corporation
2#
3# Released under the MIT license (see COPYING.MIT)
4
5# This module provides a class for starting qemu images using runqemu.
6# It's used by testimage.bbclass.
7
8import subprocess
9import os
Brad Bishop6e60e8b2018-02-01 10:27:11 -050010import sys
Patrick Williamsc124f4f2015-09-15 14:41:29 -050011import time
12import signal
13import re
14import socket
15import select
16import errno
Patrick Williamsf1e5d692016-03-30 15:21:19 -050017import string
Patrick Williamsc124f4f2015-09-15 14:41:29 -050018import threading
Patrick Williamsf1e5d692016-03-30 15:21:19 -050019import codecs
Patrick Williamsc124f4f2015-09-15 14:41:29 -050020import logging
Brad Bishopd7bf8c12018-02-25 22:55:05 -050021from oeqa.utils.dump import HostDumper
Patrick Williamsc124f4f2015-09-15 14:41:29 -050022
Patrick Williamsf1e5d692016-03-30 15:21:19 -050023# Get Unicode non printable control chars
Patrick Williamsc0f7c042017-02-23 20:41:17 -060024control_range = list(range(0,32))+list(range(127,160))
25control_chars = [chr(x) for x in control_range
26 if chr(x) not in string.printable]
Patrick Williamsf1e5d692016-03-30 15:21:19 -050027re_control_char = re.compile('[%s]' % re.escape("".join(control_chars)))
28
Patrick Williamsc124f4f2015-09-15 14:41:29 -050029class QemuRunner:
30
Brad Bishopd7bf8c12018-02-25 22:55:05 -050031 def __init__(self, machine, rootfs, display, tmpdir, deploy_dir_image, logfile, boottime, dump_dir, dump_host_cmds, use_kvm, logger):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050032
33 # Popen object for runqemu
34 self.runqemu = None
35 # pid of the qemu process that runqemu will start
36 self.qemupid = None
Brad Bishop6e60e8b2018-02-01 10:27:11 -050037 # target ip - from the command line or runqemu output
Patrick Williamsc124f4f2015-09-15 14:41:29 -050038 self.ip = None
39 # host ip - where qemu is running
40 self.server_ip = None
Brad Bishop6e60e8b2018-02-01 10:27:11 -050041 # target ip netmask
42 self.netmask = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -050043
44 self.machine = machine
45 self.rootfs = rootfs
46 self.display = display
47 self.tmpdir = tmpdir
48 self.deploy_dir_image = deploy_dir_image
49 self.logfile = logfile
50 self.boottime = boottime
51 self.logged = False
52 self.thread = None
Patrick Williamsc0f7c042017-02-23 20:41:17 -060053 self.use_kvm = use_kvm
Brad Bishopd7bf8c12018-02-25 22:55:05 -050054 self.msg = ''
Patrick Williamsc124f4f2015-09-15 14:41:29 -050055
Brad Bishopd7bf8c12018-02-25 22:55:05 -050056 self.runqemutime = 120
57 self.qemu_pidfile = 'pidfile_'+str(os.getpid())
Patrick Williamsc124f4f2015-09-15 14:41:29 -050058 self.host_dumper = HostDumper(dump_host_cmds, dump_dir)
59
Brad Bishopd7bf8c12018-02-25 22:55:05 -050060 self.logger = logger
61
Patrick Williamsc124f4f2015-09-15 14:41:29 -050062 def create_socket(self):
63 try:
64 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
65 sock.setblocking(0)
66 sock.bind(("127.0.0.1",0))
67 sock.listen(2)
68 port = sock.getsockname()[1]
Brad Bishopd7bf8c12018-02-25 22:55:05 -050069 self.logger.debug("Created listening socket for qemu serial console on: 127.0.0.1:%s" % port)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050070 return (sock, port)
71
72 except socket.error:
73 sock.close()
74 raise
75
76 def log(self, msg):
77 if self.logfile:
Patrick Williamsf1e5d692016-03-30 15:21:19 -050078 # It is needed to sanitize the data received from qemu
79 # because is possible to have control characters
Brad Bishop6e60e8b2018-02-01 10:27:11 -050080 msg = msg.decode("utf-8", errors='ignore')
Patrick Williamsc0f7c042017-02-23 20:41:17 -060081 msg = re_control_char.sub('', msg)
Brad Bishopd7bf8c12018-02-25 22:55:05 -050082 self.msg += msg
Patrick Williamsf1e5d692016-03-30 15:21:19 -050083 with codecs.open(self.logfile, "a", encoding="utf-8") as f:
Patrick Williamsc124f4f2015-09-15 14:41:29 -050084 f.write("%s" % msg)
85
86 def getOutput(self, o):
87 import fcntl
88 fl = fcntl.fcntl(o, fcntl.F_GETFL)
89 fcntl.fcntl(o, fcntl.F_SETFL, fl | os.O_NONBLOCK)
Patrick Williamsc0f7c042017-02-23 20:41:17 -060090 return os.read(o.fileno(), 1000000).decode("utf-8")
Patrick Williamsc124f4f2015-09-15 14:41:29 -050091
92
93 def handleSIGCHLD(self, signum, frame):
94 if self.runqemu and self.runqemu.poll():
95 if self.runqemu.returncode:
Brad Bishopd7bf8c12018-02-25 22:55:05 -050096 self.logger.debug('runqemu exited with code %d' % self.runqemu.returncode)
97 self.logger.debug("Output from runqemu:\n%s" % self.getOutput(self.runqemu.stdout))
Patrick Williamsc124f4f2015-09-15 14:41:29 -050098 self.stop()
99 self._dump_host()
100 raise SystemExit
101
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500102 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 -0500103 env = os.environ.copy()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500104 if self.display:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500105 env["DISPLAY"] = self.display
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500106 # Set this flag so that Qemu doesn't do any grabs as SDL grabs
107 # interact badly with screensavers.
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500108 env["QEMU_DONT_GRAB"] = "1"
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500109 if not os.path.exists(self.rootfs):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500110 self.logger.error("Invalid rootfs %s" % self.rootfs)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500111 return False
112 if not os.path.exists(self.tmpdir):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500113 self.logger.error("Invalid TMPDIR path %s" % self.tmpdir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500114 return False
115 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500116 env["OE_TMPDIR"] = self.tmpdir
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500117 if not os.path.exists(self.deploy_dir_image):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500118 self.logger.error("Invalid DEPLOY_DIR_IMAGE path %s" % self.deploy_dir_image)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500119 return False
120 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500121 env["DEPLOY_DIR_IMAGE"] = self.deploy_dir_image
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500122
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500123 if not launch_cmd:
124 launch_cmd = 'runqemu %s %s ' % ('snapshot' if discard_writes else '', runqemuparams)
125 if self.use_kvm:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500126 self.logger.debug('Using kvm for runqemu')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500127 launch_cmd += ' kvm'
128 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500129 self.logger.debug('Not using kvm for runqemu')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500130 if not self.display:
131 launch_cmd += ' nographic'
132 launch_cmd += ' %s %s' % (self.machine, self.rootfs)
133
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500134 return self.launch(launch_cmd, qemuparams=qemuparams, get_ip=get_ip, extra_bootparams=extra_bootparams, env=env)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500135
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500136 def launch(self, launch_cmd, get_ip = True, qemuparams = None, extra_bootparams = None, env = None):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500137 try:
138 threadsock, threadport = self.create_socket()
139 self.server_socket, self.serverport = self.create_socket()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600140 except socket.error as msg:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500141 self.logger.error("Failed to create listening socket: %s" % msg[1])
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500142 return False
143
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600144 bootparams = 'console=tty1 console=ttyS0,115200n8 printk.time=1'
145 if extra_bootparams:
146 bootparams = bootparams + ' ' + extra_bootparams
147
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500148 # Ask QEMU to store the QEMU process PID in file, this way we don't have to parse running processes
149 # and analyze descendents in order to determine it.
150 if os.path.exists(self.qemu_pidfile):
151 os.remove(self.qemu_pidfile)
152 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 -0500153 if qemuparams:
154 self.qemuparams = self.qemuparams[:-1] + " " + qemuparams + " " + '\"'
155
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500156 launch_cmd += ' tcpserial=%s %s' % (self.serverport, self.qemuparams)
157
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500158 self.origchldhandler = signal.getsignal(signal.SIGCHLD)
159 signal.signal(signal.SIGCHLD, self.handleSIGCHLD)
160
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500161 self.logger.debug('launchcmd=%s'%(launch_cmd))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600162
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500163 # FIXME: We pass in stdin=subprocess.PIPE here to work around stty
164 # blocking at the end of the runqemu script when using this within
165 # oe-selftest (this makes stty error out immediately). There ought
166 # to be a proper fix but this will suffice for now.
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500167 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 -0500168 output = self.runqemu.stdout
169
170 #
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600171 # We need the preexec_fn above so that all runqemu processes can easily be killed
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500172 # (by killing their process group). This presents a problem if this controlling
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600173 # process itself is killed however since those processes don't notice the death
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500174 # of the parent and merrily continue on.
175 #
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600176 # Rather than hack runqemu to deal with this, we add something here instead.
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500177 # Basically we fork off another process which holds an open pipe to the parent
178 # and also is setpgrp. If/when the pipe sees EOF from the parent dieing, it kills
179 # the process group. This is like pctrl's PDEATHSIG but for a process group
180 # rather than a single process.
181 #
182 r, w = os.pipe()
183 self.monitorpid = os.fork()
184 if self.monitorpid:
185 os.close(r)
186 self.monitorpipe = os.fdopen(w, "w")
187 else:
188 # child process
189 os.setpgrp()
190 os.close(w)
191 r = os.fdopen(r)
192 x = r.read()
193 os.killpg(os.getpgid(self.runqemu.pid), signal.SIGTERM)
194 sys.exit(0)
195
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500196 self.logger.debug("runqemu started, pid is %s" % self.runqemu.pid)
197 self.logger.debug("waiting at most %s seconds for qemu pid" % self.runqemutime)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500198 endtime = time.time() + self.runqemutime
199 while not self.is_alive() and time.time() < endtime:
200 if self.runqemu.poll():
201 if self.runqemu.returncode:
202 # No point waiting any longer
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500203 self.logger.debug('runqemu exited with code %d' % self.runqemu.returncode)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500204 self._dump_host()
205 self.stop()
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500206 self.logger.debug("Output from runqemu:\n%s" % self.getOutput(output))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500207 return False
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500208 time.sleep(0.5)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500209
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500210 if not self.is_alive():
211 self.logger.error("Qemu pid didn't appear in %s seconds" % self.runqemutime)
212 # Dump all processes to help us to figure out what is going on...
213 ps = subprocess.Popen(['ps', 'axww', '-o', 'pid,ppid,command '], stdout=subprocess.PIPE).communicate()[0]
214 processes = ps.decode("utf-8")
215 self.logger.debug("Running processes:\n%s" % processes)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500216 self._dump_host()
217 self.stop()
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500218 op = self.getOutput(output)
219 if op:
220 self.logger.error("Output from runqemu:\n%s" % op)
221 else:
222 self.logger.error("No output from runqemu.\n")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500223 return False
224
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500225 # We are alive: qemu is running
226 out = self.getOutput(output)
227 netconf = False # network configuration is not required by default
228 self.logger.debug("qemu started in %s seconds - qemu procces pid is %s" % (time.time() - (endtime - self.runqemutime), self.qemupid))
229 if get_ip:
230 cmdline = ''
231 with open('/proc/%s/cmdline' % self.qemupid) as p:
232 cmdline = p.read()
233 # It is needed to sanitize the data received
234 # because is possible to have control characters
235 cmdline = re_control_char.sub(' ', cmdline)
236 try:
237 ips = re.findall("((?:[0-9]{1,3}\.){3}[0-9]{1,3})", cmdline.split("ip=")[1])
238 self.ip = ips[0]
239 self.server_ip = ips[1]
240 self.logger.debug("qemu cmdline used:\n{}".format(cmdline))
241 except (IndexError, ValueError):
242 # Try to get network configuration from runqemu output
243 match = re.match('.*Network configuration: ([0-9.]+)::([0-9.]+):([0-9.]+)$.*',
244 out, re.MULTILINE|re.DOTALL)
245 if match:
246 self.ip, self.server_ip, self.netmask = match.groups()
247 # network configuration is required as we couldn't get it
248 # from the runqemu command line, so qemu doesn't run kernel
249 # and guest networking is not configured
250 netconf = True
251 else:
252 self.logger.error("Couldn't get ip from qemu command line and runqemu output! "
253 "Here is the qemu command line used:\n%s\n"
254 "and output from runqemu:\n%s" % (cmdline, out))
255 self._dump_host()
256 self.stop()
257 return False
258
259 self.logger.debug("Target IP: %s" % self.ip)
260 self.logger.debug("Server IP: %s" % self.server_ip)
261
262 self.thread = LoggingThread(self.log, threadsock, self.logger)
263 self.thread.start()
264 if not self.thread.connection_established.wait(self.boottime):
265 self.logger.error("Didn't receive a console connection from qemu. "
266 "Here is the qemu command line used:\n%s\nand "
267 "output from runqemu:\n%s" % (cmdline, out))
268 self.stop_thread()
269 return False
270
271 self.logger.debug("Output from runqemu:\n%s", out)
272 self.logger.debug("Waiting at most %d seconds for login banner" % self.boottime)
273 endtime = time.time() + self.boottime
274 socklist = [self.server_socket]
275 reachedlogin = False
276 stopread = False
277 qemusock = None
278 bootlog = b''
279 data = b''
280 while time.time() < endtime and not stopread:
281 try:
282 sread, swrite, serror = select.select(socklist, [], [], 5)
283 except InterruptedError:
284 continue
285 for sock in sread:
286 if sock is self.server_socket:
287 qemusock, addr = self.server_socket.accept()
288 qemusock.setblocking(0)
289 socklist.append(qemusock)
290 socklist.remove(self.server_socket)
291 self.logger.debug("Connection from %s:%s" % addr)
292 else:
293 data = data + sock.recv(1024)
294 if data:
295 bootlog += data
296 data = b''
297 if b' login:' in bootlog:
298 self.server_socket = qemusock
299 stopread = True
300 reachedlogin = True
301 self.logger.debug("Reached login banner")
302 else:
303 socklist.remove(sock)
304 sock.close()
305 stopread = True
306
307
308 if not reachedlogin:
309 self.logger.debug("Target didn't reached login boot in %d seconds" % self.boottime)
310 tail = lambda l: "\n".join(l.splitlines()[-25:])
311 # in case bootlog is empty, use tail qemu log store at self.msg
312 lines = tail(bootlog if bootlog else self.msg)
313 self.logger.debug("Last 25 lines of text:\n%s" % lines)
314 self.logger.debug("Check full boot log: %s" % self.logfile)
315 self._dump_host()
316 self.stop()
317 return False
318
319 # If we are not able to login the tests can continue
320 try:
321 (status, output) = self.run_serial("root\n", raw=True)
322 if re.search("root@[a-zA-Z0-9\-]+:~#", output):
323 self.logged = True
324 self.logger.debug("Logged as root in serial console")
325 if netconf:
326 # configure guest networking
327 cmd = "ifconfig eth0 %s netmask %s up\n" % (self.ip, self.netmask)
328 output = self.run_serial(cmd, raw=True)[1]
329 if re.search("root@[a-zA-Z0-9\-]+:~#", output):
330 self.logger.debug("configured ip address %s", self.ip)
331 else:
332 self.logger.debug("Couldn't configure guest networking")
333 else:
334 self.logger.debug("Couldn't login into serial console"
335 " as root using blank password")
336 except:
337 self.logger.debug("Serial console failed while trying to login")
338 return True
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500339
340 def stop(self):
341 self.stop_thread()
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500342 self.stop_qemu_system()
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500343 if hasattr(self, "origchldhandler"):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500344 signal.signal(signal.SIGCHLD, self.origchldhandler)
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500345 if self.runqemu:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600346 if hasattr(self, "monitorpid"):
347 os.kill(self.monitorpid, signal.SIGKILL)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500348 self.logger.debug("Sending SIGTERM to runqemu")
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600349 try:
350 os.killpg(os.getpgid(self.runqemu.pid), signal.SIGTERM)
351 except OSError as e:
352 if e.errno != errno.ESRCH:
353 raise
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500354 endtime = time.time() + self.runqemutime
355 while self.runqemu.poll() is None and time.time() < endtime:
356 time.sleep(1)
357 if self.runqemu.poll() is None:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500358 self.logger.debug("Sending SIGKILL to runqemu")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500359 os.killpg(os.getpgid(self.runqemu.pid), signal.SIGKILL)
360 self.runqemu = None
361 if hasattr(self, 'server_socket') and self.server_socket:
362 self.server_socket.close()
363 self.server_socket = None
364 self.qemupid = None
365 self.ip = None
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500366 if os.path.exists(self.qemu_pidfile):
367 os.remove(self.qemu_pidfile)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500368
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500369 def stop_qemu_system(self):
370 if self.qemupid:
371 try:
372 # qemu-system behaves well and a SIGTERM is enough
373 os.kill(self.qemupid, signal.SIGTERM)
374 except ProcessLookupError as e:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500375 self.logger.warn('qemu-system ended unexpectedly')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500376
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500377 def stop_thread(self):
378 if self.thread and self.thread.is_alive():
379 self.thread.stop()
380 self.thread.join()
381
382 def restart(self, qemuparams = None):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500383 self.logger.debug("Restarting qemu process")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500384 if self.runqemu.poll() is None:
385 self.stop()
386 if self.start(qemuparams):
387 return True
388 return False
389
390 def is_alive(self):
391 if not self.runqemu:
392 return False
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500393 if os.path.isfile(self.qemu_pidfile):
394 f = open(self.qemu_pidfile, 'r')
395 qemu_pid = f.read()
396 f.close()
397 qemupid = int(qemu_pid)
398 if os.path.exists("/proc/" + str(qemupid)):
399 self.qemupid = qemupid
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500400 return True
401 return False
402
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500403 def run_serial(self, command, raw=False, timeout=5):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500404 # We assume target system have echo to get command status
405 if not raw:
406 command = "%s; echo $?\n" % command
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500407
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500408 data = ''
409 status = 0
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600410 self.server_socket.sendall(command.encode('utf-8'))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500411 start = time.time()
412 end = start + timeout
413 while True:
414 now = time.time()
415 if now >= end:
416 data += "<<< run_serial(): command timed out after %d seconds without output >>>\r\n\r\n" % timeout
417 break
418 try:
419 sread, _, _ = select.select([self.server_socket],[],[], end - now)
420 except InterruptedError:
421 continue
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500422 if sread:
423 answer = self.server_socket.recv(1024)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500424 if answer:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600425 data += answer.decode('utf-8')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500426 # Search the prompt to stop
427 if re.search("[a-zA-Z0-9]+@[a-zA-Z0-9\-]+:~#", data):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500428 break
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500429 else:
430 raise Exception("No data on serial console socket")
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500431
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500432 if data:
433 if raw:
434 status = 1
435 else:
436 # Remove first line (command line) and last line (prompt)
437 data = data[data.find('$?\r\n')+4:data.rfind('\r\n')]
438 index = data.rfind('\r\n')
439 if index == -1:
440 status_cmd = data
441 data = ""
442 else:
443 status_cmd = data[index+2:]
444 data = data[:index]
445 if (status_cmd == "0"):
446 status = 1
447 return (status, str(data))
448
449
450 def _dump_host(self):
451 self.host_dumper.create_dir("qemu")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500452 self.logger.warn("Qemu ended unexpectedly, dump data from host"
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500453 " is in %s" % self.host_dumper.dump_dir)
454 self.host_dumper.dump_host()
455
456# This class is for reading data from a socket and passing it to logfunc
457# to be processed. It's completely event driven and has a straightforward
458# event loop. The mechanism for stopping the thread is a simple pipe which
459# will wake up the poll and allow for tearing everything down.
460class LoggingThread(threading.Thread):
461 def __init__(self, logfunc, sock, logger):
462 self.connection_established = threading.Event()
463 self.serversock = sock
464 self.logfunc = logfunc
465 self.logger = logger
466 self.readsock = None
467 self.running = False
468
469 self.errorevents = select.POLLERR | select.POLLHUP | select.POLLNVAL
470 self.readevents = select.POLLIN | select.POLLPRI
471
472 threading.Thread.__init__(self, target=self.threadtarget)
473
474 def threadtarget(self):
475 try:
476 self.eventloop()
477 finally:
478 self.teardown()
479
480 def run(self):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500481 self.logger.debug("Starting logging thread")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500482 self.readpipe, self.writepipe = os.pipe()
483 threading.Thread.run(self)
484
485 def stop(self):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500486 self.logger.debug("Stopping logging thread")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500487 if self.running:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600488 os.write(self.writepipe, bytes("stop", "utf-8"))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500489
490 def teardown(self):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500491 self.logger.debug("Tearing down logging thread")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500492 self.close_socket(self.serversock)
493
494 if self.readsock is not None:
495 self.close_socket(self.readsock)
496
497 self.close_ignore_error(self.readpipe)
498 self.close_ignore_error(self.writepipe)
499 self.running = False
500
501 def eventloop(self):
502 poll = select.poll()
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500503 event_read_mask = self.errorevents | self.readevents
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500504 poll.register(self.serversock.fileno())
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500505 poll.register(self.readpipe, event_read_mask)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500506
507 breakout = False
508 self.running = True
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500509 self.logger.debug("Starting thread event loop")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500510 while not breakout:
511 events = poll.poll()
512 for event in events:
513 # An error occurred, bail out
514 if event[1] & self.errorevents:
515 raise Exception(self.stringify_event(event[1]))
516
517 # Event to stop the thread
518 if self.readpipe == event[0]:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500519 self.logger.debug("Stop event received")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500520 breakout = True
521 break
522
523 # A connection request was received
524 elif self.serversock.fileno() == event[0]:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500525 self.logger.debug("Connection request received")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500526 self.readsock, _ = self.serversock.accept()
527 self.readsock.setblocking(0)
528 poll.unregister(self.serversock.fileno())
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500529 poll.register(self.readsock.fileno(), event_read_mask)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500530
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500531 self.logger.debug("Setting connection established event")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500532 self.connection_established.set()
533
534 # Actual data to be logged
535 elif self.readsock.fileno() == event[0]:
536 data = self.recv(1024)
537 self.logfunc(data)
538
539 # Since the socket is non-blocking make sure to honor EAGAIN
540 # and EWOULDBLOCK.
541 def recv(self, count):
542 try:
543 data = self.readsock.recv(count)
544 except socket.error as e:
545 if e.errno == errno.EAGAIN or e.errno == errno.EWOULDBLOCK:
546 return ''
547 else:
548 raise
549
550 if data is None:
551 raise Exception("No data on read ready socket")
552 elif not data:
553 # This actually means an orderly shutdown
554 # happened. But for this code it counts as an
555 # error since the connection shouldn't go away
556 # until qemu exits.
557 raise Exception("Console connection closed unexpectedly")
558
559 return data
560
561 def stringify_event(self, event):
562 val = ''
563 if select.POLLERR == event:
564 val = 'POLLER'
565 elif select.POLLHUP == event:
566 val = 'POLLHUP'
567 elif select.POLLNVAL == event:
568 val = 'POLLNVAL'
569 return val
570
571 def close_socket(self, sock):
572 sock.shutdown(socket.SHUT_RDWR)
573 sock.close()
574
575 def close_ignore_error(self, fd):
576 try:
577 os.close(fd)
578 except OSError:
579 pass