status: Display 'build-remote' events.
[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 (format port (info (G_ "building ~a...")) drv)
329 (newline port))
330 (('build-succeeded drv . _)
331 (when (or print-log? (not (extended-build-trace-supported?)))
332 (format port (success (G_ "successfully built ~a")) drv)
333 (newline port))
334 (match (build-status-building status)
335 (() #t)
336 (ongoing ;when max-jobs > 1
337 (format port
338 (N_ "The following build is still in progress:~%~{ ~a~%~}~%"
339 "The following builds are still in progress:~%~{ ~a~%~}~%"
340 (length ongoing))
341 ongoing))))
342 (('build-failed drv . _)
343 (format port (failure (G_ "build of ~a failed")) drv)
344 (newline port)
345 (match (derivation-log-file drv)
346 (#f
347 (format port (failure (G_ "Could not find build log for '~a'."))
348 drv))
349 (log
350 (format port (info (G_ "View build log at '~a'.")) log)))
351 (newline port))
352 (('substituter-started item _ ...)
353 (when (or print-log? (not (extended-build-trace-supported?)))
354 (format port (info (G_ "substituting ~a...")) item)
355 (newline port)))
356 (('download-started item uri _ ...)
357 (format port (info (G_ "downloading from ~a...")) uri)
358 (newline port))
359 (('download-progress item uri
360 (= string->number size)
361 (= string->number transferred))
362 ;; Print a progress bar, but only if there's only one on-going
363 ;; job--otherwise the output would be intermingled.
364 (when (= 1 (simultaneous-jobs status))
365 (match (find (matching-download item)
366 (build-status-downloading status))
367 (#f #f) ;shouldn't happen!
368 (download
369 ;; XXX: It would be nice to memoize the abbreviation.
370 (let ((uri (if (string-contains uri "/nar/")
371 (nar-uri-abbreviation uri)
372 (basename uri))))
373 (display-download-progress uri size
374 #:start-time
375 (download-start download)
376 #:transferred transferred))))))
377 (('substituter-succeeded item _ ...)
378 ;; If there are no jobs running, we already reported download completion
379 ;; so there's nothing left to do.
380 (unless (and (zero? (simultaneous-jobs status))
381 (extended-build-trace-supported?))
382 (format port (success (G_ "substitution of ~a complete")) item)
383 (newline port)))
384 (('substituter-failed item _ ...)
385 (format port (failure (G_ "substitution of ~a failed")) item)
386 (newline port))
387 (('hash-mismatch item algo expected actual _ ...)
388 ;; TRANSLATORS: The final string looks like "sha256 hash mismatch for
389 ;; /gnu/store/…-sth:", where "sha256" is the hash algorithm.
390 (format port (failure (G_ "~a hash mismatch for ~a:")) algo item)
391 (newline port)
392 (format port (info (G_ "\
393 expected hash: ~a
394 actual hash: ~a~%"))
395 expected actual))
396 (('build-remote drv host _ ...)
397 (format port (info (G_ "offloading build of ~a to '~a'")) drv host)
398 (newline port))
399 (('build-log pid line)
400 (if (multiplexed-output-supported?)
401 (if (not pid)
402 (begin
403 ;; LINE comes from the daemon, not from builders. Let it
404 ;; through.
405 (display line port)
406 (force-output port))
407 (print-log-line line))
408 (cond ((string-prefix? "substitute: " line)
409 ;; The daemon prefixes early messages coming with 'guix
410 ;; substitute' with "substitute:". These are useful ("updating
411 ;; substitutes from URL"), so let them through.
412 (display line port)
413 (force-output port))
414 ((string-prefix? "waiting for locks" line)
415 ;; This is when a derivation is already being built and we're just
416 ;; waiting for the build to complete.
417 (display (info (string-trim-right line)) port)
418 (newline))
419 (else
420 (print-log-line line)))))
421 (_
422 event)))
423
424 (define* (print-build-event/quiet event old-status status
425 #:optional
426 (port (current-error-port))
427 #:key
428 (colorize? (color-output? port)))
429 (print-build-event event old-status status port
430 #:colorize? colorize?
431 #:print-log? #f))
432
433 (define* (build-status-updater #:optional (on-change (const #t)))
434 "Return a procedure that can be passed to 'build-event-output-port'. That
435 procedure computes the new build status upon each event and calls ON-CHANGE:
436
437 (ON-CHANGE event status new-status)
438
439 ON-CHANGE can display the build status, build events, etc."
440 (lambda (event status)
441 (let ((new (compute-status event status)))
442 (on-change event status new)
443 new)))
444
445 \f
446 ;;;
447 ;;; Build port.
448 ;;;
449
450 (define (maybe-utf8->string bv)
451 "Attempt to decode BV as UTF-8 string and return it. Gracefully handle the
452 case where BV does not contain only valid UTF-8."
453 (catch 'decoding-error
454 (lambda ()
455 (utf8->string bv))
456 (lambda _
457 ;; This is the sledgehammer but it's the only safe way we have to
458 ;; properly handle this. It's expensive but it's rarely needed.
459 (let ((port (open-bytevector-input-port bv)))
460 (set-port-encoding! port "UTF-8")
461 (set-port-conversion-strategy! port 'substitute)
462 (let ((str (read-string port)))
463 (close-port port)
464 str)))))
465
466 (define (bytevector-index bv number offset count)
467 "Search for NUMBER in BV starting from OFFSET and reading up to COUNT bytes;
468 return the offset where NUMBER first occurs or #f if it could not be found."
469 (let loop ((offset offset)
470 (count count))
471 (cond ((zero? count) #f)
472 ((= (bytevector-u8-ref bv offset) number) offset)
473 (else (loop (+ 1 offset) (- count 1))))))
474
475 (define (split-lines str)
476 "Split STR into lines in a way that preserves newline characters."
477 (let loop ((str str)
478 (result '()))
479 (if (string-null? str)
480 (reverse result)
481 (match (string-index str #\newline)
482 (#f
483 (loop "" (cons str result)))
484 (index
485 (loop (string-drop str (+ index 1))
486 (cons (string-take str (+ index 1)) result)))))))
487
488 (define* (build-event-output-port proc #:optional (seed (build-status)))
489 "Return an output port for use as 'current-build-output-port' that calls
490 PROC with its current state value, initialized with SEED, on every build
491 event. Build events passed to PROC are tuples corresponding to the \"build
492 traces\" produced by the daemon:
493
494 (build-started \"/gnu/store/...-foo.drv\" ...)
495 (substituter-started \"/gnu/store/...-foo\" ...)
496
497 and so on.
498
499 The second return value is a thunk to retrieve the current state."
500 (define %fragments
501 ;; Line fragments received so far.
502 '())
503
504 (define %state
505 ;; Current state for PROC.
506 seed)
507
508 ;; When true, this represents the current state while reading a
509 ;; "@ build-log" trace: the current builder PID, the previously-read
510 ;; bytevectors, and the number of bytes that remain to be read.
511 (define %build-output-pid #f)
512 (define %build-output '())
513 (define %build-output-left #f)
514
515 (define (process-line line)
516 (cond ((string-prefix? "@ " line)
517 (match (string-tokenize (string-drop line 2))
518 (("build-log" (= string->number pid) (= string->number len))
519 (set! %build-output-pid pid)
520 (set! %build-output '())
521 (set! %build-output-left len))
522 (((= string->symbol event-name) args ...)
523 (set! %state
524 (proc (cons event-name args)
525 %state)))))
526 (else
527 (set! %state (proc (list 'build-log #f line)
528 %state)))))
529
530 (define (process-build-output pid output)
531 ;; Transform OUTPUT in 'build-log' events or download events as generated
532 ;; by extended build traces.
533 (define (line->event line)
534 (match (and (string-prefix? "@ " line)
535 (string-tokenize (string-drop line 2)))
536 ((type . args)
537 (if (or (string-prefix? "download-" type)
538 (string=? "build-remote" type))
539 (cons (string->symbol type) args)
540 `(build-log ,pid ,line)))
541 (_
542 `(build-log ,pid ,line))))
543
544 (let* ((lines (split-lines output))
545 (events (map line->event lines)))
546 (set! %state (fold proc %state events))))
547
548 (define (bytevector-range bv offset count)
549 (let ((ptr (bytevector->pointer bv offset)))
550 (pointer->bytevector ptr count)))
551
552 (define (write! bv offset count)
553 (if %build-output-pid
554 (let ((keep (min count %build-output-left)))
555 (set! %build-output
556 (let ((bv* (make-bytevector keep)))
557 (bytevector-copy! bv offset bv* 0 keep)
558 (cons bv* %build-output)))
559 (set! %build-output-left
560 (- %build-output-left keep))
561
562 (when (zero? %build-output-left)
563 (process-build-output %build-output-pid
564 (string-concatenate-reverse
565 (map maybe-utf8->string %build-output))) ;XXX
566 (set! %build-output '())
567 (set! %build-output-pid #f))
568 keep)
569 (match (bytevector-index bv (char->integer #\newline)
570 offset count)
571 ((? integer? cr)
572 (let* ((tail (maybe-utf8->string
573 (bytevector-range bv offset (- cr -1 offset))))
574 (line (string-concatenate-reverse
575 (cons tail %fragments))))
576 (process-line line)
577 (set! %fragments '())
578 (- cr -1 offset)))
579 (#f
580 (unless (zero? count)
581 (let ((str (maybe-utf8->string
582 (bytevector-range bv offset count))))
583 (set! %fragments (cons str %fragments))))
584 count))))
585
586 (define port
587 (make-custom-binary-output-port "filtering-input-port"
588 write!
589 #f #f
590 #f))
591
592 ;; The build port actually receives Unicode strings.
593 (set-port-encoding! port "UTF-8")
594 (cond-expand
595 ((and guile-2 (not guile-2.2)) #t)
596 (else (setvbuf port 'line)))
597 (values port (lambda () %state)))
598
599 (define (call-with-status-report on-event thunk)
600 (parameterize ((current-terminal-columns (terminal-columns))
601 (current-build-output-port
602 (build-event-output-port (build-status-updater on-event))))
603 (thunk)))
604
605 (define-syntax-rule (with-status-report on-event exp ...)
606 "Set up build status reporting to the user using the ON-EVENT procedure;
607 evaluate EXP... in that context."
608 (call-with-status-report on-event (lambda () exp ...)))