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-9 gnu)
34 #:use-module (srfi srfi-19)
35 #:use-module (srfi srfi-26)
36 #:use-module (ice-9 regex)
37 #:use-module (ice-9 match)
38 #:use-module (ice-9 format)
39 #:use-module (ice-9 binary-ports)
40 #:autoload (ice-9 rdelim) (read-string)
41 #:use-module (rnrs bytevectors)
42 #:use-module ((system foreign)
43 #:select (bytevector->pointer pointer->bytevector))
44 #:export (build-event-output-port
50 build-status-downloading
51 build-status-builds-completed
52 build-status-downloads-completed
70 print-build-event/quiet
74 with-status-verbosity))
78 ;;; This module provides facilities to track the status of ongoing builds and
79 ;;; downloads in a given session, as well as tools to report about the current
80 ;;; status to user interfaces. It does so by analyzing the output of
81 ;;; 'current-build-output-port'. The build status is maintained in a
82 ;;; <build-status> record.
88 ;;; Build status tracking.
91 ;; Builds and substitutions performed by the daemon.
92 (define-record-type* <build-status> build-status make-build-status
94 (building build-status-building ;list of <build>
96 (downloading build-status-downloading ;list of <download>
98 (builds-completed build-status-builds-completed ;list of <build>
100 (downloads-completed build-status-downloads-completed ;list of <download>
103 ;; On-going or completed build.
104 (define-immutable-record-type <build>
105 (%build derivation id system log-file completion)
107 (derivation build-derivation) ;string (.drv file name)
108 (id build-id) ;#f | integer
109 (system build-system) ;string
110 (log-file build-log-file) ;#f | string
111 (completion build-completion ;#f | integer (percentage)
112 set-build-completion))
114 (define* (build derivation system #:key id log-file completion)
115 "Return a new build."
116 (%build derivation id system log-file completion))
118 ;; On-going or completed downloads. Downloads can be stem from substitutes
119 ;; and from "builtin:download" fixed-output derivations.
120 (define-record-type <download>
121 (%download item uri size start end transferred)
123 (item download-item) ;store item
124 (uri download-uri) ;string | #f
125 (size download-size) ;integer | #f
126 (start download-start) ;<time>
127 (end download-end) ;#f | <time>
128 (transferred download-transferred)) ;integer
130 (define* (download item uri
132 (start (current-time time-monotonic)) end
134 "Return a new download."
135 (%download item uri size start end transferred))
137 (define (matching-build drv)
138 "Return a predicate that matches builds of DRV."
140 (string=? drv (build-derivation build))))
142 (define (matching-download item)
143 "Return a predicate that matches downloads of ITEM."
145 (string=? item (download-item download))))
147 (define %percentage-line-rx
148 ;; Things like CMake write lines like "[ 10%] gcc -c …". This regexp
150 (make-regexp "^[[:space:]]*\\[ *([0-9]+)%\\]"))
152 (define %fraction-line-rx
153 ;; The 'compiled-modules' derivations and Ninja produce reports like
154 ;; "[ 1/32]" at the beginning of each line, while GHC prints "[ 6 of 45]".
155 ;; This regexp matches these.
156 (make-regexp "^[[:space:]]*\\[ *([0-9]+) *(/|of) *([0-9]+)\\]"))
158 (define (update-build status id line)
159 "Update STATUS based on LINE, a build output line for ID that might contain
160 a completion indication."
162 (find (lambda (build)
163 (and (build-id build)
164 (= (build-id build) id)))
165 (build-status-building status)))
168 (let ((build (find-build)))
171 (building (cons (set-build-completion build %)
172 (delq build (build-status-building status)))))))
174 (cond ((string-any #\nul line)
175 ;; Don't try to match a regexp here.
177 ((regexp-exec %percentage-line-rx line)
180 (let ((% (string->number (match:substring match 1))))
182 ((regexp-exec %fraction-line-rx line)
185 (let ((done (string->number (match:substring match 1)))
186 (total (string->number (match:substring match 3))))
187 (update (* 100. (/ done total))))))
191 (define* (compute-status event status
193 (current-time current-time)
194 (derivation-path->output-path
195 derivation-path->output-path))
196 "Given EVENT, a tuple like (build-started \"/gnu/store/...-foo.drv\" ...),
197 compute a new status based on STATUS."
199 (('build-started drv "-" system log-file . rest)
200 (let ((build (build drv system
202 ((pid . _) (string->number pid))
204 #:log-file (if (string-null? log-file)
209 (building (cons build (build-status-building status))))))
210 (((or 'build-succeeded 'build-failed) drv _ ...)
211 (let ((build (find (matching-build drv)
212 (build-status-building status))))
213 ;; If BUILD is #f, this may be because DRV corresponds to a
214 ;; fixed-output derivation that is listed as a download.
218 (building (delq build (build-status-building status)))
220 (cons build (build-status-builds-completed status))))
223 ;; Note: Ignore 'substituter-started' and 'substituter-succeeded' because
224 ;; they're not as informative as 'download-started' and
225 ;; 'download-succeeded'.
227 (('download-started item uri (= string->number size))
228 ;; This is presumably a fixed-output derivation so move it from
229 ;; 'building' to 'downloading'. XXX: This doesn't work in 'check' mode
230 ;; because ITEM is different from DRV's output.
233 (building (remove (lambda (build)
234 (let ((drv (build-derivation build)))
235 (equal? (false-if-exception
236 (derivation-path->output-path drv))
238 (build-status-building status)))
239 (downloading (cons (download item uri #:size size
240 #:start (current-time time-monotonic))
241 (build-status-downloading status)))))
242 (('download-succeeded item uri (= string->number size))
243 (let ((current (find (matching-download item)
244 (build-status-downloading status))))
247 (downloading (delq current (build-status-downloading status)))
249 (cons (download item uri
251 #:start (download-start current)
253 #:end (current-time time-monotonic))
254 (build-status-downloads-completed status))))))
255 (('substituter-succeeded item _ ...)
256 (match (find (matching-download item)
257 (build-status-downloading status))
259 ;; Presumably we already got a 'download-succeeded' event for ITEM,
260 ;; everything is fine.
263 ;; Maybe the build process didn't emit a 'download-succeeded' event
264 ;; for ITEM, so remove CURRENT from the queue now.
267 (downloading (delq current (build-status-downloading status)))
269 (cons (download item (download-uri current)
270 #:size (download-size current)
271 #:start (download-start current)
272 #:transferred (download-size current)
273 #:end (current-time time-monotonic))
274 (build-status-downloads-completed status)))))))
275 (('download-progress item uri
276 (= string->number size)
277 (= string->number transferred))
278 (let ((downloads (remove (matching-download item)
279 (build-status-downloading status)))
280 (current (find (matching-download item)
281 (build-status-downloading status))))
284 (downloading (cons (download item uri
288 (download-start current))
289 (current-time time-monotonic))
290 #:transferred transferred)
292 (('build-log (? integer? pid) line)
293 (update-build status pid line))
297 (define (simultaneous-jobs status)
298 "Return the number of on-going builds and downloads for STATUS."
299 (+ (length (build-status-building status))
300 (length (build-status-downloading status))))
307 (define (extended-build-trace-supported?)
308 "Return true if the currently used store is known to support \"extended
309 build traces\" such as \"@ download-progress\" traces."
310 ;; Support for extended build traces was added in protocol version #x162.
311 (and (current-store-protocol-version)
312 (>= (current-store-protocol-version) #x162)))
314 (define (multiplexed-output-supported?)
315 "Return true if the daemon supports \"multiplexed output\"--i.e., \"@
317 (and (current-store-protocol-version)
318 (>= (current-store-protocol-version) #x163)))
325 (let ((steps (circular-list "\\" "|" "/" "-")))
327 "Display a spinner on PORT."
328 (when (isatty?* port)
332 (display "\r\x1b[K" port)
334 (force-output port)))))))
336 (define (color-output? port)
337 "Return true if we should write colored output to PORT."
338 (and (not (getenv "INSIDE_EMACS"))
339 (not (getenv "NO_COLOR"))
342 (define-syntax color-rules
344 "Return a procedure that colorizes the string it is passed according to
345 the given rules. Each rule has the form:
347 (REGEXP COLOR1 COLOR2 ...)
349 where COLOR1 specifies how to colorize the first submatch of REGEXP, and so
351 ((_ (regexp colors ...) rest ...)
352 (let ((next (color-rules rest ...))
353 (rx (make-regexp regexp)))
355 (if (string-index str #\nul)
357 (match (regexp-exec rx str)
364 (string-concatenate-reverse result))
367 (cons (colorize-string (match:substring m n)
374 (define colorize-log-line
375 ;; Take a string and return a possibly colorized string according to the
378 ("^(phase)(.*)(succeeded after)(.*)(seconds)(.*)"
379 GREEN BOLD GREEN RESET GREEN BLUE)
380 ("^(phase)(.*)(failed after)(.*)(seconds)(.*)"
381 RED BLUE RED BLUE RED BLUE)
382 ("^(.*)(error|fail|failed|\\<FAIL|FAILED)([[:blank:]]*)(:)(.*)"
383 RESET RED BOLD BOLD BOLD)
384 ("^(.*)(warning)([[:blank:]]*)(:)(.*)"
385 RESET MAGENTA BOLD BOLD BOLD)))
387 (define (hook-message hook-type)
388 "Return a human-readable string for the profile hook type HOOK-TYPE."
391 (G_ "building directory of Info manuals..."))
393 (G_ "building GHC package cache..."))
394 ('ca-certificate-bundle
395 (G_ "building CA certificate bundle..."))
397 (G_ "generating GLib schema cache..."))
399 (G_ "creating GTK+ icon theme cache..."))
401 (G_ "building cache files for GTK+ input methods..."))
402 ('xdg-desktop-database
403 (G_ "building XDG desktop file cache..."))
405 (G_ "building XDG MIME database..."))
407 (G_ "building fonts directory..."))
408 ('texlive-configuration
409 (G_ "building TeX Live configuration..."))
411 (G_ "building database for manual pages..."))
412 ('package-cache ;package cache generated by 'guix pull'
413 (G_ "building package cache..."))
416 (define* (print-build-event event old-status status
417 #:optional (port (current-error-port))
419 (colorize? (color-output? port))
421 "Print information about EVENT and STATUS to PORT. When COLORIZE? is true,
422 produce colorful output. When PRINT-LOG? is true, display the build log in
423 addition to build events."
426 (cut colorize-string <> 'BOLD)
431 (cut colorize-string <> 'GREEN 'BOLD)
436 (cut colorize-string <> 'RED 'BOLD)
439 (define (report-build-progress %)
440 (let ((% (min (max % 0) 100))) ;sanitize
441 (erase-current-line port)
442 (format port "~3d% " (inexact->exact (round %)))
443 (display (progress-bar % (- (current-terminal-columns) 5))
445 (force-output port)))
447 (define print-log-line
451 (display (colorize-log-line line) port))
453 (display line port)))
455 (match (build-status-building status)
457 (match (build-completion build)
458 ((? number? %) (report-build-progress %))
463 (define erase-current-line*
466 (erase-current-line port)
471 (erase-current-line* port)) ;clear the spinner or progress bar
473 (('build-started drv . _)
474 (let ((properties (derivation-properties
475 (read-derivation-from-file drv))))
476 (match (assq-ref properties 'type)
478 (let ((count (match (assq-ref properties 'graft)
480 (lst (or (assq-ref lst 'count) 0)))))
481 (format port (info (N_ "applying ~a graft for ~a..."
482 "applying ~a grafts for ~a..."
486 (let ((hook-type (assq-ref properties 'hook)))
487 (or (and=> (hook-message hook-type)
489 (format port (info msg))))
490 (format port (info (G_ "running profile hook of type '~a'..."))
493 (format port (info (G_ "building ~a...")) drv))))
495 (('build-succeeded drv . _)
496 (when (or print-log? (not (extended-build-trace-supported?)))
497 (format port (success (G_ "successfully built ~a")) drv)
499 (match (build-status-building status)
501 (ongoing ;when max-jobs > 1
503 (N_ "The following build is still in progress:~%~{ ~a~%~}~%"
504 "The following builds are still in progress:~%~{ ~a~%~}~%"
506 (map build-derivation ongoing)))))
507 (('build-failed drv . _)
508 (format port (failure (G_ "build of ~a failed")) drv)
510 (match (derivation-log-file drv)
512 (format port (failure (G_ "Could not find build log for '~a'."))
515 (format port (info (G_ "View build log at '~a'.")) log)))
517 (('substituter-started item _ ...)
518 (when (or print-log? (not (extended-build-trace-supported?)))
519 (format port (info (G_ "substituting ~a...")) item)
521 (('download-started item uri _ ...)
522 (format port (info (G_ "downloading from ~a...")) uri)
524 (('download-progress item uri
525 (= string->number size)
526 (= string->number transferred))
527 ;; Print a progress bar, but only if there's only one on-going
528 ;; job--otherwise the output would be intermingled.
529 (when (= 1 (simultaneous-jobs status))
530 (match (find (matching-download item)
531 (build-status-downloading status))
532 (#f #f) ;shouldn't happen!
534 ;; XXX: It would be nice to memoize the abbreviation.
535 (let ((uri (if (string-contains uri "/nar/")
536 (nar-uri-abbreviation uri)
538 (display-download-progress uri size
540 (download-start download)
541 #:transferred transferred))))))
542 (('substituter-succeeded item _ ...)
543 ;; If there are no jobs running, we already reported download completion
544 ;; so there's nothing left to do.
545 (unless (and (zero? (simultaneous-jobs status))
546 (extended-build-trace-supported?))
547 (format port (success (G_ "substitution of ~a complete")) item)
549 (('substituter-failed item _ ...)
550 (format port (failure (G_ "substitution of ~a failed")) item)
552 (('hash-mismatch item algo expected actual _ ...)
553 ;; TRANSLATORS: The final string looks like "sha256 hash mismatch for
554 ;; /gnu/store/…-sth:", where "sha256" is the hash algorithm.
555 (format port (failure (G_ "~a hash mismatch for ~a:")) algo item)
557 (format port (info (G_ "\
561 (('build-remote drv host _ ...)
562 (format port (info (G_ "offloading build of ~a to '~a'")) drv host)
564 (('build-log pid line)
565 (if (multiplexed-output-supported?)
568 ;; LINE comes from the daemon, not from builders. Let it
572 (print-log-line pid line))
573 (cond ((string-prefix? "substitute: " line)
574 ;; The daemon prefixes early messages coming with 'guix
575 ;; substitute' with "substitute:". These are useful ("updating
576 ;; substitutes from URL"), so let them through.
579 ((string-prefix? "waiting for locks" line)
580 ;; This is when a derivation is already being built and we're just
581 ;; waiting for the build to complete.
582 (display (info (string-trim-right line)) port)
585 (print-log-line pid line)))))
589 (define* (print-build-event/quiet event old-status status
591 (port (current-error-port))
593 (colorize? (color-output? port)))
594 (print-build-event event old-status status port
595 #:colorize? colorize?
598 (define* (build-status-updater #:optional (on-change (const #t)))
599 "Return a procedure that can be passed to 'build-event-output-port'. That
600 procedure computes the new build status upon each event and calls ON-CHANGE:
602 (ON-CHANGE event status new-status)
604 ON-CHANGE can display the build status, build events, etc."
605 (lambda (event status)
606 (let ((new (compute-status event status)))
607 (on-change event status new)
615 (define (maybe-utf8->string bv)
616 "Attempt to decode BV as UTF-8 string and return it. Gracefully handle the
617 case where BV does not contain only valid UTF-8."
618 (catch 'decoding-error
622 ;; This is the sledgehammer but it's the only safe way we have to
623 ;; properly handle this. It's expensive but it's rarely needed.
624 (let ((port (open-bytevector-input-port bv)))
625 (set-port-encoding! port "UTF-8")
626 (set-port-conversion-strategy! port 'substitute)
627 (let ((str (read-string port)))
631 (define (bytevector-index bv number offset count)
632 "Search for NUMBER in BV starting from OFFSET and reading up to COUNT bytes;
633 return the offset where NUMBER first occurs or #f if it could not be found."
634 (let loop ((offset offset)
636 (cond ((zero? count) #f)
637 ((= (bytevector-u8-ref bv offset) number) offset)
638 (else (loop (+ 1 offset) (- count 1))))))
640 (define (split-lines str)
641 "Split STR into lines in a way that preserves newline characters."
644 (if (string-null? str)
646 (match (string-index str #\newline)
648 (loop "" (cons str result)))
650 (loop (string-drop str (+ index 1))
651 (cons (string-take str (+ index 1)) result)))))))
653 (define* (build-event-output-port proc #:optional (seed (build-status)))
654 "Return an output port for use as 'current-build-output-port' that calls
655 PROC with its current state value, initialized with SEED, on every build
656 event. Build events passed to PROC are tuples corresponding to the \"build
657 traces\" produced by the daemon:
659 (build-started \"/gnu/store/...-foo.drv\" ...)
660 (substituter-started \"/gnu/store/...-foo\" ...)
664 The second return value is a thunk to retrieve the current state."
666 ;; Line fragments received so far.
670 ;; Current state for PROC.
673 ;; When true, this represents the current state while reading a
674 ;; "@ build-log" trace: the current builder PID, the previously-read
675 ;; bytevectors, and the number of bytes that remain to be read.
676 (define %build-output-pid #f)
677 (define %build-output '())
678 (define %build-output-left #f)
680 (define (process-line line)
681 (cond ((string-prefix? "@ " line)
682 ;; Note: Drop the trailing \n, and use 'string-split' to preserve
683 ;; spaces (the log file part of 'build-started' events can be the
685 (match (string-split (string-drop (string-drop-right line 1) 2)
687 (("build-log" (= string->number pid) (= string->number len))
688 (set! %build-output-pid pid)
689 (set! %build-output '())
690 (set! %build-output-left len))
691 (((= string->symbol event-name) args ...)
693 (proc (cons event-name args)
696 (set! %state (proc (list 'build-log #f line)
699 (define (process-build-output pid output)
700 ;; Transform OUTPUT in 'build-log' events or download events as generated
701 ;; by extended build traces.
702 (define (line->event line)
703 (match (and (string-prefix? "@ " line)
704 (string-tokenize (string-drop line 2)))
706 (if (or (string-prefix? "download-" type)
707 (string=? "build-remote" type))
708 (cons (string->symbol type) args)
709 `(build-log ,pid ,line)))
711 `(build-log ,pid ,line))))
713 (let* ((lines (split-lines output))
714 (events (map line->event lines)))
715 (set! %state (fold proc %state events))))
717 (define (bytevector-range bv offset count)
718 (let ((ptr (bytevector->pointer bv offset)))
719 (pointer->bytevector ptr count)))
721 (define (write! bv offset count)
722 (if %build-output-pid
723 (let ((keep (min count %build-output-left)))
725 (let ((bv* (make-bytevector keep)))
726 (bytevector-copy! bv offset bv* 0 keep)
727 (cons bv* %build-output)))
728 (set! %build-output-left
729 (- %build-output-left keep))
731 (when (zero? %build-output-left)
732 (process-build-output %build-output-pid
733 (string-concatenate-reverse
734 (map maybe-utf8->string %build-output))) ;XXX
735 (set! %build-output '())
736 (set! %build-output-pid #f))
738 (match (bytevector-index bv (char->integer #\newline)
741 (let* ((tail (maybe-utf8->string
742 (bytevector-range bv offset (- cr -1 offset))))
743 (line (string-concatenate-reverse
744 (cons tail %fragments))))
746 (set! %fragments '())
749 (unless (zero? count)
750 (let ((str (maybe-utf8->string
751 (bytevector-range bv offset count))))
752 (set! %fragments (cons str %fragments))))
756 (make-custom-binary-output-port "filtering-input-port"
761 ;; The build port actually receives Unicode strings.
762 (set-port-encoding! port "UTF-8")
764 (values port (lambda () %state)))
766 (define (call-with-status-report on-event thunk)
767 (parameterize ((current-terminal-columns (terminal-columns))
768 (current-build-output-port
769 (build-event-output-port (build-status-updater on-event))))
772 (define-syntax-rule (with-status-report on-event exp ...)
773 "Set up build status reporting to the user using the ON-EVENT procedure;
774 evaluate EXP... in that context."
775 (call-with-status-report on-event (lambda () exp ...)))
777 (define (logger-for-level level)
778 "Return the logging procedure that corresponds to LEVEL."
779 (cond ((<= level 0) (const #t))
780 ((= level 1) print-build-event/quiet)
781 (else print-build-event)))
783 (define (call-with-status-verbosity level thunk)
784 (call-with-status-report (logger-for-level level) thunk))
786 (define-syntax-rule (with-status-verbosity level exp ...)
787 "Set up build status reporting to the user at the given LEVEL: 0 means
788 silent, 1 means quiet, 2 means verbose. Evaluate EXP... in that context."
789 (call-with-status-verbosity level (lambda () exp ...)))