status: Tweak colorization.
[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 #:use-module (rnrs bytevectors)
38 #:use-module ((system foreign)
39 #:select (bytevector->pointer pointer->bytevector))
40 #:export (build-event-output-port
41 compute-status
42
43 build-status
44 build-status?
45 build-status-building
46 build-status-downloading
47 build-status-builds-completed
48 build-status-downloads-completed
49
50 download?
51 download
52 download-item
53 download-uri
54 download-size
55 download-start
56 download-end
57 download-transferred
58
59 build-status-updater
60 print-build-event
61 print-build-event/quiet
62 print-build-status
63
64 with-status-report))
65
66 ;;; Commentary:
67 ;;;
68 ;;; This module provides facilities to track the status of ongoing builds and
69 ;;; downloads in a given session, as well as tools to report about the current
70 ;;; status to user interfaces. It does so by analyzing the output of
71 ;;; 'current-build-output-port'. The build status is maintained in a
72 ;;; <build-status> record.
73 ;;;
74 ;;; Code:
75
76 \f
77 ;;;
78 ;;; Build status tracking.
79 ;;;
80
81 ;; Builds and substitutions performed by the daemon.
82 (define-record-type* <build-status> build-status make-build-status
83 build-status?
84 (building build-status-building ;list of drv
85 (default '()))
86 (downloading build-status-downloading ;list of <download>
87 (default '()))
88 (builds-completed build-status-builds-completed ;list of drv
89 (default '()))
90 (downloads-completed build-status-downloads-completed ;list of store items
91 (default '())))
92
93 ;; On-going or completed downloads. Downloads can be stem from substitutes
94 ;; and from "builtin:download" fixed-output derivations.
95 (define-record-type <download>
96 (%download item uri size start end transferred)
97 download?
98 (item download-item) ;store item
99 (uri download-uri) ;string | #f
100 (size download-size) ;integer | #f
101 (start download-start) ;<time>
102 (end download-end) ;#f | <time>
103 (transferred download-transferred)) ;integer
104
105 (define* (download item uri
106 #:key size
107 (start (current-time time-monotonic)) end
108 (transferred 0))
109 "Return a new download."
110 (%download item uri size start end transferred))
111
112 (define (matching-download item)
113 "Return a predicate that matches downloads of ITEM."
114 (lambda (download)
115 (string=? item (download-item download))))
116
117 (define* (compute-status event status
118 #:key (current-time current-time))
119 "Given EVENT, a tuple like (build-started \"/gnu/store/...-foo.drv\" ...),
120 compute a new status based on STATUS."
121 (match event
122 (('build-started drv _ ...)
123 (build-status
124 (inherit status)
125 (building (cons drv (build-status-building status)))))
126 (((or 'build-succeeded 'build-failed) drv _ ...)
127 (build-status
128 (inherit status)
129 (building (delete drv (build-status-building status)))
130 (builds-completed (cons drv (build-status-builds-completed status)))))
131
132 ;; Note: Ignore 'substituter-started' and 'substituter-succeeded' because
133 ;; they're not as informative as 'download-started' and
134 ;; 'download-succeeded'.
135
136 (('download-started item uri (= string->number size))
137 ;; This is presumably a fixed-output derivation so move it from
138 ;; 'building' to 'downloading'. XXX: This doesn't work in 'check' mode
139 ;; because ITEM is different from DRV's output.
140 (build-status
141 (inherit status)
142 (building (remove (lambda (drv)
143 (equal? (false-if-exception
144 (derivation->output-path
145 (read-derivation-from-file drv)))
146 item))
147 (build-status-building status)))
148 (downloading (cons (download item uri #:size size
149 #:start (current-time time-monotonic))
150 (build-status-downloading status)))))
151 (('download-succeeded item uri (= string->number size))
152 (let ((current (find (matching-download item)
153 (build-status-downloading status))))
154 (build-status
155 (inherit status)
156 (downloading (delq current (build-status-downloading status)))
157 (downloads-completed
158 (cons (download item uri
159 #:size size
160 #:start (download-start current)
161 #:transferred size
162 #:end (current-time time-monotonic))
163 (build-status-downloads-completed status))))))
164 (('substituter-succeeded item _ ...)
165 (match (find (matching-download item)
166 (build-status-downloading status))
167 (#f
168 ;; Presumably we already got a 'download-succeeded' event for ITEM,
169 ;; everything is fine.
170 status)
171 (current
172 ;; Maybe the build process didn't emit a 'download-succeeded' event
173 ;; for ITEM, so remove CURRENT from the queue now.
174 (build-status
175 (inherit status)
176 (downloading (delq current (build-status-downloading status)))
177 (downloads-completed
178 (cons (download item (download-uri current)
179 #:size (download-size current)
180 #:start (download-start current)
181 #:transferred (download-size current)
182 #:end (current-time time-monotonic))
183 (build-status-downloads-completed status)))))))
184 (('download-progress item uri
185 (= string->number size)
186 (= string->number transferred))
187 (let ((downloads (remove (matching-download item)
188 (build-status-downloading status)))
189 (current (find (matching-download item)
190 (build-status-downloading status))))
191 (build-status
192 (inherit status)
193 (downloading (cons (download item uri
194 #:size size
195 #:start
196 (or (and current
197 (download-start current))
198 (current-time time-monotonic))
199 #:transferred transferred)
200 downloads)))))
201 (_
202 status)))
203
204 (define (simultaneous-jobs status)
205 "Return the number of on-going builds and downloads for STATUS."
206 (+ (length (build-status-building status))
207 (length (build-status-downloading status))))
208
209 \f
210 ;;;
211 ;;; Rendering.
212 ;;;
213
214 (define (extended-build-trace-supported?)
215 "Return true if the currently used store is known to support \"extended
216 build traces\" such as \"@ download-progress\" traces."
217 ;; Support for extended build traces was added in protocol version #x162.
218 (and (current-store-protocol-version)
219 (>= (current-store-protocol-version) #x162)))
220
221 (define spin!
222 (let ((steps (circular-list "\\" "|" "/" "-")))
223 (lambda (port)
224 "Display a spinner on PORT."
225 (match steps
226 ((first . rest)
227 (set! steps rest)
228 (display "\r\x1b[K" port)
229 (display first port)
230 (force-output port))))))
231
232 (define (color-output? port)
233 "Return true if we should write colored output to PORT."
234 (and (not (getenv "INSIDE_EMACS"))
235 (not (getenv "NO_COLOR"))
236 (isatty? port)))
237
238 (define-syntax color-rules
239 (syntax-rules ()
240 "Return a procedure that colorizes the string it is passed according to
241 the given rules. Each rule has the form:
242
243 (REGEXP COLOR1 COLOR2 ...)
244
245 where COLOR1 specifies how to colorize the first submatch of REGEXP, and so
246 on."
247 ((_ (regexp colors ...) rest ...)
248 (let ((next (color-rules rest ...))
249 (rx (make-regexp regexp)))
250 (lambda (str)
251 (if (string-index str #\nul)
252 str
253 (match (regexp-exec rx str)
254 (#f (next str))
255 (m (let loop ((n 1)
256 (c '(colors ...))
257 (result '()))
258 (match c
259 (()
260 (string-concatenate-reverse result))
261 ((first . tail)
262 (loop (+ n 1) tail
263 (cons (colorize-string (match:substring m n)
264 first)
265 result)))))))))))
266 ((_)
267 (lambda (str)
268 str))))
269
270 (define colorize-log-line
271 ;; Take a string and return a possibly colorized string according to the
272 ;; rules below.
273 (color-rules
274 ("^(phase)(.*)(succeeded after)(.*)(seconds)(.*)"
275 GREEN BOLD GREEN RESET GREEN BLUE)
276 ("^(phase)(.*)(failed after)(.*)(seconds)(.*)"
277 RED BLUE RED BLUE RED BLUE)
278 ("^(.*)(error|fail|failed|\\<FAIL|FAILED)([[:blank:]]*)(:)(.*)"
279 RESET RED BOLD BOLD BOLD)
280 ("^(.*)(warning)([[:blank:]]*)(:)(.*)"
281 RESET MAGENTA BOLD BOLD BOLD)))
282
283 (define* (print-build-event event old-status status
284 #:optional (port (current-error-port))
285 #:key
286 (colorize? (color-output? port))
287 (print-log? #t))
288 "Print information about EVENT and STATUS to PORT. When COLORIZE? is true,
289 produce colorful output. When PRINT-LOG? is true, display the build log in
290 addition to build events."
291 (define info
292 (if colorize?
293 (cut colorize-string <> 'BOLD)
294 identity))
295
296 (define success
297 (if colorize?
298 (cut colorize-string <> 'GREEN 'BOLD)
299 identity))
300
301 (define failure
302 (if colorize?
303 (cut colorize-string <> 'RED 'BOLD)
304 identity))
305
306 (define print-log-line
307 (if print-log?
308 (if colorize?
309 (lambda (line)
310 (display (colorize-log-line line) port))
311 (cut display <> port))
312 (lambda (line)
313 (spin! port))))
314
315 (display "\r" port) ;erase the spinner
316 (match event
317 (('build-started drv . _)
318 (format port (info (G_ "building ~a...")) drv)
319 (newline port))
320 (('build-succeeded drv . _)
321 (format port (success (G_ "successfully built ~a")) drv)
322 (newline port)
323 (match (build-status-building status)
324 (() #t)
325 (ongoing ;when max-jobs > 1
326 (format port
327 (N_ "The following build is still in progress:~%~{ ~a~%~}~%"
328 "The following builds are still in progress:~%~{ ~a~%~}~%"
329 (length ongoing))
330 ongoing))))
331 (('build-failed drv . _)
332 (format port (failure (G_ "build of ~a failed")) drv)
333 (newline port)
334 (match (derivation-log-file drv)
335 (#f
336 (format port (failure (G_ "Could not find build log for '~a'."))
337 drv))
338 (log
339 (format port (info (G_ "View build log at '~a'.")) log)))
340 (newline port))
341 (('substituter-started item _ ...)
342 (when (or print-log? (not (extended-build-trace-supported?)))
343 (format port (info (G_ "substituting ~a...")) item)
344 (newline port)))
345 (('download-started item uri _ ...)
346 (format port (info (G_ "downloading from ~a...")) uri)
347 (newline port))
348 (('download-progress item uri
349 (= string->number size)
350 (= string->number transferred))
351 ;; Print a progress bar, but only if there's only one on-going
352 ;; job--otherwise the output would be intermingled.
353 (when (= 1 (simultaneous-jobs status))
354 (match (find (matching-download item)
355 (build-status-downloading status))
356 (#f #f) ;shouldn't happen!
357 (download
358 ;; XXX: It would be nice to memoize the abbreviation.
359 (let ((uri (if (string-contains uri "/nar/")
360 (nar-uri-abbreviation uri)
361 (basename uri))))
362 (display-download-progress uri size
363 #:start-time
364 (download-start download)
365 #:transferred transferred))))))
366 (('substituter-succeeded item _ ...)
367 ;; If there are no jobs running, we already reported download completion
368 ;; so there's nothing left to do.
369 (unless (and (zero? (simultaneous-jobs status))
370 (extended-build-trace-supported?))
371 (format port (success (G_ "substitution of ~a complete")) item)
372 (newline port)))
373 (('substituter-failed item _ ...)
374 (format port (failure (G_ "substitution of ~a failed")) item)
375 (newline port))
376 (('hash-mismatch item algo expected actual _ ...)
377 ;; TRANSLATORS: The final string looks like "sha256 hash mismatch for
378 ;; /gnu/store/…-sth:", where "sha256" is the hash algorithm.
379 (format port (failure (G_ "~a hash mismatch for ~a:")) algo item)
380 (newline port)
381 (format port (info (G_ "\
382 expected hash: ~a
383 actual hash: ~a~%"))
384 expected actual))
385 (('build-log line)
386 ;; The daemon prefixes early messages coming with 'guix substitute' with
387 ;; "substitute:". These are useful ("updating substitutes from URL"), so
388 ;; let them through.
389 (if (string-prefix? "substitute: " line)
390 (begin
391 (format port line)
392 (force-output port))
393 (print-log-line line)))
394 (_
395 event)))
396
397 (define* (print-build-event/quiet event old-status status
398 #:optional
399 (port (current-error-port))
400 #:key
401 (colorize? (color-output? port)))
402 (print-build-event event old-status status port
403 #:colorize? colorize?
404 #:print-log? #f))
405
406 (define* (build-status-updater #:optional (on-change (const #t)))
407 "Return a procedure that can be passed to 'build-event-output-port'. That
408 procedure computes the new build status upon each event and calls ON-CHANGE:
409
410 (ON-CHANGE event status new-status)
411
412 ON-CHANGE can display the build status, build events, etc."
413 (lambda (event status)
414 (let ((new (compute-status event status)))
415 (on-change event status new)
416 new)))
417
418 \f
419 ;;;
420 ;;; Build port.
421 ;;;
422
423 (define %newline
424 (char-set #\return #\newline))
425
426 (define* (build-event-output-port proc #:optional (seed (build-status)))
427 "Return an output port for use as 'current-build-output-port' that calls
428 PROC with its current state value, initialized with SEED, on every build
429 event. Build events passed to PROC are tuples corresponding to the \"build
430 traces\" produced by the daemon:
431
432 (build-started \"/gnu/store/...-foo.drv\" ...)
433 (substituter-started \"/gnu/store/...-foo\" ...)
434
435 and so on.
436
437 The second return value is a thunk to retrieve the current state."
438 (define %fragments
439 ;; Line fragments received so far.
440 '())
441
442 (define %state
443 ;; Current state for PROC.
444 seed)
445
446 (define (process-line line)
447 (if (string-prefix? "@ " line)
448 (match (string-tokenize (string-drop line 2))
449 (((= string->symbol event-name) args ...)
450 (set! %state
451 (proc (cons event-name args)
452 %state))))
453 (set! %state (proc (list 'build-log line)
454 %state))))
455
456 (define (bytevector-range bv offset count)
457 (let ((ptr (bytevector->pointer bv offset)))
458 (pointer->bytevector ptr count)))
459
460 (define (write! bv offset count)
461 (let loop ((str (utf8->string (bytevector-range bv offset count))))
462 (match (string-index str %newline)
463 ((? integer? cr)
464 (let ((tail (string-take str (+ 1 cr))))
465 (process-line (string-concatenate-reverse
466 (cons tail %fragments)))
467 (set! %fragments '())
468 (loop (string-drop str (+ 1 cr)))))
469 (#f
470 (unless (string-null? str)
471 (set! %fragments (cons str %fragments)))
472 count))))
473
474 (define port
475 (make-custom-binary-output-port "filtering-input-port"
476 write!
477 #f #f
478 #f))
479
480 ;; The build port actually receives Unicode strings.
481 (set-port-encoding! port "UTF-8")
482 (setvbuf port (cond-expand (guile-2.2 'line) (else _IOLBF)))
483
484 (values port (lambda () %state)))
485
486 (define (call-with-status-report on-event thunk)
487 (parameterize ((current-terminal-columns (terminal-columns))
488 (current-build-output-port
489 (build-event-output-port (build-status-updater on-event))))
490 (thunk)))
491
492 (define-syntax-rule (with-status-report on-event exp ...)
493 "Set up build status reporting to the user using the ON-EVENT procedure;
494 evaluate EXP... in that context."
495 (call-with-status-report on-event (lambda () exp ...)))