blob: 4b74337652344ada6163579736dc5815f2dd2cbd [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
Andrew Geissler82c905d2020-04-13 13:39:40 -050024from collections import defaultdict
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
Brad Bishop19323692019-04-05 15:28:33 -040034 def __init__(self, machine, rootfs, display, tmpdir, deploy_dir_image, logfile, boottime, dump_dir, dump_host_cmds,
Andrew Geissler82c905d2020-04-13 13:39:40 -050035 use_kvm, logger, use_slirp=False, serial_ports=2, boot_patterns = defaultdict(str), use_ovmf=False):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050036
37 # Popen object for runqemu
38 self.runqemu = None
Andrew Geissler82c905d2020-04-13 13:39:40 -050039 self.runqemu_exited = False
Patrick Williamsc124f4f2015-09-15 14:41:29 -050040 # pid of the qemu process that runqemu will start
41 self.qemupid = None
Brad Bishop6e60e8b2018-02-01 10:27:11 -050042 # target ip - from the command line or runqemu output
Patrick Williamsc124f4f2015-09-15 14:41:29 -050043 self.ip = None
44 # host ip - where qemu is running
45 self.server_ip = None
Brad Bishop6e60e8b2018-02-01 10:27:11 -050046 # target ip netmask
47 self.netmask = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -050048
49 self.machine = machine
50 self.rootfs = rootfs
51 self.display = display
52 self.tmpdir = tmpdir
53 self.deploy_dir_image = deploy_dir_image
54 self.logfile = logfile
55 self.boottime = boottime
56 self.logged = False
57 self.thread = None
Patrick Williamsc0f7c042017-02-23 20:41:17 -060058 self.use_kvm = use_kvm
Andrew Geissler82c905d2020-04-13 13:39:40 -050059 self.use_ovmf = use_ovmf
Brad Bishop19323692019-04-05 15:28:33 -040060 self.use_slirp = use_slirp
Andrew Geissler82c905d2020-04-13 13:39:40 -050061 self.serial_ports = serial_ports
Brad Bishopd7bf8c12018-02-25 22:55:05 -050062 self.msg = ''
Andrew Geissler82c905d2020-04-13 13:39:40 -050063 self.boot_patterns = boot_patterns
Patrick Williamsc124f4f2015-09-15 14:41:29 -050064
Brad Bishopd7bf8c12018-02-25 22:55:05 -050065 self.runqemutime = 120
66 self.qemu_pidfile = 'pidfile_'+str(os.getpid())
Patrick Williamsc124f4f2015-09-15 14:41:29 -050067 self.host_dumper = HostDumper(dump_host_cmds, dump_dir)
Brad Bishop15ae2502019-06-18 21:44:24 -040068 self.monitorpipe = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -050069
Brad Bishopd7bf8c12018-02-25 22:55:05 -050070 self.logger = logger
71
Andrew Geissler82c905d2020-04-13 13:39:40 -050072 # Enable testing other OS's
73 # Set commands for target communication, and default to Linux ALWAYS
74 # Other OS's or baremetal applications need to provide their
75 # own implementation passing it through QemuRunner's constructor
76 # or by passing them through TESTIMAGE_BOOT_PATTERNS[flag]
77 # provided variables, where <flag> is one of the mentioned below.
78 accepted_patterns = ['search_reached_prompt', 'send_login_user', 'search_login_succeeded', 'search_cmd_finished']
79 default_boot_patterns = defaultdict(str)
80 # Default to the usual paterns used to communicate with the target
81 default_boot_patterns['search_reached_prompt'] = b' login:'
82 default_boot_patterns['send_login_user'] = 'root\n'
83 default_boot_patterns['search_login_succeeded'] = r"root@[a-zA-Z0-9\-]+:~#"
84 default_boot_patterns['search_cmd_finished'] = r"[a-zA-Z0-9]+@[a-zA-Z0-9\-]+:~#"
85
86 # Only override patterns that were set e.g. login user TESTIMAGE_BOOT_PATTERNS[send_login_user] = "webserver\n"
87 for pattern in accepted_patterns:
88 if not self.boot_patterns[pattern]:
89 self.boot_patterns[pattern] = default_boot_patterns[pattern]
90
Patrick Williamsc124f4f2015-09-15 14:41:29 -050091 def create_socket(self):
92 try:
93 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
94 sock.setblocking(0)
95 sock.bind(("127.0.0.1",0))
96 sock.listen(2)
97 port = sock.getsockname()[1]
Brad Bishopd7bf8c12018-02-25 22:55:05 -050098 self.logger.debug("Created listening socket for qemu serial console on: 127.0.0.1:%s" % port)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050099 return (sock, port)
100
101 except socket.error:
102 sock.close()
103 raise
104
105 def log(self, msg):
106 if self.logfile:
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500107 # It is needed to sanitize the data received from qemu
108 # because is possible to have control characters
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500109 msg = msg.decode("utf-8", errors='ignore')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600110 msg = re_control_char.sub('', msg)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500111 self.msg += msg
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500112 with codecs.open(self.logfile, "a", encoding="utf-8") as f:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500113 f.write("%s" % msg)
114
115 def getOutput(self, o):
116 import fcntl
117 fl = fcntl.fcntl(o, fcntl.F_GETFL)
118 fcntl.fcntl(o, fcntl.F_SETFL, fl | os.O_NONBLOCK)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600119 return os.read(o.fileno(), 1000000).decode("utf-8")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500120
121
122 def handleSIGCHLD(self, signum, frame):
123 if self.runqemu and self.runqemu.poll():
124 if self.runqemu.returncode:
Andrew Geissler82c905d2020-04-13 13:39:40 -0500125 self.logger.error('runqemu exited with code %d' % self.runqemu.returncode)
126 self.logger.error('Output from runqemu:\n%s' % self.getOutput(self.runqemu.stdout))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500127 self.stop()
128 self._dump_host()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500129
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500130 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 -0500131 env = os.environ.copy()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500132 if self.display:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500133 env["DISPLAY"] = self.display
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500134 # Set this flag so that Qemu doesn't do any grabs as SDL grabs
135 # interact badly with screensavers.
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500136 env["QEMU_DONT_GRAB"] = "1"
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500137 if not os.path.exists(self.rootfs):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500138 self.logger.error("Invalid rootfs %s" % self.rootfs)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500139 return False
140 if not os.path.exists(self.tmpdir):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500141 self.logger.error("Invalid TMPDIR path %s" % self.tmpdir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500142 return False
143 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500144 env["OE_TMPDIR"] = self.tmpdir
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500145 if not os.path.exists(self.deploy_dir_image):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500146 self.logger.error("Invalid DEPLOY_DIR_IMAGE path %s" % self.deploy_dir_image)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500147 return False
148 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500149 env["DEPLOY_DIR_IMAGE"] = self.deploy_dir_image
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500150
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500151 if not launch_cmd:
Brad Bishop08902b02019-08-20 09:16:51 -0400152 launch_cmd = 'runqemu %s' % ('snapshot' if discard_writes else '')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500153 if self.use_kvm:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500154 self.logger.debug('Using kvm for runqemu')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500155 launch_cmd += ' kvm'
156 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500157 self.logger.debug('Not using kvm for runqemu')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500158 if not self.display:
159 launch_cmd += ' nographic'
Brad Bishop19323692019-04-05 15:28:33 -0400160 if self.use_slirp:
161 launch_cmd += ' slirp'
Andrew Geissler82c905d2020-04-13 13:39:40 -0500162 if self.use_ovmf:
163 launch_cmd += ' ovmf'
Brad Bishop08902b02019-08-20 09:16:51 -0400164 launch_cmd += ' %s %s %s' % (runqemuparams, self.machine, self.rootfs)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500165
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500166 return self.launch(launch_cmd, qemuparams=qemuparams, get_ip=get_ip, extra_bootparams=extra_bootparams, env=env)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500167
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500168 def launch(self, launch_cmd, get_ip = True, qemuparams = None, extra_bootparams = None, env = None):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500169 try:
Andrew Geissler82c905d2020-04-13 13:39:40 -0500170 if self.serial_ports >= 2:
171 self.threadsock, threadport = self.create_socket()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500172 self.server_socket, self.serverport = self.create_socket()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600173 except socket.error as msg:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500174 self.logger.error("Failed to create listening socket: %s" % msg[1])
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500175 return False
176
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600177 bootparams = 'console=tty1 console=ttyS0,115200n8 printk.time=1'
178 if extra_bootparams:
179 bootparams = bootparams + ' ' + extra_bootparams
180
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500181 # Ask QEMU to store the QEMU process PID in file, this way we don't have to parse running processes
182 # and analyze descendents in order to determine it.
183 if os.path.exists(self.qemu_pidfile):
184 os.remove(self.qemu_pidfile)
Brad Bishop15ae2502019-06-18 21:44:24 -0400185 self.qemuparams = 'bootparams="{0}" qemuparams="-pidfile {1}"'.format(bootparams, self.qemu_pidfile)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500186 if qemuparams:
187 self.qemuparams = self.qemuparams[:-1] + " " + qemuparams + " " + '\"'
188
Andrew Geissler82c905d2020-04-13 13:39:40 -0500189 if self.serial_ports >= 2:
190 launch_cmd += ' tcpserial=%s:%s %s' % (threadport, self.serverport, self.qemuparams)
191 else:
192 launch_cmd += ' tcpserial=%s %s' % (self.serverport, self.qemuparams)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500193
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500194 self.origchldhandler = signal.getsignal(signal.SIGCHLD)
195 signal.signal(signal.SIGCHLD, self.handleSIGCHLD)
196
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500197 self.logger.debug('launchcmd=%s'%(launch_cmd))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600198
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500199 # FIXME: We pass in stdin=subprocess.PIPE here to work around stty
200 # blocking at the end of the runqemu script when using this within
201 # oe-selftest (this makes stty error out immediately). There ought
202 # to be a proper fix but this will suffice for now.
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500203 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 -0500204 output = self.runqemu.stdout
205
206 #
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600207 # We need the preexec_fn above so that all runqemu processes can easily be killed
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500208 # (by killing their process group). This presents a problem if this controlling
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600209 # process itself is killed however since those processes don't notice the death
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500210 # of the parent and merrily continue on.
211 #
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600212 # Rather than hack runqemu to deal with this, we add something here instead.
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500213 # Basically we fork off another process which holds an open pipe to the parent
214 # and also is setpgrp. If/when the pipe sees EOF from the parent dieing, it kills
215 # the process group. This is like pctrl's PDEATHSIG but for a process group
216 # rather than a single process.
217 #
218 r, w = os.pipe()
219 self.monitorpid = os.fork()
220 if self.monitorpid:
221 os.close(r)
222 self.monitorpipe = os.fdopen(w, "w")
223 else:
224 # child process
225 os.setpgrp()
226 os.close(w)
227 r = os.fdopen(r)
228 x = r.read()
229 os.killpg(os.getpgid(self.runqemu.pid), signal.SIGTERM)
230 sys.exit(0)
231
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500232 self.logger.debug("runqemu started, pid is %s" % self.runqemu.pid)
Brad Bishop316dfdd2018-06-25 12:45:53 -0400233 self.logger.debug("waiting at most %s seconds for qemu pid (%s)" %
234 (self.runqemutime, time.strftime("%D %H:%M:%S")))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500235 endtime = time.time() + self.runqemutime
236 while not self.is_alive() and time.time() < endtime:
237 if self.runqemu.poll():
Andrew Geissler82c905d2020-04-13 13:39:40 -0500238 if self.runqemu_exited:
239 return False
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500240 if self.runqemu.returncode:
241 # No point waiting any longer
Brad Bishop96ff1982019-08-19 13:50:42 -0400242 self.logger.warning('runqemu exited with code %d' % self.runqemu.returncode)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500243 self._dump_host()
Brad Bishop96ff1982019-08-19 13:50:42 -0400244 self.logger.warning("Output from runqemu:\n%s" % self.getOutput(output))
Brad Bishopf86d0552018-12-04 14:18:15 -0800245 self.stop()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500246 return False
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500247 time.sleep(0.5)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500248
Andrew Geissler82c905d2020-04-13 13:39:40 -0500249 if self.runqemu_exited:
250 return False
251
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500252 if not self.is_alive():
Brad Bishop316dfdd2018-06-25 12:45:53 -0400253 self.logger.error("Qemu pid didn't appear in %s seconds (%s)" %
254 (self.runqemutime, time.strftime("%D %H:%M:%S")))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500255 # Dump all processes to help us to figure out what is going on...
256 ps = subprocess.Popen(['ps', 'axww', '-o', 'pid,ppid,command '], stdout=subprocess.PIPE).communicate()[0]
257 processes = ps.decode("utf-8")
258 self.logger.debug("Running processes:\n%s" % processes)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500259 self._dump_host()
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500260 op = self.getOutput(output)
Brad Bishopf86d0552018-12-04 14:18:15 -0800261 self.stop()
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500262 if op:
263 self.logger.error("Output from runqemu:\n%s" % op)
264 else:
265 self.logger.error("No output from runqemu.\n")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500266 return False
267
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500268 # We are alive: qemu is running
269 out = self.getOutput(output)
270 netconf = False # network configuration is not required by default
Brad Bishop316dfdd2018-06-25 12:45:53 -0400271 self.logger.debug("qemu started in %s seconds - qemu procces pid is %s (%s)" %
272 (time.time() - (endtime - self.runqemutime),
273 self.qemupid, time.strftime("%D %H:%M:%S")))
Andrew Geissler82c905d2020-04-13 13:39:40 -0500274 cmdline = ''
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500275 if get_ip:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500276 with open('/proc/%s/cmdline' % self.qemupid) as p:
277 cmdline = p.read()
278 # It is needed to sanitize the data received
279 # because is possible to have control characters
280 cmdline = re_control_char.sub(' ', cmdline)
281 try:
Brad Bishop19323692019-04-05 15:28:33 -0400282 if self.use_slirp:
283 tcp_ports = cmdline.split("hostfwd=tcp::")[1]
284 host_port = tcp_ports[:tcp_ports.find('-')]
285 self.ip = "localhost:%s" % host_port
286 else:
287 ips = re.findall(r"((?:[0-9]{1,3}\.){3}[0-9]{1,3})", cmdline.split("ip=")[1])
288 self.ip = ips[0]
289 self.server_ip = ips[1]
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500290 self.logger.debug("qemu cmdline used:\n{}".format(cmdline))
291 except (IndexError, ValueError):
292 # Try to get network configuration from runqemu output
Brad Bishopf86d0552018-12-04 14:18:15 -0800293 match = re.match(r'.*Network configuration: ([0-9.]+)::([0-9.]+):([0-9.]+)$.*',
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500294 out, re.MULTILINE|re.DOTALL)
295 if match:
296 self.ip, self.server_ip, self.netmask = match.groups()
297 # network configuration is required as we couldn't get it
298 # from the runqemu command line, so qemu doesn't run kernel
299 # and guest networking is not configured
300 netconf = True
301 else:
302 self.logger.error("Couldn't get ip from qemu command line and runqemu output! "
303 "Here is the qemu command line used:\n%s\n"
304 "and output from runqemu:\n%s" % (cmdline, out))
305 self._dump_host()
306 self.stop()
307 return False
308
309 self.logger.debug("Target IP: %s" % self.ip)
310 self.logger.debug("Server IP: %s" % self.server_ip)
311
Andrew Geissler82c905d2020-04-13 13:39:40 -0500312 if self.serial_ports >= 2:
313 self.thread = LoggingThread(self.log, self.threadsock, self.logger)
314 self.thread.start()
315 if not self.thread.connection_established.wait(self.boottime):
316 self.logger.error("Didn't receive a console connection from qemu. "
317 "Here is the qemu command line used:\n%s\nand "
318 "output from runqemu:\n%s" % (cmdline, out))
319 self.stop_thread()
320 return False
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500321
322 self.logger.debug("Output from runqemu:\n%s", out)
Brad Bishop316dfdd2018-06-25 12:45:53 -0400323 self.logger.debug("Waiting at most %d seconds for login banner (%s)" %
324 (self.boottime, time.strftime("%D %H:%M:%S")))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500325 endtime = time.time() + self.boottime
326 socklist = [self.server_socket]
327 reachedlogin = False
328 stopread = False
329 qemusock = None
330 bootlog = b''
331 data = b''
332 while time.time() < endtime and not stopread:
333 try:
334 sread, swrite, serror = select.select(socklist, [], [], 5)
335 except InterruptedError:
336 continue
337 for sock in sread:
338 if sock is self.server_socket:
339 qemusock, addr = self.server_socket.accept()
340 qemusock.setblocking(0)
341 socklist.append(qemusock)
342 socklist.remove(self.server_socket)
343 self.logger.debug("Connection from %s:%s" % addr)
344 else:
345 data = data + sock.recv(1024)
346 if data:
347 bootlog += data
Andrew Geissler82c905d2020-04-13 13:39:40 -0500348 if self.serial_ports < 2:
349 # this socket has mixed console/kernel data, log it to logfile
350 self.log(data)
351
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500352 data = b''
Andrew Geissler82c905d2020-04-13 13:39:40 -0500353 if self.boot_patterns['search_reached_prompt'] in bootlog:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500354 self.server_socket = qemusock
355 stopread = True
356 reachedlogin = True
Brad Bishop316dfdd2018-06-25 12:45:53 -0400357 self.logger.debug("Reached login banner in %s seconds (%s)" %
358 (time.time() - (endtime - self.boottime),
359 time.strftime("%D %H:%M:%S")))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500360 else:
Brad Bishop316dfdd2018-06-25 12:45:53 -0400361 # no need to check if reachedlogin unless we support multiple connections
362 self.logger.debug("QEMU socket disconnected before login banner reached. (%s)" %
363 time.strftime("%D %H:%M:%S"))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500364 socklist.remove(sock)
365 sock.close()
366 stopread = True
367
368
369 if not reachedlogin:
Brad Bishop316dfdd2018-06-25 12:45:53 -0400370 if time.time() >= endtime:
Brad Bishop96ff1982019-08-19 13:50:42 -0400371 self.logger.warning("Target didn't reach login banner in %d seconds (%s)" %
Brad Bishop316dfdd2018-06-25 12:45:53 -0400372 (self.boottime, time.strftime("%D %H:%M:%S")))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500373 tail = lambda l: "\n".join(l.splitlines()[-25:])
Brad Bishopd89cb5f2019-04-10 09:02:41 -0400374 bootlog = bootlog.decode("utf-8")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500375 # in case bootlog is empty, use tail qemu log store at self.msg
376 lines = tail(bootlog if bootlog else self.msg)
Brad Bishop96ff1982019-08-19 13:50:42 -0400377 self.logger.warning("Last 25 lines of text:\n%s" % lines)
378 self.logger.warning("Check full boot log: %s" % self.logfile)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500379 self._dump_host()
380 self.stop()
381 return False
382
383 # If we are not able to login the tests can continue
384 try:
Andrew Geissler82c905d2020-04-13 13:39:40 -0500385 (status, output) = self.run_serial(self.boot_patterns['send_login_user'], raw=True)
386 if re.search(self.boot_patterns['search_login_succeeded'], output):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500387 self.logged = True
388 self.logger.debug("Logged as root in serial console")
389 if netconf:
390 # configure guest networking
391 cmd = "ifconfig eth0 %s netmask %s up\n" % (self.ip, self.netmask)
392 output = self.run_serial(cmd, raw=True)[1]
Brad Bishopf86d0552018-12-04 14:18:15 -0800393 if re.search(r"root@[a-zA-Z0-9\-]+:~#", output):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500394 self.logger.debug("configured ip address %s", self.ip)
395 else:
396 self.logger.debug("Couldn't configure guest networking")
397 else:
Brad Bishop96ff1982019-08-19 13:50:42 -0400398 self.logger.warning("Couldn't login into serial console"
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500399 " as root using blank password")
Brad Bishop96ff1982019-08-19 13:50:42 -0400400 self.logger.warning("The output:\n%s" % output)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500401 except:
Brad Bishop96ff1982019-08-19 13:50:42 -0400402 self.logger.warning("Serial console failed while trying to login")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500403 return True
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500404
405 def stop(self):
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500406 if hasattr(self, "origchldhandler"):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500407 signal.signal(signal.SIGCHLD, self.origchldhandler)
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800408 self.stop_thread()
409 self.stop_qemu_system()
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500410 if self.runqemu:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600411 if hasattr(self, "monitorpid"):
412 os.kill(self.monitorpid, signal.SIGKILL)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500413 self.logger.debug("Sending SIGTERM to runqemu")
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600414 try:
415 os.killpg(os.getpgid(self.runqemu.pid), signal.SIGTERM)
416 except OSError as e:
417 if e.errno != errno.ESRCH:
418 raise
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500419 endtime = time.time() + self.runqemutime
420 while self.runqemu.poll() is None and time.time() < endtime:
421 time.sleep(1)
422 if self.runqemu.poll() is None:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500423 self.logger.debug("Sending SIGKILL to runqemu")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500424 os.killpg(os.getpgid(self.runqemu.pid), signal.SIGKILL)
Brad Bishopf86d0552018-12-04 14:18:15 -0800425 self.runqemu.stdin.close()
426 self.runqemu.stdout.close()
Andrew Geissler82c905d2020-04-13 13:39:40 -0500427 self.runqemu_exited = True
Brad Bishopf86d0552018-12-04 14:18:15 -0800428
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500429 if hasattr(self, 'server_socket') and self.server_socket:
430 self.server_socket.close()
431 self.server_socket = None
Brad Bishopf86d0552018-12-04 14:18:15 -0800432 if hasattr(self, 'threadsock') and self.threadsock:
433 self.threadsock.close()
434 self.threadsock = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500435 self.qemupid = None
436 self.ip = None
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500437 if os.path.exists(self.qemu_pidfile):
Andrew Geissler82c905d2020-04-13 13:39:40 -0500438 try:
439 os.remove(self.qemu_pidfile)
440 except FileNotFoundError as e:
441 # We raced, ignore
442 pass
Brad Bishopf86d0552018-12-04 14:18:15 -0800443 if self.monitorpipe:
444 self.monitorpipe.close()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500445
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500446 def stop_qemu_system(self):
447 if self.qemupid:
448 try:
449 # qemu-system behaves well and a SIGTERM is enough
450 os.kill(self.qemupid, signal.SIGTERM)
451 except ProcessLookupError as e:
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800452 self.logger.warning('qemu-system ended unexpectedly')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500453
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500454 def stop_thread(self):
455 if self.thread and self.thread.is_alive():
456 self.thread.stop()
457 self.thread.join()
458
459 def restart(self, qemuparams = None):
Brad Bishop96ff1982019-08-19 13:50:42 -0400460 self.logger.warning("Restarting qemu process")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500461 if self.runqemu.poll() is None:
462 self.stop()
463 if self.start(qemuparams):
464 return True
465 return False
466
467 def is_alive(self):
Andrew Geissler82c905d2020-04-13 13:39:40 -0500468 if not self.runqemu or self.runqemu.poll() is not None or self.runqemu_exited:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500469 return False
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500470 if os.path.isfile(self.qemu_pidfile):
Brad Bishop96ff1982019-08-19 13:50:42 -0400471 # when handling pidfile, qemu creates the file, stat it, lock it and then write to it
472 # so it's possible that the file has been created but the content is empty
473 pidfile_timeout = time.time() + 3
474 while time.time() < pidfile_timeout:
475 with open(self.qemu_pidfile, 'r') as f:
476 qemu_pid = f.read().strip()
477 # file created but not yet written contents
478 if not qemu_pid:
479 time.sleep(0.5)
480 continue
481 else:
482 if os.path.exists("/proc/" + qemu_pid):
483 self.qemupid = int(qemu_pid)
484 return True
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500485 return False
486
Brad Bishop977dc1a2019-02-06 16:01:43 -0500487 def run_serial(self, command, raw=False, timeout=60):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500488 # We assume target system have echo to get command status
489 if not raw:
490 command = "%s; echo $?\n" % command
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500491
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500492 data = ''
493 status = 0
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600494 self.server_socket.sendall(command.encode('utf-8'))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500495 start = time.time()
496 end = start + timeout
497 while True:
498 now = time.time()
499 if now >= end:
500 data += "<<< run_serial(): command timed out after %d seconds without output >>>\r\n\r\n" % timeout
501 break
502 try:
503 sread, _, _ = select.select([self.server_socket],[],[], end - now)
504 except InterruptedError:
505 continue
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500506 if sread:
507 answer = self.server_socket.recv(1024)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500508 if answer:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600509 data += answer.decode('utf-8')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500510 # Search the prompt to stop
Andrew Geissler82c905d2020-04-13 13:39:40 -0500511 if re.search(self.boot_patterns['search_cmd_finished'], data):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500512 break
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500513 else:
514 raise Exception("No data on serial console socket")
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500515
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500516 if data:
517 if raw:
518 status = 1
519 else:
520 # Remove first line (command line) and last line (prompt)
521 data = data[data.find('$?\r\n')+4:data.rfind('\r\n')]
522 index = data.rfind('\r\n')
523 if index == -1:
524 status_cmd = data
525 data = ""
526 else:
527 status_cmd = data[index+2:]
528 data = data[:index]
529 if (status_cmd == "0"):
530 status = 1
531 return (status, str(data))
532
533
534 def _dump_host(self):
535 self.host_dumper.create_dir("qemu")
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800536 self.logger.warning("Qemu ended unexpectedly, dump data from host"
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500537 " is in %s" % self.host_dumper.dump_dir)
538 self.host_dumper.dump_host()
539
540# This class is for reading data from a socket and passing it to logfunc
541# to be processed. It's completely event driven and has a straightforward
542# event loop. The mechanism for stopping the thread is a simple pipe which
543# will wake up the poll and allow for tearing everything down.
544class LoggingThread(threading.Thread):
545 def __init__(self, logfunc, sock, logger):
546 self.connection_established = threading.Event()
547 self.serversock = sock
548 self.logfunc = logfunc
549 self.logger = logger
550 self.readsock = None
551 self.running = False
552
553 self.errorevents = select.POLLERR | select.POLLHUP | select.POLLNVAL
554 self.readevents = select.POLLIN | select.POLLPRI
555
556 threading.Thread.__init__(self, target=self.threadtarget)
557
558 def threadtarget(self):
559 try:
560 self.eventloop()
561 finally:
562 self.teardown()
563
564 def run(self):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500565 self.logger.debug("Starting logging thread")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500566 self.readpipe, self.writepipe = os.pipe()
567 threading.Thread.run(self)
568
569 def stop(self):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500570 self.logger.debug("Stopping logging thread")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500571 if self.running:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600572 os.write(self.writepipe, bytes("stop", "utf-8"))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500573
574 def teardown(self):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500575 self.logger.debug("Tearing down logging thread")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500576 self.close_socket(self.serversock)
577
578 if self.readsock is not None:
579 self.close_socket(self.readsock)
580
581 self.close_ignore_error(self.readpipe)
582 self.close_ignore_error(self.writepipe)
583 self.running = False
584
585 def eventloop(self):
586 poll = select.poll()
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500587 event_read_mask = self.errorevents | self.readevents
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500588 poll.register(self.serversock.fileno())
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500589 poll.register(self.readpipe, event_read_mask)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500590
591 breakout = False
592 self.running = True
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500593 self.logger.debug("Starting thread event loop")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500594 while not breakout:
595 events = poll.poll()
596 for event in events:
597 # An error occurred, bail out
598 if event[1] & self.errorevents:
599 raise Exception(self.stringify_event(event[1]))
600
601 # Event to stop the thread
602 if self.readpipe == event[0]:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500603 self.logger.debug("Stop event received")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500604 breakout = True
605 break
606
607 # A connection request was received
608 elif self.serversock.fileno() == event[0]:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500609 self.logger.debug("Connection request received")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500610 self.readsock, _ = self.serversock.accept()
611 self.readsock.setblocking(0)
612 poll.unregister(self.serversock.fileno())
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500613 poll.register(self.readsock.fileno(), event_read_mask)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500614
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500615 self.logger.debug("Setting connection established event")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500616 self.connection_established.set()
617
618 # Actual data to be logged
619 elif self.readsock.fileno() == event[0]:
620 data = self.recv(1024)
621 self.logfunc(data)
622
623 # Since the socket is non-blocking make sure to honor EAGAIN
624 # and EWOULDBLOCK.
625 def recv(self, count):
626 try:
627 data = self.readsock.recv(count)
628 except socket.error as e:
629 if e.errno == errno.EAGAIN or e.errno == errno.EWOULDBLOCK:
630 return ''
631 else:
632 raise
633
634 if data is None:
635 raise Exception("No data on read ready socket")
636 elif not data:
637 # This actually means an orderly shutdown
638 # happened. But for this code it counts as an
639 # error since the connection shouldn't go away
640 # until qemu exits.
641 raise Exception("Console connection closed unexpectedly")
642
643 return data
644
645 def stringify_event(self, event):
646 val = ''
647 if select.POLLERR == event:
648 val = 'POLLER'
649 elif select.POLLHUP == event:
650 val = 'POLLHUP'
651 elif select.POLLNVAL == event:
652 val = 'POLLNVAL'
653 return val
654
655 def close_socket(self, sock):
656 sock.shutdown(socket.SHUT_RDWR)
657 sock.close()
658
659 def close_ignore_error(self, fd):
660 try:
661 os.close(fd)
662 except OSError:
663 pass