1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2017, 2018, 2019 Ludovic Courtès <ludo@gnu.org>
3 ;;; Copyright © 2018, 2019 Ricardo Wurmus <rekado@elephly.net>
5 ;;; This file is part of GNU Guix.
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.
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.
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/>.
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
49 build-status-downloading
50 build-status-builds-completed
51 build-status-downloads-completed
64 print-build-event/quiet
68 with-status-verbosity))
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.
82 ;;; Build status tracking.
85 ;; Builds and substitutions performed by the daemon.
86 (define-record-type* <build-status> build-status make-build-status
88 (building build-status-building ;list of drv
90 (downloading build-status-downloading ;list of <download>
92 (builds-completed build-status-builds-completed ;list of drv
94 (downloads-completed build-status-downloads-completed ;list of store items
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)
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
109 (define* (download item uri
111 (start (current-time time-monotonic)) end
113 "Return a new download."
114 (%download item uri size start end transferred))
116 (define (matching-download item)
117 "Return a predicate that matches downloads of ITEM."
119 (string=? item (download-item download))))
121 (define* (compute-status event status
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."
129 (('build-started drv _ ...)
132 (building (cons drv (build-status-building status)))))
133 (((or 'build-succeeded 'build-failed) drv _ ...)
136 (building (delete drv (build-status-building status)))
137 (builds-completed (cons drv (build-status-builds-completed status)))))
139 ;; Note: Ignore 'substituter-started' and 'substituter-succeeded' because
140 ;; they're not as informative as 'download-started' and
141 ;; 'download-succeeded'.
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.
149 (building (remove (lambda (drv)
150 (equal? (false-if-exception
151 (derivation-path->output-path drv))
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))))
162 (downloading (delq current (build-status-downloading status)))
164 (cons (download item uri
166 #:start (download-start current)
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))
174 ;; Presumably we already got a 'download-succeeded' event for ITEM,
175 ;; everything is fine.
178 ;; Maybe the build process didn't emit a 'download-succeeded' event
179 ;; for ITEM, so remove CURRENT from the queue now.
182 (downloading (delq current (build-status-downloading status)))
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))))
199 (downloading (cons (download item uri
203 (download-start current))
204 (current-time time-monotonic))
205 #:transferred transferred)
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))))
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)))
227 (define (multiplexed-output-supported?)
228 "Return true if the daemon supports \"multiplexed output\"--i.e., \"@
230 (and (current-store-protocol-version)
231 (>= (current-store-protocol-version) #x163)))
238 (let ((steps (circular-list "\\" "|" "/" "-")))
240 "Display a spinner on PORT."
241 (when (isatty?* port)
245 (display "\r\x1b[K" port)
247 (force-output port)))))))
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"))
255 (define-syntax color-rules
257 "Return a procedure that colorizes the string it is passed according to
258 the given rules. Each rule has the form:
260 (REGEXP COLOR1 COLOR2 ...)
262 where COLOR1 specifies how to colorize the first submatch of REGEXP, and so
264 ((_ (regexp colors ...) rest ...)
265 (let ((next (color-rules rest ...))
266 (rx (make-regexp regexp)))
268 (if (string-index str #\nul)
270 (match (regexp-exec rx str)
277 (string-concatenate-reverse result))
280 (cons (colorize-string (match:substring m n)
287 (define colorize-log-line
288 ;; Take a string and return a possibly colorized string according to the
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)))
300 (define (hook-message hook-type)
301 "Return a human-readable string for the profile hook type HOOK-TYPE."
304 (G_ "building directory of Info manuals..."))
306 (G_ "building GHC package cache..."))
307 ('ca-certificate-bundle
308 (G_ "building CA certificate bundle..."))
310 (G_ "generating GLib schema cache..."))
312 (G_ "creating GTK+ icon theme cache..."))
314 (G_ "building cache files for GTK+ input methods..."))
315 ('xdg-desktop-database
316 (G_ "building XDG desktop file cache..."))
318 (G_ "building XDG MIME database..."))
320 (G_ "building fonts directory..."))
321 ('texlive-configuration
322 (G_ "building TeX Live configuration..."))
324 (G_ "building database for manual pages..."))
325 ('package-cache ;package cache generated by 'guix pull'
326 (G_ "building package cache..."))
329 (define* (print-build-event event old-status status
330 #:optional (port (current-error-port))
332 (colorize? (color-output? port))
334 "Print information about EVENT and STATUS to PORT. When COLORIZE? is true,
335 produce colorful output. When PRINT-LOG? is true, display the build log in
336 addition to build events."
339 (cut colorize-string <> 'BOLD)
344 (cut colorize-string <> 'GREEN 'BOLD)
349 (cut colorize-string <> 'RED 'BOLD)
352 (define print-log-line
356 (display (colorize-log-line line) port))
357 (cut display <> port))
362 (display "\r" port)) ;erase the spinner
364 (('build-started drv . _)
365 (let ((properties (derivation-properties
366 (read-derivation-from-file drv))))
367 (match (assq-ref properties 'type)
369 (let ((count (match (assq-ref properties 'graft)
371 (lst (or (assq-ref lst 'count) 0)))))
372 (format port (info (N_ "applying ~a graft for ~a..."
373 "applying ~a grafts for ~a..."
377 (let ((hook-type (assq-ref properties 'hook)))
378 (or (and=> (hook-message hook-type)
380 (format port (info msg))))
381 (format port (info (G_ "running profile hook of type '~a'..."))
384 (format port (info (G_ "building ~a...")) drv))))
386 (('build-succeeded drv . _)
387 (when (or print-log? (not (extended-build-trace-supported?)))
388 (format port (success (G_ "successfully built ~a")) drv)
390 (match (build-status-building status)
392 (ongoing ;when max-jobs > 1
394 (N_ "The following build is still in progress:~%~{ ~a~%~}~%"
395 "The following builds are still in progress:~%~{ ~a~%~}~%"
398 (('build-failed drv . _)
399 (format port (failure (G_ "build of ~a failed")) drv)
401 (match (derivation-log-file drv)
403 (format port (failure (G_ "Could not find build log for '~a'."))
406 (format port (info (G_ "View build log at '~a'.")) log)))
408 (('substituter-started item _ ...)
409 (when (or print-log? (not (extended-build-trace-supported?)))
410 (format port (info (G_ "substituting ~a...")) item)
412 (('download-started item uri _ ...)
413 (format port (info (G_ "downloading from ~a...")) uri)
415 (('download-progress item uri
416 (= string->number size)
417 (= string->number transferred))
418 ;; Print a progress bar, but only if there's only one on-going
419 ;; job--otherwise the output would be intermingled.
420 (when (= 1 (simultaneous-jobs status))
421 (match (find (matching-download item)
422 (build-status-downloading status))
423 (#f #f) ;shouldn't happen!
425 ;; XXX: It would be nice to memoize the abbreviation.
426 (let ((uri (if (string-contains uri "/nar/")
427 (nar-uri-abbreviation uri)
429 (display-download-progress uri size
431 (download-start download)
432 #:transferred transferred))))))
433 (('substituter-succeeded item _ ...)
434 ;; If there are no jobs running, we already reported download completion
435 ;; so there's nothing left to do.
436 (unless (and (zero? (simultaneous-jobs status))
437 (extended-build-trace-supported?))
438 (format port (success (G_ "substitution of ~a complete")) item)
440 (('substituter-failed item _ ...)
441 (format port (failure (G_ "substitution of ~a failed")) item)
443 (('hash-mismatch item algo expected actual _ ...)
444 ;; TRANSLATORS: The final string looks like "sha256 hash mismatch for
445 ;; /gnu/store/…-sth:", where "sha256" is the hash algorithm.
446 (format port (failure (G_ "~a hash mismatch for ~a:")) algo item)
448 (format port (info (G_ "\
452 (('build-remote drv host _ ...)
453 (format port (info (G_ "offloading build of ~a to '~a'")) drv host)
455 (('build-log pid line)
456 (if (multiplexed-output-supported?)
459 ;; LINE comes from the daemon, not from builders. Let it
463 (print-log-line line))
464 (cond ((string-prefix? "substitute: " line)
465 ;; The daemon prefixes early messages coming with 'guix
466 ;; substitute' with "substitute:". These are useful ("updating
467 ;; substitutes from URL"), so let them through.
470 ((string-prefix? "waiting for locks" line)
471 ;; This is when a derivation is already being built and we're just
472 ;; waiting for the build to complete.
473 (display (info (string-trim-right line)) port)
476 (print-log-line line)))))
480 (define* (print-build-event/quiet event old-status status
482 (port (current-error-port))
484 (colorize? (color-output? port)))
485 (print-build-event event old-status status port
486 #:colorize? colorize?
489 (define* (build-status-updater #:optional (on-change (const #t)))
490 "Return a procedure that can be passed to 'build-event-output-port'. That
491 procedure computes the new build status upon each event and calls ON-CHANGE:
493 (ON-CHANGE event status new-status)
495 ON-CHANGE can display the build status, build events, etc."
496 (lambda (event status)
497 (let ((new (compute-status event status)))
498 (on-change event status new)
506 (define (maybe-utf8->string bv)
507 "Attempt to decode BV as UTF-8 string and return it. Gracefully handle the
508 case where BV does not contain only valid UTF-8."
509 (catch 'decoding-error
513 ;; This is the sledgehammer but it's the only safe way we have to
514 ;; properly handle this. It's expensive but it's rarely needed.
515 (let ((port (open-bytevector-input-port bv)))
516 (set-port-encoding! port "UTF-8")
517 (set-port-conversion-strategy! port 'substitute)
518 (let ((str (read-string port)))
522 (define (bytevector-index bv number offset count)
523 "Search for NUMBER in BV starting from OFFSET and reading up to COUNT bytes;
524 return the offset where NUMBER first occurs or #f if it could not be found."
525 (let loop ((offset offset)
527 (cond ((zero? count) #f)
528 ((= (bytevector-u8-ref bv offset) number) offset)
529 (else (loop (+ 1 offset) (- count 1))))))
531 (define (split-lines str)
532 "Split STR into lines in a way that preserves newline characters."
535 (if (string-null? str)
537 (match (string-index str #\newline)
539 (loop "" (cons str result)))
541 (loop (string-drop str (+ index 1))
542 (cons (string-take str (+ index 1)) result)))))))
544 (define* (build-event-output-port proc #:optional (seed (build-status)))
545 "Return an output port for use as 'current-build-output-port' that calls
546 PROC with its current state value, initialized with SEED, on every build
547 event. Build events passed to PROC are tuples corresponding to the \"build
548 traces\" produced by the daemon:
550 (build-started \"/gnu/store/...-foo.drv\" ...)
551 (substituter-started \"/gnu/store/...-foo\" ...)
555 The second return value is a thunk to retrieve the current state."
557 ;; Line fragments received so far.
561 ;; Current state for PROC.
564 ;; When true, this represents the current state while reading a
565 ;; "@ build-log" trace: the current builder PID, the previously-read
566 ;; bytevectors, and the number of bytes that remain to be read.
567 (define %build-output-pid #f)
568 (define %build-output '())
569 (define %build-output-left #f)
571 (define (process-line line)
572 (cond ((string-prefix? "@ " line)
573 (match (string-tokenize (string-drop line 2))
574 (("build-log" (= string->number pid) (= string->number len))
575 (set! %build-output-pid pid)
576 (set! %build-output '())
577 (set! %build-output-left len))
578 (((= string->symbol event-name) args ...)
580 (proc (cons event-name args)
583 (set! %state (proc (list 'build-log #f line)
586 (define (process-build-output pid output)
587 ;; Transform OUTPUT in 'build-log' events or download events as generated
588 ;; by extended build traces.
589 (define (line->event line)
590 (match (and (string-prefix? "@ " line)
591 (string-tokenize (string-drop line 2)))
593 (if (or (string-prefix? "download-" type)
594 (string=? "build-remote" type))
595 (cons (string->symbol type) args)
596 `(build-log ,pid ,line)))
598 `(build-log ,pid ,line))))
600 (let* ((lines (split-lines output))
601 (events (map line->event lines)))
602 (set! %state (fold proc %state events))))
604 (define (bytevector-range bv offset count)
605 (let ((ptr (bytevector->pointer bv offset)))
606 (pointer->bytevector ptr count)))
608 (define (write! bv offset count)
609 (if %build-output-pid
610 (let ((keep (min count %build-output-left)))
612 (let ((bv* (make-bytevector keep)))
613 (bytevector-copy! bv offset bv* 0 keep)
614 (cons bv* %build-output)))
615 (set! %build-output-left
616 (- %build-output-left keep))
618 (when (zero? %build-output-left)
619 (process-build-output %build-output-pid
620 (string-concatenate-reverse
621 (map maybe-utf8->string %build-output))) ;XXX
622 (set! %build-output '())
623 (set! %build-output-pid #f))
625 (match (bytevector-index bv (char->integer #\newline)
628 (let* ((tail (maybe-utf8->string
629 (bytevector-range bv offset (- cr -1 offset))))
630 (line (string-concatenate-reverse
631 (cons tail %fragments))))
633 (set! %fragments '())
636 (unless (zero? count)
637 (let ((str (maybe-utf8->string
638 (bytevector-range bv offset count))))
639 (set! %fragments (cons str %fragments))))
643 (make-custom-binary-output-port "filtering-input-port"
648 ;; The build port actually receives Unicode strings.
649 (set-port-encoding! port "UTF-8")
651 (values port (lambda () %state)))
653 (define (call-with-status-report on-event thunk)
654 (parameterize ((current-terminal-columns (terminal-columns))
655 (current-build-output-port
656 (build-event-output-port (build-status-updater on-event))))
659 (define-syntax-rule (with-status-report on-event exp ...)
660 "Set up build status reporting to the user using the ON-EVENT procedure;
661 evaluate EXP... in that context."
662 (call-with-status-report on-event (lambda () exp ...)))
664 (define (logger-for-level level)
665 "Return the logging procedure that corresponds to LEVEL."
666 (cond ((<= level 0) (const #t))
667 ((= level 1) print-build-event/quiet)
668 (else print-build-event)))
670 (define (call-with-status-verbosity level thunk)
671 (call-with-status-report (logger-for-level level) thunk))
673 (define-syntax-rule (with-status-verbosity level exp ...)
674 "Set up build status reporting to the user at the given LEVEL: 0 means
675 silent, 1 means quiet, 2 means verbose. Evaluate EXP... in that context."
676 (call-with-status-verbosity level (lambda () exp ...)))