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