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