utils.scm 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2018, 2020 Mathieu Othacehe <m.othacehe@gmail.com>
  3. ;;; Copyright © 2019, 2020, 2022 Ludovic Courtès <ludo@gnu.org>
  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 installer utils)
  20. #:use-module (gnu services herd)
  21. #:use-module (guix utils)
  22. #:use-module ((guix build syscalls) #:select (openpty login-tty))
  23. #:use-module (guix build utils)
  24. #:use-module (guix i18n)
  25. #:use-module (srfi srfi-1)
  26. #:use-module (srfi srfi-9)
  27. #:use-module (srfi srfi-9 gnu)
  28. #:use-module (srfi srfi-19)
  29. #:use-module (srfi srfi-34)
  30. #:use-module (srfi srfi-35)
  31. #:use-module (ice-9 control)
  32. #:use-module (ice-9 match)
  33. #:use-module (ice-9 popen)
  34. #:use-module (ice-9 rdelim)
  35. #:use-module (ice-9 regex)
  36. #:use-module (ice-9 format)
  37. #:use-module (ice-9 textual-ports)
  38. #:export (<secret>
  39. secret?
  40. make-secret
  41. secret-content
  42. read-lines
  43. read-all
  44. nearest-exact-integer
  45. read-percentage
  46. run-external-command-with-handler
  47. run-external-command-with-handler/tty
  48. run-external-command-with-line-hooks
  49. run-command
  50. run-command-in-installer
  51. syslog-port
  52. %syslog-line-hook
  53. installer-log-port
  54. %installer-log-line-hook
  55. %default-installer-line-hooks
  56. installer-log-line
  57. call-with-time
  58. let/time
  59. with-server-socket
  60. current-server-socket
  61. current-clients
  62. send-to-clients
  63. with-silent-shepherd))
  64. (define-record-type <secret>
  65. (make-secret content)
  66. secret?
  67. (content secret-content))
  68. (set-record-type-printer!
  69. <secret>
  70. (lambda (secret port)
  71. (format port "<secret>")))
  72. (define* (read-lines #:optional (port (current-input-port)))
  73. "Read lines from PORT and return them as a list."
  74. (let loop ((line (read-line port))
  75. (lines '()))
  76. (if (eof-object? line)
  77. (reverse lines)
  78. (loop (read-line port)
  79. (cons line lines)))))
  80. (define (read-all file)
  81. "Return the content of the given FILE as a string."
  82. (call-with-input-file file
  83. get-string-all))
  84. (define (nearest-exact-integer x)
  85. "Given a real number X, return the nearest exact integer, with ties going to
  86. the nearest exact even integer."
  87. (inexact->exact (round x)))
  88. (define (read-percentage percentage)
  89. "Read PERCENTAGE string and return the corresponding percentage as a
  90. number. If no percentage is found, return #f"
  91. (let ((result (string-match "^([0-9]+)%$" percentage)))
  92. (and result
  93. (string->number (match:substring result 1)))))
  94. (define* (run-external-command-with-handler handler command)
  95. "Run command specified by the list COMMAND in a child with output handler
  96. HANDLER. HANDLER is a procedure taking an input port, to which the command
  97. will write its standard output and error. Returns the integer status value of
  98. the child process as returned by waitpid."
  99. (match-let (((input . output) (pipe)))
  100. ;; Hack to work around Guile bug 52835
  101. (define dup-output (duplicate-port output "w"))
  102. ;; Void pipe, but holds the pid for close-pipe.
  103. (define dummy-pipe
  104. (with-input-from-file "/dev/null"
  105. (lambda ()
  106. (with-output-to-port output
  107. (lambda ()
  108. (with-error-to-port dup-output
  109. (lambda ()
  110. (apply open-pipe* (cons "" command)))))))))
  111. (close-port output)
  112. (close-port dup-output)
  113. (handler input)
  114. (close-port input)
  115. (close-pipe dummy-pipe)))
  116. (define (run-external-command-with-handler/tty handler command)
  117. "Run command specified by the list COMMAND in a child operating in a
  118. pseudoterminal with output handler HANDLER. HANDLER is a procedure taking an
  119. input port, to which the command will write its standard output and error.
  120. Returns the integer status value of the child process as returned by waitpid."
  121. (define-values (controller inferior)
  122. (openpty))
  123. (match (primitive-fork)
  124. (0
  125. (catch #t
  126. (lambda ()
  127. (close-fdes controller)
  128. (login-tty inferior)
  129. (apply execlp (car command) command))
  130. (lambda _
  131. (primitive-exit 127))))
  132. (pid
  133. (close-fdes inferior)
  134. (let* ((port (fdopen controller "r0"))
  135. (result (false-if-exception
  136. (handler port))))
  137. (close-port port)
  138. (cdr (waitpid pid))))))
  139. (define* (run-external-command-with-line-hooks line-hooks command
  140. #:key (tty? #false))
  141. "Run command specified by the list COMMAND in a child, processing each
  142. output line with the procedures in LINE-HOOKS. If TTY is set to #true, the
  143. COMMAND will be run in a pseudoterminal. Returns the integer status value of
  144. the child process as returned by waitpid."
  145. (define (handler input)
  146. (and
  147. ;; Lines for progress bars etc. end in \r; treat is as a line ending so
  148. ;; those lines are printed right away.
  149. (and=> (read-delimited "\r\n" input 'concat)
  150. (lambda (line)
  151. (if (eof-object? line)
  152. #f
  153. (begin (for-each (lambda (f) (f line))
  154. (append line-hooks
  155. %default-installer-line-hooks))
  156. #t))))
  157. (handler input)))
  158. (if tty?
  159. (run-external-command-with-handler/tty handler command)
  160. (run-external-command-with-handler handler command)))
  161. (define* (run-command command #:key (tty? #f))
  162. "Run COMMAND, a list of strings. Return true if COMMAND exited
  163. successfully, #f otherwise. If TTY is set to #true, the COMMAND will be run
  164. in a pseudoterminal."
  165. (define (pause)
  166. (format #t (G_ "Press Enter to continue.~%"))
  167. (send-to-clients '(pause))
  168. (match (select (cons (current-input-port) (current-clients))
  169. '() '())
  170. (((port _ ...) _ _)
  171. (read-line port))))
  172. (installer-log-line "running command ~s" command)
  173. (define result (run-external-command-with-line-hooks
  174. (list display) command
  175. #:tty? tty?))
  176. (define exit-val (status:exit-val result))
  177. (define term-sig (status:term-sig result))
  178. (define stop-sig (status:stop-sig result))
  179. (define succeeded?
  180. (cond
  181. ((and exit-val (not (zero? exit-val)))
  182. (installer-log-line "command ~s exited with value ~a"
  183. command exit-val)
  184. (format #t (G_ "Command ~s exited with value ~a")
  185. command exit-val)
  186. #f)
  187. (term-sig
  188. (installer-log-line "command ~s killed by signal ~a"
  189. command term-sig)
  190. (format #t (G_ "Command ~s killed by signal ~a")
  191. command term-sig)
  192. #f)
  193. (stop-sig
  194. (installer-log-line "command ~s stopped by signal ~a"
  195. command stop-sig)
  196. (format #t (G_ "Command ~s stopped by signal ~a")
  197. command stop-sig)
  198. #f)
  199. (else
  200. (installer-log-line "command ~s succeeded" command)
  201. (format #t (G_ "Command ~s succeeded") command)
  202. #t)))
  203. (newline)
  204. (pause)
  205. succeeded?)
  206. (define run-command-in-installer
  207. (make-parameter
  208. (lambda (. args)
  209. (raise
  210. (condition
  211. (&serious)
  212. (&message (message "run-command-in-installer not set")))))))
  213. ;;;
  214. ;;; Logging.
  215. ;;;
  216. (define (call-with-time thunk kont)
  217. "Call THUNK and pass KONT the elapsed time followed by THUNK's return
  218. values."
  219. (let* ((start (current-time time-monotonic))
  220. (result (call-with-values thunk list))
  221. (end (current-time time-monotonic)))
  222. (apply kont (time-difference end start) result)))
  223. (define-syntax-rule (let/time ((time result exp)) body ...)
  224. (call-with-time (lambda () exp) (lambda (time result) body ...)))
  225. (define (open-syslog-port)
  226. "Return an open port (a socket) to /dev/log or #f if that wasn't possible."
  227. (let ((sock (socket AF_UNIX SOCK_DGRAM 0)))
  228. (catch 'system-error
  229. (lambda ()
  230. (connect sock AF_UNIX "/dev/log")
  231. (setvbuf sock 'line)
  232. sock)
  233. (lambda args
  234. (close-port sock)
  235. #f))))
  236. (define syslog-port
  237. (let ((port #f))
  238. (lambda ()
  239. "Return an output port to syslog."
  240. (unless port
  241. (set! port (open-syslog-port)))
  242. (or port (%make-void-port "w")))))
  243. (define (%syslog-line-hook line)
  244. (let ((line (if (string-suffix? "\r" line)
  245. (string-append (string-drop-right line 1) "\n")
  246. line)))
  247. (format (syslog-port) "installer[~d]: ~a" (getpid) line)))
  248. (define-syntax syslog
  249. (lambda (s)
  250. "Like 'format', but write to syslog."
  251. (syntax-case s ()
  252. ((_ fmt args ...)
  253. (string? (syntax->datum #'fmt))
  254. (with-syntax ((fmt (string-append "installer[~d]: "
  255. (syntax->datum #'fmt))))
  256. #'(format (syslog-port) fmt (getpid) args ...))))))
  257. (define (open-new-log-port)
  258. (define now (localtime (time-second (current-time))))
  259. (define filename
  260. (format #f "/tmp/installer.~a.log"
  261. (strftime "%F.%T" now)))
  262. (open filename (logior O_RDWR
  263. O_CREAT)))
  264. (define installer-log-port
  265. (let ((port #f))
  266. (lambda ()
  267. "Return an input and output port to the installer log."
  268. (unless port
  269. (set! port (open-new-log-port)))
  270. port)))
  271. (define (%installer-log-line-hook line)
  272. (display line (installer-log-port)))
  273. (define %default-installer-line-hooks
  274. (list %syslog-line-hook
  275. %installer-log-line-hook))
  276. (define-syntax installer-log-line
  277. (lambda (s)
  278. "Like 'format', but uses the default line hooks, and only formats one line."
  279. (syntax-case s ()
  280. ((_ fmt args ...)
  281. (string? (syntax->datum #'fmt))
  282. (with-syntax ((fmt (string-append (syntax->datum #'fmt) "\n")))
  283. #'(let ((formatted (format #f fmt args ...)))
  284. (for-each (lambda (f) (f formatted))
  285. %default-installer-line-hooks)))))))
  286. ;;;
  287. ;;; Client protocol.
  288. ;;;
  289. (define %client-socket-file
  290. ;; Unix-domain socket where the installer accepts connections.
  291. "/var/guix/installer-socket")
  292. (define current-server-socket
  293. ;; Socket on which the installer is currently accepting connections, or #f.
  294. (make-parameter #f))
  295. (define current-clients
  296. ;; List of currently connected clients.
  297. (make-parameter '()))
  298. (define* (open-server-socket
  299. #:optional (socket-file %client-socket-file))
  300. "Open SOCKET-FILE as a Unix-domain socket to accept incoming connections and
  301. return it."
  302. (mkdir-p (dirname socket-file))
  303. (when (file-exists? socket-file)
  304. (delete-file socket-file))
  305. (let ((sock (socket AF_UNIX SOCK_STREAM 0)))
  306. (bind sock AF_UNIX socket-file)
  307. (listen sock 0)
  308. sock))
  309. (define (call-with-server-socket thunk)
  310. (if (current-server-socket)
  311. (thunk)
  312. (let ((socket (open-server-socket)))
  313. (dynamic-wind
  314. (const #t)
  315. (lambda ()
  316. (parameterize ((current-server-socket socket))
  317. (thunk)))
  318. (lambda ()
  319. (close-port socket))))))
  320. (define-syntax-rule (with-server-socket exp ...)
  321. "Evaluate EXP with 'current-server-socket' parameterized to a currently
  322. accepting socket."
  323. (call-with-server-socket (lambda () exp ...)))
  324. (define* (send-to-clients exp)
  325. "Send EXP to all the current clients."
  326. (define remainder
  327. (fold (lambda (client remainder)
  328. (catch 'system-error
  329. (lambda ()
  330. (write exp client)
  331. (newline client)
  332. (force-output client)
  333. (cons client remainder))
  334. (lambda args
  335. ;; We might get EPIPE if the client disconnects; when that
  336. ;; happens, remove CLIENT from the set of available clients.
  337. (let ((errno (system-error-errno args)))
  338. (if (memv errno (list EPIPE ECONNRESET ECONNABORTED))
  339. (begin
  340. (installer-log-line
  341. "removing client ~s due to ~s while replying"
  342. (fileno client) (strerror errno))
  343. (false-if-exception (close-port client))
  344. remainder)
  345. (cons client remainder))))))
  346. '()
  347. (current-clients)))
  348. (current-clients (reverse remainder))
  349. exp)
  350. (define-syntax-rule (with-silent-shepherd exp ...)
  351. "Evaluate EXP while discarding shepherd messages."
  352. (parameterize ((shepherd-message-port
  353. (%make-void-port "w")))
  354. exp ...))