marionette.scm 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2016, 2017, 2018, 2019, 2020, 2021 Ludovic Courtès <ludo@gnu.org>
  3. ;;; Copyright © 2018 Chris Marusich <cmmarusich@gmail.com>
  4. ;;;
  5. ;;; This file is part of GNU Guix.
  6. ;;;
  7. ;;; GNU Guix is free software; you can redistribute it and/or modify it
  8. ;;; under the terms of the GNU General Public License as published by
  9. ;;; the Free Software Foundation; either version 3 of the License, or (at
  10. ;;; your option) any later version.
  11. ;;;
  12. ;;; GNU Guix is distributed in the hope that it will be useful, but
  13. ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;;; GNU General Public License for more details.
  16. ;;;
  17. ;;; You should have received a copy of the GNU General Public License
  18. ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
  19. (define-module (gnu build marionette)
  20. #:use-module (srfi srfi-9)
  21. #:use-module (srfi srfi-26)
  22. #:use-module (srfi srfi-64)
  23. #:use-module (rnrs io ports)
  24. #:use-module (ice-9 match)
  25. #:use-module (ice-9 popen)
  26. #:export (marionette?
  27. make-marionette
  28. marionette-eval
  29. wait-for-file
  30. wait-for-tcp-port
  31. wait-for-unix-socket
  32. marionette-control
  33. marionette-screen-text
  34. wait-for-screen-text
  35. %qwerty-us-keystrokes
  36. marionette-type
  37. system-test-runner))
  38. ;;; Commentary:
  39. ;;;
  40. ;;; Instrumentation tools for QEMU virtual machines (VMs). A "marionette" is
  41. ;;; essentially a VM (a QEMU instance) with its monitor connected to a
  42. ;;; Unix-domain socket, and with a REPL inside the guest listening on a
  43. ;;; virtual console, which is itself connected to the host via a Unix-domain
  44. ;;; socket--these are the marionette's strings, connecting it to the almighty
  45. ;;; puppeteer.
  46. ;;;
  47. ;;; Code:
  48. (define-record-type <marionette>
  49. (marionette command pid monitor repl)
  50. marionette?
  51. (command marionette-command) ;list of strings
  52. (pid marionette-pid) ;integer
  53. (monitor marionette-monitor) ;port
  54. (repl %marionette-repl)) ;promise of a port
  55. (define-syntax-rule (marionette-repl marionette)
  56. (force (%marionette-repl marionette)))
  57. (define* (wait-for-monitor-prompt port #:key (quiet? #t))
  58. "Read from PORT until we have seen all of QEMU's monitor prompt. When
  59. QUIET? is false, the monitor's output is written to the current output port."
  60. (define full-prompt
  61. (string->list "(qemu) "))
  62. (let loop ((prompt full-prompt)
  63. (matches '())
  64. (prefix '()))
  65. (match prompt
  66. (()
  67. ;; It's useful to set QUIET? so we don't display the echo of our own
  68. ;; commands.
  69. (unless quiet?
  70. (for-each (lambda (line)
  71. (format #t "qemu monitor: ~a~%" line))
  72. (string-tokenize (list->string (reverse prefix))
  73. (char-set-complement (char-set #\newline))))))
  74. ((chr rest ...)
  75. (let ((read (read-char port)))
  76. (cond ((eqv? read chr)
  77. (loop rest (cons read matches) prefix))
  78. ((eof-object? read)
  79. (error "EOF while waiting for QEMU monitor prompt"
  80. (list->string (reverse prefix))))
  81. (else
  82. (loop full-prompt
  83. '()
  84. (cons read (append matches prefix))))))))))
  85. (define* (make-marionette command
  86. #:key (socket-directory "/tmp") (timeout 20))
  87. "Return a QEMU marionette--i.e., a virtual machine with open connections to the
  88. QEMU monitor and to the guest's backdoor REPL."
  89. (define (file->sockaddr file)
  90. (make-socket-address AF_UNIX
  91. (string-append socket-directory "/" file)))
  92. (define extra-options
  93. (list "-nographic"
  94. "-monitor" (string-append "unix:" socket-directory "/monitor")
  95. "-chardev" (string-append "socket,id=repl,path=" socket-directory
  96. "/repl")
  97. ;; See
  98. ;; <http://www.linux-kvm.org/page/VMchannel_Requirements#Invocation>.
  99. "-device" "virtio-serial"
  100. "-device" "virtserialport,chardev=repl,name=org.gnu.guix.port.0"))
  101. (define (accept* port)
  102. (match (select (list port) '() (list port) timeout)
  103. (((port) () ())
  104. (accept port))
  105. (_
  106. (error "timeout in 'accept'" port))))
  107. (let ((monitor (socket AF_UNIX SOCK_STREAM 0))
  108. (repl (socket AF_UNIX SOCK_STREAM 0)))
  109. (bind monitor (file->sockaddr "monitor"))
  110. (listen monitor 1)
  111. (bind repl (file->sockaddr "repl"))
  112. (listen repl 1)
  113. (match (primitive-fork)
  114. (0
  115. (catch #t
  116. (lambda ()
  117. (close monitor)
  118. (close repl)
  119. (match command
  120. ((program . args)
  121. (apply execl program program
  122. (append args extra-options)))))
  123. (lambda (key . args)
  124. (print-exception (current-error-port)
  125. (stack-ref (make-stack #t) 1)
  126. key args)
  127. (primitive-exit 1))))
  128. (pid
  129. (format #t "QEMU runs as PID ~a~%" pid)
  130. (match (accept* monitor)
  131. ((monitor-conn . _)
  132. (display "connected to QEMU's monitor\n")
  133. (close-port monitor)
  134. (wait-for-monitor-prompt monitor-conn)
  135. (display "read QEMU monitor prompt\n")
  136. (marionette (append command extra-options) pid
  137. monitor-conn
  138. ;; The following 'accept' call connects immediately, but
  139. ;; we don't know whether the guest has connected until
  140. ;; we actually receive the 'ready' message.
  141. (match (accept* repl)
  142. ((repl-conn . addr)
  143. (display "connected to guest REPL\n")
  144. (close-port repl)
  145. ;; Delay reception of the 'ready' message so that the
  146. ;; caller can already send monitor commands.
  147. (delay
  148. (match (read repl-conn)
  149. ('ready
  150. (display "marionette is ready\n")
  151. repl-conn))))))))))))
  152. (define (marionette-eval exp marionette)
  153. "Evaluate EXP in MARIONETTE's backdoor REPL. Return the result."
  154. (match marionette
  155. (($ <marionette> command pid monitor (= force repl))
  156. (write exp repl)
  157. (newline repl)
  158. (read repl))))
  159. (define* (wait-for-file file marionette
  160. #:key (timeout 10) (read 'read))
  161. "Wait until FILE exists in MARIONETTE; READ its content and return it. If
  162. FILE has not shown up after TIMEOUT seconds, raise an error."
  163. (match (marionette-eval
  164. `(let loop ((i ,timeout))
  165. (cond ((file-exists? ,file)
  166. (cons 'success (call-with-input-file ,file ,read)))
  167. ((> i 0)
  168. (sleep 1)
  169. (loop (- i 1)))
  170. (else
  171. 'failure)))
  172. marionette)
  173. (('success . result)
  174. result)
  175. ('failure
  176. (error "file didn't show up" file))))
  177. (define* (wait-for-tcp-port port marionette
  178. #:key (timeout 20))
  179. "Wait for up to TIMEOUT seconds for PORT to accept connections in
  180. MARIONETTE. Raise an error on failure."
  181. ;; Note: The 'connect' loop has to run within the guest because, when we
  182. ;; forward ports to the host, connecting to the host never raises
  183. ;; ECONNREFUSED.
  184. (match (marionette-eval
  185. `(begin
  186. (let ((sock (socket PF_INET SOCK_STREAM 0)))
  187. (let loop ((i 0))
  188. (catch 'system-error
  189. (lambda ()
  190. (connect sock AF_INET INADDR_LOOPBACK ,port)
  191. (close-port sock)
  192. 'success)
  193. (lambda args
  194. (if (< i ,timeout)
  195. (begin
  196. (sleep 1)
  197. (loop (+ 1 i)))
  198. 'failure))))))
  199. marionette)
  200. ('success #t)
  201. ('failure
  202. (error "nobody's listening on port" port))))
  203. (define* (wait-for-unix-socket file-name marionette
  204. #:key (timeout 20))
  205. "Wait for up to TIMEOUT seconds for FILE-NAME, a Unix domain socket, to
  206. accept connections in MARIONETTE. Raise an error on failure."
  207. (match (marionette-eval
  208. `(begin
  209. (let ((sock (socket PF_UNIX SOCK_STREAM 0)))
  210. (let loop ((i 0))
  211. (catch 'system-error
  212. (lambda ()
  213. (connect sock AF_UNIX ,file-name)
  214. (close-port sock)
  215. 'success)
  216. (lambda args
  217. (if (< i ,timeout)
  218. (begin
  219. (sleep 1)
  220. (loop (+ 1 i)))
  221. 'failure))))))
  222. marionette)
  223. ('success #t)
  224. ('failure
  225. (error "nobody's listening on unix domain socket" file-name))))
  226. (define (marionette-control command marionette)
  227. "Run COMMAND in the QEMU monitor of MARIONETTE. COMMAND is a string such as
  228. \"sendkey ctrl-alt-f1\" or \"screendump foo.ppm\" (info \"(qemu-doc)
  229. pcsys_monitor\")."
  230. (match marionette
  231. (($ <marionette> _ _ monitor)
  232. (display command monitor)
  233. (newline monitor)
  234. ;; The "quit" command terminates QEMU immediately, with no output.
  235. (unless (string=? command "quit") (wait-for-monitor-prompt monitor)))))
  236. (define* (marionette-screen-text marionette
  237. #:key
  238. (ocrad "ocrad"))
  239. "Take a screenshot of MARIONETTE, perform optical character
  240. recognition (OCR), and return the text read from the screen as a string. Do
  241. this by invoking OCRAD (file name for GNU Ocrad's command)"
  242. (define (random-file-name)
  243. (string-append "/tmp/marionette-screenshot-"
  244. (number->string (random (expt 2 32)) 16)
  245. ".ppm"))
  246. (let ((image (random-file-name)))
  247. (dynamic-wind
  248. (const #t)
  249. (lambda ()
  250. (marionette-control (string-append "screendump " image)
  251. marionette)
  252. ;; Tell Ocrad to invert the image colors (make it black on white) and
  253. ;; to scale the image up, which significantly improves the quality of
  254. ;; the result. In spite of this, be aware that OCR confuses "y" and
  255. ;; "V" and sometimes erroneously introduces white space.
  256. (let* ((pipe (open-pipe* OPEN_READ ocrad
  257. "-i" "-s" "10" image))
  258. (text (get-string-all pipe)))
  259. (unless (zero? (close-pipe pipe))
  260. (error "'ocrad' failed" ocrad))
  261. text))
  262. (lambda ()
  263. (false-if-exception (delete-file image))))))
  264. (define* (wait-for-screen-text marionette predicate
  265. #:key (timeout 30) (ocrad "ocrad"))
  266. "Wait for TIMEOUT seconds or until the screen text on MARIONETTE matches
  267. PREDICATE, whichever comes first. Raise an error when TIMEOUT is exceeded."
  268. (define start
  269. (car (gettimeofday)))
  270. (define end
  271. (+ start timeout))
  272. (let loop ()
  273. (if (> (car (gettimeofday)) end)
  274. (error "'wait-for-screen-text' timeout" predicate)
  275. (or (predicate (marionette-screen-text marionette #:ocrad ocrad))
  276. (begin
  277. (sleep 1)
  278. (loop))))))
  279. (define %qwerty-us-keystrokes
  280. ;; Maps "special" characters to their keystrokes.
  281. '((#\newline . "ret")
  282. (#\space . "spc")
  283. (#\- . "minus")
  284. (#\+ . "shift-equal")
  285. (#\* . "shift-8")
  286. (#\= . "equal")
  287. (#\? . "shift-slash")
  288. (#\[ . "bracket_left")
  289. (#\] . "bracket_right")
  290. (#\{ . "shift-bracket_left")
  291. (#\} . "shift-bracket_right")
  292. (#\( . "shift-9")
  293. (#\) . "shift-0")
  294. (#\/ . "slash")
  295. (#\< . "shift-comma")
  296. (#\> . "shift-dot")
  297. (#\. . "dot")
  298. (#\, . "comma")
  299. (#\; . "semicolon")
  300. (#\' . "apostrophe")
  301. (#\" . "shift-apostrophe")
  302. (#\` . "grave_accent")
  303. (#\bs . "backspace")
  304. (#\tab . "tab")))
  305. (define (character->keystroke chr keystrokes)
  306. "Return the keystroke for CHR according to the keyboard layout defined by
  307. KEYSTROKES."
  308. (if (char-set-contains? char-set:upper-case chr)
  309. (string-append "shift-" (string (char-downcase chr)))
  310. (or (assoc-ref keystrokes chr)
  311. (string chr))))
  312. (define* (string->keystroke-commands str
  313. #:optional
  314. (keystrokes
  315. %qwerty-us-keystrokes))
  316. "Return a list of QEMU monitor commands to send the keystrokes corresponding
  317. to STR. KEYSTROKES is an alist specifying a mapping from characters to
  318. keystrokes."
  319. (string-fold-right (lambda (chr result)
  320. (cons (string-append
  321. "sendkey "
  322. (character->keystroke chr keystrokes))
  323. result))
  324. '()
  325. str))
  326. (define* (marionette-type str marionette
  327. #:key (keystrokes %qwerty-us-keystrokes))
  328. "Type STR on MARIONETTE's keyboard, using the KEYSTROKES alist to map characters
  329. to actual keystrokes."
  330. (for-each (cut marionette-control <> marionette)
  331. (string->keystroke-commands str keystrokes)))
  332. ;;;
  333. ;;; Test helper.
  334. ;;;
  335. (define* (system-test-runner #:optional log-directory)
  336. "Return a SRFI-64 test runner that calls 'exit' upon 'test-end'. When
  337. LOG-DIRECTORY is specified, create log file within it."
  338. (let ((runner (test-runner-simple)))
  339. ;; Log to a file under LOG-DIRECTORY.
  340. (test-runner-on-group-begin! runner
  341. (let ((on-begin (test-runner-on-group-begin runner)))
  342. (lambda (runner suite-name count)
  343. (when log-directory
  344. (catch 'system-error
  345. (lambda ()
  346. (mkdir log-directory))
  347. (lambda args
  348. (unless (= (system-error-errno args) EEXIST)
  349. (apply throw args))))
  350. (set! test-log-to-file
  351. (string-append log-directory "/" suite-name ".log")))
  352. (on-begin runner suite-name count))))
  353. ;; The default behavior on 'test-end' is to only write a line if the test
  354. ;; failed. Arrange to also write a line on success.
  355. (test-runner-on-test-end! runner
  356. (let ((on-end (test-runner-on-test-end runner)))
  357. (lambda (runner)
  358. (let* ((kind (test-result-ref runner 'result-kind))
  359. (results (test-result-alist runner))
  360. (test-name (assq-ref results 'test-name)))
  361. (unless (memq kind '(fail xpass))
  362. (format (current-output-port) "~a: ~a~%"
  363. (string-upcase (symbol->string kind))
  364. test-name)))
  365. (on-end runner))))
  366. ;; On 'test-end', display test results and exit with zero if and only if
  367. ;; there were no test failures.
  368. (test-runner-on-final! runner
  369. (lambda (runner)
  370. (let ((success? (= (test-runner-fail-count runner) 0)))
  371. (test-on-final-simple runner)
  372. (when (not success?)
  373. (let* ((log-port (test-runner-aux-value runner))
  374. (log-file (port-filename log-port)))
  375. (format (current-error-port)
  376. "\nTests failed, dumping log file '~a'.\n\n"
  377. log-file)
  378. ;; At this point LOG-PORT is not closed yet; flush it.
  379. (force-output log-port)
  380. ;; Brute force to avoid dependency on (guix build utils) for
  381. ;; 'dump-port'.
  382. (let ((content (call-with-input-file log-file
  383. get-bytevector-all)))
  384. (put-bytevector (current-error-port) content))))
  385. (exit success?))))
  386. runner))
  387. ;;; marionette.scm ends here