blob: cd95d33bdc815870465d0a57e5a438d75c78cd84 [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,
Brad Bishop35a77422020-05-26 13:25:03 -040035 use_kvm, logger, use_slirp=False, serial_ports=2, boot_patterns = defaultdict(str)):
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
Brad Bishop19323692019-04-05 15:28:33 -040059 self.use_slirp = use_slirp
Andrew Geissler82c905d2020-04-13 13:39:40 -050060 self.serial_ports = serial_ports
Brad Bishopd7bf8c12018-02-25 22:55:05 -050061 self.msg = ''
Andrew Geissler82c905d2020-04-13 13:39:40 -050062 self.boot_patterns = boot_patterns
Patrick Williamsc124f4f2015-09-15 14:41:29 -050063
Brad Bishopd7bf8c12018-02-25 22:55:05 -050064 self.runqemutime = 120
65 self.qemu_pidfile = 'pidfile_'+str(os.getpid())
Patrick Williamsc124f4f2015-09-15 14:41:29 -050066 self.host_dumper = HostDumper(dump_host_cmds, dump_dir)
Brad Bishop15ae2502019-06-18 21:44:24 -040067 self.monitorpipe = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -050068
Brad Bishopd7bf8c12018-02-25 22:55:05 -050069 self.logger = logger
70
Andrew Geissler82c905d2020-04-13 13:39:40 -050071 # Enable testing other OS's
72 # Set commands for target communication, and default to Linux ALWAYS
73 # Other OS's or baremetal applications need to provide their
74 # own implementation passing it through QemuRunner's constructor
75 # or by passing them through TESTIMAGE_BOOT_PATTERNS[flag]
76 # provided variables, where <flag> is one of the mentioned below.
77 accepted_patterns = ['search_reached_prompt', 'send_login_user', 'search_login_succeeded', 'search_cmd_finished']
78 default_boot_patterns = defaultdict(str)
79 # Default to the usual paterns used to communicate with the target
80 default_boot_patterns['search_reached_prompt'] = b' login:'
81 default_boot_patterns['send_login_user'] = 'root\n'
82 default_boot_patterns['search_login_succeeded'] = r"root@[a-zA-Z0-9\-]+:~#"
83 default_boot_patterns['search_cmd_finished'] = r"[a-zA-Z0-9]+@[a-zA-Z0-9\-]+:~#"
84
85 # Only override patterns that were set e.g. login user TESTIMAGE_BOOT_PATTERNS[send_login_user] = "webserver\n"
86 for pattern in accepted_patterns:
87 if not self.boot_patterns[pattern]:
88 self.boot_patterns[pattern] = default_boot_patterns[pattern]
89
Patrick Williamsc124f4f2015-09-15 14:41:29 -050090 def create_socket(self):
91 try:
92 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
93 sock.setblocking(0)
94 sock.bind(("127.0.0.1",0))
95 sock.listen(2)
96 port = sock.getsockname()[1]
Brad Bishopd7bf8c12018-02-25 22:55:05 -050097 self.logger.debug("Created listening socket for qemu serial console on: 127.0.0.1:%s" % port)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050098 return (sock, port)
99
100 except socket.error:
101 sock.close()
102 raise
103
104 def log(self, msg):
105 if self.logfile:
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500106 # It is needed to sanitize the data received from qemu
107 # because is possible to have control characters
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500108 msg = msg.decode("utf-8", errors='ignore')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600109 msg = re_control_char.sub('', msg)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500110 self.msg += msg
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500111 with codecs.open(self.logfile, "a", encoding="utf-8") as f:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500112 f.write("%s" % msg)
113
114 def getOutput(self, o):
115 import fcntl
116 fl = fcntl.fcntl(o, fcntl.F_GETFL)
117 fcntl.fcntl(o, fcntl.F_SETFL, fl | os.O_NONBLOCK)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600118 return os.read(o.fileno(), 1000000).decode("utf-8")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500119
120
121 def handleSIGCHLD(self, signum, frame):
122 if self.runqemu and self.runqemu.poll():
123 if self.runqemu.returncode:
Andrew Geissler82c905d2020-04-13 13:39:40 -0500124 self.logger.error('runqemu exited with code %d' % self.runqemu.returncode)
125 self.logger.error('Output from runqemu:\n%s' % self.getOutput(self.runqemu.stdout))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500126 self.stop()
127 self._dump_host()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500128
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500129 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 -0500130 env = os.environ.copy()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500131 if self.display:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500132 env["DISPLAY"] = self.display
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500133 # Set this flag so that Qemu doesn't do any grabs as SDL grabs
134 # interact badly with screensavers.
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500135 env["QEMU_DONT_GRAB"] = "1"
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500136 if not os.path.exists(self.rootfs):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500137 self.logger.error("Invalid rootfs %s" % self.rootfs)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500138 return False
139 if not os.path.exists(self.tmpdir):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500140 self.logger.error("Invalid TMPDIR path %s" % self.tmpdir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500141 return False
142 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500143 env["OE_TMPDIR"] = self.tmpdir
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500144 if not os.path.exists(self.deploy_dir_image):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500145 self.logger.error("Invalid DEPLOY_DIR_IMAGE path %s" % self.deploy_dir_image)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500146 return False
147 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500148 env["DEPLOY_DIR_IMAGE"] = self.deploy_dir_image
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500149
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500150 if not launch_cmd:
Brad Bishop08902b02019-08-20 09:16:51 -0400151 launch_cmd = 'runqemu %s' % ('snapshot' if discard_writes else '')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500152 if self.use_kvm:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500153 self.logger.debug('Using kvm for runqemu')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500154 launch_cmd += ' kvm'
155 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500156 self.logger.debug('Not using kvm for runqemu')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500157 if not self.display:
158 launch_cmd += ' nographic'
Brad Bishop19323692019-04-05 15:28:33 -0400159 if self.use_slirp:
160 launch_cmd += ' slirp'
Brad Bishop08902b02019-08-20 09:16:51 -0400161 launch_cmd += ' %s %s %s' % (runqemuparams, self.machine, self.rootfs)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500162
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500163 return self.launch(launch_cmd, qemuparams=qemuparams, get_ip=get_ip, extra_bootparams=extra_bootparams, env=env)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500164
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500165 def launch(self, launch_cmd, get_ip = True, qemuparams = None, extra_bootparams = None, env = None):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500166 try:
Andrew Geissler82c905d2020-04-13 13:39:40 -0500167 if self.serial_ports >= 2:
168 self.threadsock, threadport = self.create_socket()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500169 self.server_socket, self.serverport = self.create_socket()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600170 except socket.error as msg:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500171 self.logger.error("Failed to create listening socket: %s" % msg[1])
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500172 return False
173
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600174 bootparams = 'console=tty1 console=ttyS0,115200n8 printk.time=1'
175 if extra_bootparams:
176 bootparams = bootparams + ' ' + extra_bootparams
177
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500178 # Ask QEMU to store the QEMU process PID in file, this way we don't have to parse running processes
179 # and analyze descendents in order to determine it.
180 if os.path.exists(self.qemu_pidfile):
181 os.remove(self.qemu_pidfile)
Brad Bishop15ae2502019-06-18 21:44:24 -0400182 self.qemuparams = 'bootparams="{0}" qemuparams="-pidfile {1}"'.format(bootparams, self.qemu_pidfile)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500183 if qemuparams:
184 self.qemuparams = self.qemuparams[:-1] + " " + qemuparams + " " + '\"'
185
Andrew Geissler82c905d2020-04-13 13:39:40 -0500186 if self.serial_ports >= 2:
187 launch_cmd += ' tcpserial=%s:%s %s' % (threadport, self.serverport, self.qemuparams)
188 else:
189 launch_cmd += ' tcpserial=%s %s' % (self.serverport, self.qemuparams)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500190
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500191 self.origchldhandler = signal.getsignal(signal.SIGCHLD)
192 signal.signal(signal.SIGCHLD, self.handleSIGCHLD)
193
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500194 self.logger.debug('launchcmd=%s'%(launch_cmd))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600195
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500196 # FIXME: We pass in stdin=subprocess.PIPE here to work around stty
197 # blocking at the end of the runqemu script when using this within
198 # oe-selftest (this makes stty error out immediately). There ought
199 # to be a proper fix but this will suffice for now.
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500200 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 -0500201 output = self.runqemu.stdout
202
203 #
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600204 # We need the preexec_fn above so that all runqemu processes can easily be killed
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500205 # (by killing their process group). This presents a problem if this controlling
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600206 # process itself is killed however since those processes don't notice the death
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500207 # of the parent and merrily continue on.
208 #
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600209 # Rather than hack runqemu to deal with this, we add something here instead.
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500210 # Basically we fork off another process which holds an open pipe to the parent
211 # and also is setpgrp. If/when the pipe sees EOF from the parent dieing, it kills
212 # the process group. This is like pctrl's PDEATHSIG but for a process group
213 # rather than a single process.
214 #
215 r, w = os.pipe()
216 self.monitorpid = os.fork()
217 if self.monitorpid:
218 os.close(r)
219 self.monitorpipe = os.fdopen(w, "w")
220 else:
221 # child process
222 os.setpgrp()
223 os.close(w)
224 r = os.fdopen(r)
225 x = r.read()
226 os.killpg(os.getpgid(self.runqemu.pid), signal.SIGTERM)
227 sys.exit(0)
228
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500229 self.logger.debug("runqemu started, pid is %s" % self.runqemu.pid)
Brad Bishop316dfdd2018-06-25 12:45:53 -0400230 self.logger.debug("waiting at most %s seconds for qemu pid (%s)" %
231 (self.runqemutime, time.strftime("%D %H:%M:%S")))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500232 endtime = time.time() + self.runqemutime
233 while not self.is_alive() and time.time() < endtime:
234 if self.runqemu.poll():
Andrew Geissler82c905d2020-04-13 13:39:40 -0500235 if self.runqemu_exited:
236 return False
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500237 if self.runqemu.returncode:
238 # No point waiting any longer
Brad Bishop96ff1982019-08-19 13:50:42 -0400239 self.logger.warning('runqemu exited with code %d' % self.runqemu.returncode)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500240 self._dump_host()
Brad Bishop96ff1982019-08-19 13:50:42 -0400241 self.logger.warning("Output from runqemu:\n%s" % self.getOutput(output))
Brad Bishopf86d0552018-12-04 14:18:15 -0800242 self.stop()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500243 return False
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500244 time.sleep(0.5)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500245
Andrew Geissler82c905d2020-04-13 13:39:40 -0500246 if self.runqemu_exited:
247 return False
248
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500249 if not self.is_alive():
Brad Bishop316dfdd2018-06-25 12:45:53 -0400250 self.logger.error("Qemu pid didn't appear in %s seconds (%s)" %
251 (self.runqemutime, time.strftime("%D %H:%M:%S")))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500252 # Dump all processes to help us to figure out what is going on...
253 ps = subprocess.Popen(['ps', 'axww', '-o', 'pid,ppid,command '], stdout=subprocess.PIPE).communicate()[0]
254 processes = ps.decode("utf-8")
255 self.logger.debug("Running processes:\n%s" % processes)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500256 self._dump_host()
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500257 op = self.getOutput(output)
Brad Bishopf86d0552018-12-04 14:18:15 -0800258 self.stop()
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500259 if op:
260 self.logger.error("Output from runqemu:\n%s" % op)
261 else:
262 self.logger.error("No output from runqemu.\n")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500263 return False
264
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500265 # We are alive: qemu is running
266 out = self.getOutput(output)
267 netconf = False # network configuration is not required by default
Brad Bishop316dfdd2018-06-25 12:45:53 -0400268 self.logger.debug("qemu started in %s seconds - qemu procces pid is %s (%s)" %
269 (time.time() - (endtime - self.runqemutime),
270 self.qemupid, time.strftime("%D %H:%M:%S")))
Andrew Geissler82c905d2020-04-13 13:39:40 -0500271 cmdline = ''
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500272 if get_ip:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500273 with open('/proc/%s/cmdline' % self.qemupid) as p:
274 cmdline = p.read()
275 # It is needed to sanitize the data received
276 # because is possible to have control characters
277 cmdline = re_control_char.sub(' ', cmdline)
278 try:
Brad Bishop19323692019-04-05 15:28:33 -0400279 if self.use_slirp:
280 tcp_ports = cmdline.split("hostfwd=tcp::")[1]
281 host_port = tcp_ports[:tcp_ports.find('-')]
282 self.ip = "localhost:%s" % host_port
283 else:
284 ips = re.findall(r"((?:[0-9]{1,3}\.){3}[0-9]{1,3})", cmdline.split("ip=")[1])
285 self.ip = ips[0]
286 self.server_ip = ips[1]
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500287 self.logger.debug("qemu cmdline used:\n{}".format(cmdline))
288 except (IndexError, ValueError):
289 # Try to get network configuration from runqemu output
Brad Bishopf86d0552018-12-04 14:18:15 -0800290 match = re.match(r'.*Network configuration: ([0-9.]+)::([0-9.]+):([0-9.]+)$.*',
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500291 out, re.MULTILINE|re.DOTALL)
292 if match:
293 self.ip, self.server_ip, self.netmask = match.groups()
294 # network configuration is required as we couldn't get it
295 # from the runqemu command line, so qemu doesn't run kernel
296 # and guest networking is not configured
297 netconf = True
298 else:
299 self.logger.error("Couldn't get ip from qemu command line and runqemu output! "
300 "Here is the qemu command line used:\n%s\n"
301 "and output from runqemu:\n%s" % (cmdline, out))
302 self._dump_host()
303 self.stop()
304 return False
305
306 self.logger.debug("Target IP: %s" % self.ip)
307 self.logger.debug("Server IP: %s" % self.server_ip)
308
Andrew Geissler82c905d2020-04-13 13:39:40 -0500309 if self.serial_ports >= 2:
310 self.thread = LoggingThread(self.log, self.threadsock, self.logger)
311 self.thread.start()
312 if not self.thread.connection_established.wait(self.boottime):
313 self.logger.error("Didn't receive a console connection from qemu. "
314 "Here is the qemu command line used:\n%s\nand "
315 "output from runqemu:\n%s" % (cmdline, out))
316 self.stop_thread()
317 return False
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500318
319 self.logger.debug("Output from runqemu:\n%s", out)
Brad Bishop316dfdd2018-06-25 12:45:53 -0400320 self.logger.debug("Waiting at most %d seconds for login banner (%s)" %
321 (self.boottime, time.strftime("%D %H:%M:%S")))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500322 endtime = time.time() + self.boottime
323 socklist = [self.server_socket]
324 reachedlogin = False
325 stopread = False
326 qemusock = None
327 bootlog = b''
328 data = b''
329 while time.time() < endtime and not stopread:
330 try:
331 sread, swrite, serror = select.select(socklist, [], [], 5)
332 except InterruptedError:
333 continue
334 for sock in sread:
335 if sock is self.server_socket:
336 qemusock, addr = self.server_socket.accept()
337 qemusock.setblocking(0)
338 socklist.append(qemusock)
339 socklist.remove(self.server_socket)
340 self.logger.debug("Connection from %s:%s" % addr)
341 else:
342 data = data + sock.recv(1024)
343 if data:
344 bootlog += data
Andrew Geissler82c905d2020-04-13 13:39:40 -0500345 if self.serial_ports < 2:
346 # this socket has mixed console/kernel data, log it to logfile
347 self.log(data)
348
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500349 data = b''
Andrew Geissler82c905d2020-04-13 13:39:40 -0500350 if self.boot_patterns['search_reached_prompt'] in bootlog:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500351 self.server_socket = qemusock
352 stopread = True
353 reachedlogin = True
Brad Bishop316dfdd2018-06-25 12:45:53 -0400354 self.logger.debug("Reached login banner in %s seconds (%s)" %
355 (time.time() - (endtime - self.boottime),
356 time.strftime("%D %H:%M:%S")))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500357 else:
Brad Bishop316dfdd2018-06-25 12:45:53 -0400358 # no need to check if reachedlogin unless we support multiple connections
359 self.logger.debug("QEMU socket disconnected before login banner reached. (%s)" %
360 time.strftime("%D %H:%M:%S"))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500361 socklist.remove(sock)
362 sock.close()
363 stopread = True
364
365
366 if not reachedlogin:
Brad Bishop316dfdd2018-06-25 12:45:53 -0400367 if time.time() >= endtime:
Brad Bishop96ff1982019-08-19 13:50:42 -0400368 self.logger.warning("Target didn't reach login banner in %d seconds (%s)" %
Brad Bishop316dfdd2018-06-25 12:45:53 -0400369 (self.boottime, time.strftime("%D %H:%M:%S")))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500370 tail = lambda l: "\n".join(l.splitlines()[-25:])
Brad Bishopd89cb5f2019-04-10 09:02:41 -0400371 bootlog = bootlog.decode("utf-8")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500372 # in case bootlog is empty, use tail qemu log store at self.msg
373 lines = tail(bootlog if bootlog else self.msg)
Brad Bishop96ff1982019-08-19 13:50:42 -0400374 self.logger.warning("Last 25 lines of text:\n%s" % lines)
375 self.logger.warning("Check full boot log: %s" % self.logfile)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500376 self._dump_host()
377 self.stop()
378 return False
379
380 # If we are not able to login the tests can continue
381 try:
Andrew Geissler82c905d2020-04-13 13:39:40 -0500382 (status, output) = self.run_serial(self.boot_patterns['send_login_user'], raw=True)
383 if re.search(self.boot_patterns['search_login_succeeded'], output):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500384 self.logged = True
385 self.logger.debug("Logged as root in serial console")
386 if netconf:
387 # configure guest networking
388 cmd = "ifconfig eth0 %s netmask %s up\n" % (self.ip, self.netmask)
389 output = self.run_serial(cmd, raw=True)[1]
Brad Bishopf86d0552018-12-04 14:18:15 -0800390 if re.search(r"root@[a-zA-Z0-9\-]+:~#", output):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500391 self.logger.debug("configured ip address %s", self.ip)
392 else:
393 self.logger.debug("Couldn't configure guest networking")
394 else:
Brad Bishop96ff1982019-08-19 13:50:42 -0400395 self.logger.warning("Couldn't login into serial console"
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500396 " as root using blank password")
Brad Bishop96ff1982019-08-19 13:50:42 -0400397 self.logger.warning("The output:\n%s" % output)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500398 except:
Brad Bishop96ff1982019-08-19 13:50:42 -0400399 self.logger.warning("Serial console failed while trying to login")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500400 return True
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500401
402 def stop(self):
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500403 if hasattr(self, "origchldhandler"):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500404 signal.signal(signal.SIGCHLD, self.origchldhandler)
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800405 self.stop_thread()
406 self.stop_qemu_system()
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500407 if self.runqemu:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600408 if hasattr(self, "monitorpid"):
409 os.kill(self.monitorpid, signal.SIGKILL)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500410 self.logger.debug("Sending SIGTERM to runqemu")
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600411 try:
412 os.killpg(os.getpgid(self.runqemu.pid), signal.SIGTERM)
413 except OSError as e:
414 if e.errno != errno.ESRCH:
415 raise
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500416 endtime = time.time() + self.runqemutime
417 while self.runqemu.poll() is None and time.time() < endtime:
418 time.sleep(1)
419 if self.runqemu.poll() is None:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500420 self.logger.debug("Sending SIGKILL to runqemu")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500421 os.killpg(os.getpgid(self.runqemu.pid), signal.SIGKILL)
Brad Bishopf86d0552018-12-04 14:18:15 -0800422 self.runqemu.stdin.close()
423 self.runqemu.stdout.close()
Andrew Geissler82c905d2020-04-13 13:39:40 -0500424 self.runqemu_exited = True
Brad Bishopf86d0552018-12-04 14:18:15 -0800425
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500426 if hasattr(self, 'server_socket') and self.server_socket:
427 self.server_socket.close()
428 self.server_socket = None
Brad Bishopf86d0552018-12-04 14:18:15 -0800429 if hasattr(self, 'threadsock') and self.threadsock:
430 self.threadsock.close()
431 self.threadsock = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500432 self.qemupid = None
433 self.ip = None
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500434 if os.path.exists(self.qemu_pidfile):
Andrew Geissler82c905d2020-04-13 13:39:40 -0500435 try:
436 os.remove(self.qemu_pidfile)
437 except FileNotFoundError as e:
438 # We raced, ignore
439 pass
Brad Bishopf86d0552018-12-04 14:18:15 -0800440 if self.monitorpipe:
441 self.monitorpipe.close()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500442
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500443 def stop_qemu_system(self):
444 if self.qemupid:
445 try:
446 # qemu-system behaves well and a SIGTERM is enough
447 os.kill(self.qemupid, signal.SIGTERM)
448 except ProcessLookupError as e:
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800449 self.logger.warning('qemu-system ended unexpectedly')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500450
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500451 def stop_thread(self):
452 if self.thread and self.thread.is_alive():
453 self.thread.stop()
454 self.thread.join()
455
456 def restart(self, qemuparams = None):
Brad Bishop96ff1982019-08-19 13:50:42 -0400457 self.logger.warning("Restarting qemu process")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500458 if self.runqemu.poll() is None:
459 self.stop()
460 if self.start(qemuparams):
461 return True
462 return False
463
464 def is_alive(self):
Andrew Geissler82c905d2020-04-13 13:39:40 -0500465 if not self.runqemu or self.runqemu.poll() is not None or self.runqemu_exited:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500466 return False
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500467 if os.path.isfile(self.qemu_pidfile):
Brad Bishop96ff1982019-08-19 13:50:42 -0400468 # when handling pidfile, qemu creates the file, stat it, lock it and then write to it
469 # so it's possible that the file has been created but the content is empty
470 pidfile_timeout = time.time() + 3
471 while time.time() < pidfile_timeout:
472 with open(self.qemu_pidfile, 'r') as f:
473 qemu_pid = f.read().strip()
474 # file created but not yet written contents
475 if not qemu_pid:
476 time.sleep(0.5)
477 continue
478 else:
479 if os.path.exists("/proc/" + qemu_pid):
480 self.qemupid = int(qemu_pid)
481 return True
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500482 return False
483
Brad Bishop977dc1a2019-02-06 16:01:43 -0500484 def run_serial(self, command, raw=False, timeout=60):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500485 # We assume target system have echo to get command status
486 if not raw:
487 command = "%s; echo $?\n" % command
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500488
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500489 data = ''
490 status = 0
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600491 self.server_socket.sendall(command.encode('utf-8'))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500492 start = time.time()
493 end = start + timeout
494 while True:
495 now = time.time()
496 if now >= end:
497 data += "<<< run_serial(): command timed out after %d seconds without output >>>\r\n\r\n" % timeout
498 break
499 try:
500 sread, _, _ = select.select([self.server_socket],[],[], end - now)
501 except InterruptedError:
502 continue
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500503 if sread:
504 answer = self.server_socket.recv(1024)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500505 if answer:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600506 data += answer.decode('utf-8')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500507 # Search the prompt to stop
Andrew Geissler82c905d2020-04-13 13:39:40 -0500508 if re.search(self.boot_patterns['search_cmd_finished'], data):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500509 break
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500510 else:
511 raise Exception("No data on serial console socket")
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500512
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500513 if data:
514 if raw:
515 status = 1
516 else:
517 # Remove first line (command line) and last line (prompt)
518 data = data[data.find('$?\r\n')+4:data.rfind('\r\n')]
519 index = data.rfind('\r\n')
520 if index == -1:
521 status_cmd = data
522 data = ""
523 else:
524 status_cmd = data[index+2:]
525 data = data[:index]
526 if (status_cmd == "0"):
527 status = 1
528 return (status, str(data))
529
530
531 def _dump_host(self):
532 self.host_dumper.create_dir("qemu")
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800533 self.logger.warning("Qemu ended unexpectedly, dump data from host"
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500534 " is in %s" % self.host_dumper.dump_dir)
535 self.host_dumper.dump_host()
536
537# This class is for reading data from a socket and passing it to logfunc
538# to be processed. It's completely event driven and has a straightforward
539# event loop. The mechanism for stopping the thread is a simple pipe which
540# will wake up the poll and allow for tearing everything down.
541class LoggingThread(threading.Thread):
542 def __init__(self, logfunc, sock, logger):
543 self.connection_established = threading.Event()
544 self.serversock = sock
545 self.logfunc = logfunc
546 self.logger = logger
547 self.readsock = None
548 self.running = False
549
550 self.errorevents = select.POLLERR | select.POLLHUP | select.POLLNVAL
551 self.readevents = select.POLLIN | select.POLLPRI
552
553 threading.Thread.__init__(self, target=self.threadtarget)
554
555 def threadtarget(self):
556 try:
557 self.eventloop()
558 finally:
559 self.teardown()
560
561 def run(self):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500562 self.logger.debug("Starting logging thread")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500563 self.readpipe, self.writepipe = os.pipe()
564 threading.Thread.run(self)
565
566 def stop(self):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500567 self.logger.debug("Stopping logging thread")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500568 if self.running:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600569 os.write(self.writepipe, bytes("stop", "utf-8"))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500570
571 def teardown(self):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500572 self.logger.debug("Tearing down logging thread")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500573 self.close_socket(self.serversock)
574
575 if self.readsock is not None:
576 self.close_socket(self.readsock)
577
578 self.close_ignore_error(self.readpipe)
579 self.close_ignore_error(self.writepipe)
580 self.running = False
581
582 def eventloop(self):
583 poll = select.poll()
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500584 event_read_mask = self.errorevents | self.readevents
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500585 poll.register(self.serversock.fileno())
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500586 poll.register(self.readpipe, event_read_mask)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500587
588 breakout = False
589 self.running = True
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500590 self.logger.debug("Starting thread event loop")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500591 while not breakout:
592 events = poll.poll()
593 for event in events:
594 # An error occurred, bail out
595 if event[1] & self.errorevents:
596 raise Exception(self.stringify_event(event[1]))
597
598 # Event to stop the thread
599 if self.readpipe == event[0]:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500600 self.logger.debug("Stop event received")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500601 breakout = True
602 break
603
604 # A connection request was received
605 elif self.serversock.fileno() == event[0]:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500606 self.logger.debug("Connection request received")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500607 self.readsock, _ = self.serversock.accept()
608 self.readsock.setblocking(0)
609 poll.unregister(self.serversock.fileno())
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500610 poll.register(self.readsock.fileno(), event_read_mask)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500611
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500612 self.logger.debug("Setting connection established event")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500613 self.connection_established.set()
614
615 # Actual data to be logged
616 elif self.readsock.fileno() == event[0]:
617 data = self.recv(1024)
618 self.logfunc(data)
619
620 # Since the socket is non-blocking make sure to honor EAGAIN
621 # and EWOULDBLOCK.
622 def recv(self, count):
623 try:
624 data = self.readsock.recv(count)
625 except socket.error as e:
626 if e.errno == errno.EAGAIN or e.errno == errno.EWOULDBLOCK:
627 return ''
628 else:
629 raise
630
631 if data is None:
632 raise Exception("No data on read ready socket")
633 elif not data:
634 # This actually means an orderly shutdown
635 # happened. But for this code it counts as an
636 # error since the connection shouldn't go away
637 # until qemu exits.
638 raise Exception("Console connection closed unexpectedly")
639
640 return data
641
642 def stringify_event(self, event):
643 val = ''
644 if select.POLLERR == event:
645 val = 'POLLER'
646 elif select.POLLHUP == event:
647 val = 'POLLHUP'
648 elif select.POLLNVAL == event:
649 val = 'POLLNVAL'
650 return val
651
652 def close_socket(self, sock):
653 sock.shutdown(socket.SHUT_RDWR)
654 sock.close()
655
656 def close_ignore_error(self, fd):
657 try:
658 os.close(fd)
659 except OSError:
660 pass