status: Gracefully handle invalid UTF-8 in build logs.
[jackhill/guix/guix.git] / guix / status.scm
1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2017, 2018 Ludovic Courtès <ludo@gnu.org>
3 ;;;
4 ;;; This file is part of GNU Guix.
5 ;;;
6 ;;; GNU Guix is free software; you can redistribute it and/or modify it
7 ;;; under the terms of the GNU General Public License as published by
8 ;;; the Free Software Foundation; either version 3 of the License, or (at
9 ;;; your option) any later version.
10 ;;;
11 ;;; GNU Guix is distributed in the hope that it will be useful, but
12 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 ;;; GNU General Public License for more details.
15 ;;;
16 ;;; You should have received a copy of the GNU General Public License
17 ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
18
19 (define-module (guix status)
20 #:use-module (guix records)
21 #:use-module (guix i18n)
22 #:use-module ((guix ui) #:select (colorize-string))
23 #:use-module (guix progress)
24 #:autoload (guix build syscalls) (terminal-columns)
25 #:use-module ((guix build download)
26 #:select (nar-uri-abbreviation))
27 #:use-module (guix store)
28 #:use-module (guix derivations)
29 #:use-module (srfi srfi-1)
30 #:use-module (srfi srfi-9)
31 #:use-module (srfi srfi-19)
32 #:use-module (srfi srfi-26)
33 #:use-module (ice-9 regex)
34 #:use-module (ice-9 match)
35 #:use-module (ice-9 format)
36 #:use-module (ice-9 binary-ports)
37 #:autoload (ice-9 rdelim) (read-string)
38 #:use-module (rnrs bytevectors)
39 #:use-module ((system foreign)
40 #:select (bytevector->pointer pointer->bytevector))
41 #:export (build-event-output-port
42 compute-status
43
44 build-status
45 build-status?
46 build-status-building
47 build-status-downloading
48 build-status-builds-completed
49 build-status-downloads-completed
50
51 download?
52 download
53 download-item
54 download-uri
55 download-size
56 download-start
57 download-end
58 download-transferred
59
60 build-status-updater
61 print-build-event
62 print-build-event/quiet
63 print-build-status
64
65 with-status-report))
66
67 ;;; Commentary:
68 ;;;
69 ;;; This module provides facilities to track the status of ongoing builds and
70 ;;; downloads in a given session, as well as tools to report about the current
71 ;;; status to user interfaces. It does so by analyzing the output of
72 ;;; 'current-build-output-port'. The build status is maintained in a
73 ;;; <build-status> record.
74 ;;;
75 ;;; Code:
76
77 \f
78 ;;;
79 ;;; Build status tracking.
80 ;;;
81
82 ;; Builds and substitutions performed by the daemon.
83 (define-record-type* <build-status> build-status make-build-status
84 build-status?
85 (building build-status-building ;list of drv
86 (default '()))
87 (downloading build-status-downloading ;list of <download>
88 (default '()))
89 (builds-completed build-status-builds-completed ;list of drv
90 (default '()))
91 (downloads-completed build-status-downloads-completed ;list of store items
92 (default '())))
93
94 ;; On-going or completed downloads. Downloads can be stem from substitutes
95 ;; and from "builtin:download" fixed-output derivations.
96 (define-record-type <download>
97 (%download item uri size start end transferred)
98 download?
99 (item download-item) ;store item
100 (uri download-uri) ;string | #f
101 (size download-size) ;integer | #f
102 (start download-start) ;<time>
103 (end download-end) ;#f | <time>
104 (transferred download-transferred)) ;integer
105
106 (define* (download item uri
107 #:key size
108 (start (current-time time-monotonic)) end
109 (transferred 0))
110 "Return a new download."
111 (%download item uri size start end transferred))
112
113 (define (matching-download item)
114 "Return a predicate that matches downloads of ITEM."
115 (lambda (download)
116 (string=? item (download-item download))))
117
118 (define* (compute-status event status
119 #:key (current-time current-time))
120 "Given EVENT, a tuple like (build-started \"/gnu/store/...-foo.drv\" ...),
121 compute a new status based on STATUS."
122 (match event
123 (('build-started drv _ ...)
124 (build-status
125 (inherit status)
126 (building (cons drv (build-status-building status)))))
127 (((or 'build-succeeded 'build-failed) drv _ ...)
128 (build-status
129 (inherit status)
130 (building (delete drv (build-status-building status)))
131 (builds-completed (cons drv (build-status-builds-completed status)))))
132
133 ;; Note: Ignore 'substituter-started' and 'substituter-succeeded' because
134 ;; they're not as informative as 'download-started' and
135 ;; 'download-succeeded'.
136
137 (('download-started item uri (= string->number size))
138 ;; This is presumably a fixed-output derivation so move it from
139 ;; 'building' to 'downloading'. XXX: This doesn't work in 'check' mode
140 ;; because ITEM is different from DRV's output.
141 (build-status
142 (inherit status)
143 (building (remove (lambda (drv)
144 (equal? (false-if-exception
145 (derivation->output-path
146 (read-derivation-from-file drv)))
147 item))
148 (build-status-building status)))
149 (downloading (cons (download item uri #:size size
150 #:start (current-time time-monotonic))
151 (build-status-downloading status)))))
152 (('download-succeeded item uri (= string->number size))
153 (let ((current (find (matching-download item)
154 (build-status-downloading status))))
155 (build-status
156 (inherit status)
157 (downloading (delq current (build-status-downloading status)))
158 (downloads-completed
159 (cons (download item uri
160 #:size size
161 #:start (download-start current)
162 #:transferred size
163 #:end (current-time time-monotonic))
164 (build-status-downloads-completed status))))))
165 (('substituter-succeeded item _ ...)
166 (match (find (matching-download item)
167 (build-status-downloading status))
168 (#f
169 ;; Presumably we already got a 'download-succeeded' event for ITEM,
170 ;; everything is fine.
171 status)
172 (current
173 ;; Maybe the build process didn't emit a 'download-succeeded' event
174 ;; for ITEM, so remove CURRENT from the queue now.
175 (build-status
176 (inherit status)
177 (downloading (delq current (build-status-downloading status)))
178 (downloads-completed
179 (cons (download item (download-uri current)
180 #:size (download-size current)
181 #:start (download-start current)
182 #:transferred (download-size current)
183 #:end (current-time time-monotonic))
184 (build-status-downloads-completed status)))))))
185 (('download-progress item uri
186 (= string->number size)
187 (= string->number transferred))
188 (let ((downloads (remove (matching-download item)
189 (build-status-downloading status)))
190 (current (find (matching-download item)
191 (build-status-downloading status))))
192 (build-status
193 (inherit status)
194 (downloading (cons (download item uri
195 #:size size
196 #:start
197 (or (and current
198 (download-start current))
199 (current-time time-monotonic))
200 #:transferred transferred)
201 downloads)))))
202 (_
203 status)))
204
205 (define (simultaneous-jobs status)
206 "Return the number of on-going builds and downloads for STATUS."
207 (+ (length (build-status-building status))
208 (length (build-status-downloading status))))
209
210 \f
211 ;;;
212 ;;; Rendering.
213 ;;;
214
215 (define (extended-build-trace-supported?)
216 "Return true if the currently used store is known to support \"extended
217 build traces\" such as \"@ download-progress\" traces."
218 ;; Support for extended build traces was added in protocol version #x162.
219 (and (current-store-protocol-version)
220 (>= (current-store-protocol-version) #x162)))
221
222 (define spin!
223 (let ((steps (circular-list "\\" "|" "/" "-")))
224 (lambda (port)
225 "Display a spinner on PORT."
226 (match steps
227 ((first . rest)
228 (set! steps rest)
229 (display "\r\x1b[K" port)
230 (display first port)
231 (force-output port))))))
232
233 (define (color-output? port)
234 "Return true if we should write colored output to PORT."
235 (and (not (getenv "INSIDE_EMACS"))
236 (not (getenv "NO_COLOR"))
237 (isatty? port)))
238
239 (define-syntax color-rules
240 (syntax-rules ()
241 "Return a procedure that colorizes the string it is passed according to
242 the given rules. Each rule has the form:
243
244 (REGEXP COLOR1 COLOR2 ...)
245
246 where COLOR1 specifies how to colorize the first submatch of REGEXP, and so
247 on."
248 ((_ (regexp colors ...) rest ...)
249 (let ((next (color-rules rest ...))
250 (rx (make-regexp regexp)))
251 (lambda (str)
252 (if (string-index str #\nul)
253 str
254 (match (regexp-exec rx str)
255 (#f (next str))
256 (m (let loop ((n 1)
257 (c '(colors ...))
258 (result '()))
259 (match c
260 (()
261 (string-concatenate-reverse result))
262 ((first . tail)
263 (loop (+ n 1) tail
264 (cons (colorize-string (match:substring m n)
265 first)
266 result)))))))))))
267 ((_)
268 (lambda (str)
269 str))))
270
271 (define colorize-log-line
272 ;; Take a string and return a possibly colorized string according to the
273 ;; rules below.
274 (color-rules
275 ("^(phase)(.*)(succeeded after)(.*)(seconds)(.*)"
276 GREEN BOLD GREEN RESET GREEN BLUE)
277 ("^(phase)(.*)(failed after)(.*)(seconds)(.*)"
278 RED BLUE RED BLUE RED BLUE)
279 ("^(.*)(error|fail|failed|\\<FAIL|FAILED)([[:blank:]]*)(:)(.*)"
280 RESET RED BOLD BOLD BOLD)
281 ("^(.*)(warning)([[:blank:]]*)(:)(.*)"
282 RESET MAGENTA BOLD BOLD BOLD)))
283
284 (define* (print-build-event event old-status status
285 #:optional (port (current-error-port))
286 #:key
287 (colorize? (color-output? port))
288 (print-log? #t))
289 "Print information about EVENT and STATUS to PORT. When COLORIZE? is true,
290 produce colorful output. When PRINT-LOG? is true, display the build log in
291 addition to build events."
292 (define info
293 (if colorize?
294 (cut colorize-string <> 'BOLD)
295 identity))
296
297 (define success
298 (if colorize?
299 (cut colorize-string <> 'GREEN 'BOLD)
300 identity))
301
302 (define failure
303 (if colorize?
304 (cut colorize-string <> 'RED 'BOLD)
305 identity))
306
307 (define print-log-line
308 (if print-log?
309 (if colorize?
310 (lambda (line)
311 (display (colorize-log-line line) port))
312 (cut display <> port))
313 (lambda (line)
314 (spin! port))))
315
316 (display "\r" port) ;erase the spinner
317 (match event
318 (('build-started drv . _)
319 (format port (info (G_ "building ~a...")) drv)
320 (newline port))
321 (('build-succeeded drv . _)
322 (format port (success (G_ "successfully built ~a")) drv)
323 (newline port)
324 (match (build-status-building status)
325 (() #t)
326 (ongoing ;when max-jobs > 1
327 (format port
328 (N_ "The following build is still in progress:~%~{ ~a~%~}~%"
329 "The following builds are still in progress:~%~{ ~a~%~}~%"
330 (length ongoing))
331 ongoing))))
332 (('build-failed drv . _)
333 (format port (failure (G_ "build of ~a failed")) drv)
334 (newline port)
335 (match (derivation-log-file drv)
336 (#f
337 (format port (failure (G_ "Could not find build log for '~a'."))
338 drv))
339 (log
340 (format port (info (G_ "View build log at '~a'.")) log)))
341 (newline port))
342 (('substituter-started item _ ...)
343 (when (or print-log? (not (extended-build-trace-supported?)))
344 (format port (info (G_ "substituting ~a...")) item)
345 (newline port)))
346 (('download-started item uri _ ...)
347 (format port (info (G_ "downloading from ~a...")) uri)
348 (newline port))
349 (('download-progress item uri
350 (= string->number size)
351 (= string->number transferred))
352 ;; Print a progress bar, but only if there's only one on-going
353 ;; job--otherwise the output would be intermingled.
354 (when (= 1 (simultaneous-jobs status))
355 (match (find (matching-download item)
356 (build-status-downloading status))
357 (#f #f) ;shouldn't happen!
358 (download
359 ;; XXX: It would be nice to memoize the abbreviation.
360 (let ((uri (if (string-contains uri "/nar/")
361 (nar-uri-abbreviation uri)
362 (basename uri))))
363 (display-download-progress uri size
364 #:start-time
365 (download-start download)
366 #:transferred transferred))))))
367 (('substituter-succeeded item _ ...)
368 ;; If there are no jobs running, we already reported download completion
369 ;; so there's nothing left to do.
370 (unless (and (zero? (simultaneous-jobs status))
371 (extended-build-trace-supported?))
372 (format port (success (G_ "substitution of ~a complete")) item)
373 (newline port)))
374 (('substituter-failed item _ ...)
375 (format port (failure (G_ "substitution of ~a failed")) item)
376 (newline port))
377 (('hash-mismatch item algo expected actual _ ...)
378 ;; TRANSLATORS: The final string looks like "sha256 hash mismatch for
379 ;; /gnu/store/…-sth:", where "sha256" is the hash algorithm.
380 (format port (failure (G_ "~a hash mismatch for ~a:")) algo item)
381 (newline port)
382 (format port (info (G_ "\
383 expected hash: ~a
384 actual hash: ~a~%"))
385 expected actual))
386 (('build-log line)
387 ;; TODO: Better distinguish daemon messages and build log lines.
388 (cond ((string-prefix? "substitute: " line)
389 ;; The daemon prefixes early messages coming with 'guix
390 ;; substitute' with "substitute:". These are useful ("updating
391 ;; substitutes from URL"), so let them through.
392 (format port line)
393 (force-output port))
394 ((string-prefix? "waiting for locks" line)
395 ;; This is when a derivation is already being built and we're just
396 ;; waiting for the build to complete.
397 (display (info (string-trim-right line)) port)
398 (newline))
399 (else
400 (print-log-line line))))
401 (_
402 event)))
403
404 (define* (print-build-event/quiet event old-status status
405 #:optional
406 (port (current-error-port))
407 #:key
408 (colorize? (color-output? port)))
409 (print-build-event event old-status status port
410 #:colorize? colorize?
411 #:print-log? #f))
412
413 (define* (build-status-updater #:optional (on-change (const #t)))
414 "Return a procedure that can be passed to 'build-event-output-port'. That
415 procedure computes the new build status upon each event and calls ON-CHANGE:
416
417 (ON-CHANGE event status new-status)
418
419 ON-CHANGE can display the build status, build events, etc."
420 (lambda (event status)
421 (let ((new (compute-status event status)))
422 (on-change event status new)
423 new)))
424
425 \f
426 ;;;
427 ;;; Build port.
428 ;;;
429
430 (define %newline
431 (char-set #\return #\newline))
432
433 (define (maybe-utf8->string bv)
434 "Attempt to decode BV as UTF-8 string and return it. Gracefully handle the
435 case where BV does not contain only valid UTF-8."
436 (catch 'decoding-error
437 (lambda ()
438 (utf8->string bv))
439 (lambda _
440 ;; This is the sledgehammer but it's the only safe way we have to
441 ;; properly handle this. It's expensive but it's rarely needed.
442 (let ((port (open-bytevector-input-port bv)))
443 (set-port-encoding! port "UTF-8")
444 (set-port-conversion-strategy! port 'substitute)
445 (let ((str (read-string port)))
446 (close-port port)
447 str)))))
448
449 (define* (build-event-output-port proc #:optional (seed (build-status)))
450 "Return an output port for use as 'current-build-output-port' that calls
451 PROC with its current state value, initialized with SEED, on every build
452 event. Build events passed to PROC are tuples corresponding to the \"build
453 traces\" produced by the daemon:
454
455 (build-started \"/gnu/store/...-foo.drv\" ...)
456 (substituter-started \"/gnu/store/...-foo\" ...)
457
458 and so on.
459
460 The second return value is a thunk to retrieve the current state."
461 (define %fragments
462 ;; Line fragments received so far.
463 '())
464
465 (define %state
466 ;; Current state for PROC.
467 seed)
468
469 (define (process-line line)
470 (if (string-prefix? "@ " line)
471 (match (string-tokenize (string-drop line 2))
472 (((= string->symbol event-name) args ...)
473 (set! %state
474 (proc (cons event-name args)
475 %state))))
476 (set! %state (proc (list 'build-log line)
477 %state))))
478
479 (define (bytevector-range bv offset count)
480 (let ((ptr (bytevector->pointer bv offset)))
481 (pointer->bytevector ptr count)))
482
483 (define (write! bv offset count)
484 (let loop ((str (maybe-utf8->string (bytevector-range bv offset count))))
485 (match (string-index str %newline)
486 ((? integer? cr)
487 (let ((tail (string-take str (+ 1 cr))))
488 (process-line (string-concatenate-reverse
489 (cons tail %fragments)))
490 (set! %fragments '())
491 (loop (string-drop str (+ 1 cr)))))
492 (#f
493 (unless (string-null? str)
494 (set! %fragments (cons str %fragments)))
495 count))))
496
497 (define port
498 (make-custom-binary-output-port "filtering-input-port"
499 write!
500 #f #f
501 #f))
502
503 ;; The build port actually receives Unicode strings.
504 (set-port-encoding! port "UTF-8")
505 (setvbuf port (cond-expand (guile-2.2 'line) (else _IOLBF)))
506
507 (values port (lambda () %state)))
508
509 (define (call-with-status-report on-event thunk)
510 (parameterize ((current-terminal-columns (terminal-columns))
511 (current-build-output-port
512 (build-event-output-port (build-status-updater on-event))))
513 (thunk)))
514
515 (define-syntax-rule (with-status-report on-event exp ...)
516 "Set up build status reporting to the user using the ON-EVENT procedure;
517 evaluate EXP... in that context."
518 (call-with-status-report on-event (lambda () exp ...)))