qemurunner.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. # Copyright (C) 2013 Intel Corporation
  2. #
  3. # Released under the MIT license (see COPYING.MIT)
  4. # This module provides a class for starting qemu images using runqemu.
  5. # It's used by testimage.bbclass.
  6. import subprocess
  7. import os
  8. import sys
  9. import time
  10. import signal
  11. import re
  12. import socket
  13. import select
  14. import errno
  15. import string
  16. import threading
  17. import codecs
  18. import logging
  19. from oeqa.utils.dump import HostDumper
  20. # Get Unicode non printable control chars
  21. control_range = list(range(0,32))+list(range(127,160))
  22. control_chars = [chr(x) for x in control_range
  23. if chr(x) not in string.printable]
  24. re_control_char = re.compile('[%s]' % re.escape("".join(control_chars)))
  25. class QemuRunner:
  26. def __init__(self, machine, rootfs, display, tmpdir, deploy_dir_image, logfile, boottime, dump_dir, dump_host_cmds, use_kvm, logger):
  27. # Popen object for runqemu
  28. self.runqemu = None
  29. # pid of the qemu process that runqemu will start
  30. self.qemupid = None
  31. # target ip - from the command line or runqemu output
  32. self.ip = None
  33. # host ip - where qemu is running
  34. self.server_ip = None
  35. # target ip netmask
  36. self.netmask = None
  37. self.machine = machine
  38. self.rootfs = rootfs
  39. self.display = display
  40. self.tmpdir = tmpdir
  41. self.deploy_dir_image = deploy_dir_image
  42. self.logfile = logfile
  43. self.boottime = boottime
  44. self.logged = False
  45. self.thread = None
  46. self.use_kvm = use_kvm
  47. self.msg = ''
  48. self.runqemutime = 120
  49. self.qemu_pidfile = 'pidfile_'+str(os.getpid())
  50. self.host_dumper = HostDumper(dump_host_cmds, dump_dir)
  51. self.logger = logger
  52. def create_socket(self):
  53. try:
  54. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  55. sock.setblocking(0)
  56. sock.bind(("127.0.0.1",0))
  57. sock.listen(2)
  58. port = sock.getsockname()[1]
  59. self.logger.debug("Created listening socket for qemu serial console on: 127.0.0.1:%s" % port)
  60. return (sock, port)
  61. except socket.error:
  62. sock.close()
  63. raise
  64. def log(self, msg):
  65. if self.logfile:
  66. # It is needed to sanitize the data received from qemu
  67. # because is possible to have control characters
  68. msg = msg.decode("utf-8", errors='ignore')
  69. msg = re_control_char.sub('', msg)
  70. self.msg += msg
  71. with codecs.open(self.logfile, "a", encoding="utf-8") as f:
  72. f.write("%s" % msg)
  73. def getOutput(self, o):
  74. import fcntl
  75. fl = fcntl.fcntl(o, fcntl.F_GETFL)
  76. fcntl.fcntl(o, fcntl.F_SETFL, fl | os.O_NONBLOCK)
  77. return os.read(o.fileno(), 1000000).decode("utf-8")
  78. def handleSIGCHLD(self, signum, frame):
  79. if self.runqemu and self.runqemu.poll():
  80. if self.runqemu.returncode:
  81. self.logger.debug('runqemu exited with code %d' % self.runqemu.returncode)
  82. self.logger.debug("Output from runqemu:\n%s" % self.getOutput(self.runqemu.stdout))
  83. self.stop()
  84. self._dump_host()
  85. raise SystemExit
  86. def start(self, qemuparams = None, get_ip = True, extra_bootparams = None, runqemuparams='', launch_cmd=None, discard_writes=True):
  87. env = os.environ.copy()
  88. if self.display:
  89. env["DISPLAY"] = self.display
  90. # Set this flag so that Qemu doesn't do any grabs as SDL grabs
  91. # interact badly with screensavers.
  92. env["QEMU_DONT_GRAB"] = "1"
  93. if not os.path.exists(self.rootfs):
  94. self.logger.error("Invalid rootfs %s" % self.rootfs)
  95. return False
  96. if not os.path.exists(self.tmpdir):
  97. self.logger.error("Invalid TMPDIR path %s" % self.tmpdir)
  98. return False
  99. else:
  100. env["OE_TMPDIR"] = self.tmpdir
  101. if not os.path.exists(self.deploy_dir_image):
  102. self.logger.error("Invalid DEPLOY_DIR_IMAGE path %s" % self.deploy_dir_image)
  103. return False
  104. else:
  105. env["DEPLOY_DIR_IMAGE"] = self.deploy_dir_image
  106. if not launch_cmd:
  107. launch_cmd = 'runqemu %s %s ' % ('snapshot' if discard_writes else '', runqemuparams)
  108. if self.use_kvm:
  109. self.logger.debug('Using kvm for runqemu')
  110. launch_cmd += ' kvm'
  111. else:
  112. self.logger.debug('Not using kvm for runqemu')
  113. if not self.display:
  114. launch_cmd += ' nographic'
  115. launch_cmd += ' %s %s' % (self.machine, self.rootfs)
  116. return self.launch(launch_cmd, qemuparams=qemuparams, get_ip=get_ip, extra_bootparams=extra_bootparams, env=env)
  117. def launch(self, launch_cmd, get_ip = True, qemuparams = None, extra_bootparams = None, env = None):
  118. try:
  119. threadsock, threadport = self.create_socket()
  120. self.server_socket, self.serverport = self.create_socket()
  121. except socket.error as msg:
  122. self.logger.error("Failed to create listening socket: %s" % msg[1])
  123. return False
  124. bootparams = 'console=tty1 console=ttyS0,115200n8 printk.time=1'
  125. if extra_bootparams:
  126. bootparams = bootparams + ' ' + extra_bootparams
  127. # Ask QEMU to store the QEMU process PID in file, this way we don't have to parse running processes
  128. # and analyze descendents in order to determine it.
  129. if os.path.exists(self.qemu_pidfile):
  130. os.remove(self.qemu_pidfile)
  131. self.qemuparams = 'bootparams="{0}" qemuparams="-serial tcp:127.0.0.1:{1} -pidfile {2}"'.format(bootparams, threadport, self.qemu_pidfile)
  132. if qemuparams:
  133. self.qemuparams = self.qemuparams[:-1] + " " + qemuparams + " " + '\"'
  134. launch_cmd += ' tcpserial=%s %s' % (self.serverport, self.qemuparams)
  135. self.origchldhandler = signal.getsignal(signal.SIGCHLD)
  136. signal.signal(signal.SIGCHLD, self.handleSIGCHLD)
  137. self.logger.debug('launchcmd=%s'%(launch_cmd))
  138. # FIXME: We pass in stdin=subprocess.PIPE here to work around stty
  139. # blocking at the end of the runqemu script when using this within
  140. # oe-selftest (this makes stty error out immediately). There ought
  141. # to be a proper fix but this will suffice for now.
  142. self.runqemu = subprocess.Popen(launch_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, preexec_fn=os.setpgrp, env=env)
  143. output = self.runqemu.stdout
  144. #
  145. # We need the preexec_fn above so that all runqemu processes can easily be killed
  146. # (by killing their process group). This presents a problem if this controlling
  147. # process itself is killed however since those processes don't notice the death
  148. # of the parent and merrily continue on.
  149. #
  150. # Rather than hack runqemu to deal with this, we add something here instead.
  151. # Basically we fork off another process which holds an open pipe to the parent
  152. # and also is setpgrp. If/when the pipe sees EOF from the parent dieing, it kills
  153. # the process group. This is like pctrl's PDEATHSIG but for a process group
  154. # rather than a single process.
  155. #
  156. r, w = os.pipe()
  157. self.monitorpid = os.fork()
  158. if self.monitorpid:
  159. os.close(r)
  160. self.monitorpipe = os.fdopen(w, "w")
  161. else:
  162. # child process
  163. os.setpgrp()
  164. os.close(w)
  165. r = os.fdopen(r)
  166. x = r.read()
  167. os.killpg(os.getpgid(self.runqemu.pid), signal.SIGTERM)
  168. sys.exit(0)
  169. self.logger.debug("runqemu started, pid is %s" % self.runqemu.pid)
  170. self.logger.debug("waiting at most %s seconds for qemu pid (%s)" %
  171. (self.runqemutime, time.strftime("%D %H:%M:%S")))
  172. endtime = time.time() + self.runqemutime
  173. while not self.is_alive() and time.time() < endtime:
  174. if self.runqemu.poll():
  175. if self.runqemu.returncode:
  176. # No point waiting any longer
  177. self.logger.debug('runqemu exited with code %d' % self.runqemu.returncode)
  178. self._dump_host()
  179. self.stop()
  180. self.logger.debug("Output from runqemu:\n%s" % self.getOutput(output))
  181. return False
  182. time.sleep(0.5)
  183. if not self.is_alive():
  184. self.logger.error("Qemu pid didn't appear in %s seconds (%s)" %
  185. (self.runqemutime, time.strftime("%D %H:%M:%S")))
  186. # Dump all processes to help us to figure out what is going on...
  187. ps = subprocess.Popen(['ps', 'axww', '-o', 'pid,ppid,command '], stdout=subprocess.PIPE).communicate()[0]
  188. processes = ps.decode("utf-8")
  189. self.logger.debug("Running processes:\n%s" % processes)
  190. self._dump_host()
  191. self.stop()
  192. op = self.getOutput(output)
  193. if op:
  194. self.logger.error("Output from runqemu:\n%s" % op)
  195. else:
  196. self.logger.error("No output from runqemu.\n")
  197. return False
  198. # We are alive: qemu is running
  199. out = self.getOutput(output)
  200. netconf = False # network configuration is not required by default
  201. self.logger.debug("qemu started in %s seconds - qemu procces pid is %s (%s)" %
  202. (time.time() - (endtime - self.runqemutime),
  203. self.qemupid, time.strftime("%D %H:%M:%S")))
  204. if get_ip:
  205. cmdline = ''
  206. with open('/proc/%s/cmdline' % self.qemupid) as p:
  207. cmdline = p.read()
  208. # It is needed to sanitize the data received
  209. # because is possible to have control characters
  210. cmdline = re_control_char.sub(' ', cmdline)
  211. try:
  212. ips = re.findall("((?:[0-9]{1,3}\.){3}[0-9]{1,3})", cmdline.split("ip=")[1])
  213. self.ip = ips[0]
  214. self.server_ip = ips[1]
  215. self.logger.debug("qemu cmdline used:\n{}".format(cmdline))
  216. except (IndexError, ValueError):
  217. # Try to get network configuration from runqemu output
  218. match = re.match('.*Network configuration: ([0-9.]+)::([0-9.]+):([0-9.]+)$.*',
  219. out, re.MULTILINE|re.DOTALL)
  220. if match:
  221. self.ip, self.server_ip, self.netmask = match.groups()
  222. # network configuration is required as we couldn't get it
  223. # from the runqemu command line, so qemu doesn't run kernel
  224. # and guest networking is not configured
  225. netconf = True
  226. else:
  227. self.logger.error("Couldn't get ip from qemu command line and runqemu output! "
  228. "Here is the qemu command line used:\n%s\n"
  229. "and output from runqemu:\n%s" % (cmdline, out))
  230. self._dump_host()
  231. self.stop()
  232. return False
  233. self.logger.debug("Target IP: %s" % self.ip)
  234. self.logger.debug("Server IP: %s" % self.server_ip)
  235. self.thread = LoggingThread(self.log, threadsock, self.logger)
  236. self.thread.start()
  237. if not self.thread.connection_established.wait(self.boottime):
  238. self.logger.error("Didn't receive a console connection from qemu. "
  239. "Here is the qemu command line used:\n%s\nand "
  240. "output from runqemu:\n%s" % (cmdline, out))
  241. self.stop_thread()
  242. return False
  243. self.logger.debug("Output from runqemu:\n%s", out)
  244. self.logger.debug("Waiting at most %d seconds for login banner (%s)" %
  245. (self.boottime, time.strftime("%D %H:%M:%S")))
  246. endtime = time.time() + self.boottime
  247. socklist = [self.server_socket]
  248. reachedlogin = False
  249. stopread = False
  250. qemusock = None
  251. bootlog = b''
  252. data = b''
  253. while time.time() < endtime and not stopread:
  254. try:
  255. sread, swrite, serror = select.select(socklist, [], [], 5)
  256. except InterruptedError:
  257. continue
  258. for sock in sread:
  259. if sock is self.server_socket:
  260. qemusock, addr = self.server_socket.accept()
  261. qemusock.setblocking(0)
  262. socklist.append(qemusock)
  263. socklist.remove(self.server_socket)
  264. self.logger.debug("Connection from %s:%s" % addr)
  265. else:
  266. data = data + sock.recv(1024)
  267. if data:
  268. bootlog += data
  269. data = b''
  270. if b' login:' in bootlog:
  271. self.server_socket = qemusock
  272. stopread = True
  273. reachedlogin = True
  274. self.logger.debug("Reached login banner in %s seconds (%s)" %
  275. (time.time() - (endtime - self.boottime),
  276. time.strftime("%D %H:%M:%S")))
  277. else:
  278. # no need to check if reachedlogin unless we support multiple connections
  279. self.logger.debug("QEMU socket disconnected before login banner reached. (%s)" %
  280. time.strftime("%D %H:%M:%S"))
  281. socklist.remove(sock)
  282. sock.close()
  283. stopread = True
  284. if not reachedlogin:
  285. if time.time() >= endtime:
  286. self.logger.debug("Target didn't reach login banner in %d seconds (%s)" %
  287. (self.boottime, time.strftime("%D %H:%M:%S")))
  288. tail = lambda l: "\n".join(l.splitlines()[-25:])
  289. # in case bootlog is empty, use tail qemu log store at self.msg
  290. lines = tail(bootlog if bootlog else self.msg)
  291. self.logger.debug("Last 25 lines of text:\n%s" % lines)
  292. self.logger.debug("Check full boot log: %s" % self.logfile)
  293. self._dump_host()
  294. self.stop()
  295. return False
  296. # If we are not able to login the tests can continue
  297. try:
  298. (status, output) = self.run_serial("root\n", raw=True)
  299. if re.search("root@[a-zA-Z0-9\-]+:~#", output):
  300. self.logged = True
  301. self.logger.debug("Logged as root in serial console")
  302. if netconf:
  303. # configure guest networking
  304. cmd = "ifconfig eth0 %s netmask %s up\n" % (self.ip, self.netmask)
  305. output = self.run_serial(cmd, raw=True)[1]
  306. if re.search("root@[a-zA-Z0-9\-]+:~#", output):
  307. self.logger.debug("configured ip address %s", self.ip)
  308. else:
  309. self.logger.debug("Couldn't configure guest networking")
  310. else:
  311. self.logger.debug("Couldn't login into serial console"
  312. " as root using blank password")
  313. except:
  314. self.logger.debug("Serial console failed while trying to login")
  315. return True
  316. def stop(self):
  317. self.stop_thread()
  318. self.stop_qemu_system()
  319. if hasattr(self, "origchldhandler"):
  320. signal.signal(signal.SIGCHLD, self.origchldhandler)
  321. if self.runqemu:
  322. if hasattr(self, "monitorpid"):
  323. os.kill(self.monitorpid, signal.SIGKILL)
  324. self.logger.debug("Sending SIGTERM to runqemu")
  325. try:
  326. os.killpg(os.getpgid(self.runqemu.pid), signal.SIGTERM)
  327. except OSError as e:
  328. if e.errno != errno.ESRCH:
  329. raise
  330. endtime = time.time() + self.runqemutime
  331. while self.runqemu.poll() is None and time.time() < endtime:
  332. time.sleep(1)
  333. if self.runqemu.poll() is None:
  334. self.logger.debug("Sending SIGKILL to runqemu")
  335. os.killpg(os.getpgid(self.runqemu.pid), signal.SIGKILL)
  336. self.runqemu = None
  337. if hasattr(self, 'server_socket') and self.server_socket:
  338. self.server_socket.close()
  339. self.server_socket = None
  340. self.qemupid = None
  341. self.ip = None
  342. if os.path.exists(self.qemu_pidfile):
  343. os.remove(self.qemu_pidfile)
  344. def stop_qemu_system(self):
  345. if self.qemupid:
  346. try:
  347. # qemu-system behaves well and a SIGTERM is enough
  348. os.kill(self.qemupid, signal.SIGTERM)
  349. except ProcessLookupError as e:
  350. self.logger.warning('qemu-system ended unexpectedly')
  351. def stop_thread(self):
  352. if self.thread and self.thread.is_alive():
  353. self.thread.stop()
  354. self.thread.join()
  355. def restart(self, qemuparams = None):
  356. self.logger.debug("Restarting qemu process")
  357. if self.runqemu.poll() is None:
  358. self.stop()
  359. if self.start(qemuparams):
  360. return True
  361. return False
  362. def is_alive(self):
  363. if not self.runqemu:
  364. return False
  365. if os.path.isfile(self.qemu_pidfile):
  366. f = open(self.qemu_pidfile, 'r')
  367. qemu_pid = f.read()
  368. f.close()
  369. qemupid = int(qemu_pid)
  370. if os.path.exists("/proc/" + str(qemupid)):
  371. self.qemupid = qemupid
  372. return True
  373. return False
  374. def run_serial(self, command, raw=False, timeout=5):
  375. # We assume target system have echo to get command status
  376. if not raw:
  377. command = "%s; echo $?\n" % command
  378. data = ''
  379. status = 0
  380. self.server_socket.sendall(command.encode('utf-8'))
  381. start = time.time()
  382. end = start + timeout
  383. while True:
  384. now = time.time()
  385. if now >= end:
  386. data += "<<< run_serial(): command timed out after %d seconds without output >>>\r\n\r\n" % timeout
  387. break
  388. try:
  389. sread, _, _ = select.select([self.server_socket],[],[], end - now)
  390. except InterruptedError:
  391. continue
  392. if sread:
  393. answer = self.server_socket.recv(1024)
  394. if answer:
  395. data += answer.decode('utf-8')
  396. # Search the prompt to stop
  397. if re.search("[a-zA-Z0-9]+@[a-zA-Z0-9\-]+:~#", data):
  398. break
  399. else:
  400. raise Exception("No data on serial console socket")
  401. if data:
  402. if raw:
  403. status = 1
  404. else:
  405. # Remove first line (command line) and last line (prompt)
  406. data = data[data.find('$?\r\n')+4:data.rfind('\r\n')]
  407. index = data.rfind('\r\n')
  408. if index == -1:
  409. status_cmd = data
  410. data = ""
  411. else:
  412. status_cmd = data[index+2:]
  413. data = data[:index]
  414. if (status_cmd == "0"):
  415. status = 1
  416. return (status, str(data))
  417. def _dump_host(self):
  418. self.host_dumper.create_dir("qemu")
  419. self.logger.warning("Qemu ended unexpectedly, dump data from host"
  420. " is in %s" % self.host_dumper.dump_dir)
  421. self.host_dumper.dump_host()
  422. # This class is for reading data from a socket and passing it to logfunc
  423. # to be processed. It's completely event driven and has a straightforward
  424. # event loop. The mechanism for stopping the thread is a simple pipe which
  425. # will wake up the poll and allow for tearing everything down.
  426. class LoggingThread(threading.Thread):
  427. def __init__(self, logfunc, sock, logger):
  428. self.connection_established = threading.Event()
  429. self.serversock = sock
  430. self.logfunc = logfunc
  431. self.logger = logger
  432. self.readsock = None
  433. self.running = False
  434. self.errorevents = select.POLLERR | select.POLLHUP | select.POLLNVAL
  435. self.readevents = select.POLLIN | select.POLLPRI
  436. threading.Thread.__init__(self, target=self.threadtarget)
  437. def threadtarget(self):
  438. try:
  439. self.eventloop()
  440. finally:
  441. self.teardown()
  442. def run(self):
  443. self.logger.debug("Starting logging thread")
  444. self.readpipe, self.writepipe = os.pipe()
  445. threading.Thread.run(self)
  446. def stop(self):
  447. self.logger.debug("Stopping logging thread")
  448. if self.running:
  449. os.write(self.writepipe, bytes("stop", "utf-8"))
  450. def teardown(self):
  451. self.logger.debug("Tearing down logging thread")
  452. self.close_socket(self.serversock)
  453. if self.readsock is not None:
  454. self.close_socket(self.readsock)
  455. self.close_ignore_error(self.readpipe)
  456. self.close_ignore_error(self.writepipe)
  457. self.running = False
  458. def eventloop(self):
  459. poll = select.poll()
  460. event_read_mask = self.errorevents | self.readevents
  461. poll.register(self.serversock.fileno())
  462. poll.register(self.readpipe, event_read_mask)
  463. breakout = False
  464. self.running = True
  465. self.logger.debug("Starting thread event loop")
  466. while not breakout:
  467. events = poll.poll()
  468. for event in events:
  469. # An error occurred, bail out
  470. if event[1] & self.errorevents:
  471. raise Exception(self.stringify_event(event[1]))
  472. # Event to stop the thread
  473. if self.readpipe == event[0]:
  474. self.logger.debug("Stop event received")
  475. breakout = True
  476. break
  477. # A connection request was received
  478. elif self.serversock.fileno() == event[0]:
  479. self.logger.debug("Connection request received")
  480. self.readsock, _ = self.serversock.accept()
  481. self.readsock.setblocking(0)
  482. poll.unregister(self.serversock.fileno())
  483. poll.register(self.readsock.fileno(), event_read_mask)
  484. self.logger.debug("Setting connection established event")
  485. self.connection_established.set()
  486. # Actual data to be logged
  487. elif self.readsock.fileno() == event[0]:
  488. data = self.recv(1024)
  489. self.logfunc(data)
  490. # Since the socket is non-blocking make sure to honor EAGAIN
  491. # and EWOULDBLOCK.
  492. def recv(self, count):
  493. try:
  494. data = self.readsock.recv(count)
  495. except socket.error as e:
  496. if e.errno == errno.EAGAIN or e.errno == errno.EWOULDBLOCK:
  497. return ''
  498. else:
  499. raise
  500. if data is None:
  501. raise Exception("No data on read ready socket")
  502. elif not data:
  503. # This actually means an orderly shutdown
  504. # happened. But for this code it counts as an
  505. # error since the connection shouldn't go away
  506. # until qemu exits.
  507. raise Exception("Console connection closed unexpectedly")
  508. return data
  509. def stringify_event(self, event):
  510. val = ''
  511. if select.POLLERR == event:
  512. val = 'POLLER'
  513. elif select.POLLHUP == event:
  514. val = 'POLLHUP'
  515. elif select.POLLNVAL == event:
  516. val = 'POLLNVAL'
  517. return val
  518. def close_socket(self, sock):
  519. sock.shutdown(socket.SHUT_RDWR)
  520. sock.close()
  521. def close_ignore_error(self, fd):
  522. try:
  523. os.close(fd)
  524. except OSError:
  525. pass