blob: ba44b96f532353dc67261bfdfca2e49b21ac9925 [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 -050020from oeqa.utils.dump import HostDumper
21
22import logging
23logger = logging.getLogger("BitBake.QemuRunner")
Patrick Williamsc0f7c042017-02-23 20:41:17 -060024logger.addHandler(logging.StreamHandler())
Patrick Williamsc124f4f2015-09-15 14:41:29 -050025
Patrick Williamsf1e5d692016-03-30 15:21:19 -050026# Get Unicode non printable control chars
Patrick Williamsc0f7c042017-02-23 20:41:17 -060027control_range = list(range(0,32))+list(range(127,160))
28control_chars = [chr(x) for x in control_range
29 if chr(x) not in string.printable]
Patrick Williamsf1e5d692016-03-30 15:21:19 -050030re_control_char = re.compile('[%s]' % re.escape("".join(control_chars)))
31
Patrick Williamsc124f4f2015-09-15 14:41:29 -050032class QemuRunner:
33
Patrick Williamsc0f7c042017-02-23 20:41:17 -060034 def __init__(self, machine, rootfs, display, tmpdir, deploy_dir_image, logfile, boottime, dump_dir, dump_host_cmds, use_kvm):
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
Patrick Williamsc124f4f2015-09-15 14:41:29 -050057
58 self.runqemutime = 60
59 self.host_dumper = HostDumper(dump_host_cmds, dump_dir)
60
61 def create_socket(self):
62 try:
63 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
64 sock.setblocking(0)
65 sock.bind(("127.0.0.1",0))
66 sock.listen(2)
67 port = sock.getsockname()[1]
68 logger.info("Created listening socket for qemu serial console on: 127.0.0.1:%s" % port)
69 return (sock, port)
70
71 except socket.error:
72 sock.close()
73 raise
74
75 def log(self, msg):
76 if self.logfile:
Patrick Williamsf1e5d692016-03-30 15:21:19 -050077 # It is needed to sanitize the data received from qemu
78 # because is possible to have control characters
Brad Bishop6e60e8b2018-02-01 10:27:11 -050079 msg = msg.decode("utf-8", errors='ignore')
Patrick Williamsc0f7c042017-02-23 20:41:17 -060080 msg = re_control_char.sub('', msg)
Patrick Williamsf1e5d692016-03-30 15:21:19 -050081 with codecs.open(self.logfile, "a", encoding="utf-8") as f:
Patrick Williamsc124f4f2015-09-15 14:41:29 -050082 f.write("%s" % msg)
83
84 def getOutput(self, o):
85 import fcntl
86 fl = fcntl.fcntl(o, fcntl.F_GETFL)
87 fcntl.fcntl(o, fcntl.F_SETFL, fl | os.O_NONBLOCK)
Patrick Williamsc0f7c042017-02-23 20:41:17 -060088 return os.read(o.fileno(), 1000000).decode("utf-8")
Patrick Williamsc124f4f2015-09-15 14:41:29 -050089
90
91 def handleSIGCHLD(self, signum, frame):
92 if self.runqemu and self.runqemu.poll():
93 if self.runqemu.returncode:
94 logger.info('runqemu exited with code %d' % self.runqemu.returncode)
95 logger.info("Output from runqemu:\n%s" % self.getOutput(self.runqemu.stdout))
96 self.stop()
97 self._dump_host()
98 raise SystemExit
99
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500100 def start(self, qemuparams = None, get_ip = True, extra_bootparams = None, runqemuparams='', launch_cmd=None, discard_writes=True):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500101 if self.display:
102 os.environ["DISPLAY"] = self.display
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500103 # Set this flag so that Qemu doesn't do any grabs as SDL grabs
104 # interact badly with screensavers.
105 os.environ["QEMU_DONT_GRAB"] = "1"
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500106 if not os.path.exists(self.rootfs):
107 logger.error("Invalid rootfs %s" % self.rootfs)
108 return False
109 if not os.path.exists(self.tmpdir):
110 logger.error("Invalid TMPDIR path %s" % self.tmpdir)
111 return False
112 else:
113 os.environ["OE_TMPDIR"] = self.tmpdir
114 if not os.path.exists(self.deploy_dir_image):
115 logger.error("Invalid DEPLOY_DIR_IMAGE path %s" % self.deploy_dir_image)
116 return False
117 else:
118 os.environ["DEPLOY_DIR_IMAGE"] = self.deploy_dir_image
119
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500120 if not launch_cmd:
121 launch_cmd = 'runqemu %s %s ' % ('snapshot' if discard_writes else '', runqemuparams)
122 if self.use_kvm:
123 logger.info('Using kvm for runqemu')
124 launch_cmd += ' kvm'
125 else:
126 logger.info('Not using kvm for runqemu')
127 if not self.display:
128 launch_cmd += ' nographic'
129 launch_cmd += ' %s %s' % (self.machine, self.rootfs)
130
131 return self.launch(launch_cmd, qemuparams=qemuparams, get_ip=get_ip, extra_bootparams=extra_bootparams)
132
133 def launch(self, launch_cmd, get_ip = True, qemuparams = None, extra_bootparams = None):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500134 try:
135 threadsock, threadport = self.create_socket()
136 self.server_socket, self.serverport = self.create_socket()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600137 except socket.error as msg:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500138 logger.error("Failed to create listening socket: %s" % msg[1])
139 return False
140
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600141 bootparams = 'console=tty1 console=ttyS0,115200n8 printk.time=1'
142 if extra_bootparams:
143 bootparams = bootparams + ' ' + extra_bootparams
144
145 self.qemuparams = 'bootparams="{0}" qemuparams="-serial tcp:127.0.0.1:{1}"'.format(bootparams, threadport)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500146 if qemuparams:
147 self.qemuparams = self.qemuparams[:-1] + " " + qemuparams + " " + '\"'
148
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500149 launch_cmd += ' tcpserial=%s %s' % (self.serverport, self.qemuparams)
150
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500151 self.origchldhandler = signal.getsignal(signal.SIGCHLD)
152 signal.signal(signal.SIGCHLD, self.handleSIGCHLD)
153
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600154 logger.info('launchcmd=%s'%(launch_cmd))
155
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500156 # FIXME: We pass in stdin=subprocess.PIPE here to work around stty
157 # blocking at the end of the runqemu script when using this within
158 # oe-selftest (this makes stty error out immediately). There ought
159 # to be a proper fix but this will suffice for now.
160 self.runqemu = subprocess.Popen(launch_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, preexec_fn=os.setpgrp)
161 output = self.runqemu.stdout
162
163 #
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600164 # We need the preexec_fn above so that all runqemu processes can easily be killed
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500165 # (by killing their process group). This presents a problem if this controlling
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600166 # process itself is killed however since those processes don't notice the death
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500167 # of the parent and merrily continue on.
168 #
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600169 # Rather than hack runqemu to deal with this, we add something here instead.
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500170 # Basically we fork off another process which holds an open pipe to the parent
171 # and also is setpgrp. If/when the pipe sees EOF from the parent dieing, it kills
172 # the process group. This is like pctrl's PDEATHSIG but for a process group
173 # rather than a single process.
174 #
175 r, w = os.pipe()
176 self.monitorpid = os.fork()
177 if self.monitorpid:
178 os.close(r)
179 self.monitorpipe = os.fdopen(w, "w")
180 else:
181 # child process
182 os.setpgrp()
183 os.close(w)
184 r = os.fdopen(r)
185 x = r.read()
186 os.killpg(os.getpgid(self.runqemu.pid), signal.SIGTERM)
187 sys.exit(0)
188
189 logger.info("runqemu started, pid is %s" % self.runqemu.pid)
190 logger.info("waiting at most %s seconds for qemu pid" % self.runqemutime)
191 endtime = time.time() + self.runqemutime
192 while not self.is_alive() and time.time() < endtime:
193 if self.runqemu.poll():
194 if self.runqemu.returncode:
195 # No point waiting any longer
196 logger.info('runqemu exited with code %d' % self.runqemu.returncode)
197 self._dump_host()
198 self.stop()
199 logger.info("Output from runqemu:\n%s" % self.getOutput(output))
200 return False
201 time.sleep(1)
202
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500203 out = self.getOutput(output)
204 netconf = False # network configuration is not required by default
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500205 if self.is_alive():
206 logger.info("qemu started - qemu procces pid is %s" % self.qemupid)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500207 if get_ip:
208 cmdline = ''
209 with open('/proc/%s/cmdline' % self.qemupid) as p:
210 cmdline = p.read()
211 # It is needed to sanitize the data received
212 # because is possible to have control characters
213 cmdline = re_control_char.sub('', cmdline)
214 try:
215 ips = re.findall("((?:[0-9]{1,3}\.){3}[0-9]{1,3})", cmdline.split("ip=")[1])
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500216 self.ip = ips[0]
217 self.server_ip = ips[1]
218 logger.info("qemu cmdline used:\n{}".format(cmdline))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600219 except (IndexError, ValueError):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500220 # Try to get network configuration from runqemu output
221 match = re.match('.*Network configuration: ([0-9.]+)::([0-9.]+):([0-9.]+)$.*',
222 out, re.MULTILINE|re.DOTALL)
223 if match:
224 self.ip, self.server_ip, self.netmask = match.groups()
225 # network configuration is required as we couldn't get it
226 # from the runqemu command line, so qemu doesn't run kernel
227 # and guest networking is not configured
228 netconf = True
229 else:
230 logger.error("Couldn't get ip from qemu command line and runqemu output! "
231 "Here is the qemu command line used:\n%s\n"
232 "and output from runqemu:\n%s" % (cmdline, out))
233 self._dump_host()
234 self.stop()
235 return False
236
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500237 logger.info("Target IP: %s" % self.ip)
238 logger.info("Server IP: %s" % self.server_ip)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500239
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500240 self.thread = LoggingThread(self.log, threadsock, logger)
241 self.thread.start()
242 if not self.thread.connection_established.wait(self.boottime):
243 logger.error("Didn't receive a console connection from qemu. "
244 "Here is the qemu command line used:\n%s\nand "
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500245 "output from runqemu:\n%s" % (cmdline, out))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500246 self.stop_thread()
247 return False
248
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500249 logger.info("Output from runqemu:\n%s", out)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500250 logger.info("Waiting at most %d seconds for login banner" % self.boottime)
251 endtime = time.time() + self.boottime
252 socklist = [self.server_socket]
253 reachedlogin = False
254 stopread = False
255 qemusock = None
256 bootlog = ''
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600257 data = b''
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500258 while time.time() < endtime and not stopread:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500259 try:
260 sread, swrite, serror = select.select(socklist, [], [], 5)
261 except InterruptedError:
262 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500263 for sock in sread:
264 if sock is self.server_socket:
265 qemusock, addr = self.server_socket.accept()
266 qemusock.setblocking(0)
267 socklist.append(qemusock)
268 socklist.remove(self.server_socket)
269 logger.info("Connection from %s:%s" % addr)
270 else:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600271 data = data + sock.recv(1024)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500272 if data:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600273 try:
274 data = data.decode("utf-8", errors="surrogateescape")
275 bootlog += data
276 data = b''
277 if re.search(".* login:", bootlog):
278 self.server_socket = qemusock
279 stopread = True
280 reachedlogin = True
281 logger.info("Reached login banner")
282 except UnicodeDecodeError:
283 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500284 else:
285 socklist.remove(sock)
286 sock.close()
287 stopread = True
288
289 if not reachedlogin:
290 logger.info("Target didn't reached login boot in %d seconds" % self.boottime)
291 lines = "\n".join(bootlog.splitlines()[-25:])
292 logger.info("Last 25 lines of text:\n%s" % lines)
293 logger.info("Check full boot log: %s" % self.logfile)
294 self._dump_host()
295 self.stop()
296 return False
297
298 # If we are not able to login the tests can continue
299 try:
300 (status, output) = self.run_serial("root\n", raw=True)
301 if re.search("root@[a-zA-Z0-9\-]+:~#", output):
302 self.logged = True
303 logger.info("Logged as root in serial console")
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500304 if netconf:
305 # configure guest networking
306 cmd = "ifconfig eth0 %s netmask %s up\n" % (self.ip, self.netmask)
307 output = self.run_serial(cmd, raw=True)[1]
308 if re.search("root@[a-zA-Z0-9\-]+:~#", output):
309 logger.info("configured ip address %s", self.ip)
310 else:
311 logger.info("Couldn't configure guest networking")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500312 else:
313 logger.info("Couldn't login into serial console"
314 " as root using blank password")
315 except:
316 logger.info("Serial console failed while trying to login")
317
318 else:
319 logger.info("Qemu pid didn't appeared in %s seconds" % self.runqemutime)
320 self._dump_host()
321 self.stop()
322 logger.info("Output from runqemu:\n%s" % self.getOutput(output))
323 return False
324
325 return self.is_alive()
326
327 def stop(self):
328 self.stop_thread()
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500329 self.stop_qemu_system()
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500330 if hasattr(self, "origchldhandler"):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500331 signal.signal(signal.SIGCHLD, self.origchldhandler)
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500332 if self.runqemu:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600333 if hasattr(self, "monitorpid"):
334 os.kill(self.monitorpid, signal.SIGKILL)
335 logger.info("Sending SIGTERM to runqemu")
336 try:
337 os.killpg(os.getpgid(self.runqemu.pid), signal.SIGTERM)
338 except OSError as e:
339 if e.errno != errno.ESRCH:
340 raise
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500341 endtime = time.time() + self.runqemutime
342 while self.runqemu.poll() is None and time.time() < endtime:
343 time.sleep(1)
344 if self.runqemu.poll() is None:
345 logger.info("Sending SIGKILL to runqemu")
346 os.killpg(os.getpgid(self.runqemu.pid), signal.SIGKILL)
347 self.runqemu = None
348 if hasattr(self, 'server_socket') and self.server_socket:
349 self.server_socket.close()
350 self.server_socket = None
351 self.qemupid = None
352 self.ip = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500353
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500354 def stop_qemu_system(self):
355 if self.qemupid:
356 try:
357 # qemu-system behaves well and a SIGTERM is enough
358 os.kill(self.qemupid, signal.SIGTERM)
359 except ProcessLookupError as e:
360 logger.warn('qemu-system ended unexpectedly')
361
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500362 def stop_thread(self):
363 if self.thread and self.thread.is_alive():
364 self.thread.stop()
365 self.thread.join()
366
367 def restart(self, qemuparams = None):
368 logger.info("Restarting qemu process")
369 if self.runqemu.poll() is None:
370 self.stop()
371 if self.start(qemuparams):
372 return True
373 return False
374
375 def is_alive(self):
376 if not self.runqemu:
377 return False
378 qemu_child = self.find_child(str(self.runqemu.pid))
379 if qemu_child:
380 self.qemupid = qemu_child[0]
381 if os.path.exists("/proc/" + str(self.qemupid)):
382 return True
383 return False
384
385 def find_child(self,parent_pid):
386 #
387 # Walk the process tree from the process specified looking for a qemu-system. Return its [pid'cmd]
388 #
389 ps = subprocess.Popen(['ps', 'axww', '-o', 'pid,ppid,command'], stdout=subprocess.PIPE).communicate()[0]
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600390 processes = ps.decode("utf-8").split('\n')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500391 nfields = len(processes[0].split()) - 1
392 pids = {}
393 commands = {}
394 for row in processes[1:]:
395 data = row.split(None, nfields)
396 if len(data) != 3:
397 continue
398 if data[1] not in pids:
399 pids[data[1]] = []
400
401 pids[data[1]].append(data[0])
402 commands[data[0]] = data[2]
403
404 if parent_pid not in pids:
405 return []
406
407 parents = []
408 newparents = pids[parent_pid]
409 while newparents:
410 next = []
411 for p in newparents:
412 if p in pids:
413 for n in pids[p]:
414 if n not in parents and n not in next:
415 next.append(n)
416 if p not in parents:
417 parents.append(p)
418 newparents = next
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600419 #print("Children matching %s:" % str(parents))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500420 for p in parents:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600421 # Need to be careful here since runqemu runs "ldd qemu-system-xxxx"
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500422 # Also, old versions of ldd (2.11) run "LD_XXXX qemu-system-xxxx"
423 basecmd = commands[p].split()[0]
424 basecmd = os.path.basename(basecmd)
425 if "qemu-system" in basecmd and "-serial tcp" in commands[p]:
426 return [int(p),commands[p]]
427
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500428 def run_serial(self, command, raw=False, timeout=5):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500429 # We assume target system have echo to get command status
430 if not raw:
431 command = "%s; echo $?\n" % command
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500432
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500433 data = ''
434 status = 0
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600435 self.server_socket.sendall(command.encode('utf-8'))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500436 start = time.time()
437 end = start + timeout
438 while True:
439 now = time.time()
440 if now >= end:
441 data += "<<< run_serial(): command timed out after %d seconds without output >>>\r\n\r\n" % timeout
442 break
443 try:
444 sread, _, _ = select.select([self.server_socket],[],[], end - now)
445 except InterruptedError:
446 continue
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500447 if sread:
448 answer = self.server_socket.recv(1024)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500449 if answer:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600450 data += answer.decode('utf-8')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500451 # Search the prompt to stop
452 if re.search("[a-zA-Z0-9]+@[a-zA-Z0-9\-]+:~#", data):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500453 break
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500454 else:
455 raise Exception("No data on serial console socket")
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500456
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500457 if data:
458 if raw:
459 status = 1
460 else:
461 # Remove first line (command line) and last line (prompt)
462 data = data[data.find('$?\r\n')+4:data.rfind('\r\n')]
463 index = data.rfind('\r\n')
464 if index == -1:
465 status_cmd = data
466 data = ""
467 else:
468 status_cmd = data[index+2:]
469 data = data[:index]
470 if (status_cmd == "0"):
471 status = 1
472 return (status, str(data))
473
474
475 def _dump_host(self):
476 self.host_dumper.create_dir("qemu")
477 logger.warn("Qemu ended unexpectedly, dump data from host"
478 " is in %s" % self.host_dumper.dump_dir)
479 self.host_dumper.dump_host()
480
481# This class is for reading data from a socket and passing it to logfunc
482# to be processed. It's completely event driven and has a straightforward
483# event loop. The mechanism for stopping the thread is a simple pipe which
484# will wake up the poll and allow for tearing everything down.
485class LoggingThread(threading.Thread):
486 def __init__(self, logfunc, sock, logger):
487 self.connection_established = threading.Event()
488 self.serversock = sock
489 self.logfunc = logfunc
490 self.logger = logger
491 self.readsock = None
492 self.running = False
493
494 self.errorevents = select.POLLERR | select.POLLHUP | select.POLLNVAL
495 self.readevents = select.POLLIN | select.POLLPRI
496
497 threading.Thread.__init__(self, target=self.threadtarget)
498
499 def threadtarget(self):
500 try:
501 self.eventloop()
502 finally:
503 self.teardown()
504
505 def run(self):
506 self.logger.info("Starting logging thread")
507 self.readpipe, self.writepipe = os.pipe()
508 threading.Thread.run(self)
509
510 def stop(self):
511 self.logger.info("Stopping logging thread")
512 if self.running:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600513 os.write(self.writepipe, bytes("stop", "utf-8"))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500514
515 def teardown(self):
516 self.logger.info("Tearing down logging thread")
517 self.close_socket(self.serversock)
518
519 if self.readsock is not None:
520 self.close_socket(self.readsock)
521
522 self.close_ignore_error(self.readpipe)
523 self.close_ignore_error(self.writepipe)
524 self.running = False
525
526 def eventloop(self):
527 poll = select.poll()
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500528 event_read_mask = self.errorevents | self.readevents
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500529 poll.register(self.serversock.fileno())
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500530 poll.register(self.readpipe, event_read_mask)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500531
532 breakout = False
533 self.running = True
534 self.logger.info("Starting thread event loop")
535 while not breakout:
536 events = poll.poll()
537 for event in events:
538 # An error occurred, bail out
539 if event[1] & self.errorevents:
540 raise Exception(self.stringify_event(event[1]))
541
542 # Event to stop the thread
543 if self.readpipe == event[0]:
544 self.logger.info("Stop event received")
545 breakout = True
546 break
547
548 # A connection request was received
549 elif self.serversock.fileno() == event[0]:
550 self.logger.info("Connection request received")
551 self.readsock, _ = self.serversock.accept()
552 self.readsock.setblocking(0)
553 poll.unregister(self.serversock.fileno())
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500554 poll.register(self.readsock.fileno(), event_read_mask)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500555
556 self.logger.info("Setting connection established event")
557 self.connection_established.set()
558
559 # Actual data to be logged
560 elif self.readsock.fileno() == event[0]:
561 data = self.recv(1024)
562 self.logfunc(data)
563
564 # Since the socket is non-blocking make sure to honor EAGAIN
565 # and EWOULDBLOCK.
566 def recv(self, count):
567 try:
568 data = self.readsock.recv(count)
569 except socket.error as e:
570 if e.errno == errno.EAGAIN or e.errno == errno.EWOULDBLOCK:
571 return ''
572 else:
573 raise
574
575 if data is None:
576 raise Exception("No data on read ready socket")
577 elif not data:
578 # This actually means an orderly shutdown
579 # happened. But for this code it counts as an
580 # error since the connection shouldn't go away
581 # until qemu exits.
582 raise Exception("Console connection closed unexpectedly")
583
584 return data
585
586 def stringify_event(self, event):
587 val = ''
588 if select.POLLERR == event:
589 val = 'POLLER'
590 elif select.POLLHUP == event:
591 val = 'POLLHUP'
592 elif select.POLLNVAL == event:
593 val = 'POLLNVAL'
594 return val
595
596 def close_socket(self, sock):
597 sock.shutdown(socket.SHUT_RDWR)
598 sock.close()
599
600 def close_ignore_error(self, fd):
601 try:
602 os.close(fd)
603 except OSError:
604 pass