Merge branch 'master' into staging
[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 ;;; Copyright © 2018 Ricardo Wurmus <rekado@elephly.net>
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
20 (define-module (guix status)
21 #:use-module (guix records)
22 #:use-module (guix i18n)
23 #:use-module ((guix ui) #:select (colorize-string))
24 #:use-module (guix progress)
25 #:autoload (guix build syscalls) (terminal-columns)
26 #:use-module ((guix build download)
27 #:select (nar-uri-abbreviation))
28 #:use-module (guix store)
29 #:use-module (guix derivations)
30 #:use-module (srfi srfi-1)
31 #:use-module (srfi srfi-9)
32 #:use-module (srfi srfi-19)
33 #:use-module (srfi srfi-26)
34 #:use-module (ice-9 regex)
35 #:use-module (ice-9 match)
36 #:use-module (ice-9 format)
37 #:use-module (ice-9 binary-ports)
38 #:autoload (ice-9 rdelim) (read-string)
39 #:use-module (rnrs bytevectors)
40 #:use-module ((system foreign)
41 #:select (bytevector->pointer pointer->bytevector))
42 #:export (build-event-output-port
43 compute-status
44
45 build-status
46 build-status?
47 build-status-building
48 build-status-downloading
49 build-status-builds-completed
50 build-status-downloads-completed
51
52 download?
53 download
54 download-item
55 download-uri
56 download-size
57 download-start
58 download-end
59 download-transferred
60
61 build-status-updater
62 print-build-event
63 print-build-event/quiet
64 print-build-status
65
66 with-status-report))
67
68 ;;; Commentary:
69 ;;;
70 ;;; This module provides facilities to track the status of ongoing builds and
71 ;;; downloads in a given session, as well as tools to report about the current
72 ;;; status to user interfaces. It does so by analyzing the output of
73 ;;; 'current-build-output-port'. The build status is maintained in a
74 ;;; <build-status> record.
75 ;;;
76 ;;; Code:
77
78 \f
79 ;;;
80 ;;; Build status tracking.
81 ;;;
82
83 ;; Builds and substitutions performed by the daemon.
84 (define-record-type* <build-status> build-status make-build-status
85 build-status?
86 (building build-status-building ;list of drv
87 (default '()))
88 (downloading build-status-downloading ;list of <download>
89 (default '()))
90 (builds-completed build-status-builds-completed ;list of drv
91 (default '()))
92 (downloads-completed build-status-downloads-completed ;list of store items
93 (default '())))
94
95 ;; On-going or completed downloads. Downloads can be stem from substitutes
96 ;; and from "builtin:download" fixed-output derivations.
97 (define-record-type <download>
98 (%download item uri size start end transferred)
99 download?
100 (item download-item) ;store item
101 (uri download-uri) ;string | #f
102 (size download-size) ;integer | #f
103 (start download-start) ;<time>
104 (end download-end) ;#f | <time>
105 (transferred download-transferred)) ;integer
106
107 (define* (download item uri
108 #:key size
109 (start (current-time time-monotonic)) end
110 (transferred 0))
111 "Return a new download."
112 (%download item uri size start end transferred))
113
114 (define (matching-download item)
115 "Return a predicate that matches downloads of ITEM."
116 (lambda (download)
117 (string=? item (download-item download))))
118
119 (define* (compute-status event status
120 #:key
121 (current-time current-time)
122 (derivation-path->output-path
123 derivation-path->output-path))
124 "Given EVENT, a tuple like (build-started \"/gnu/store/...-foo.drv\" ...),
125 compute a new status based on STATUS."
126 (match event
127 (('build-started drv _ ...)
128 (build-status
129 (inherit status)
130 (building (cons drv (build-status-building status)))))
131 (((or 'build-succeeded 'build-failed) drv _ ...)
132 (build-status
133 (inherit status)
134 (building (delete drv (build-status-building status)))
135 (builds-completed (cons drv (build-status-builds-completed status)))))
136
137 ;; Note: Ignore 'substituter-started' and 'substituter-succeeded' because
138 ;; they're not as informative as 'download-started' and
139 ;; 'download-succeeded'.
140
141 (('download-started item uri (= string->number size))
142 ;; This is presumably a fixed-output derivation so move it from
143 ;; 'building' to 'downloading'. XXX: This doesn't work in 'check' mode
144 ;; because ITEM is different from DRV's output.
145 (build-status
146 (inherit status)
147 (building (remove (lambda (drv)
148 (equal? (false-if-exception
149 (derivation-path->output-path drv))
150 item))
151 (build-status-building status)))
152 (downloading (cons (download item uri #:size size
153 #:start (current-time time-monotonic))
154 (build-status-downloading status)))))
155 (('download-succeeded item uri (= string->number size))
156 (let ((current (find (matching-download item)
157 (build-status-downloading status))))
158 (build-status
159 (inherit status)
160 (downloading (delq current (build-status-downloading status)))
161 (downloads-completed
162 (cons (download item uri
163 #:size size
164 #:start (download-start current)
165 #:transferred size
166 #:end (current-time time-monotonic))
167 (build-status-downloads-completed status))))))
168 (('substituter-succeeded item _ ...)
169 (match (find (matching-download item)
170 (build-status-downloading status))
171 (#f
172 ;; Presumably we already got a 'download-succeeded' event for ITEM,
173 ;; everything is fine.
174 status)
175 (current
176 ;; Maybe the build process didn't emit a 'download-succeeded' event
177 ;; for ITEM, so remove CURRENT from the queue now.
178 (build-status
179 (inherit status)
180 (downloading (delq current (build-status-downloading status)))
181 (downloads-completed
182 (cons (download item (download-uri current)
183 #:size (download-size current)
184 #:start (download-start current)
185 #:transferred (download-size current)
186 #:end (current-time time-monotonic))
187 (build-status-downloads-completed status)))))))
188 (('download-progress item uri
189 (= string->number size)
190 (= string->number transferred))
191 (let ((downloads (remove (matching-download item)
192 (build-status-downloading status)))
193 (current (find (matching-download item)
194 (build-status-downloading status))))
195 (build-status
196 (inherit status)
197 (downloading (cons (download item uri
198 #:size size
199 #:start
200 (or (and current
201 (download-start current))
202 (current-time time-monotonic))
203 #:transferred transferred)
204 downloads)))))
205 (_
206 status)))
207
208 (define (simultaneous-jobs status)
209 "Return the number of on-going builds and downloads for STATUS."
210 (+ (length (build-status-building status))
211 (length (build-status-downloading status))))
212
213 \f
214 ;;;
215 ;;; Rendering.
216 ;;;
217
218 (define (extended-build-trace-supported?)
219 "Return true if the currently used store is known to support \"extended
220 build traces\" such as \"@ download-progress\" traces."
221 ;; Support for extended build traces was added in protocol version #x162.
222 (and (current-store-protocol-version)
223 (>= (current-store-protocol-version) #x162)))
224
225 (define (multiplexed-output-supported?)
226 "Return true if the daemon supports \"multiplexed output\"--i.e., \"@
227 build-log\" traces."
228 (and (current-store-protocol-version)
229 (>= (current-store-protocol-version) #x163)))
230
231 (define spin!
232 (let ((steps (circular-list "\\" "|" "/" "-")))
233 (lambda (port)
234 "Display a spinner on PORT."
235 (match steps
236 ((first . rest)
237 (set! steps rest)
238 (display "\r\x1b[K" port)
239 (display first port)
240 (force-output port))))))
241
242 (define (color-output? port)
243 "Return true if we should write colored output to PORT."
244 (and (not (getenv "INSIDE_EMACS"))
245 (not (getenv "NO_COLOR"))
246 (isatty? port)))
247
248 (define-syntax color-rules
249 (syntax-rules ()
250 "Return a procedure that colorizes the string it is passed according to
251 the given rules. Each rule has the form:
252
253 (REGEXP COLOR1 COLOR2 ...)
254
255 where COLOR1 specifies how to colorize the first submatch of REGEXP, and so
256 on."
257 ((_ (regexp colors ...) rest ...)
258 (let ((next (color-rules rest ...))
259 (rx (make-regexp regexp)))
260 (lambda (str)
261 (if (string-index str #\nul)
262 str
263 (match (regexp-exec rx str)
264 (#f (next str))
265 (m (let loop ((n 1)
266 (c '(colors ...))
267 (result '()))
268 (match c
269 (()
270 (string-concatenate-reverse result))
271 ((first . tail)
272 (loop (+ n 1) tail
273 (cons (colorize-string (match:substring m n)
274 first)
275 result)))))))))))
276 ((_)
277 (lambda (str)
278 str))))
279
280 (define colorize-log-line
281 ;; Take a string and return a possibly colorized string according to the
282 ;; rules below.
283 (color-rules
284 ("^(phase)(.*)(succeeded after)(.*)(seconds)(.*)"
285 GREEN BOLD GREEN RESET GREEN BLUE)
286 ("^(phase)(.*)(failed after)(.*)(seconds)(.*)"
287 RED BLUE RED BLUE RED BLUE)
288 ("^(.*)(error|fail|failed|\\<FAIL|FAILED)([[:blank:]]*)(:)(.*)"
289 RESET RED BOLD BOLD BOLD)
290 ("^(.*)(warning)([[:blank:]]*)(:)(.*)"
291 RESET MAGENTA BOLD BOLD BOLD)))
292
293 (define (hook-message hook-type)
294 "Return a human-readable string for the profile hook type HOOK-TYPE."
295 (match hook-type
296 ('info-dir
297 (G_ "building directory of Info manuals..."))
298 ('ghc-package-cache
299 (G_ "building GHC package cache..."))
300 ('ca-certificate-bundle
301 (G_ "building CA certificate bundle..."))
302 ('glib-schemas
303 (G_ "generating GLib schema cache..."))
304 ('gtk-icon-themes
305 (G_ "creating GTK+ icon theme cache..."))
306 ('gtk-im-modules
307 (G_ "building cache files for GTK+ input methods..."))
308 ('xdg-desktop-database
309 (G_ "building XDG desktop file cache..."))
310 ('xdg-mime-database
311 (G_ "building XDG MIME database..."))
312 ('fonts-dir
313 (G_ "building fonts directory..."))
314 ('manual-database
315 (G_ "building database for manual pages..."))
316 (_ #f)))
317
318 (define* (print-build-event event old-status status
319 #:optional (port (current-error-port))
320 #:key
321 (colorize? (color-output? port))
322 (print-log? #t))
323 "Print information about EVENT and STATUS to PORT. When COLORIZE? is true,
324 produce colorful output. When PRINT-LOG? is true, display the build log in
325 addition to build events."
326 (define info
327 (if colorize?
328 (cut colorize-string <> 'BOLD)
329 identity))
330
331 (define success
332 (if colorize?
333 (cut colorize-string <> 'GREEN 'BOLD)
334 identity))
335
336 (define failure
337 (if colorize?
338 (cut colorize-string <> 'RED 'BOLD)
339 identity))
340
341 (define print-log-line
342 (if print-log?
343 (if colorize?
344 (lambda (line)
345 (display (colorize-log-line line) port))
346 (cut display <> port))
347 (lambda (line)
348 (spin! port))))
349
350 (unless print-log?
351 (display "\r" port)) ;erase the spinner
352 (match event
353 (('build-started drv . _)
354 (let ((properties (derivation-properties
355 (read-derivation-from-file drv))))
356 (match (assq-ref properties 'type)
357 ('graft
358 (let ((count (match (assq-ref properties 'graft)
359 (#f 0)
360 (lst (or (assq-ref lst 'count) 0)))))
361 (format port (info (N_ "applying ~a graft for ~a..."
362 "applying ~a grafts for ~a..."
363 count))
364 count drv)))
365 ('profile-hook
366 (let ((hook-type (assq-ref properties 'hook)))
367 (or (and=> (hook-message hook-type)
368 (lambda (msg)
369 (format port (info msg))))
370 (format port (info (G_ "running profile hook of type '~a'..."))
371 hook-type))))
372 (_
373 (format port (info (G_ "building ~a...")) drv))))
374 (newline port))
375 (('build-succeeded drv . _)
376 (when (or print-log? (not (extended-build-trace-supported?)))
377 (format port (success (G_ "successfully built ~a")) drv)
378 (newline port))
379 (match (build-status-building status)
380 (() #t)
381 (ongoing ;when max-jobs > 1
382 (format port
383 (N_ "The following build is still in progress:~%~{ ~a~%~}~%"
384 "The following builds are still in progress:~%~{ ~a~%~}~%"
385 (length ongoing))
386 ongoing))))
387 (('build-failed drv . _)
388 (format port (failure (G_ "build of ~a failed")) drv)
389 (newline port)
390 (match (derivation-log-file drv)
391 (#f
392 (format port (failure (G_ "Could not find build log for '~a'."))
393 drv))
394 (log
395 (format port (info (G_ "View build log at '~a'.")) log)))
396 (newline port))
397 (('substituter-started item _ ...)
398 (when (or print-log? (not (extended-build-trace-supported?)))
399 (format port (info (G_ "substituting ~a...")) item)
400 (newline port)))
401 (('download-started item uri _ ...)
402 (format port (info (G_ "downloading from ~a...")) uri)
403 (newline port))
404 (('download-progress item uri
405 (= string->number size)
406 (= string->number transferred))
407 ;; Print a progress bar, but only if there's only one on-going
408 ;; job--otherwise the output would be intermingled.
409 (when (= 1 (simultaneous-jobs status))
410 (match (find (matching-download item)
411 (build-status-downloading status))
412 (#f #f) ;shouldn't happen!
413 (download
414 ;; XXX: It would be nice to memoize the abbreviation.
415 (let ((uri (if (string-contains uri "/nar/")
416 (nar-uri-abbreviation uri)
417 (basename uri))))
418 (display-download-progress uri size
419 #:start-time
420 (download-start download)
421 #:transferred transferred))))))
422 (('substituter-succeeded item _ ...)
423 ;; If there are no jobs running, we already reported download completion
424 ;; so there's nothing left to do.
425 (unless (and (zero? (simultaneous-jobs status))
426 (extended-build-trace-supported?))
427 (format port (success (G_ "substitution of ~a complete")) item)
428 (newline port)))
429 (('substituter-failed item _ ...)
430 (format port (failure (G_ "substitution of ~a failed")) item)
431 (newline port))
432 (('hash-mismatch item algo expected actual _ ...)
433 ;; TRANSLATORS: The final string looks like "sha256 hash mismatch for
434 ;; /gnu/store/…-sth:", where "sha256" is the hash algorithm.
435 (format port (failure (G_ "~a hash mismatch for ~a:")) algo item)
436 (newline port)
437 (format port (info (G_ "\
438 expected hash: ~a
439 actual hash: ~a~%"))
440 expected actual))
441 (('build-remote drv host _ ...)
442 (format port (info (G_ "offloading build of ~a to '~a'")) drv host)
443 (newline port))
444 (('build-log pid line)
445 (if (multiplexed-output-supported?)
446 (if (not pid)
447 (begin
448 ;; LINE comes from the daemon, not from builders. Let it
449 ;; through.
450 (display line port)
451 (force-output port))
452 (print-log-line line))
453 (cond ((string-prefix? "substitute: " line)
454 ;; The daemon prefixes early messages coming with 'guix
455 ;; substitute' with "substitute:". These are useful ("updating
456 ;; substitutes from URL"), so let them through.
457 (display line port)
458 (force-output port))
459 ((string-prefix? "waiting for locks" line)
460 ;; This is when a derivation is already being built and we're just
461 ;; waiting for the build to complete.
462 (display (info (string-trim-right line)) port)
463 (newline))
464 (else
465 (print-log-line line)))))
466 (_
467 event)))
468
469 (define* (print-build-event/quiet event old-status status
470 #:optional
471 (port (current-error-port))
472 #:key
473 (colorize? (color-output? port)))
474 (print-build-event event old-status status port
475 #:colorize? colorize?
476 #:print-log? #f))
477
478 (define* (build-status-updater #:optional (on-change (const #t)))
479 "Return a procedure that can be passed to 'build-event-output-port'. That
480 procedure computes the new build status upon each event and calls ON-CHANGE:
481
482 (ON-CHANGE event status new-status)
483
484 ON-CHANGE can display the build status, build events, etc."
485 (lambda (event status)
486 (let ((new (compute-status event status)))
487 (on-change event status new)
488 new)))
489
490 \f
491 ;;;
492 ;;; Build port.
493 ;;;
494
495 (define (maybe-utf8->string bv)
496 "Attempt to decode BV as UTF-8 string and return it. Gracefully handle the
497 case where BV does not contain only valid UTF-8."
498 (catch 'decoding-error
499 (lambda ()
500 (utf8->string bv))
501 (lambda _
502 ;; This is the sledgehammer but it's the only safe way we have to
503 ;; properly handle this. It's expensive but it's rarely needed.
504 (let ((port (open-bytevector-input-port bv)))
505 (set-port-encoding! port "UTF-8")
506 (set-port-conversion-strategy! port 'substitute)
507 (let ((str (read-string port)))
508 (close-port port)
509 str)))))
510
511 (define (bytevector-index bv number offset count)
512 "Search for NUMBER in BV starting from OFFSET and reading up to COUNT bytes;
513 return the offset where NUMBER first occurs or #f if it could not be found."
514 (let loop ((offset offset)
515 (count count))
516 (cond ((zero? count) #f)
517 ((= (bytevector-u8-ref bv offset) number) offset)
518 (else (loop (+ 1 offset) (- count 1))))))
519
520 (define (split-lines str)
521 "Split STR into lines in a way that preserves newline characters."
522 (let loop ((str str)
523 (result '()))
524 (if (string-null? str)
525 (reverse result)
526 (match (string-index str #\newline)
527 (#f
528 (loop "" (cons str result)))
529 (index
530 (loop (string-drop str (+ index 1))
531 (cons (string-take str (+ index 1)) result)))))))
532
533 (define* (build-event-output-port proc #:optional (seed (build-status)))
534 "Return an output port for use as 'current-build-output-port' that calls
535 PROC with its current state value, initialized with SEED, on every build
536 event. Build events passed to PROC are tuples corresponding to the \"build
537 traces\" produced by the daemon:
538
539 (build-started \"/gnu/store/...-foo.drv\" ...)
540 (substituter-started \"/gnu/store/...-foo\" ...)
541
542 and so on.
543
544 The second return value is a thunk to retrieve the current state."
545 (define %fragments
546 ;; Line fragments received so far.
547 '())
548
549 (define %state
550 ;; Current state for PROC.
551 seed)
552
553 ;; When true, this represents the current state while reading a
554 ;; "@ build-log" trace: the current builder PID, the previously-read
555 ;; bytevectors, and the number of bytes that remain to be read.
556 (define %build-output-pid #f)
557 (define %build-output '())
558 (define %build-output-left #f)
559
560 (define (process-line line)
561 (cond ((string-prefix? "@ " line)
562 (match (string-tokenize (string-drop line 2))
563 (("build-log" (= string->number pid) (= string->number len))
564 (set! %build-output-pid pid)
565 (set! %build-output '())
566 (set! %build-output-left len))
567 (((= string->symbol event-name) args ...)
568 (set! %state
569 (proc (cons event-name args)
570 %state)))))
571 (else
572 (set! %state (proc (list 'build-log #f line)
573 %state)))))
574
575 (define (process-build-output pid output)
576 ;; Transform OUTPUT in 'build-log' events or download events as generated
577 ;; by extended build traces.
578 (define (line->event line)
579 (match (and (string-prefix? "@ " line)
580 (string-tokenize (string-drop line 2)))
581 ((type . args)
582 (if (or (string-prefix? "download-" type)
583 (string=? "build-remote" type))
584 (cons (string->symbol type) args)
585 `(build-log ,pid ,line)))
586 (_
587 `(build-log ,pid ,line))))
588
589 (let* ((lines (split-lines output))
590 (events (map line->event lines)))
591 (set! %state (fold proc %state events))))
592
593 (define (bytevector-range bv offset count)
594 (let ((ptr (bytevector->pointer bv offset)))
595 (pointer->bytevector ptr count)))
596
597 (define (write! bv offset count)
598 (if %build-output-pid
599 (let ((keep (min count %build-output-left)))
600 (set! %build-output
601 (let ((bv* (make-bytevector keep)))
602 (bytevector-copy! bv offset bv* 0 keep)
603 (cons bv* %build-output)))
604 (set! %build-output-left
605 (- %build-output-left keep))
606
607 (when (zero? %build-output-left)
608 (process-build-output %build-output-pid
609 (string-concatenate-reverse
610 (map maybe-utf8->string %build-output))) ;XXX
611 (set! %build-output '())
612 (set! %build-output-pid #f))
613 keep)
614 (match (bytevector-index bv (char->integer #\newline)
615 offset count)
616 ((? integer? cr)
617 (let* ((tail (maybe-utf8->string
618 (bytevector-range bv offset (- cr -1 offset))))
619 (line (string-concatenate-reverse
620 (cons tail %fragments))))
621 (process-line line)
622 (set! %fragments '())
623 (- cr -1 offset)))
624 (#f
625 (unless (zero? count)
626 (let ((str (maybe-utf8->string
627 (bytevector-range bv offset count))))
628 (set! %fragments (cons str %fragments))))
629 count))))
630
631 (define port
632 (make-custom-binary-output-port "filtering-input-port"
633 write!
634 #f #f
635 #f))
636
637 ;; The build port actually receives Unicode strings.
638 (set-port-encoding! port "UTF-8")
639 (cond-expand
640 ((and guile-2 (not guile-2.2)) #t)
641 (else (setvbuf port 'line)))
642 (values port (lambda () %state)))
643
644 (define (call-with-status-report on-event thunk)
645 (parameterize ((current-terminal-columns (terminal-columns))
646 (current-build-output-port
647 (build-event-output-port (build-status-updater on-event))))
648 (thunk)))
649
650 (define-syntax-rule (with-status-report on-event exp ...)
651 "Set up build status reporting to the user using the ON-EVENT procedure;
652 evaluate EXP... in that context."
653 (call-with-status-report on-event (lambda () exp ...)))