[PATCH 0/3] Move some (guix scripts substitute) code to two new modules

DoneSubmitted by Christopher Baines.
Details
2 participants
  • Ludovic Courtès
  • Christopher Baines
Owner
unassigned
Severity
normal
C
C
Christopher Baines wrote on 24 Dec 2020 18:17
(address . guix-patches@gnu.org)
87y2hn9l8j.fsf@cbaines.net
These commits are still a work in progress, but I think the changes lookpretty positive.


Christopher Baines (3): guix: Move narinfo code from substitute script to module. guix: Untangle (guix narinfo) from (guix scripts substitute). guix: Split (guix substitute) from (guix scripts substitute).
Makefile.am | 2 + guix/narinfo.scm | 325 +++++++++++++++ guix/scripts/challenge.scm | 3 +- guix/scripts/substitute.scm | 778 +----------------------------------- guix/scripts/weather.scm | 3 +- guix/substitute.scm | 527 ++++++++++++++++++++++++ 6 files changed, 875 insertions(+), 763 deletions(-) create mode 100644 guix/narinfo.scm create mode 100644 guix/substitute.scm
-----BEGIN PGP SIGNATURE-----
iQKlBAEBCgCPFiEEPonu50WOcg2XVOCyXiijOwuE9XcFAl/kzTxfFIAAAAAALgAoaXNzdWVyLWZwckBub3RhdGlvbnMub3BlbnBncC5maWZ0aGhvcnNlbWFuLm5ldDNFODlFRUU3NDU4RTcyMEQ5NzU0RTBCMjVFMjhBMzNCMEI4NEY1NzcRHG1haWxAY2JhaW5lcy5uZXQACgkQXiijOwuE9XcIhQ//Yx9AKeXICHeFkqSh5peBN5Zcv9DtL4MjRN3uxZAm9JDDz2JKyqoXDaqWx6Qp/YNCmdEYCitrTfm5waSsQYcvzCn1s0S44zzc3lY2OhBPcp4o3V9Rtm6aIyP30CbjaQ16bf8wDizgTAdmJ467dwRd0eCu+nhOcvlb+0bzUuCkwX15X2wNtoyGb3+XVuJC/0A9ITlCkVoThIDYkdOxbQdVIASc0J5ZzJpd/fbqqtcB/tEoAy9dAm2LVSSIcOBIqrUOw49KsmwYWSv7pq8xhcjidOAyn7p3uRifLDocE34q2a6NRcF5bmrv4yj/ZbQvHnu/6pwi7v2j/61AAD51vZWgBuUjuFg0BhBoC4gfIa1wk4xHWryCBkZPmoA+c+sidY2xlOWwVqF4Ush5+b8BpQlH1rTDQDqgHdBXE0BMSIJdatLFf0wqaEyscOWmAHoEzAu/B+mJAlf/rIQAnA7rcATesWBTbla0+UTBRRm3w+sCDaHcU49O0yGR1cJRbNqF/9urNbr6mEjBFqsRQGBZCoxZkJnCm9eWBGltpk465Aztm5nCCIlFUY2ax2syeoVcq0C6D1J5owxKAanuiBP1xDxqxn/a7LoelAJdUp2OHH/uYXDUVPxmDd11Gs+LeUJZFMLwydd1O8qBunbFx/Rc04shCrIzJ8+pBcnXUUjRt4n4w5M==rgD0-----END PGP SIGNATURE-----
C
C
Christopher Baines wrote on 24 Dec 2020 18:22
[PATCH 2/3] guix: Untangle (guix narinfo) from (guix scripts substitute).
(address . 45409@debbugs.gnu.org)
20201224172221.21057-2-mail@cbaines.net
Moving the code left the %allow-unauthenticated-substitutes? parameter workingacross both modules, which isn't very clear. Instead just use%allow-unauthenticated-substitutes? in the substitute module.
* guix/scripts/substitute.scm (process-query, process-substitution): Changethe authorized? argument to lookup-narinfo and lookup-narinfos/diverse basedon %allow-unauthenticated-substitutes?.* guix/narinfo.scm (valid-narinfo?): Remove use of%allow-unauthenticated-substitutes?.--- guix/narinfo.scm | 63 ++++++++++++++++++------------------- guix/scripts/substitute.scm | 16 +++++++--- 2 files changed, 42 insertions(+), 37 deletions(-)
Toggle diff (133 lines)diff --git a/guix/narinfo.scm b/guix/narinfo.scmindex 3ecb2f039e..8aa9e53ebd 100644--- a/guix/narinfo.scm+++ b/guix/narinfo.scm@@ -2,6 +2,7 @@ ;;; Copyright © 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org> ;;; Copyright © 2014 Nikita Karetnikov <nikita@karetnikov.org> ;;; Copyright © 2018 Kyle Meyer <kyle@kyleam.com>+;;; Copyright © 2020 Christopher Baines <mail@cbaines.net> ;;; ;;; This file is part of GNU Guix. ;;;@@ -26,7 +27,6 @@ #:use-module (guix base64) #:use-module (guix records) #:use-module (guix diagnostics)- #:use-module (guix scripts substitute) #:use-module (gcrypt hash) #:use-module (gcrypt pk-crypto) #:use-module (rnrs bytevectors)@@ -209,38 +209,37 @@ No authentication and authorization checks are performed here!" (define* (valid-narinfo? narinfo #:optional (acl (current-acl)) #:key verbose?) "Return #t if NARINFO's signature is not valid."- (or (%allow-unauthenticated-substitutes?)- (let ((hash (narinfo-sha256 narinfo))- (signature (narinfo-signature narinfo))- (uri (uri->string (first (narinfo-uris narinfo)))))- (and hash signature- (signature-case (signature hash acl)- (valid-signature #t)- (invalid-signature- (when verbose?- (format (current-error-port)- "invalid signature for substitute at '~a'~%"- uri))- #f)- (hash-mismatch- (when verbose?- (format (current-error-port)- "hash mismatch for substitute at '~a'~%"- uri))- #f)- (unauthorized-key- (when verbose?- (format (current-error-port)- "substitute at '~a' is signed by an \+ (let ((hash (narinfo-sha256 narinfo))+ (signature (narinfo-signature narinfo))+ (uri (uri->string (first (narinfo-uris narinfo)))))+ (and hash signature+ (signature-case (signature hash acl)+ (valid-signature #t)+ (invalid-signature+ (when verbose?+ (format (current-error-port)+ "invalid signature for substitute at '~a'~%"+ uri))+ #f)+ (hash-mismatch+ (when verbose?+ (format (current-error-port)+ "hash mismatch for substitute at '~a'~%"+ uri))+ #f)+ (unauthorized-key+ (when verbose?+ (format (current-error-port)+ "substitute at '~a' is signed by an \ unauthorized party~%"- uri))- #f)- (corrupt-signature- (when verbose?- (format (current-error-port)- "corrupt signature for substitute at '~a'~%"- uri))- #f))))))+ uri))+ #f)+ (corrupt-signature+ (when verbose?+ (format (current-error-port)+ "corrupt signature for substitute at '~a'~%"+ uri))+ #f))))) (define (write-narinfo narinfo port) "Write NARINFO to PORT."diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex 72242b73f1..e2d30f1760 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -2,6 +2,7 @@ ;;; Copyright © 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org> ;;; Copyright © 2014 Nikita Karetnikov <nikita@karetnikov.org> ;;; Copyright © 2018 Kyle Meyer <kyle@kyleam.com>+;;; Copyright © 2020 Christopher Baines <mail@cbaines.net> ;;; ;;; This file is part of GNU Guix. ;;;@@ -692,11 +693,14 @@ expected by the daemon." "Reply to COMMAND, a query as written by the daemon to this process's standard input. Use ACL as the access-control list against which to check authorized substitutes."- (define (valid? obj)- (valid-narinfo? obj acl))+ (define valid?+ (if (%allow-unauthenticated-substitutes?)+ (begin+ (warn-about-missing-authentication) - (when (%allow-unauthenticated-substitutes?)- (warn-about-missing-authentication))+ (const #t))+ (lambda (obj)+ (valid-narinfo? obj acl)))) (match (string-tokenize command) (("have" paths ..1)@@ -797,7 +801,9 @@ DESTINATION is in the store, deduplicate its files. Print a status line on the current output port." (define narinfo (lookup-narinfo cache-urls store-item- (cut valid-narinfo? <> acl)))+ (if (%allow-unauthenticated-substitutes?)+ (const #t)+ (cut valid-narinfo? <> acl)))) (define destination-in-store? (string-prefix? (string-append (%store-prefix) "/")-- 2.29.2
C
C
Christopher Baines wrote on 24 Dec 2020 18:22
[PATCH 1/3] guix: Move narinfo code from substitute script to module.
(address . 45409@debbugs.gnu.org)
20201224172221.21057-1-mail@cbaines.net
This separation between the code for dealing with narinfos from the code doingthat for a purpose should make things clearer, and better support componentsother that the substitute script in using this code.
This is just moving the code around, no code should have been significantlychanged.
* guix/scripts/substitute.scm (<narinfo>): Move record type to (guix narinfo).(fields->alist, narinfo-hash-algorithm+value, narinfo-hash->sha256,narinfo-signature->canonical-sexp, narinfo-maker, read-narinfo,narinfo-sha256, valid-narinfo?, write-narinfo, narinfo->string,string->narinfo, equivalent-narinfo?, supported-compression?,compresses-better?, narinfo-best-uri): Move procedures to (guix narinfo).(%compression-methods): Move variable to (guix narinfo).* guix/narinfo.scm: New file.* Makefile.am (MODULES): Add it.--- Makefile.am | 1 + guix/narinfo.scm | 326 ++++++++++++++++++++++++++++++++++++ guix/scripts/challenge.scm | 1 + guix/scripts/substitute.scm | 282 +------------------------------ guix/scripts/weather.scm | 1 + 5 files changed, 331 insertions(+), 280 deletions(-) create mode 100644 guix/narinfo.scm
Toggle diff (699 lines)diff --git a/Makefile.am b/Makefile.amindex e0ee65fcce..8ca837a3ee 100644--- a/Makefile.am+++ b/Makefile.am@@ -103,6 +103,7 @@ MODULES = \ guix/profiles.scm \ guix/serialization.scm \ guix/nar.scm \+ guix/narinfo.scm \ guix/derivations.scm \ guix/grafts.scm \ guix/repl.scm \diff --git a/guix/narinfo.scm b/guix/narinfo.scmnew file mode 100644index 0000000000..3ecb2f039e--- /dev/null+++ b/guix/narinfo.scm@@ -0,0 +1,326 @@+;;; GNU Guix --- Functional package management for GNU+;;; Copyright © 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>+;;; Copyright © 2014 Nikita Karetnikov <nikita@karetnikov.org>+;;; Copyright © 2018 Kyle Meyer <kyle@kyleam.com>+;;;+;;; This file is part of GNU Guix.+;;;+;;; GNU Guix is free software; you can redistribute it and/or modify it+;;; under the terms of the GNU General Public License as published by+;;; the Free Software Foundation; either version 3 of the License, or (at+;;; your option) any later version.+;;;+;;; GNU Guix is distributed in the hope that it will be useful, but+;;; WITHOUT ANY WARRANTY; without even the implied warranty of+;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+;;; GNU General Public License for more details.+;;;+;;; You should have received a copy of the GNU General Public License+;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.++(define-module (guix narinfo)+ #:use-module (guix ui)+ #:use-module (guix pki)+ #:use-module (guix i18n)+ #:use-module (guix base32)+ #:use-module (guix base64)+ #:use-module (guix records)+ #:use-module (guix diagnostics)+ #:use-module (guix scripts substitute)+ #:use-module (gcrypt hash)+ #:use-module (gcrypt pk-crypto)+ #:use-module (rnrs bytevectors)+ #:use-module (srfi srfi-1)+ #:use-module (srfi srfi-9)+ #:use-module (srfi srfi-26)+ #:use-module (ice-9 match)+ #:use-module (ice-9 binary-ports)+ #:use-module (web uri)+ #:export (narinfo-signature->canonical-sexp++ narinfo?+ narinfo-path+ narinfo-uris+ narinfo-uri-base+ narinfo-compressions+ narinfo-file-hashes+ narinfo-file-sizes+ narinfo-hash+ narinfo-size+ narinfo-references+ narinfo-deriver+ narinfo-system+ narinfo-signature++ narinfo-hash-algorithm+value++ narinfo-hash->sha256+ narinfo-best-uri++ valid-narinfo?++ read-narinfo+ write-narinfo++ string->narinfo+ narinfo->string++ equivalent-narinfo?))++(define-record-type <narinfo>+ (%make-narinfo path uri-base uris compressions file-sizes file-hashes+ nar-hash nar-size references deriver system+ signature contents)+ narinfo?+ (path narinfo-path)+ (uri-base narinfo-uri-base) ;URI of the cache it originates from+ (uris narinfo-uris) ;list of strings+ (compressions narinfo-compressions) ;list of strings+ (file-sizes narinfo-file-sizes) ;list of (integers | #f)+ (file-hashes narinfo-file-hashes)+ (nar-hash narinfo-hash)+ (nar-size narinfo-size)+ (references narinfo-references)+ (deriver narinfo-deriver)+ (system narinfo-system)+ (signature narinfo-signature) ; canonical sexp+ ;; The original contents of a narinfo file. This field is needed because we+ ;; want to preserve the exact textual representation for verification purposes.+ ;; See <https://lists.gnu.org/archive/html/guix-devel/2014-02/msg00340.html>+ ;; for more information.+ (contents narinfo-contents))++(define (narinfo-hash-algorithm+value narinfo)+ "Return two values: the hash algorithm used by NARINFO and its value as a+bytevector."+ (match (string-tokenize (narinfo-hash narinfo)+ (char-set-complement (char-set #\:)))+ ((algorithm base32)+ (values (lookup-hash-algorithm (string->symbol algorithm))+ (nix-base32-string->bytevector base32)))+ (_+ (raise (formatted-message+ (G_ "invalid narinfo hash: ~s") (narinfo-hash narinfo))))))++(define (narinfo-hash->sha256 hash)+ "If the string HASH denotes a sha256 hash, return it as a bytevector.+Otherwise return #f."+ (and (string-prefix? "sha256:" hash)+ (nix-base32-string->bytevector (string-drop hash 7))))++(define (narinfo-signature->canonical-sexp str)+ "Return the value of a narinfo's 'Signature' field as a canonical sexp."+ (match (string-split str #\;)+ ((version host-name sig)+ (let ((maybe-number (string->number version)))+ (cond ((not (number? maybe-number))+ (leave (G_ "signature version must be a number: ~s~%")+ version))+ ;; Currently, there are no other versions.+ ((not (= 1 maybe-number))+ (leave (G_ "unsupported signature version: ~a~%")+ maybe-number))+ (else+ (let ((signature (utf8->string (base64-decode sig))))+ (catch 'gcry-error+ (lambda ()+ (string->canonical-sexp signature))+ (lambda (key proc err)+ (leave (G_ "signature is not a valid \+s-expression: ~s~%")+ signature))))))))+ (x+ (leave (G_ "invalid format of the signature field: ~a~%") x))))++(define (narinfo-maker str cache-url)+ "Return a narinfo constructor for narinfos originating from CACHE-URL. STR+must contain the original contents of a narinfo file."+ (lambda (path urls compressions file-hashes file-sizes+ nar-hash nar-size references deriver system+ signature)+ "Return a new <narinfo> object."+ (define len (length urls))+ (%make-narinfo path cache-url+ ;; Handle the case where URL is a relative URL.+ (map (lambda (url)+ (or (string->uri url)+ (string->uri+ (string-append cache-url "/" url))))+ urls)+ compressions+ (match file-sizes+ (() (make-list len #f))+ ((lst ...) (map string->number lst)))+ (match file-hashes+ (() (make-list len #f))+ ((lst ...) (map string->number lst)))+ nar-hash+ (and=> nar-size string->number)+ (string-tokenize references)+ (match deriver+ ((or #f "") #f)+ (_ deriver))+ system+ (false-if-exception+ (and=> signature narinfo-signature->canonical-sexp))+ str)))++(define fields->alist+ ;; The narinfo format is really just like recutils.+ recutils->alist)++(define* (read-narinfo port #:optional url+ #:key size)+ "Read a narinfo from PORT. If URL is true, it must be a string used to+build full URIs from relative URIs found while reading PORT. When SIZE is+true, read at most SIZE bytes from PORT; otherwise, read as much as possible.++No authentication and authorization checks are performed here!"+ (let ((str (utf8->string (if size+ (get-bytevector-n port size)+ (get-bytevector-all port)))))+ (alist->record (call-with-input-string str fields->alist)+ (narinfo-maker str url)+ '("StorePath" "URL" "Compression"+ "FileHash" "FileSize" "NarHash" "NarSize"+ "References" "Deriver" "System"+ "Signature")+ '("URL" "Compression" "FileSize" "FileHash"))))++(define (narinfo-sha256 narinfo)+ "Return the sha256 hash of NARINFO as a bytevector, or #f if NARINFO lacks a+'Signature' field."+ (define %mandatory-fields+ ;; List of fields that must be signed. If they are not signed, the+ ;; narinfo is considered unsigned.+ '("StorePath" "NarHash" "References"))++ (let ((contents (narinfo-contents narinfo)))+ (match (string-contains contents "Signature:")+ (#f #f)+ (index+ (let* ((above-signature (string-take contents index))+ (signed-fields (match (call-with-input-string above-signature+ fields->alist)+ (((fields . values) ...) fields))))+ (and (every (cut member <> signed-fields) %mandatory-fields)+ (sha256 (string->utf8 above-signature))))))))++(define* (valid-narinfo? narinfo #:optional (acl (current-acl))+ #:key verbose?)+ "Return #t if NARINFO's signature is not valid."+ (or (%allow-unauthenticated-substitutes?)+ (let ((hash (narinfo-sha256 narinfo))+ (signature (narinfo-signature narinfo))+ (uri (uri->string (first (narinfo-uris narinfo)))))+ (and hash signature+ (signature-case (signature hash acl)+ (valid-signature #t)+ (invalid-signature+ (when verbose?+ (format (current-error-port)+ "invalid signature for substitute at '~a'~%"+ uri))+ #f)+ (hash-mismatch+ (when verbose?+ (format (current-error-port)+ "hash mismatch for substitute at '~a'~%"+ uri))+ #f)+ (unauthorized-key+ (when verbose?+ (format (current-error-port)+ "substitute at '~a' is signed by an \+unauthorized party~%"+ uri))+ #f)+ (corrupt-signature+ (when verbose?+ (format (current-error-port)+ "corrupt signature for substitute at '~a'~%"+ uri))+ #f))))))++(define (write-narinfo narinfo port)+ "Write NARINFO to PORT."+ (put-bytevector port (string->utf8 (narinfo-contents narinfo))))++(define (narinfo->string narinfo)+ "Return the external representation of NARINFO."+ (call-with-output-string (cut write-narinfo narinfo <>)))++(define (string->narinfo str cache-uri)+ "Return the narinfo represented by STR. Assume CACHE-URI as the base URI of+the cache STR originates form."+ (call-with-input-string str (cut read-narinfo <> cache-uri)))++(define (equivalent-narinfo? narinfo1 narinfo2)+ "Return true if NARINFO1 and NARINFO2 are equivalent--i.e., if they describe+the same store item. This ignores unnecessary metadata such as the Nar URL."+ (and (string=? (narinfo-hash narinfo1)+ (narinfo-hash narinfo2))++ ;; The following is not needed if all we want is to download a valid+ ;; nar, but it's necessary if we want valid narinfo.+ (string=? (narinfo-path narinfo1)+ (narinfo-path narinfo2))+ (equal? (narinfo-references narinfo1)+ (narinfo-references narinfo2))++ (= (narinfo-size narinfo1)+ (narinfo-size narinfo2))))++(define %compression-methods+ ;; Known compression methods and a thunk to determine whether they're+ ;; supported. See 'decompressed-port' in (guix utils).+ `(("gzip" . ,(const #t))+ ("lzip" . ,(const #t))+ ("xz" . ,(const #t))+ ("bzip2" . ,(const #t))+ ("none" . ,(const #t))))++(define (supported-compression? compression)+ "Return true if COMPRESSION, a string, denotes a supported compression+method."+ (match (assoc-ref %compression-methods compression)+ (#f #f)+ (supported? (supported?))))++(define (compresses-better? compression1 compression2)+ "Return true if COMPRESSION1 generally compresses better than COMPRESSION2;+this is a rough approximation."+ (match compression1+ ("none" #f)+ ("gzip" (string=? compression2 "none"))+ (_ (or (string=? compression2 "none")+ (string=? compression2 "gzip")))))++(define (narinfo-best-uri narinfo)+ "Select the \"best\" URI to download NARINFO's nar, and return three values:+the URI, its compression method (a string), and the compressed file size."+ (define choices+ (filter (match-lambda+ ((uri compression file-size)+ (supported-compression? compression)))+ (zip (narinfo-uris narinfo)+ (narinfo-compressions narinfo)+ (narinfo-file-sizes narinfo))))++ (define (file-size<? c1 c2)+ (match c1+ ((uri1 compression1 (? integer? file-size1))+ (match c2+ ((uri2 compression2 (? integer? file-size2))+ (< file-size1 file-size2))+ (_ #t)))+ ((uri compression1 #f)+ (match c2+ ((uri2 compression2 _)+ (compresses-better? compression1 compression2))))+ (_ #f))) ;we can't tell++ (match (sort choices file-size<?)+ (((uri compression file-size) _ ...)+ (values uri compression file-size))))+diff --git a/guix/scripts/challenge.scm b/guix/scripts/challenge.scmindex d0a456ac1d..cc9cbe6f27 100644--- a/guix/scripts/challenge.scm+++ b/guix/scripts/challenge.scm@@ -28,6 +28,7 @@ #:use-module ((guix progress) #:hide (dump-port*)) #:use-module (guix serialization) #:use-module (guix scripts substitute)+ #:use-module (guix narinfo) #:use-module (rnrs bytevectors) #:autoload (guix http-client) (http-fetch) #:use-module ((guix build syscalls) #:select (terminal-columns))diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex 8084c89ae5..72242b73f1 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -21,6 +21,7 @@ (define-module (guix scripts substitute) #:use-module (guix ui) #:use-module (guix scripts)+ #:use-module (guix narinfo) #:use-module (guix store) #:use-module (guix utils) #:use-module (guix combinators)@@ -66,29 +67,8 @@ #:use-module (web request) #:use-module (web response) #:use-module (guix http-client)- #:export (narinfo-signature->canonical-sexp-- narinfo?- narinfo-path- narinfo-uris- narinfo-uri-base- narinfo-compressions- narinfo-file-hashes- narinfo-file-sizes- narinfo-hash- narinfo-size- narinfo-references- narinfo-deriver- narinfo-system- narinfo-signature-- narinfo-hash->sha256- narinfo-best-uri-- lookup-narinfos+ #:export (lookup-narinfos lookup-narinfos/diverse- read-narinfo- write-narinfo %allow-unauthenticated-substitutes? %error-to-file-descriptor-4?@@ -148,10 +128,6 @@ disabled!~%")) ;; How often we want to remove files corresponding to expired cache entries. (* 7 24 3600)) -(define fields->alist- ;; The narinfo format is really just like recutils.- recutils->alist)- (define %fetch-timeout ;; Number of seconds after which networking is considered "slow". 5)@@ -235,191 +211,6 @@ connection (typically PORT) is kept open once data has been fetched from URI." (leave (G_ "unsupported substitute URI scheme: ~a~%") (uri->string uri))))) - -(define-record-type <narinfo>- (%make-narinfo path uri-base uris compressions file-sizes file-hashes- nar-hash nar-size references deriver system- signature contents)- narinfo?- (path narinfo-path)- (uri-base narinfo-uri-base) ;URI of the cache it originates from- (uris narinfo-uris) ;list of strings- (compressions narinfo-compressions) ;list of strings- (file-sizes narinfo-file-sizes) ;list of (integers | #f)- (file-hashes narinfo-file-hashes)- (nar-hash narinfo-hash)- (nar-size narinfo-size)- (references narinfo-references)- (deriver narinfo-deriver)- (system narinfo-system)- (signature narinfo-signature) ; canonical sexp- ;; The original contents of a narinfo file. This field is needed because we- ;; want to preserve the exact textual representation for verification purposes.- ;; See <https://lists.gnu.org/archive/html/guix-devel/2014-02/msg00340.html>- ;; for more information.- (contents narinfo-contents))--(define (narinfo-hash-algorithm+value narinfo)- "Return two values: the hash algorithm used by NARINFO and its value as a-bytevector."- (match (string-tokenize (narinfo-hash narinfo)- (char-set-complement (char-set #\:)))- ((algorithm base32)- (values (lookup-hash-algorithm (string->symbol algorithm))- (nix-base32-string->bytevector base32)))- (_- (raise (formatted-message- (G_ "invalid narinfo hash: ~s") (narinfo-hash narinfo))))))--(define (narinfo-hash->sha256 hash)- "If the string HASH denotes a sha256 hash, return it as a bytevector.-Otherwise return #f."- (and (string-prefix? "sha256:" hash)- (nix-base32-string->bytevector (string-drop hash 7))))--(define (narinfo-signature->canonical-sexp str)- "Return the value of a narinfo's 'Signature' field as a canonical sexp."- (match (string-split str #\;)- ((version host-name sig)- (let ((maybe-number (string->number version)))- (cond ((not (number? maybe-number))- (leave (G_ "signature version must be a number: ~s~%")- version))- ;; Currently, there are no other versions.- ((not (= 1 maybe-number))- (leave (G_ "unsupported signature version: ~a~%")- maybe-number))- (else- (let ((signature (utf8->string (base64-decode sig))))- (catch 'gcry-error- (lambda ()- (string->canonical-sexp signature))- (lambda (key proc err)- (leave (G_ "signature is not a valid \-s-expression: ~s~%")- signature))))))))- (x- (leave (G_ "invalid format of the signature field: ~a~%") x))))--(define (narinfo-maker str cache-url)- "Return a narinfo constructor for narinfos originating from CACHE-URL. STR-must contain the original contents of a narinfo file."- (lambda (path urls compressions file-hashes file-sizes- nar-hash nar-size references deriver system- signature)- "Return a new <narinfo> object."- (define len (length urls))- (%make-narinfo path cache-url- ;; Handle the case where URL is a relative URL.- (map (lambda (url)- (or (string->uri url)- (string->uri- (string-append cache-url "/" url))))- urls)- compressions- (match file-sizes- (() (make-list len #f))- ((lst ...) (map string->number lst)))- (match file-hashes- (() (make-list len #f))- ((lst ...) (map string->number lst)))- nar-hash- (and=> nar-size string->number)- (string-tokenize references)- (match deriver- ((or #f "") #f)- (_ deriver))- system- (false-if-exception- (and=> signature narinfo-signature->canonical-sexp))- str)))--(define* (read-narinfo port #:optional url- #:key size)- "Read a narinfo from PORT. If URL is true, it must be a string used to-build full URIs from relative URIs found while reading PORT. When SIZE is-true, read at most SIZE bytes from PORT; otherwise, read as much as possible.--No authentication and authorization checks are performed here!"- (let ((str (utf8->string (if size- (get-bytevector-n port size)- (get-bytevector-all port)))))- (alist->record (call-with-input-string str fields->alist)- (narinfo-maker str url)- '("StorePath" "URL" "Compression"- "FileHash" "FileSize" "NarHash" "NarSize"- "References" "Deriver" "System"- "Signature")- '("URL" "Compression" "FileSize" "FileHash"))))--(define (narinfo-sha256 narinfo)- "Return the sha256 hash of NARINFO as a bytevector, or #f if NARINFO lacks a-'Signature' field."- (define %mandatory-fields- ;; List of fields that must be signed. If they are not signed, the- ;; narinfo is considered unsigned.- '("StorePath" "NarHash" "References"))-- (let ((contents (narinfo-contents narinfo)))- (match (string-contains contents "Signature:")- (#f #f)- (index- (let* ((above-signature (string-take contents index))- (signed-fields (match (call-with-input-string above-signature- fields->alist)- (((fields . values) ...) fields))))- (and (every (cut member <> signed-fields) %mandatory-fields)- (sha256 (string->utf8 above-signature))))))))--(define* (valid-narinfo? narinfo #:optional (acl (current-acl))- #:key verbose?)- "Return #t if NARINFO's signature is not valid."- (or (%allow-unauthenticated-substitutes?)- (let ((hash (narinfo-sha256 narinfo))- (signature (narinfo-signature narinfo))- (uri (uri->string (first (narinfo-uris narinfo)))))- (and hash signature- (signature-case (signature hash acl)- (valid-signature #t)- (invalid-signature- (when verbose?- (format (current-error-port)- "invalid signature for substitute at '~a'~%"- uri))- #f)- (hash-mismatch- (when verbose?- (format (current-error-port)- "hash mismatch for substitute at '~a'~%"- uri))- #f)- (unauthorized-key- (when verbose?- (format (current-error-port)- "substitute at '~a' is signed by an \-unauthorized party~%"- uri))- #f)- (corrupt-signature- (when verbose?- (format (current-error-port)- "corrupt signature for substitute at '~a'~%"- uri))- #f))))))--(define (write-narinfo narinfo port)- "Write NARINFO to PORT."- (put-bytevector port (string->utf8 (narinfo-contents narinfo))))--(define (narinfo->string narinfo)- "Return the external representation of NARINFO."- (call-with-output-string (cut write-narinfo narinfo <>)))--(define (string->narinfo str cache-uri)- "Return the narinfo represented by STR. Assume CACHE-URI as the base URI of-the cache STR originates form."- (call-with-input-string str (cut read-narinfo <> cache-uri)))- (define (narinfo-cache-file cache-url path) "Return the name of the local file that contains an entry for PATH. The entry is stored in a sub-directory specific to CACHE-URL."@@ -741,22 +532,6 @@ information is available locally." (let ((missing (fetch-narinfos cache missing))) (append cached (or missing '())))))) -(define (equivalent-narinfo? narinfo1 narinfo2)- "Return true if NARINFO1 and NARINFO2 are equivalent--i.e., if they describe-the same store item. This ignores unnecessary metadata such as the Nar URL."- (and (string=? (narinfo-hash narinfo1)- (narinfo-hash narinfo2))-- ;; The following is not needed if all we want is to download a valid- ;; nar, but it's necessary if we want valid narinfo.- (string=? (narinfo-path narinfo1)- (narinfo-path narinfo2))- (equal? (narinfo-references narinfo1)- (narinfo-references narinfo2))-- (= (narinfo-size narinfo1)- (narinfo-size narinfo2))))- (define (lookup-narinfos/diverse caches paths authorized?) "Look up narinfos for PATHS on all of CACHES, a list of URLS, in that order. That is, when a cache lacks an AUTHORIZED? narinfo, look it up in the next@@ -939,59 +714,6 @@ authorized substitutes." (wtf (error "unknown `--query' command" wtf)))) -(define %compression-methods- ;; Known compression methods and a thunk to determine whether they're- ;; supported. See 'decompressed-port' in (guix utils).- `(("gzip" . ,(const #t))- ("lzip" . ,(const #t))- ("xz" . ,(const #t))- ("bzip2" . ,(const #t))- ("none" . ,(const #t))))--(define (supported-compression? compression)- "Return true if COMPRESSION, a string, denotes a supported compression-method."- (match (assoc-ref %compression-methods compression)- (#f #f)- (supported? (supported?))))--(define (compresses-better? compression1 compression2)- "Return true if COMPRESSION1 generally compresses better than COMPRESSION2;-this is a rough approximation."- (match compression1- ("none" #f)- ("gzip" (string=? compression2 "none"))- (_ (or (string=? compression2 "none")- (string=? compression2 "gzip")))))--(define (narinfo-best-uri narinfo)- "Select the \"best\" URI to download NARINFO's nar, and return three values:-the URI, its compression method (a string), and the compressed file size."- (define choices- (filter (match-lambda- ((uri compression file-size)- (supported-compression? compression)))- (zip (narinfo-uris narinfo)- (narinfo-compressions narinfo)- (narinfo-file-sizes narinfo))))-- (define (file-size<? c1 c2)- (match c1- ((uri1 compression1 (? integer? file-size1))- (match c2- ((uri2 compression2 (? integer? file-size2))- (< file-size1 file-size2))- (_ #t)))- ((uri compression1 #f)- (match c2- ((uri2 compression2 _)- (compresses-better? compression1 compression2))))- (_ #f))) ;we can't tell-- (match (sort choices file-size<?)- (((uri compression file-size) _ ...)- (values uri compression file-size))))- (define %max-cached-connections ;; Maximum number of connections kept in cache by ;; 'open-connection-for-uri/cached'.diff --git a/guix/scripts/weather.scm b/guix/scripts/weather.scmindex f28070ddc4..97e4a73802 100644--- a/guix/scripts/weather.scm+++ b/guix/scripts/weather.scm@@ -33,6 +33,7 @@ #:use-module ((guix build syscalls) #:select (terminal-columns)) #:use-module ((guix build utils) #:select (every*)) #:use-module (guix scripts substitute)+ #:use-module (guix narinfo) #:use-module (guix http-client) #:use-module (guix ci) #:use-module (guix sets)-- 2.29.2
C
C
Christopher Baines wrote on 24 Dec 2020 18:22
[PATCH 3/3] guix: Split (guix substitute) from (guix scripts substitute).
(address . 45409@debbugs.gnu.org)
20201224172221.21057-3-mail@cbaines.net
This means there's a module for working with substitutes, rather than all thecode sitting in the script. The need for this can be seen with the weather andchallenge scripts, that now don't have to use code from the substitute script,but can instead use the substitute module.
The separation here between the actual functionality of the substitute scriptand the underlying functionality used both there and elsewhere should makemaintenance easier moving forward.
This commit just moves code, none of the code should have been changedsignificantly.--- Makefile.am | 1 + guix/scripts/challenge.scm | 2 +- guix/scripts/substitute.scm | 482 +-------------------------------- guix/scripts/weather.scm | 2 +- guix/substitute.scm | 527 ++++++++++++++++++++++++++++++++++++ 5 files changed, 535 insertions(+), 479 deletions(-) create mode 100644 guix/substitute.scm
Toggle diff (1123 lines)diff --git a/Makefile.am b/Makefile.amindex 8ca837a3ee..5c3b565853 100644--- a/Makefile.am+++ b/Makefile.am@@ -89,6 +89,7 @@ MODULES = \ guix/memoization.scm \ guix/utils.scm \ guix/sets.scm \+ guix/substitute.scm \ guix/modules.scm \ guix/download.scm \ guix/discovery.scm \diff --git a/guix/scripts/challenge.scm b/guix/scripts/challenge.scmindex cc9cbe6f27..ea54b1a0a2 100644--- a/guix/scripts/challenge.scm+++ b/guix/scripts/challenge.scm@@ -27,8 +27,8 @@ #:use-module (guix packages) #:use-module ((guix progress) #:hide (dump-port*)) #:use-module (guix serialization)- #:use-module (guix scripts substitute) #:use-module (guix narinfo)+ #:use-module (guix substitute) #:use-module (rnrs bytevectors) #:autoload (guix http-client) (http-fetch) #:use-module ((guix build syscalls) #:select (terminal-columns))diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex e2d30f1760..d57b83154a 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -23,38 +23,30 @@ #:use-module (guix ui) #:use-module (guix scripts) #:use-module (guix narinfo)+ #:use-module (guix substitute) #:use-module (guix store) #:use-module (guix utils)- #:use-module (guix combinators)- #:use-module (guix config)- #:use-module (guix records)- #:use-module (guix diagnostics) #:use-module (guix i18n) #:use-module ((guix serialization) #:select (restore-file dump-file)) #:autoload (guix store deduplication) (dump-file/deduplicate) #:autoload (guix scripts discover) (read-substitute-urls) #:use-module (gcrypt hash) #:use-module (guix base32)- #:use-module (guix base64) #:use-module (guix cache) #:use-module (gcrypt pk-crypto) #:use-module (guix pki)- #:use-module ((guix build utils) #:select (mkdir-p dump-port))+ #:use-module ((guix build utils) #:select (mkdir-p)) #:use-module ((guix build download)- #:select (uri-abbreviation nar-uri-abbreviation+ #:select (nar-uri-abbreviation (open-connection-for-uri- . guix:open-connection-for-uri)- store-path-abbreviation byte-count->string))+ . guix:open-connection-for-uri))) #:use-module (guix progress) #:use-module ((guix build syscalls) #:select (set-thread-name)) #:use-module (ice-9 rdelim)- #:use-module (ice-9 regex) #:use-module (ice-9 match) #:use-module (ice-9 format) #:use-module (ice-9 ftw)- #:use-module (ice-9 binary-ports)- #:use-module (ice-9 vlist) #:use-module (rnrs bytevectors) #:use-module (srfi srfi-1) #:use-module (srfi srfi-9)@@ -68,10 +60,7 @@ #:use-module (web request) #:use-module (web response) #:use-module (guix http-client)- #:export (lookup-narinfos- lookup-narinfos/diverse-- %allow-unauthenticated-substitutes?+ #:export (%allow-unauthenticated-substitutes? %error-to-file-descriptor-4? substitute-urls@@ -88,17 +77,6 @@ ;;; ;;; Code: -(define %narinfo-cache-directory- ;; A local cache of narinfos, to avoid going to the network. Most of the- ;; time, 'guix substitute' is called by guix-daemon as root and stores its- ;; cached data in /var/guix/…. However, when invoked from 'guix challenge'- ;; as a user, it stores its cache in ~/.cache.- (if (zero? (getuid))- (or (and=> (getenv "XDG_CACHE_HOME")- (cut string-append <> "/guix/substitute"))- (string-append %state-directory "/substitute/cache"))- (string-append (cache-directory #:ensure? #f) "/substitute")))- (define (warn-about-missing-authentication) (warning (G_ "authentication and authorization of substitutes \ disabled!~%"))@@ -111,20 +89,6 @@ disabled!~%")) (and=> (getenv "GUIX_ALLOW_UNAUTHENTICATED_SUBSTITUTES") (cut string-ci=? <> "yes")))) -(define %narinfo-ttl- ;; Number of seconds during which cached narinfo lookups are considered- ;; valid for substitute servers that do not advertise a TTL via the- ;; 'Cache-Control' response header.- (* 36 3600))--(define %narinfo-negative-ttl- ;; Likewise, but for negative lookups---i.e., cached lookup failures (404).- (* 1 3600))--(define %narinfo-transient-error-ttl- ;; Likewise, but for transient errors such as 504 ("Gateway timeout").- (* 10 60))- (define %narinfo-expired-cache-entry-removal-delay ;; How often we want to remove files corresponding to expired cache entries. (* 7 24 3600))@@ -212,369 +176,6 @@ connection (typically PORT) is kept open once data has been fetched from URI." (leave (G_ "unsupported substitute URI scheme: ~a~%") (uri->string uri))))) -(define (narinfo-cache-file cache-url path)- "Return the name of the local file that contains an entry for PATH. The-entry is stored in a sub-directory specific to CACHE-URL."- ;; The daemon does not sanitize its input, so PATH could be something like- ;; "/gnu/store/foo". Gracefully handle that.- (match (store-path-hash-part path)- (#f- (leave (G_ "'~a' does not name a store item~%") path))- ((? string? hash-part)- (string-append %narinfo-cache-directory "/"- (bytevector->base32-string (sha256 (string->utf8 cache-url)))- "/" hash-part))))--(define (cached-narinfo cache-url path)- "Check locally if we have valid info about PATH coming from CACHE-URL.-Return two values: a Boolean indicating whether we have valid cached info, and-that info, which may be either #f (when PATH is unavailable) or the narinfo-for PATH."- (define now- (current-time time-monotonic))-- (define cache-file- (narinfo-cache-file cache-url path))-- (catch 'system-error- (lambda ()- (call-with-input-file cache-file- (lambda (p)- (match (read p)- (('narinfo ('version 2)- ('cache-uri cache-uri)- ('date date) ('ttl ttl) ('value #f))- ;; A cached negative lookup.- (if (obsolete? date now ttl)- (values #f #f)- (values #t #f)))- (('narinfo ('version 2)- ('cache-uri cache-uri)- ('date date) ('ttl ttl) ('value value))- ;; A cached positive lookup- (if (obsolete? date now ttl)- (values #f #f)- (values #t (string->narinfo value cache-uri))))- (('narinfo ('version v) _ ...)- (values #f #f))))))- (lambda _- (values #f #f))))--(define (cache-narinfo! cache-url path narinfo ttl)- "Cache locally NARNIFO for PATH, which originates from CACHE-URL, with the-given TTL (a number of seconds or #f). NARINFO may be #f, in which case it-indicates that PATH is unavailable at CACHE-URL."- (define now- (current-time time-monotonic))-- (define (cache-entry cache-uri narinfo)- `(narinfo (version 2)- (cache-uri ,cache-uri)- (date ,(time-second now))- (ttl ,(or ttl- (if narinfo %narinfo-ttl %narinfo-negative-ttl)))- (value ,(and=> narinfo narinfo->string))))-- (let ((file (narinfo-cache-file cache-url path)))- (mkdir-p (dirname file))- (with-atomic-file-output file- (lambda (out)- (write (cache-entry cache-url narinfo) out))))-- narinfo)--(define (narinfo-request cache-url path)- "Return an HTTP request for the narinfo of PATH at CACHE-URL."- (let ((url (string-append cache-url "/" (store-path-hash-part path)- ".narinfo"))- (headers '((User-Agent . "GNU Guile"))))- (build-request (string->uri url) #:method 'GET #:headers headers)))--(define (at-most max-length lst)- "If LST is shorter than MAX-LENGTH, return it and the empty list; otherwise-return its MAX-LENGTH first elements and its tail."- (let loop ((len 0)- (lst lst)- (result '()))- (match lst- (()- (values (reverse result) '()))- ((head . tail)- (if (>= len max-length)- (values (reverse result) lst)- (loop (+ 1 len) tail (cons head result)))))))--(define* (http-multiple-get base-uri proc seed requests- #:key port (verify-certificate? #t)- (open-connection guix:open-connection-for-uri)- (keep-alive? #t)- (batch-size 1000))- "Send all of REQUESTS to the server at BASE-URI. Call PROC for each-response, passing it the request object, the response, a port from which to-read the response body, and the previous result, starting with SEED, à la-'fold'. Return the final result.--When PORT is specified, use it as the initial connection on which HTTP-requests are sent; otherwise call OPEN-CONNECTION to open a new connection for-a URI. When KEEP-ALIVE? is false, close the connection port before-returning."- (let connect ((port port)- (requests requests)- (result seed))- (define batch- (at-most batch-size requests))-- ;; (format (current-error-port) "connecting (~a requests left)..."- ;; (length requests))- (let ((p (or port (open-connection base-uri- #:verify-certificate?- verify-certificate?))))- ;; For HTTPS, P is not a file port and does not support 'setvbuf'.- (when (file-port? p)- (setvbuf p 'block (expt 2 16)))-- ;; Send BATCH in a row.- ;; XXX: Do our own caching to work around inefficiencies when- ;; communicating over TLS: <http://bugs.gnu.org/22966>.- (let-values (((buffer get) (open-bytevector-output-port)))- ;; Inherit the HTTP proxying property from P.- (set-http-proxy-port?! buffer (http-proxy-port? p))-- (for-each (cut write-request <> buffer)- batch)- (put-bytevector p (get))- (force-output p))-- ;; Now start processing responses.- (let loop ((sent batch)- (processed 0)- (result result))- (match sent- (()- (match (drop requests processed)- (()- (unless keep-alive?- (close-port p))- (reverse result))- (remainder- (connect p remainder result))))- ((head tail ...)- (let* ((resp (read-response p))- (body (response-body-port resp))- (result (proc head resp body result)))- ;; The server can choose to stop responding at any time, in which- ;; case we have to try again. Check whether that is the case.- ;; Note that even upon "Connection: close", we can read from BODY.- (match (assq 'connection (response-headers resp))- (('connection 'close)- (close-port p)- (connect #f ;try again- (drop requests (+ 1 processed))- result))- (_- (loop tail (+ 1 processed) result)))))))))) ;keep going--(define (read-to-eof port)- "Read from PORT until EOF is reached. The data are discarded."- (dump-port port (%make-void-port "w")))--(define (narinfo-from-file file url)- "Attempt to read a narinfo from FILE, using URL as the cache URL. Return #f-if file doesn't exist, and the narinfo otherwise."- (catch 'system-error- (lambda ()- (call-with-input-file file- (cut read-narinfo <> url)))- (lambda args- (if (= ENOENT (system-error-errno args))- #f- (apply throw args)))))--(define %unreachable-hosts- ;; Set of names of unreachable hosts.- (make-hash-table))--(define* (open-connection-for-uri/maybe uri- #:key- fresh?- (time %fetch-timeout))- "Open a connection to URI via 'open-connection-for-uri/cached' and return a-port to it, or, if connection failed, print a warning and return #f. Pass-#:fresh? to 'open-connection-for-uri/cached'."- (define host- (uri-host uri))-- (catch #t- (lambda ()- (open-connection-for-uri/cached uri #:timeout time- #:fresh? fresh?))- (match-lambda*- (('getaddrinfo-error error)- (unless (hash-ref %unreachable-hosts host)- (hash-set! %unreachable-hosts host #t) ;warn only once- (warning (G_ "~a: host not found: ~a~%")- host (gai-strerror error)))- #f)- (('system-error . args)- (unless (hash-ref %unreachable-hosts host)- (hash-set! %unreachable-hosts host #t)- (warning (G_ "~a: connection failed: ~a~%") host- (strerror- (system-error-errno `(system-error ,@args)))))- #f)- (args- (apply throw args)))))--(define (fetch-narinfos url paths)- "Retrieve all the narinfos for PATHS from the cache at URL and return them."- (define update-progress!- (let ((done 0)- (total (length paths)))- (lambda ()- (display "\r\x1b[K" (current-error-port)) ;erase current line- (force-output (current-error-port))- (format (current-error-port)- (G_ "updating substitutes from '~a'... ~5,1f%")- url (* 100. (/ done total)))- (set! done (+ 1 done)))))-- (define hash-part->path- (let ((mapping (fold (lambda (path result)- (vhash-cons (store-path-hash-part path) path- result))- vlist-null- paths)))- (lambda (hash)- (match (vhash-assoc hash mapping)- (#f #f)- ((_ . path) path)))))-- (define (handle-narinfo-response request response port result)- (let* ((code (response-code response))- (len (response-content-length response))- (cache (response-cache-control response))- (ttl (and cache (assoc-ref cache 'max-age))))- (update-progress!)-- ;; Make sure to read no more than LEN bytes since subsequent bytes may- ;; belong to the next response.- (if (= code 200) ; hit- (let ((narinfo (read-narinfo port url #:size len)))- (if (string=? (dirname (narinfo-path narinfo))- (%store-prefix))- (begin- (cache-narinfo! url (narinfo-path narinfo) narinfo ttl)- (cons narinfo result))- result))- (let* ((path (uri-path (request-uri request)))- (hash-part (basename- (string-drop-right path 8)))) ;drop ".narinfo"- (if len- (get-bytevector-n port len)- (read-to-eof port))- (cache-narinfo! url (hash-part->path hash-part) #f- (if (or (= 404 code) (= 202 code))- ttl- %narinfo-transient-error-ttl))- result))))-- (define (do-fetch uri)- (case (and=> uri uri-scheme)- ((http https)- ;; Note: Do not check HTTPS server certificates to avoid depending- ;; on the X.509 PKI. We can do it because we authenticate- ;; narinfos, which provides a much stronger guarantee.- (let* ((requests (map (cut narinfo-request url <>) paths))- (result (call-with-cached-connection uri- (lambda (port)- (if port- (begin- (update-progress!)- (http-multiple-get uri- handle-narinfo-response '()- requests- #:open-connection- open-connection-for-uri/cached- #:verify-certificate? #f- #:port port))- '()))- open-connection-for-uri/maybe)))- (newline (current-error-port))- result))- ((file #f)- (let* ((base (string-append (uri-path uri) "/"))- (files (map (compose (cut string-append base <> ".narinfo")- store-path-hash-part)- paths)))- (filter-map (cut narinfo-from-file <> url) files)))- (else- (leave (G_ "~s: unsupported server URI scheme~%")- (if uri (uri-scheme uri) url)))))-- (do-fetch (string->uri url)))--(define (lookup-narinfos cache paths)- "Return the narinfos for PATHS, invoking the server at CACHE when no-information is available locally."- (let-values (((cached missing)- (fold2 (lambda (path cached missing)- (let-values (((valid? value)- (cached-narinfo cache path)))- (if valid?- (if value- (values (cons value cached) missing)- (values cached missing))- (values cached (cons path missing)))))- '()- '()- paths)))- (if (null? missing)- cached- (let ((missing (fetch-narinfos cache missing)))- (append cached (or missing '()))))))--(define (lookup-narinfos/diverse caches paths authorized?)- "Look up narinfos for PATHS on all of CACHES, a list of URLS, in that order.-That is, when a cache lacks an AUTHORIZED? narinfo, look it up in the next-cache, and so on.--Return a list of narinfos for PATHS or a subset thereof. The returned-narinfos are either AUTHORIZED?, or they claim a hash that matches an-AUTHORIZED? narinfo."- (define (select-hit result)- (lambda (path)- (match (vhash-fold* cons '() path result)- ((one)- one)- ((several ..1)- (let ((authorized (find authorized? (reverse several))))- (and authorized- (find (cut equivalent-narinfo? <> authorized)- several)))))))-- (let loop ((caches caches)- (paths paths)- (result vlist-null) ;path->narinfo vhash- (hits '())) ;paths- (match paths- (() ;we're done- ;; Now iterate on all the HITS, and return exactly one match for each- ;; hit: the first narinfo that is authorized, or that has the same hash- ;; as an authorized narinfo, in the order of CACHES.- (filter-map (select-hit result) hits))- (_- (match caches- ((cache rest ...)- (let* ((narinfos (lookup-narinfos cache paths))- (definite (map narinfo-path (filter authorized? narinfos)))- (missing (lset-difference string=? paths definite))) ;XXX: perf- (loop rest missing- (fold vhash-cons result- (map narinfo-path narinfos) narinfos)- (append definite hits))))- (() ;that's it- (filter-map (select-hit result) hits)))))))- (define (lookup-narinfo caches path authorized?) "Return the narinfo for PATH in CACHES, or #f when no substitute for PATH was found."@@ -718,79 +319,6 @@ authorized substitutes." (wtf (error "unknown `--query' command" wtf)))) -(define %max-cached-connections- ;; Maximum number of connections kept in cache by- ;; 'open-connection-for-uri/cached'.- 16)--(define open-connection-for-uri/cached- (let ((cache '()))- (lambda* (uri #:key fresh? timeout verify-certificate?)- "Return a connection for URI, possibly reusing a cached connection.-When FRESH? is true, delete any cached connections for URI and open a new one.-Return #f if URI's scheme is 'file' or #f.--When true, TIMEOUT is the maximum number of milliseconds to wait for-connection establishment. When VERIFY-CERTIFICATE? is true, verify HTTPS-server certificates."- (define host (uri-host uri))- (define scheme (uri-scheme uri))- (define key (list host scheme (uri-port uri)))-- (and (not (memq scheme '(file #f)))- (match (assoc-ref cache key)- (#f- ;; Open a new connection to URI and evict old entries from- ;; CACHE, if any.- (let-values (((socket)- (guix:open-connection-for-uri- uri- #:verify-certificate? verify-certificate?- #:timeout timeout))- ((new-cache evicted)- (at-most (- %max-cached-connections 1) cache)))- (for-each (match-lambda- ((_ . port)- (false-if-exception (close-port port))))- evicted)- (set! cache (alist-cons key socket new-cache))- socket))- (socket- (if (or fresh? (port-closed? socket))- (begin- (false-if-exception (close-port socket))- (set! cache (alist-delete key cache))- (open-connection-for-uri/cached uri #:timeout timeout- #:verify-certificate?- verify-certificate?))- (begin- ;; Drain input left from the previous use.- (drain-input socket)- socket))))))))--(define* (call-with-cached-connection uri proc- #:optional- (open-connection- open-connection-for-uri/cached))- (let ((port (open-connection uri)))- (catch #t- (lambda ()- (proc port))- (lambda (key . args)- ;; If PORT was cached and the server closed the connection in the- ;; meantime, we get EPIPE. In that case, open a fresh connection and- ;; retry. We might also get 'bad-response or a similar exception from- ;; (web response) later on, once we've sent the request.- (if (or (and (eq? key 'system-error)- (= EPIPE (system-error-errno `(,key ,@args))))- (memq key '(bad-response bad-header bad-header-component)))- (proc (open-connection uri #:fresh? #t))- (apply throw key args))))))--(define-syntax-rule (with-cached-connection uri port exp ...)- "Bind PORT with EXP... to a socket connected to URI."- (call-with-cached-connection uri (lambda (port) exp ...)))- (define* (process-substitution store-item destination #:key cache-urls acl deduplicate? print-build-trace?)diff --git a/guix/scripts/weather.scm b/guix/scripts/weather.scmindex 97e4a73802..8bb557862d 100644--- a/guix/scripts/weather.scm+++ b/guix/scripts/weather.scm@@ -32,8 +32,8 @@ #:use-module (guix gexp) #:use-module ((guix build syscalls) #:select (terminal-columns)) #:use-module ((guix build utils) #:select (every*))- #:use-module (guix scripts substitute) #:use-module (guix narinfo)+ #:use-module (guix substitute) #:use-module (guix http-client) #:use-module (guix ci) #:use-module (guix sets)diff --git a/guix/substitute.scm b/guix/substitute.scmnew file mode 100644index 0000000000..c37b2c398f--- /dev/null+++ b/guix/substitute.scm@@ -0,0 +1,527 @@+;;; GNU Guix --- Functional package management for GNU+;;; Copyright © 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>+;;; Copyright © 2014 Nikita Karetnikov <nikita@karetnikov.org>+;;; Copyright © 2018 Kyle Meyer <kyle@kyleam.com>+;;;+;;; This file is part of GNU Guix.+;;;+;;; GNU Guix is free software; you can redistribute it and/or modify it+;;; under the terms of the GNU General Public License as published by+;;; the Free Software Foundation; either version 3 of the License, or (at+;;; your option) any later version.+;;;+;;; GNU Guix is distributed in the hope that it will be useful, but+;;; WITHOUT ANY WARRANTY; without even the implied warranty of+;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+;;; GNU General Public License for more details.+;;;+;;; You should have received a copy of the GNU General Public License+;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.++(define-module (guix substitute)+ #:use-module (guix ui)+ #:use-module (guix i18n)+ #:use-module (guix cache)+ #:use-module (guix store)+ #:use-module (guix utils)+ #:use-module (guix base32)+ #:use-module (guix config)+ #:use-module (guix narinfo)+ #:use-module (guix combinators)+ #:use-module ((guix build utils) #:select (mkdir-p dump-port))+ #:use-module ((guix build download)+ #:select ((open-connection-for-uri+ . guix:open-connection-for-uri)))+ #:use-module (gcrypt hash)+ #:use-module (ice-9 match)+ #:use-module (ice-9 vlist)+ #:use-module (ice-9 format)+ #:use-module (ice-9 binary-ports)+ #:use-module (rnrs bytevectors)+ #:use-module (srfi srfi-1)+ #:use-module (srfi srfi-11)+ #:use-module (srfi srfi-19)+ #:use-module (srfi srfi-26)+ #:use-module (web uri)+ #:use-module (web http)+ #:use-module (web request)+ #:use-module (web response)+ #:export (%narinfo-cache-directory++ with-cached-connection++ lookup-narinfos+ lookup-narinfos/diverse))++(define %narinfo-cache-directory+ ;; A local cache of narinfos, to avoid going to the network. Most of the+ ;; time, 'guix substitute' is called by guix-daemon as root and stores its+ ;; cached data in /var/guix/…. However, when invoked from 'guix challenge'+ ;; as a user, it stores its cache in ~/.cache.+ (if (zero? (getuid))+ (or (and=> (getenv "XDG_CACHE_HOME")+ (cut string-append <> "/guix/substitute"))+ (string-append %state-directory "/substitute/cache"))+ (string-append (cache-directory #:ensure? #f) "/substitute")))++(define %narinfo-ttl+ ;; Number of seconds during which cached narinfo lookups are considered+ ;; valid for substitute servers that do not advertise a TTL via the+ ;; 'Cache-Control' response header.+ (* 36 3600))++(define %narinfo-negative-ttl+ ;; Likewise, but for negative lookups---i.e., cached lookup failures (404).+ (* 1 3600))++(define %narinfo-transient-error-ttl+ ;; Likewise, but for transient errors such as 504 ("Gateway timeout").+ (* 10 60))++(define %fetch-timeout+ ;; Number of seconds after which networking is considered "slow".+ 5)++(define (narinfo-cache-file cache-url path)+ "Return the name of the local file that contains an entry for PATH. The+entry is stored in a sub-directory specific to CACHE-URL."+ ;; The daemon does not sanitize its input, so PATH could be something like+ ;; "/gnu/store/foo". Gracefully handle that.+ (match (store-path-hash-part path)+ (#f+ (leave (G_ "'~a' does not name a store item~%") path))+ ((? string? hash-part)+ (string-append %narinfo-cache-directory "/"+ (bytevector->base32-string (sha256 (string->utf8 cache-url)))+ "/" hash-part))))++(define (cache-narinfo! cache-url path narinfo ttl)+ "Cache locally NARNIFO for PATH, which originates from CACHE-URL, with the+given TTL (a number of seconds or #f). NARINFO may be #f, in which case it+indicates that PATH is unavailable at CACHE-URL."+ (define now+ (current-time time-monotonic))++ (define (cache-entry cache-uri narinfo)+ `(narinfo (version 2)+ (cache-uri ,cache-uri)+ (date ,(time-second now))+ (ttl ,(or ttl+ (if narinfo %narinfo-ttl %narinfo-negative-ttl)))+ (value ,(and=> narinfo narinfo->string))))++ (let ((file (narinfo-cache-file cache-url path)))+ (mkdir-p (dirname file))+ (with-atomic-file-output file+ (lambda (out)+ (write (cache-entry cache-url narinfo) out))))++ narinfo)++(define %max-cached-connections+ ;; Maximum number of connections kept in cache by+ ;; 'open-connection-for-uri/cached'.+ 16)++(define open-connection-for-uri/cached+ (let ((cache '()))+ (lambda* (uri #:key fresh? timeout verify-certificate?)+ "Return a connection for URI, possibly reusing a cached connection.+When FRESH? is true, delete any cached connections for URI and open a new one.+Return #f if URI's scheme is 'file' or #f.++When true, TIMEOUT is the maximum number of milliseconds to wait for+connection establishment. When VERIFY-CERTIFICATE? is true, verify HTTPS+server certificates."+ (define host (uri-host uri))+ (define scheme (uri-scheme uri))+ (define key (list host scheme (uri-port uri)))++ (and (not (memq scheme '(file #f)))+ (match (assoc-ref cache key)+ (#f+ ;; Open a new connection to URI and evict old entries from+ ;; CACHE, if any.+ (let-values (((socket)+ (guix:open-connection-for-uri+ uri+ #:verify-certificate? verify-certificate?+ #:timeout timeout))+ ((new-cache evicted)+ (at-most (- %max-cached-connections 1) cache)))+ (for-each (match-lambda+ ((_ . port)+ (false-if-exception (close-port port))))+ evicted)+ (set! cache (alist-cons key socket new-cache))+ socket))+ (socket+ (if (or fresh? (port-closed? socket))+ (begin+ (false-if-exception (close-port socket))+ (set! cache (alist-delete key cache))+ (open-connection-for-uri/cached uri #:timeout timeout+ #:verify-certificate?+ verify-certificate?))+ (begin+ ;; Drain input left from the previous use.+ (drain-input socket)+ socket))))))))++(define* (call-with-cached-connection uri proc+ #:optional+ (open-connection+ open-connection-for-uri/cached))+ (let ((port (open-connection uri)))+ (catch #t+ (lambda ()+ (proc port))+ (lambda (key . args)+ ;; If PORT was cached and the server closed the connection in the+ ;; meantime, we get EPIPE. In that case, open a fresh connection and+ ;; retry. We might also get 'bad-response or a similar exception from+ ;; (web response) later on, once we've sent the request.+ (if (or (and (eq? key 'system-error)+ (= EPIPE (system-error-errno `(,key ,@args))))+ (memq key '(bad-response bad-header bad-header-component)))+ (proc (open-connection uri #:fresh? #t))+ (apply throw key args))))))++(define-syntax-rule (with-cached-connection uri port exp ...)+ "Bind PORT with EXP... to a socket connected to URI."+ (call-with-cached-connection uri (lambda (port) exp ...)))++(define (at-most max-length lst)+ "If LST is shorter than MAX-LENGTH, return it and the empty list; otherwise+return its MAX-LENGTH first elements and its tail."+ (let loop ((len 0)+ (lst lst)+ (result '()))+ (match lst+ (()+ (values (reverse result) '()))+ ((head . tail)+ (if (>= len max-length)+ (values (reverse result) lst)+ (loop (+ 1 len) tail (cons head result)))))))++(define* (http-multiple-get base-uri proc seed requests+ #:key port (verify-certificate? #t)+ (open-connection guix:open-connection-for-uri)+ (keep-alive? #t)+ (batch-size 1000))+ "Send all of REQUESTS to the server at BASE-URI. Call PROC for each+response, passing it the request object, the response, a port from which to+read the response body, and the previous result, starting with SEED, à la+'fold'. Return the final result.++When PORT is specified, use it as the initial connection on which HTTP+requests are sent; otherwise call OPEN-CONNECTION to open a new connection for+a URI. When KEEP-ALIVE? is false, close the connection port before+returning."+ (let connect ((port port)+ (requests requests)+ (result seed))+ (define batch+ (at-most batch-size requests))++ ;; (format (current-error-port) "connecting (~a requests left)..."+ ;; (length requests))+ (let ((p (or port (open-connection base-uri+ #:verify-certificate?+ verify-certificate?))))+ ;; For HTTPS, P is not a file port and does not support 'setvbuf'.+ (when (file-port? p)+ (setvbuf p 'block (expt 2 16)))++ ;; Send BATCH in a row.+ ;; XXX: Do our own caching to work around inefficiencies when+ ;; communicating over TLS: <http://bugs.gnu.org/22966>.+ (let-values (((buffer get) (open-bytevector-output-port)))+ ;; Inherit the HTTP proxying property from P.+ (set-http-proxy-port?! buffer (http-proxy-port? p))++ (for-each (cut write-request <> buffer)+ batch)+ (put-bytevector p (get))+ (force-output p))++ ;; Now start processing responses.+ (let loop ((sent batch)+ (processed 0)+ (result result))+ (match sent+ (()+ (match (drop requests processed)+ (()+ (unless keep-alive?+ (close-port p))+ (reverse result))+ (remainder+ (connect p remainder result))))+ ((head tail ...)+ (let* ((resp (read-response p))+ (body (response-body-port resp))+ (result (proc head resp body result)))+ ;; The server can choose to stop responding at any time, in which+ ;; case we have to try again. Check whether that is the case.+ ;; Note that even upon "Connection: close", we can read from BODY.+ (match (assq 'connection (response-headers resp))+ (('connection 'close)+ (close-port p)+ (connect #f ;try again+ (drop requests (+ 1 processed))+ result))+ (_+ (loop tail (+ 1 processed) result)))))))))) ;keep going++(define %unreachable-hosts+ ;; Set of names of unreachable hosts.+ (make-hash-table))++(define* (open-connection-for-uri/maybe uri+ #:key+ fresh?+ (time %fetch-timeout))+ "Open a connection to URI via 'open-connection-for-uri/cached' and return a+port to it, or, if connection failed, print a warning and return #f. Pass+#:fresh? to 'open-connection-for-uri/cached'."+ (define host+ (uri-host uri))++ (catch #t+ (lambda ()+ (open-connection-for-uri/cached uri #:timeout time+ #:fresh? fresh?))+ (match-lambda*+ (('getaddrinfo-error error)+ (unless (hash-ref %unreachable-hosts host)+ (hash-set! %unreachable-hosts host #t) ;warn only once+ (warning (G_ "~a: host not found: ~a~%")+ host (gai-strerror error)))+ #f)+ (('system-error . args)+ (unless (hash-ref %unreachable-hosts host)+ (hash-set! %unreachable-hosts host #t)+ (warning (G_ "~a: connection failed: ~a~%") host+ (strerror+ (system-error-errno `(system-error ,@args)))))+ #f)+ (args+ (apply throw args)))))++(define (read-to-eof port)+ "Read from PORT until EOF is reached. The data are discarded."+ (dump-port port (%make-void-port "w")))++(define (narinfo-request cache-url path)+ "Return an HTTP request for the narinfo of PATH at CACHE-URL."+ (let ((url (string-append cache-url "/" (store-path-hash-part path)+ ".narinfo"))+ (headers '((User-Agent . "GNU Guile"))))+ (build-request (string->uri url) #:method 'GET #:headers headers)))++(define (narinfo-from-file file url)+ "Attempt to read a narinfo from FILE, using URL as the cache URL. Return #f+if file doesn't exist, and the narinfo otherwise."+ (catch 'system-error+ (lambda ()+ (call-with-input-file file+ (cut read-narinfo <> url)))+ (lambda args+ (if (= ENOENT (system-error-errno args))+ #f+ (apply throw args)))))++(define (fetch-narinfos url paths)+ "Retrieve all the narinfos for PATHS from the cache at URL and return them."+ (define update-progress!+ (let ((done 0)+ (total (length paths)))+ (lambda ()+ (display "\r\x1b[K" (current-error-port)) ;erase current line+ (force-output (current-error-port))+ (format (current-error-port)+ (G_ "updating substitutes from '~a'... ~5,1f%")+ url (* 100. (/ done total)))+ (set! done (+ 1 done)))))++ (define hash-part->path+ (let ((mapping (fold (lambda (path result)+ (vhash-cons (store-path-hash-part path) path+ result))+ vlist-null+ paths)))+ (lambda (hash)+ (match (vhash-assoc hash mapping)+ (#f #f)+ ((_ . path) path)))))++ (define (handle-narinfo-response request response port result)+ (let* ((code (response-code response))+ (len (response-content-length response))+ (cache (response-cache-control response))+ (ttl (and cache (assoc-ref cache 'max-age))))+ (update-progress!)++ ;; Make sure to read no more than LEN bytes since subsequent bytes may+ ;; belong to the next response.+ (if (= code 200) ; hit+ (let ((narinfo (read-narinfo port url #:size len)))+ (if (string=? (dirname (narinfo-path narinfo))+ (%store-prefix))+ (begin+ (cache-narinfo! url (narinfo-path narinfo) narinfo ttl)+ (cons narinfo result))+ result))+ (let* ((path (uri-path (request-uri request)))+ (hash-part (basename+ (string-drop-right path 8)))) ;drop ".narinfo"+ (if len+ (get-bytevector-n port len)+ (read-to-eof port))+ (cache-narinfo! url (hash-part->path hash-part) #f+ (if (or (= 404 code) (= 202 code))+ ttl+ %narinfo-transient-error-ttl))+ result))))++ (define (do-fetch uri)+ (case (and=> uri uri-scheme)+ ((http https)+ ;; Note: Do not check HTTPS server certificates to avoid depending+ ;; on the X.509 PKI. We can do it because we authenticate+ ;; narinfos, which provides a much stronger guarantee.+ (let* ((requests (map (cut narinfo-request url <>) paths))+ (result (call-with-cached-connection uri+ (lambda (port)+ (if port+ (begin+ (update-progress!)+ (http-multiple-get uri+ handle-narinfo-response '()+ requests+ #:open-connection+ open-connection-for-uri/cached+ #:verify-certificate? #f+ #:port port))+ '()))+ open-connection-for-uri/maybe)))+ (newline (current-error-port))+ result))+ ((file #f)+ (let* ((base (string-append (uri-path uri) "/"))+ (files (map (compose (cut string-append base <> ".narinfo")+ store-path-hash-part)+ paths)))+ (filter-map (cut narinfo-from-file <> url) files)))+ (else+ (leave (G_ "~s: unsupported server URI scheme~%")+ (if uri (uri-scheme uri) url)))))++ (do-fetch (string->uri url)))++(define (cached-narinfo cache-url path)+ "Check locally if we have valid info about PATH coming from CACHE-URL.+Return two values: a Boolean indicating whether we have valid cached info, and+that info, which may be either #f (when PATH is unavailable) or the narinfo+for PATH."+ (define now+ (current-time time-monotonic))++ (define cache-file+ (narinfo-cache-file cache-url path))++ (catch 'system-error+ (lambda ()+ (call-with-input-file cache-file+ (lambda (p)+ (match (read p)+ (('narinfo ('version 2)+ ('cache-uri cache-uri)+ ('date date) ('ttl ttl) ('value #f))+ ;; A cached negative lookup.+ (if (obsolete? date now ttl)+ (values #f #f)+ (values #t #f)))+ (('narinfo ('version 2)+ ('cache-uri cache-uri)+ ('date date) ('ttl ttl) ('value value))+ ;; A cached positive lookup+ (if (obsolete? date now ttl)+ (values #f #f)+ (values #t (string->narinfo value cache-uri))))+ (('narinfo ('version v) _ ...)+ (values #f #f))))))+ (lambda _+ (values #f #f))))++(define (lookup-narinfos cache paths)+ "Return the narinfos for PATHS, invoking the server at CACHE when no+information is available locally."+ (let-values (((cached missing)+ (fold2 (lambda (path cached missing)+ (let-values (((valid? value)+ (cached-narinfo cache path)))+ (if valid?+ (if value+ (values (cons value cached) missing)+ (values cached missing))+ (values cached (cons path missing)))))+ '()+ '()+ paths)))+ (if (null? missing)+ cached+ (let ((missing (fetch-narinfos cache missing)))+ (append cached (or missing '()))))))++(define (lookup-narinfos/diverse caches paths authorized?)+ "Look up narinfos for PATHS on all of CACHES, a list of URLS, in that order.+That is, when a cache lacks an AUTHORIZED? narinfo, look it up in the next+cache, and so on.++Return a list of narinfos for PATHS or a subset thereof. The returned+narinfos are either AUTHORIZED?, or they claim a hash that matches an+AUTHORIZED? narinfo."+ (define (select-hit result)+ (lambda (path)+ (match (vhash-fold* cons '() path result)+ ((one)+ one)+ ((several ..1)+ (let ((authorized (find authorized? (reverse several))))+ (and authorized+ (find (cut equivalent-narinfo? <> authorized)+ several)))))))++ (let loop ((caches caches)+ (paths paths)+ (result vlist-null) ;path->narinfo vhash+ (hits '())) ;paths+ (match paths+ (() ;we're done+ ;; Now iterate on all the HITS, and return exactly one match for each+ ;; hit: the first narinfo that is authorized, or that has the same hash+ ;; as an authorized narinfo, in the order of CACHES.+ (filter-map (select-hit result) hits))+ (_+ (match caches+ ((cache rest ...)+ (let* ((narinfos (lookup-narinfos cache paths))+ (definite (map narinfo-path (filter authorized? narinfos)))+ (missing (lset-difference string=? paths definite))) ;XXX: perf+ (loop rest missing+ (fold vhash-cons result+ (map narinfo-path narinfos) narinfos)+ (append definite hits))))+ (() ;that's it+ (filter-map (select-hit result) hits)))))))++;;; Local Variables:+;;; eval: (put 'with-timeout 'scheme-indent-function 1)+;;; eval: (put 'with-cached-connection 'scheme-indent-function 2)+;;; eval: (put 'call-with-cached-connection 'scheme-indent-function 1)+;;; End:++;;; substitute.scm ends here-- 2.29.2
L
L
Ludovic Courtès wrote on 3 Jan 16:03 +0100
Re: [bug#45409] [PATCH 1/3] guix: Move narinfo code from substitute script to module.
(name . Christopher Baines)(address . mail@cbaines.net)(address . 45409@debbugs.gnu.org)
87pn2m12s4.fsf@gnu.org
Hi!
Christopher Baines <mail@cbaines.net> skribis:
Toggle quote (17 lines)> This separation between the code for dealing with narinfos from the code doing> that for a purpose should make things clearer, and better support components> other that the substitute script in using this code.>> This is just moving the code around, no code should have been significantly> changed.>> * guix/scripts/substitute.scm (<narinfo>): Move record type to (guix narinfo).> (fields->alist, narinfo-hash-algorithm+value, narinfo-hash->sha256,> narinfo-signature->canonical-sexp, narinfo-maker, read-narinfo,> narinfo-sha256, valid-narinfo?, write-narinfo, narinfo->string,> string->narinfo, equivalent-narinfo?, supported-compression?,> compresses-better?, narinfo-best-uri): Move procedures to (guix narinfo).> (%compression-methods): Move variable to (guix narinfo).> * guix/narinfo.scm: New file.> * Makefile.am (MODULES): Add it.
That’s a good idea!
Please add guix/narinfo.scm to po/guix/POTFILES.in so it can betranslated.
Toggle quote (3 lines)> +(define-module (guix narinfo)> + #:use-module (guix ui)
We should try and avoid (guix ui); is (guix diagnostics) enough?
Toggle quote (2 lines)> + #:use-module (guix scripts substitute)
(guix …) modules must not depend on (guix scripts …).
Perhaps that’s just for ‘%allow-unauthenticated-substitutes?’, no? Ifso, let’s just not refer to ‘%allow-unauthenticated-substitutes?’ here.It’s a hack to allow for tests, so better keep it local to (guix scriptssubstitute).
Toggle quote (5 lines)> +(define* (valid-narinfo? narinfo #:optional (acl (current-acl))> + #:key verbose?)> + "Return #t if NARINFO's signature is not valid."> + (or (%allow-unauthenticated-substitutes?)
Yeah, let’s remove it from here. At worst, we can always use ‘mock’ intests to make ‘valid-narinfo?’ return #t unconditionally.
OK with these changes.
After the change, please make sure “make check” and “make as-derivation”still pass. For “make as-derivation”, we should also make sure‘guix-core’ doesn’t pull in everything via (guix scripts substitute).
(The zstd patches will conflict with this series but I’ll take care ofit once it’s applied.)
Thanks,Ludo’.
L
L
Ludovic Courtès wrote on 3 Jan 16:08 +0100
Re: [bug#45409] [PATCH 3/3] guix: Split (guix substitute) from (guix scripts substitute).
(name . Christopher Baines)(address . mail@cbaines.net)(address . 45409@debbugs.gnu.org)
87czym12j1.fsf@gnu.org
Hi,
Christopher Baines <mail@cbaines.net> skribis:
Toggle quote (12 lines)> This means there's a module for working with substitutes, rather than all the> code sitting in the script. The need for this can be seen with the weather and> challenge scripts, that now don't have to use code from the substitute script,> but can instead use the substitute module.>> The separation here between the actual functionality of the substitute script> and the underlying functionality used both there and elsewhere should make> maintenance easier moving forward.>> This commit just moves code, none of the code should have been changed> significantly.
It would still be nice to list the identifiers that were moved in thecommit log, it’s boring :-) but it can be helpful when browsing thehistory.
As for the split, I wouldn’t put as much into (guix substitutes) (I’duse “substitutes”, plural, for consistency with most other modules.)
As a rule of thumb, I would keep in (guix scripts substitute) anythingthat’s very much biased towards a single short-lived process: connectioncache, host name resolution failure cache, etc. These things are a bithacky and not designed for use as a library. They’re also very muchpolicy rather than mechanism, and as such they don’t belong in a properlibrary IMO.
Toggle quote (6 lines)> -(define* (http-multiple-get base-uri proc seed requests> - #:key port (verify-certificate? #t)> - (open-connection guix:open-connection-for-uri)> - (keep-alive? #t)> - (batch-size 1000))
How about moving this one to (guix http-client), as a separate patch?I think it’s a better fit and could be useful elsewhere.
Thanks!
Ludo’.
C
C
Christopher Baines wrote on 3 Jan 18:59 +0100
[PATCH v2 1/3] substitute: Untangle skipping authentication from valid-narinfo?.
(address . 45409@debbugs.gnu.org)
20210103175917.15992-1-mail@cbaines.net
Rather than having valid-narinfo? evaluate to #t if%allow-unauthenticated-substitutes? is set to #t, just use (const #t) forvalid-narinfo? when %allow-unauthenticated-substitutes? is set to #t. Thiswill allow moving valid-narinfo? in to a (guix substitutes) module.
* guix/scripts/substitute.scm (process-query, process-substitution): Changethe authorized? argument to lookup-narinfo and lookup-narinfos/diverse basedon %allow-unauthenticated-substitutes?.(valid-narinfo?): Remove use of %allow-unauthenticated-substitutes?.--- guix/scripts/substitute.scm | 77 ++++++++++++++++++++----------------- 1 file changed, 41 insertions(+), 36 deletions(-)
Toggle diff (113 lines)diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex 8084c89ae5..d66f73e75a 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -2,6 +2,7 @@ ;;; Copyright © 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org> ;;; Copyright © 2014 Nikita Karetnikov <nikita@karetnikov.org> ;;; Copyright © 2018 Kyle Meyer <kyle@kyleam.com>+;;; Copyright © 2020 Christopher Baines <mail@cbaines.net> ;;; ;;; This file is part of GNU Guix. ;;;@@ -374,38 +375,37 @@ No authentication and authorization checks are performed here!" (define* (valid-narinfo? narinfo #:optional (acl (current-acl)) #:key verbose?) "Return #t if NARINFO's signature is not valid."- (or (%allow-unauthenticated-substitutes?)- (let ((hash (narinfo-sha256 narinfo))- (signature (narinfo-signature narinfo))- (uri (uri->string (first (narinfo-uris narinfo)))))- (and hash signature- (signature-case (signature hash acl)- (valid-signature #t)- (invalid-signature- (when verbose?- (format (current-error-port)- "invalid signature for substitute at '~a'~%"- uri))- #f)- (hash-mismatch- (when verbose?- (format (current-error-port)- "hash mismatch for substitute at '~a'~%"- uri))- #f)- (unauthorized-key- (when verbose?- (format (current-error-port)- "substitute at '~a' is signed by an \+ (let ((hash (narinfo-sha256 narinfo))+ (signature (narinfo-signature narinfo))+ (uri (uri->string (first (narinfo-uris narinfo)))))+ (and hash signature+ (signature-case (signature hash acl)+ (valid-signature #t)+ (invalid-signature+ (when verbose?+ (format (current-error-port)+ "invalid signature for substitute at '~a'~%"+ uri))+ #f)+ (hash-mismatch+ (when verbose?+ (format (current-error-port)+ "hash mismatch for substitute at '~a'~%"+ uri))+ #f)+ (unauthorized-key+ (when verbose?+ (format (current-error-port)+ "substitute at '~a' is signed by an \ unauthorized party~%"- uri))- #f)- (corrupt-signature- (when verbose?- (format (current-error-port)- "corrupt signature for substitute at '~a'~%"- uri))- #f))))))+ uri))+ #f)+ (corrupt-signature+ (when verbose?+ (format (current-error-port)+ "corrupt signature for substitute at '~a'~%"+ uri))+ #f))))) (define (write-narinfo narinfo port) "Write NARINFO to PORT."@@ -917,11 +917,14 @@ expected by the daemon." "Reply to COMMAND, a query as written by the daemon to this process's standard input. Use ACL as the access-control list against which to check authorized substitutes."- (define (valid? obj)- (valid-narinfo? obj acl))+ (define valid?+ (if (%allow-unauthenticated-substitutes?)+ (begin+ (warn-about-missing-authentication) - (when (%allow-unauthenticated-substitutes?)- (warn-about-missing-authentication))+ (const #t))+ (lambda (obj)+ (valid-narinfo? obj acl)))) (match (string-tokenize command) (("have" paths ..1)@@ -1075,7 +1078,9 @@ DESTINATION is in the store, deduplicate its files. Print a status line on the current output port." (define narinfo (lookup-narinfo cache-urls store-item- (cut valid-narinfo? <> acl)))+ (if (%allow-unauthenticated-substitutes?)+ (const #t)+ (cut valid-narinfo? <> acl)))) (define destination-in-store? (string-prefix? (string-append (%store-prefix) "/")-- 2.29.2
C
C
Christopher Baines wrote on 3 Jan 18:59 +0100
[PATCH v2 2/3] guix: Move narinfo code from substitute script to module.
(address . 45409@debbugs.gnu.org)
20210103175917.15992-2-mail@cbaines.net
This separation between the code for dealing with narinfos from the code doingthat for a purpose should make things clearer, and better support componentsother that the substitute script in using this code.
This is just moving the code around, no code should have been significantlychanged.
* guix/scripts/substitute.scm (<narinfo>): Move record type to (guix narinfo).(fields->alist, narinfo-hash-algorithm+value, narinfo-hash->sha256,narinfo-signature->canonical-sexp, narinfo-maker, read-narinfo,narinfo-sha256, valid-narinfo?, write-narinfo, narinfo->string,string->narinfo, equivalent-narinfo?, supported-compression?,compresses-better?, narinfo-best-uri): Move procedures to (guix narinfo).(%compression-methods): Move variable to (guix narinfo).* guix/narinfo.scm: New file.* Makefile.am (MODULES): Add it.* po/guix/POTFILES.in: Add 'guix/narinfo.scm'.--- Makefile.am | 1 + guix/narinfo.scm | 324 ++++++++++++++++++++++++++++++++++++ guix/scripts/challenge.scm | 1 + guix/scripts/substitute.scm | 281 +------------------------------ guix/scripts/weather.scm | 1 + po/guix/POTFILES.in | 1 + tests/challenge.scm | 2 +- tests/substitute.scm | 1 + 8 files changed, 332 insertions(+), 280 deletions(-) create mode 100644 guix/narinfo.scm
Toggle diff (734 lines)diff --git a/Makefile.am b/Makefile.amindex aec2bb1474..69166a2ea1 100644--- a/Makefile.am+++ b/Makefile.am@@ -103,6 +103,7 @@ MODULES = \ guix/profiles.scm \ guix/serialization.scm \ guix/nar.scm \+ guix/narinfo.scm \ guix/derivations.scm \ guix/grafts.scm \ guix/repl.scm \diff --git a/guix/narinfo.scm b/guix/narinfo.scmnew file mode 100644index 0000000000..5965758bff--- /dev/null+++ b/guix/narinfo.scm@@ -0,0 +1,324 @@+;;; GNU Guix --- Functional package management for GNU+;;; Copyright © 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>+;;; Copyright © 2014 Nikita Karetnikov <nikita@karetnikov.org>+;;; Copyright © 2018 Kyle Meyer <kyle@kyleam.com>+;;;+;;; This file is part of GNU Guix.+;;;+;;; GNU Guix is free software; you can redistribute it and/or modify it+;;; under the terms of the GNU General Public License as published by+;;; the Free Software Foundation; either version 3 of the License, or (at+;;; your option) any later version.+;;;+;;; GNU Guix is distributed in the hope that it will be useful, but+;;; WITHOUT ANY WARRANTY; without even the implied warranty of+;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+;;; GNU General Public License for more details.+;;;+;;; You should have received a copy of the GNU General Public License+;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.++(define-module (guix narinfo)+ #:use-module (guix pki)+ #:use-module (guix i18n)+ #:use-module (guix base32)+ #:use-module (guix base64)+ #:use-module (guix records)+ #:use-module (guix diagnostics)+ #:use-module (guix scripts substitute)+ #:use-module (gcrypt hash)+ #:use-module (gcrypt pk-crypto)+ #:use-module (rnrs bytevectors)+ #:use-module (srfi srfi-1)+ #:use-module (srfi srfi-9)+ #:use-module (srfi srfi-26)+ #:use-module (ice-9 match)+ #:use-module (ice-9 binary-ports)+ #:use-module (web uri)+ #:export (narinfo-signature->canonical-sexp++ narinfo?+ narinfo-path+ narinfo-uris+ narinfo-uri-base+ narinfo-compressions+ narinfo-file-hashes+ narinfo-file-sizes+ narinfo-hash+ narinfo-size+ narinfo-references+ narinfo-deriver+ narinfo-system+ narinfo-signature++ narinfo-hash-algorithm+value++ narinfo-hash->sha256+ narinfo-best-uri++ valid-narinfo?++ read-narinfo+ write-narinfo++ string->narinfo+ narinfo->string++ equivalent-narinfo?))++(define-record-type <narinfo>+ (%make-narinfo path uri-base uris compressions file-sizes file-hashes+ nar-hash nar-size references deriver system+ signature contents)+ narinfo?+ (path narinfo-path)+ (uri-base narinfo-uri-base) ;URI of the cache it originates from+ (uris narinfo-uris) ;list of strings+ (compressions narinfo-compressions) ;list of strings+ (file-sizes narinfo-file-sizes) ;list of (integers | #f)+ (file-hashes narinfo-file-hashes)+ (nar-hash narinfo-hash)+ (nar-size narinfo-size)+ (references narinfo-references)+ (deriver narinfo-deriver)+ (system narinfo-system)+ (signature narinfo-signature) ; canonical sexp+ ;; The original contents of a narinfo file. This field is needed because we+ ;; want to preserve the exact textual representation for verification purposes.+ ;; See <https://lists.gnu.org/archive/html/guix-devel/2014-02/msg00340.html>+ ;; for more information.+ (contents narinfo-contents))++(define (narinfo-hash-algorithm+value narinfo)+ "Return two values: the hash algorithm used by NARINFO and its value as a+bytevector."+ (match (string-tokenize (narinfo-hash narinfo)+ (char-set-complement (char-set #\:)))+ ((algorithm base32)+ (values (lookup-hash-algorithm (string->symbol algorithm))+ (nix-base32-string->bytevector base32)))+ (_+ (raise (formatted-message+ (G_ "invalid narinfo hash: ~s") (narinfo-hash narinfo))))))++(define (narinfo-hash->sha256 hash)+ "If the string HASH denotes a sha256 hash, return it as a bytevector.+Otherwise return #f."+ (and (string-prefix? "sha256:" hash)+ (nix-base32-string->bytevector (string-drop hash 7))))++(define (narinfo-signature->canonical-sexp str)+ "Return the value of a narinfo's 'Signature' field as a canonical sexp."+ (match (string-split str #\;)+ ((version host-name sig)+ (let ((maybe-number (string->number version)))+ (cond ((not (number? maybe-number))+ (leave (G_ "signature version must be a number: ~s~%")+ version))+ ;; Currently, there are no other versions.+ ((not (= 1 maybe-number))+ (leave (G_ "unsupported signature version: ~a~%")+ maybe-number))+ (else+ (let ((signature (utf8->string (base64-decode sig))))+ (catch 'gcry-error+ (lambda ()+ (string->canonical-sexp signature))+ (lambda (key proc err)+ (leave (G_ "signature is not a valid \+s-expression: ~s~%")+ signature))))))))+ (x+ (leave (G_ "invalid format of the signature field: ~a~%") x))))++(define (narinfo-maker str cache-url)+ "Return a narinfo constructor for narinfos originating from CACHE-URL. STR+must contain the original contents of a narinfo file."+ (lambda (path urls compressions file-hashes file-sizes+ nar-hash nar-size references deriver system+ signature)+ "Return a new <narinfo> object."+ (define len (length urls))+ (%make-narinfo path cache-url+ ;; Handle the case where URL is a relative URL.+ (map (lambda (url)+ (or (string->uri url)+ (string->uri+ (string-append cache-url "/" url))))+ urls)+ compressions+ (match file-sizes+ (() (make-list len #f))+ ((lst ...) (map string->number lst)))+ (match file-hashes+ (() (make-list len #f))+ ((lst ...) (map string->number lst)))+ nar-hash+ (and=> nar-size string->number)+ (string-tokenize references)+ (match deriver+ ((or #f "") #f)+ (_ deriver))+ system+ (false-if-exception+ (and=> signature narinfo-signature->canonical-sexp))+ str)))++(define fields->alist+ ;; The narinfo format is really just like recutils.+ recutils->alist)++(define* (read-narinfo port #:optional url+ #:key size)+ "Read a narinfo from PORT. If URL is true, it must be a string used to+build full URIs from relative URIs found while reading PORT. When SIZE is+true, read at most SIZE bytes from PORT; otherwise, read as much as possible.++No authentication and authorization checks are performed here!"+ (let ((str (utf8->string (if size+ (get-bytevector-n port size)+ (get-bytevector-all port)))))+ (alist->record (call-with-input-string str fields->alist)+ (narinfo-maker str url)+ '("StorePath" "URL" "Compression"+ "FileHash" "FileSize" "NarHash" "NarSize"+ "References" "Deriver" "System"+ "Signature")+ '("URL" "Compression" "FileSize" "FileHash"))))++(define (narinfo-sha256 narinfo)+ "Return the sha256 hash of NARINFO as a bytevector, or #f if NARINFO lacks a+'Signature' field."+ (define %mandatory-fields+ ;; List of fields that must be signed. If they are not signed, the+ ;; narinfo is considered unsigned.+ '("StorePath" "NarHash" "References"))++ (let ((contents (narinfo-contents narinfo)))+ (match (string-contains contents "Signature:")+ (#f #f)+ (index+ (let* ((above-signature (string-take contents index))+ (signed-fields (match (call-with-input-string above-signature+ fields->alist)+ (((fields . values) ...) fields))))+ (and (every (cut member <> signed-fields) %mandatory-fields)+ (sha256 (string->utf8 above-signature))))))))++(define* (valid-narinfo? narinfo #:optional (acl (current-acl))+ #:key verbose?)+ "Return #t if NARINFO's signature is not valid."+ (let ((hash (narinfo-sha256 narinfo))+ (signature (narinfo-signature narinfo))+ (uri (uri->string (first (narinfo-uris narinfo)))))+ (and hash signature+ (signature-case (signature hash acl)+ (valid-signature #t)+ (invalid-signature+ (when verbose?+ (format (current-error-port)+ "invalid signature for substitute at '~a'~%"+ uri))+ #f)+ (hash-mismatch+ (when verbose?+ (format (current-error-port)+ "hash mismatch for substitute at '~a'~%"+ uri))+ #f)+ (unauthorized-key+ (when verbose?+ (format (current-error-port)+ "substitute at '~a' is signed by an \+unauthorized party~%"+ uri))+ #f)+ (corrupt-signature+ (when verbose?+ (format (current-error-port)+ "corrupt signature for substitute at '~a'~%"+ uri))+ #f)))))++(define (write-narinfo narinfo port)+ "Write NARINFO to PORT."+ (put-bytevector port (string->utf8 (narinfo-contents narinfo))))++(define (narinfo->string narinfo)+ "Return the external representation of NARINFO."+ (call-with-output-string (cut write-narinfo narinfo <>)))++(define (string->narinfo str cache-uri)+ "Return the narinfo represented by STR. Assume CACHE-URI as the base URI of+the cache STR originates form."+ (call-with-input-string str (cut read-narinfo <> cache-uri)))++(define (equivalent-narinfo? narinfo1 narinfo2)+ "Return true if NARINFO1 and NARINFO2 are equivalent--i.e., if they describe+the same store item. This ignores unnecessary metadata such as the Nar URL."+ (and (string=? (narinfo-hash narinfo1)+ (narinfo-hash narinfo2))++ ;; The following is not needed if all we want is to download a valid+ ;; nar, but it's necessary if we want valid narinfo.+ (string=? (narinfo-path narinfo1)+ (narinfo-path narinfo2))+ (equal? (narinfo-references narinfo1)+ (narinfo-references narinfo2))++ (= (narinfo-size narinfo1)+ (narinfo-size narinfo2))))++(define %compression-methods+ ;; Known compression methods and a thunk to determine whether they're+ ;; supported. See 'decompressed-port' in (guix utils).+ `(("gzip" . ,(const #t))+ ("lzip" . ,(const #t))+ ("xz" . ,(const #t))+ ("bzip2" . ,(const #t))+ ("none" . ,(const #t))))++(define (supported-compression? compression)+ "Return true if COMPRESSION, a string, denotes a supported compression+method."+ (match (assoc-ref %compression-methods compression)+ (#f #f)+ (supported? (supported?))))++(define (compresses-better? compression1 compression2)+ "Return true if COMPRESSION1 generally compresses better than COMPRESSION2;+this is a rough approximation."+ (match compression1+ ("none" #f)+ ("gzip" (string=? compression2 "none"))+ (_ (or (string=? compression2 "none")+ (string=? compression2 "gzip")))))++(define (narinfo-best-uri narinfo)+ "Select the \"best\" URI to download NARINFO's nar, and return three values:+the URI, its compression method (a string), and the compressed file size."+ (define choices+ (filter (match-lambda+ ((uri compression file-size)+ (supported-compression? compression)))+ (zip (narinfo-uris narinfo)+ (narinfo-compressions narinfo)+ (narinfo-file-sizes narinfo))))++ (define (file-size<? c1 c2)+ (match c1+ ((uri1 compression1 (? integer? file-size1))+ (match c2+ ((uri2 compression2 (? integer? file-size2))+ (< file-size1 file-size2))+ (_ #t)))+ ((uri compression1 #f)+ (match c2+ ((uri2 compression2 _)+ (compresses-better? compression1 compression2))))+ (_ #f))) ;we can't tell++ (match (sort choices file-size<?)+ (((uri compression file-size) _ ...)+ (values uri compression file-size))))+diff --git a/guix/scripts/challenge.scm b/guix/scripts/challenge.scmindex d0a456ac1d..cc9cbe6f27 100644--- a/guix/scripts/challenge.scm+++ b/guix/scripts/challenge.scm@@ -28,6 +28,7 @@ #:use-module ((guix progress) #:hide (dump-port*)) #:use-module (guix serialization) #:use-module (guix scripts substitute)+ #:use-module (guix narinfo) #:use-module (rnrs bytevectors) #:autoload (guix http-client) (http-fetch) #:use-module ((guix build syscalls) #:select (terminal-columns))diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex d66f73e75a..e2d30f1760 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -22,6 +22,7 @@ (define-module (guix scripts substitute) #:use-module (guix ui) #:use-module (guix scripts)+ #:use-module (guix narinfo) #:use-module (guix store) #:use-module (guix utils) #:use-module (guix combinators)@@ -67,29 +68,8 @@ #:use-module (web request) #:use-module (web response) #:use-module (guix http-client)- #:export (narinfo-signature->canonical-sexp-- narinfo?- narinfo-path- narinfo-uris- narinfo-uri-base- narinfo-compressions- narinfo-file-hashes- narinfo-file-sizes- narinfo-hash- narinfo-size- narinfo-references- narinfo-deriver- narinfo-system- narinfo-signature-- narinfo-hash->sha256- narinfo-best-uri-- lookup-narinfos+ #:export (lookup-narinfos lookup-narinfos/diverse- read-narinfo- write-narinfo %allow-unauthenticated-substitutes? %error-to-file-descriptor-4?@@ -149,10 +129,6 @@ disabled!~%")) ;; How often we want to remove files corresponding to expired cache entries. (* 7 24 3600)) -(define fields->alist- ;; The narinfo format is really just like recutils.- recutils->alist)- (define %fetch-timeout ;; Number of seconds after which networking is considered "slow". 5)@@ -236,190 +212,6 @@ connection (typically PORT) is kept open once data has been fetched from URI." (leave (G_ "unsupported substitute URI scheme: ~a~%") (uri->string uri))))) - -(define-record-type <narinfo>- (%make-narinfo path uri-base uris compressions file-sizes file-hashes- nar-hash nar-size references deriver system- signature contents)- narinfo?- (path narinfo-path)- (uri-base narinfo-uri-base) ;URI of the cache it originates from- (uris narinfo-uris) ;list of strings- (compressions narinfo-compressions) ;list of strings- (file-sizes narinfo-file-sizes) ;list of (integers | #f)- (file-hashes narinfo-file-hashes)- (nar-hash narinfo-hash)- (nar-size narinfo-size)- (references narinfo-references)- (deriver narinfo-deriver)- (system narinfo-system)- (signature narinfo-signature) ; canonical sexp- ;; The original contents of a narinfo file. This field is needed because we- ;; want to preserve the exact textual representation for verification purposes.- ;; See <https://lists.gnu.org/archive/html/guix-devel/2014-02/msg00340.html>- ;; for more information.- (contents narinfo-contents))--(define (narinfo-hash-algorithm+value narinfo)- "Return two values: the hash algorithm used by NARINFO and its value as a-bytevector."- (match (string-tokenize (narinfo-hash narinfo)- (char-set-complement (char-set #\:)))- ((algorithm base32)- (values (lookup-hash-algorithm (string->symbol algorithm))- (nix-base32-string->bytevector base32)))- (_- (raise (formatted-message- (G_ "invalid narinfo hash: ~s") (narinfo-hash narinfo))))))--(define (narinfo-hash->sha256 hash)- "If the string HASH denotes a sha256 hash, return it as a bytevector.-Otherwise return #f."- (and (string-prefix? "sha256:" hash)- (nix-base32-string->bytevector (string-drop hash 7))))--(define (narinfo-signature->canonical-sexp str)- "Return the value of a narinfo's 'Signature' field as a canonical sexp."- (match (string-split str #\;)- ((version host-name sig)- (let ((maybe-number (string->number version)))- (cond ((not (number? maybe-number))- (leave (G_ "signature version must be a number: ~s~%")- version))- ;; Currently, there are no other versions.- ((not (= 1 maybe-number))- (leave (G_ "unsupported signature version: ~a~%")- maybe-number))- (else- (let ((signature (utf8->string (base64-decode sig))))- (catch 'gcry-error- (lambda ()- (string->canonical-sexp signature))- (lambda (key proc err)- (leave (G_ "signature is not a valid \-s-expression: ~s~%")- signature))))))))- (x- (leave (G_ "invalid format of the signature field: ~a~%") x))))--(define (narinfo-maker str cache-url)- "Return a narinfo constructor for narinfos originating from CACHE-URL. STR-must contain the original contents of a narinfo file."- (lambda (path urls compressions file-hashes file-sizes- nar-hash nar-size references deriver system- signature)- "Return a new <narinfo> object."- (define len (length urls))- (%make-narinfo path cache-url- ;; Handle the case where URL is a relative URL.- (map (lambda (url)- (or (string->uri url)- (string->uri- (string-append cache-url "/" url))))- urls)- compressions- (match file-sizes- (() (make-list len #f))- ((lst ...) (map string->number lst)))- (match file-hashes- (() (make-list len #f))- ((lst ...) (map string->number lst)))- nar-hash- (and=> nar-size string->number)- (string-tokenize references)- (match deriver- ((or #f "") #f)- (_ deriver))- system- (false-if-exception- (and=> signature narinfo-signature->canonical-sexp))- str)))--(define* (read-narinfo port #:optional url- #:key size)- "Read a narinfo from PORT. If URL is true, it must be a string used to-build full URIs from relative URIs found while reading PORT. When SIZE is-true, read at most SIZE bytes from PORT; otherwise, read as much as possible.--No authentication and authorization checks are performed here!"- (let ((str (utf8->string (if size- (get-bytevector-n port size)- (get-bytevector-all port)))))- (alist->record (call-with-input-string str fields->alist)- (narinfo-maker str url)- '("StorePath" "URL" "Compression"- "FileHash" "FileSize" "NarHash" "NarSize"- "References" "Deriver" "System"- "Signature")- '("URL" "Compression" "FileSize" "FileHash"))))--(define (narinfo-sha256 narinfo)- "Return the sha256 hash of NARINFO as a bytevector, or #f if NARINFO lacks a-'Signature' field."- (define %mandatory-fields- ;; List of fields that must be signed. If they are not signed, the- ;; narinfo is considered unsigned.- '("StorePath" "NarHash" "References"))-- (let ((contents (narinfo-contents narinfo)))- (match (string-contains contents "Signature:")- (#f #f)- (index- (let* ((above-signature (string-take contents index))- (signed-fields (match (call-with-input-string above-signature- fields->alist)- (((fields . values) ...) fields))))- (and (every (cut member <> signed-fields) %mandatory-fields)- (sha256 (string->utf8 above-signature))))))))--(define* (valid-narinfo? narinfo #:optional (acl (current-acl))- #:key verbose?)- "Return #t if NARINFO's signature is not valid."- (let ((hash (narinfo-sha256 narinfo))- (signature (narinfo-signature narinfo))- (uri (uri->string (first (narinfo-uris narinfo)))))- (and hash signature- (signature-case (signature hash acl)- (valid-signature #t)- (invalid-signature- (when verbose?- (format (current-error-port)- "invalid signature for substitute at '~a'~%"- uri))- #f)- (hash-mismatch- (when verbose?- (format (current-error-port)- "hash mismatch for substitute at '~a'~%"- uri))- #f)- (unauthorized-key- (when verbose?- (format (current-error-port)- "substitute at '~a' is signed by an \-unauthorized party~%"- uri))- #f)- (corrupt-signature- (when verbose?- (format (current-error-port)- "corrupt signature for substitute at '~a'~%"- uri))- #f)))))--(define (write-narinfo narinfo port)- "Write NARINFO to PORT."- (put-bytevector port (string->utf8 (narinfo-contents narinfo))))--(define (narinfo->string narinfo)- "Return the external representation of NARINFO."- (call-with-output-string (cut write-narinfo narinfo <>)))--(define (string->narinfo str cache-uri)- "Return the narinfo represented by STR. Assume CACHE-URI as the base URI of-the cache STR originates form."- (call-with-input-string str (cut read-narinfo <> cache-uri)))- (define (narinfo-cache-file cache-url path) "Return the name of the local file that contains an entry for PATH. The entry is stored in a sub-directory specific to CACHE-URL."@@ -741,22 +533,6 @@ information is available locally." (let ((missing (fetch-narinfos cache missing))) (append cached (or missing '())))))) -(define (equivalent-narinfo? narinfo1 narinfo2)- "Return true if NARINFO1 and NARINFO2 are equivalent--i.e., if they describe-the same store item. This ignores unnecessary metadata such as the Nar URL."- (and (string=? (narinfo-hash narinfo1)- (narinfo-hash narinfo2))-- ;; The following is not needed if all we want is to download a valid- ;; nar, but it's necessary if we want valid narinfo.- (string=? (narinfo-path narinfo1)- (narinfo-path narinfo2))- (equal? (narinfo-references narinfo1)- (narinfo-references narinfo2))-- (= (narinfo-size narinfo1)- (narinfo-size narinfo2))))- (define (lookup-narinfos/diverse caches paths authorized?) "Look up narinfos for PATHS on all of CACHES, a list of URLS, in that order. That is, when a cache lacks an AUTHORIZED? narinfo, look it up in the next@@ -942,59 +718,6 @@ authorized substitutes." (wtf (error "unknown `--query' command" wtf)))) -(define %compression-methods- ;; Known compression methods and a thunk to determine whether they're- ;; supported. See 'decompressed-port' in (guix utils).- `(("gzip" . ,(const #t))- ("lzip" . ,(const #t))- ("xz" . ,(const #t))- ("bzip2" . ,(const #t))- ("none" . ,(const #t))))--(define (supported-compression? compression)- "Return true if COMPRESSION, a string, denotes a supported compression-method."- (match (assoc-ref %compression-methods compression)- (#f #f)- (supported? (supported?))))--(define (compresses-better? compression1 compression2)- "Return true if COMPRESSION1 generally compresses better than COMPRESSION2;-this is a rough approximation."- (match compression1- ("none" #f)- ("gzip" (string=? compression2 "none"))- (_ (or (string=? compression2 "none")- (string=? compression2 "gzip")))))--(define (narinfo-best-uri narinfo)- "Select the \"best\" URI to download NARINFO's nar, and return three values:-the URI, its compression method (a string), and the compressed file size."- (define choices- (filter (match-lambda- ((uri compression file-size)- (supported-compression? compression)))- (zip (narinfo-uris narinfo)- (narinfo-compressions narinfo)- (narinfo-file-sizes narinfo))))-- (define (file-size<? c1 c2)- (match c1- ((uri1 compression1 (? integer? file-size1))- (match c2- ((uri2 compression2 (? integer? file-size2))- (< file-size1 file-size2))- (_ #t)))- ((uri compression1 #f)- (match c2- ((uri2 compression2 _)- (compresses-better? compression1 compression2))))- (_ #f))) ;we can't tell-- (match (sort choices file-size<?)- (((uri compression file-size) _ ...)- (values uri compression file-size))))- (define %max-cached-connections ;; Maximum number of connections kept in cache by ;; 'open-connection-for-uri/cached'.diff --git a/guix/scripts/weather.scm b/guix/scripts/weather.scmindex f28070ddc4..97e4a73802 100644--- a/guix/scripts/weather.scm+++ b/guix/scripts/weather.scm@@ -33,6 +33,7 @@ #:use-module ((guix build syscalls) #:select (terminal-columns)) #:use-module ((guix build utils) #:select (every*)) #:use-module (guix scripts substitute)+ #:use-module (guix narinfo) #:use-module (guix http-client) #:use-module (guix ci) #:use-module (guix sets)diff --git a/po/guix/POTFILES.in b/po/guix/POTFILES.inindex 1aec3bef3c..666e630adf 100644--- a/po/guix/POTFILES.in+++ b/po/guix/POTFILES.in@@ -87,6 +87,7 @@ guix/ui.scm guix/status.scm guix/http-client.scm guix/nar.scm+guix/narinfo.scm guix/channels.scm guix/profiles.scm guix/git.scmdiff --git a/tests/challenge.scm b/tests/challenge.scmindex 9c6d6e0d58..fdd5fd238e 100644--- a/tests/challenge.scm+++ b/tests/challenge.scm@@ -27,8 +27,8 @@ #:use-module (guix packages) #:use-module (guix gexp) #:use-module (guix base32)+ #:use-module (guix narinfo) #:use-module (guix scripts challenge)- #:use-module (guix scripts substitute) #:use-module ((guix build utils) #:select (find-files)) #:use-module (gnu packages bootstrap) #:use-module (srfi srfi-1)diff --git a/tests/substitute.scm b/tests/substitute.scmindex 542aaf603f..697abc4684 100644--- a/tests/substitute.scm+++ b/tests/substitute.scm@@ -19,6 +19,7 @@ (define-module (test-substitute) #:use-module (guix scripts substitute)+ #:use-module (guix narinfo) #:use-module (guix base64) #:use-module (gcrypt hash) #:use-module (guix serialization)-- 2.29.2
C
C
Christopher Baines wrote on 3 Jan 18:59 +0100
[PATCH v2 3/3] guix: Split (guix substitutes) from (guix scripts substitute).
(address . 45409@debbugs.gnu.org)
20210103175917.15992-3-mail@cbaines.net
This means there's a module for working with substitutes, rather than all thecode sitting in the script. The need for this can be seen with the weather andchallenge scripts, that now don't have to use code from the substitute script,but can instead use the substitute module.
The separation here between the actual functionality of the substitute scriptand the underlying functionality used both there and elsewhere should makemaintenance easier moving forward.
This commit just moves code, none of the code should have been changedsignificantly.
* guix/scripts/substitute.scm (%narinfo-cache-directory, %narinfo-ttl,%narinfo-negative-ttl, %narinfo-transient-error-ttl, %unreachable-hosts,%max-cached-connections): Move variables to (guix substitutes).(narinfo-cache-file, cached-narinfo, cache-narinfo!, narinfo-request, at-most,http-multiple-get, read-to-eof, narinfo-from-file,open-connection-for-uri/maybe, fetch-narinfos, lookup-narinfos,lookup-narinfos/diverse, open-connection-for-uri/cached,call-with-cached-connection): Move procedures to (guix substitutes).(with-cached-connection): Move syntax rule to (guix substitutes).* guix/substitutes.scm: New file.* Makefile.am (MODULES): Add it.* po/guix/POTFILES.in: Add 'guix/substitutes.scm'.--- Makefile.am | 1 + guix/scripts/challenge.scm | 2 +- guix/scripts/substitute.scm | 482 +-------------------------------- guix/scripts/weather.scm | 2 +- guix/substitutes.scm | 527 ++++++++++++++++++++++++++++++++++++ po/guix/POTFILES.in | 1 + 6 files changed, 536 insertions(+), 479 deletions(-) create mode 100644 guix/substitutes.scm
Toggle diff (1135 lines)diff --git a/Makefile.am b/Makefile.amindex 69166a2ea1..fe39eae53c 100644--- a/Makefile.am+++ b/Makefile.am@@ -89,6 +89,7 @@ MODULES = \ guix/memoization.scm \ guix/utils.scm \ guix/sets.scm \+ guix/substitutes.scm \ guix/modules.scm \ guix/download.scm \ guix/discovery.scm \diff --git a/guix/scripts/challenge.scm b/guix/scripts/challenge.scmindex cc9cbe6f27..74cf163937 100644--- a/guix/scripts/challenge.scm+++ b/guix/scripts/challenge.scm@@ -27,8 +27,8 @@ #:use-module (guix packages) #:use-module ((guix progress) #:hide (dump-port*)) #:use-module (guix serialization)- #:use-module (guix scripts substitute) #:use-module (guix narinfo)+ #:use-module (guix substitutes) #:use-module (rnrs bytevectors) #:autoload (guix http-client) (http-fetch) #:use-module ((guix build syscalls) #:select (terminal-columns))diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex e2d30f1760..45c07b1038 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -23,38 +23,30 @@ #:use-module (guix ui) #:use-module (guix scripts) #:use-module (guix narinfo)+ #:use-module (guix substitutes) #:use-module (guix store) #:use-module (guix utils)- #:use-module (guix combinators)- #:use-module (guix config)- #:use-module (guix records)- #:use-module (guix diagnostics) #:use-module (guix i18n) #:use-module ((guix serialization) #:select (restore-file dump-file)) #:autoload (guix store deduplication) (dump-file/deduplicate) #:autoload (guix scripts discover) (read-substitute-urls) #:use-module (gcrypt hash) #:use-module (guix base32)- #:use-module (guix base64) #:use-module (guix cache) #:use-module (gcrypt pk-crypto) #:use-module (guix pki)- #:use-module ((guix build utils) #:select (mkdir-p dump-port))+ #:use-module ((guix build utils) #:select (mkdir-p)) #:use-module ((guix build download)- #:select (uri-abbreviation nar-uri-abbreviation+ #:select (nar-uri-abbreviation (open-connection-for-uri- . guix:open-connection-for-uri)- store-path-abbreviation byte-count->string))+ . guix:open-connection-for-uri))) #:use-module (guix progress) #:use-module ((guix build syscalls) #:select (set-thread-name)) #:use-module (ice-9 rdelim)- #:use-module (ice-9 regex) #:use-module (ice-9 match) #:use-module (ice-9 format) #:use-module (ice-9 ftw)- #:use-module (ice-9 binary-ports)- #:use-module (ice-9 vlist) #:use-module (rnrs bytevectors) #:use-module (srfi srfi-1) #:use-module (srfi srfi-9)@@ -68,10 +60,7 @@ #:use-module (web request) #:use-module (web response) #:use-module (guix http-client)- #:export (lookup-narinfos- lookup-narinfos/diverse-- %allow-unauthenticated-substitutes?+ #:export (%allow-unauthenticated-substitutes? %error-to-file-descriptor-4? substitute-urls@@ -88,17 +77,6 @@ ;;; ;;; Code: -(define %narinfo-cache-directory- ;; A local cache of narinfos, to avoid going to the network. Most of the- ;; time, 'guix substitute' is called by guix-daemon as root and stores its- ;; cached data in /var/guix/…. However, when invoked from 'guix challenge'- ;; as a user, it stores its cache in ~/.cache.- (if (zero? (getuid))- (or (and=> (getenv "XDG_CACHE_HOME")- (cut string-append <> "/guix/substitute"))- (string-append %state-directory "/substitute/cache"))- (string-append (cache-directory #:ensure? #f) "/substitute")))- (define (warn-about-missing-authentication) (warning (G_ "authentication and authorization of substitutes \ disabled!~%"))@@ -111,20 +89,6 @@ disabled!~%")) (and=> (getenv "GUIX_ALLOW_UNAUTHENTICATED_SUBSTITUTES") (cut string-ci=? <> "yes")))) -(define %narinfo-ttl- ;; Number of seconds during which cached narinfo lookups are considered- ;; valid for substitute servers that do not advertise a TTL via the- ;; 'Cache-Control' response header.- (* 36 3600))--(define %narinfo-negative-ttl- ;; Likewise, but for negative lookups---i.e., cached lookup failures (404).- (* 1 3600))--(define %narinfo-transient-error-ttl- ;; Likewise, but for transient errors such as 504 ("Gateway timeout").- (* 10 60))- (define %narinfo-expired-cache-entry-removal-delay ;; How often we want to remove files corresponding to expired cache entries. (* 7 24 3600))@@ -212,369 +176,6 @@ connection (typically PORT) is kept open once data has been fetched from URI." (leave (G_ "unsupported substitute URI scheme: ~a~%") (uri->string uri))))) -(define (narinfo-cache-file cache-url path)- "Return the name of the local file that contains an entry for PATH. The-entry is stored in a sub-directory specific to CACHE-URL."- ;; The daemon does not sanitize its input, so PATH could be something like- ;; "/gnu/store/foo". Gracefully handle that.- (match (store-path-hash-part path)- (#f- (leave (G_ "'~a' does not name a store item~%") path))- ((? string? hash-part)- (string-append %narinfo-cache-directory "/"- (bytevector->base32-string (sha256 (string->utf8 cache-url)))- "/" hash-part))))--(define (cached-narinfo cache-url path)- "Check locally if we have valid info about PATH coming from CACHE-URL.-Return two values: a Boolean indicating whether we have valid cached info, and-that info, which may be either #f (when PATH is unavailable) or the narinfo-for PATH."- (define now- (current-time time-monotonic))-- (define cache-file- (narinfo-cache-file cache-url path))-- (catch 'system-error- (lambda ()- (call-with-input-file cache-file- (lambda (p)- (match (read p)- (('narinfo ('version 2)- ('cache-uri cache-uri)- ('date date) ('ttl ttl) ('value #f))- ;; A cached negative lookup.- (if (obsolete? date now ttl)- (values #f #f)- (values #t #f)))- (('narinfo ('version 2)- ('cache-uri cache-uri)- ('date date) ('ttl ttl) ('value value))- ;; A cached positive lookup- (if (obsolete? date now ttl)- (values #f #f)- (values #t (string->narinfo value cache-uri))))- (('narinfo ('version v) _ ...)- (values #f #f))))))- (lambda _- (values #f #f))))--(define (cache-narinfo! cache-url path narinfo ttl)- "Cache locally NARNIFO for PATH, which originates from CACHE-URL, with the-given TTL (a number of seconds or #f). NARINFO may be #f, in which case it-indicates that PATH is unavailable at CACHE-URL."- (define now- (current-time time-monotonic))-- (define (cache-entry cache-uri narinfo)- `(narinfo (version 2)- (cache-uri ,cache-uri)- (date ,(time-second now))- (ttl ,(or ttl- (if narinfo %narinfo-ttl %narinfo-negative-ttl)))- (value ,(and=> narinfo narinfo->string))))-- (let ((file (narinfo-cache-file cache-url path)))- (mkdir-p (dirname file))- (with-atomic-file-output file- (lambda (out)- (write (cache-entry cache-url narinfo) out))))-- narinfo)--(define (narinfo-request cache-url path)- "Return an HTTP request for the narinfo of PATH at CACHE-URL."- (let ((url (string-append cache-url "/" (store-path-hash-part path)- ".narinfo"))- (headers '((User-Agent . "GNU Guile"))))- (build-request (string->uri url) #:method 'GET #:headers headers)))--(define (at-most max-length lst)- "If LST is shorter than MAX-LENGTH, return it and the empty list; otherwise-return its MAX-LENGTH first elements and its tail."- (let loop ((len 0)- (lst lst)- (result '()))- (match lst- (()- (values (reverse result) '()))- ((head . tail)- (if (>= len max-length)- (values (reverse result) lst)- (loop (+ 1 len) tail (cons head result)))))))--(define* (http-multiple-get base-uri proc seed requests- #:key port (verify-certificate? #t)- (open-connection guix:open-connection-for-uri)- (keep-alive? #t)- (batch-size 1000))- "Send all of REQUESTS to the server at BASE-URI. Call PROC for each-response, passing it the request object, the response, a port from which to-read the response body, and the previous result, starting with SEED, à la-'fold'. Return the final result.--When PORT is specified, use it as the initial connection on which HTTP-requests are sent; otherwise call OPEN-CONNECTION to open a new connection for-a URI. When KEEP-ALIVE? is false, close the connection port before-returning."- (let connect ((port port)- (requests requests)- (result seed))- (define batch- (at-most batch-size requests))-- ;; (format (current-error-port) "connecting (~a requests left)..."- ;; (length requests))- (let ((p (or port (open-connection base-uri- #:verify-certificate?- verify-certificate?))))- ;; For HTTPS, P is not a file port and does not support 'setvbuf'.- (when (file-port? p)- (setvbuf p 'block (expt 2 16)))-- ;; Send BATCH in a row.- ;; XXX: Do our own caching to work around inefficiencies when- ;; communicating over TLS: <http://bugs.gnu.org/22966>.- (let-values (((buffer get) (open-bytevector-output-port)))- ;; Inherit the HTTP proxying property from P.- (set-http-proxy-port?! buffer (http-proxy-port? p))-- (for-each (cut write-request <> buffer)- batch)- (put-bytevector p (get))- (force-output p))-- ;; Now start processing responses.- (let loop ((sent batch)- (processed 0)- (result result))- (match sent- (()- (match (drop requests processed)- (()- (unless keep-alive?- (close-port p))- (reverse result))- (remainder- (connect p remainder result))))- ((head tail ...)- (let* ((resp (read-response p))- (body (response-body-port resp))- (result (proc head resp body result)))- ;; The server can choose to stop responding at any time, in which- ;; case we have to try again. Check whether that is the case.- ;; Note that even upon "Connection: close", we can read from BODY.- (match (assq 'connection (response-headers resp))- (('connection 'close)- (close-port p)- (connect #f ;try again- (drop requests (+ 1 processed))- result))- (_- (loop tail (+ 1 processed) result)))))))))) ;keep going--(define (read-to-eof port)- "Read from PORT until EOF is reached. The data are discarded."- (dump-port port (%make-void-port "w")))--(define (narinfo-from-file file url)- "Attempt to read a narinfo from FILE, using URL as the cache URL. Return #f-if file doesn't exist, and the narinfo otherwise."- (catch 'system-error- (lambda ()- (call-with-input-file file- (cut read-narinfo <> url)))- (lambda args- (if (= ENOENT (system-error-errno args))- #f- (apply throw args)))))--(define %unreachable-hosts- ;; Set of names of unreachable hosts.- (make-hash-table))--(define* (open-connection-for-uri/maybe uri- #:key- fresh?- (time %fetch-timeout))- "Open a connection to URI via 'open-connection-for-uri/cached' and return a-port to it, or, if connection failed, print a warning and return #f. Pass-#:fresh? to 'open-connection-for-uri/cached'."- (define host- (uri-host uri))-- (catch #t- (lambda ()- (open-connection-for-uri/cached uri #:timeout time- #:fresh? fresh?))- (match-lambda*- (('getaddrinfo-error error)- (unless (hash-ref %unreachable-hosts host)- (hash-set! %unreachable-hosts host #t) ;warn only once- (warning (G_ "~a: host not found: ~a~%")- host (gai-strerror error)))- #f)- (('system-error . args)- (unless (hash-ref %unreachable-hosts host)- (hash-set! %unreachable-hosts host #t)- (warning (G_ "~a: connection failed: ~a~%") host- (strerror- (system-error-errno `(system-error ,@args)))))- #f)- (args- (apply throw args)))))--(define (fetch-narinfos url paths)- "Retrieve all the narinfos for PATHS from the cache at URL and return them."- (define update-progress!- (let ((done 0)- (total (length paths)))- (lambda ()- (display "\r\x1b[K" (current-error-port)) ;erase current line- (force-output (current-error-port))- (format (current-error-port)- (G_ "updating substitutes from '~a'... ~5,1f%")- url (* 100. (/ done total)))- (set! done (+ 1 done)))))-- (define hash-part->path- (let ((mapping (fold (lambda (path result)- (vhash-cons (store-path-hash-part path) path- result))- vlist-null- paths)))- (lambda (hash)- (match (vhash-assoc hash mapping)- (#f #f)- ((_ . path) path)))))-- (define (handle-narinfo-response request response port result)- (let* ((code (response-code response))- (len (response-content-length response))- (cache (response-cache-control response))- (ttl (and cache (assoc-ref cache 'max-age))))- (update-progress!)-- ;; Make sure to read no more than LEN bytes since subsequent bytes may- ;; belong to the next response.- (if (= code 200) ; hit- (let ((narinfo (read-narinfo port url #:size len)))- (if (string=? (dirname (narinfo-path narinfo))- (%store-prefix))- (begin- (cache-narinfo! url (narinfo-path narinfo) narinfo ttl)- (cons narinfo result))- result))- (let* ((path (uri-path (request-uri request)))- (hash-part (basename- (string-drop-right path 8)))) ;drop ".narinfo"- (if len- (get-bytevector-n port len)- (read-to-eof port))- (cache-narinfo! url (hash-part->path hash-part) #f- (if (or (= 404 code) (= 202 code))- ttl- %narinfo-transient-error-ttl))- result))))-- (define (do-fetch uri)- (case (and=> uri uri-scheme)- ((http https)- ;; Note: Do not check HTTPS server certificates to avoid depending- ;; on the X.509 PKI. We can do it because we authenticate- ;; narinfos, which provides a much stronger guarantee.- (let* ((requests (map (cut narinfo-request url <>) paths))- (result (call-with-cached-connection uri- (lambda (port)- (if port- (begin- (update-progress!)- (http-multiple-get uri- handle-narinfo-response '()- requests- #:open-connection- open-connection-for-uri/cached- #:verify-certificate? #f- #:port port))- '()))- open-connection-for-uri/maybe)))- (newline (current-error-port))- result))- ((file #f)- (let* ((base (string-append (uri-path uri) "/"))- (files (map (compose (cut string-append base <> ".narinfo")- store-path-hash-part)- paths)))- (filter-map (cut narinfo-from-file <> url) files)))- (else- (leave (G_ "~s: unsupported server URI scheme~%")- (if uri (uri-scheme uri) url)))))-- (do-fetch (string->uri url)))--(define (lookup-narinfos cache paths)- "Return the narinfos for PATHS, invoking the server at CACHE when no-information is available locally."- (let-values (((cached missing)- (fold2 (lambda (path cached missing)- (let-values (((valid? value)- (cached-narinfo cache path)))- (if valid?- (if value- (values (cons value cached) missing)- (values cached missing))- (values cached (cons path missing)))))- '()- '()- paths)))- (if (null? missing)- cached- (let ((missing (fetch-narinfos cache missing)))- (append cached (or missing '()))))))--(define (lookup-narinfos/diverse caches paths authorized?)- "Look up narinfos for PATHS on all of CACHES, a list of URLS, in that order.-That is, when a cache lacks an AUTHORIZED? narinfo, look it up in the next-cache, and so on.--Return a list of narinfos for PATHS or a subset thereof. The returned-narinfos are either AUTHORIZED?, or they claim a hash that matches an-AUTHORIZED? narinfo."- (define (select-hit result)- (lambda (path)- (match (vhash-fold* cons '() path result)- ((one)- one)- ((several ..1)- (let ((authorized (find authorized? (reverse several))))- (and authorized- (find (cut equivalent-narinfo? <> authorized)- several)))))))-- (let loop ((caches caches)- (paths paths)- (result vlist-null) ;path->narinfo vhash- (hits '())) ;paths- (match paths- (() ;we're done- ;; Now iterate on all the HITS, and return exactly one match for each- ;; hit: the first narinfo that is authorized, or that has the same hash- ;; as an authorized narinfo, in the order of CACHES.- (filter-map (select-hit result) hits))- (_- (match caches- ((cache rest ...)- (let* ((narinfos (lookup-narinfos cache paths))- (definite (map narinfo-path (filter authorized? narinfos)))- (missing (lset-difference string=? paths definite))) ;XXX: perf- (loop rest missing- (fold vhash-cons result- (map narinfo-path narinfos) narinfos)- (append definite hits))))- (() ;that's it- (filter-map (select-hit result) hits)))))))- (define (lookup-narinfo caches path authorized?) "Return the narinfo for PATH in CACHES, or #f when no substitute for PATH was found."@@ -718,79 +319,6 @@ authorized substitutes." (wtf (error "unknown `--query' command" wtf)))) -(define %max-cached-connections- ;; Maximum number of connections kept in cache by- ;; 'open-connection-for-uri/cached'.- 16)--(define open-connection-for-uri/cached- (let ((cache '()))- (lambda* (uri #:key fresh? timeout verify-certificate?)- "Return a connection for URI, possibly reusing a cached connection.-When FRESH? is true, delete any cached connections for URI and open a new one.-Return #f if URI's scheme is 'file' or #f.--When true, TIMEOUT is the maximum number of milliseconds to wait for-connection establishment. When VERIFY-CERTIFICATE? is true, verify HTTPS-server certificates."- (define host (uri-host uri))- (define scheme (uri-scheme uri))- (define key (list host scheme (uri-port uri)))-- (and (not (memq scheme '(file #f)))- (match (assoc-ref cache key)- (#f- ;; Open a new connection to URI and evict old entries from- ;; CACHE, if any.- (let-values (((socket)- (guix:open-connection-for-uri- uri- #:verify-certificate? verify-certificate?- #:timeout timeout))- ((new-cache evicted)- (at-most (- %max-cached-connections 1) cache)))- (for-each (match-lambda- ((_ . port)- (false-if-exception (close-port port))))- evicted)- (set! cache (alist-cons key socket new-cache))- socket))- (socket- (if (or fresh? (port-closed? socket))- (begin- (false-if-exception (close-port socket))- (set! cache (alist-delete key cache))- (open-connection-for-uri/cached uri #:timeout timeout- #:verify-certificate?- verify-certificate?))- (begin- ;; Drain input left from the previous use.- (drain-input socket)- socket))))))))--(define* (call-with-cached-connection uri proc- #:optional- (open-connection- open-connection-for-uri/cached))- (let ((port (open-connection uri)))- (catch #t- (lambda ()- (proc port))- (lambda (key . args)- ;; If PORT was cached and the server closed the connection in the- ;; meantime, we get EPIPE. In that case, open a fresh connection and- ;; retry. We might also get 'bad-response or a similar exception from- ;; (web response) later on, once we've sent the request.- (if (or (and (eq? key 'system-error)- (= EPIPE (system-error-errno `(,key ,@args))))- (memq key '(bad-response bad-header bad-header-component)))- (proc (open-connection uri #:fresh? #t))- (apply throw key args))))))--(define-syntax-rule (with-cached-connection uri port exp ...)- "Bind PORT with EXP... to a socket connected to URI."- (call-with-cached-connection uri (lambda (port) exp ...)))- (define* (process-substitution store-item destination #:key cache-urls acl deduplicate? print-build-trace?)diff --git a/guix/scripts/weather.scm b/guix/scripts/weather.scmindex 97e4a73802..527a63560d 100644--- a/guix/scripts/weather.scm+++ b/guix/scripts/weather.scm@@ -32,8 +32,8 @@ #:use-module (guix gexp) #:use-module ((guix build syscalls) #:select (terminal-columns)) #:use-module ((guix build utils) #:select (every*))- #:use-module (guix scripts substitute) #:use-module (guix narinfo)+ #:use-module (guix substitutes) #:use-module (guix http-client) #:use-module (guix ci) #:use-module (guix sets)diff --git a/guix/substitutes.scm b/guix/substitutes.scmnew file mode 100644index 0000000000..80942185e6--- /dev/null+++ b/guix/substitutes.scm@@ -0,0 +1,527 @@+;;; GNU Guix --- Functional package management for GNU+;;; Copyright © 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>+;;; Copyright © 2014 Nikita Karetnikov <nikita@karetnikov.org>+;;; Copyright © 2018 Kyle Meyer <kyle@kyleam.com>+;;;+;;; This file is part of GNU Guix.+;;;+;;; GNU Guix is free software; you can redistribute it and/or modify it+;;; under the terms of the GNU General Public License as published by+;;; the Free Software Foundation; either version 3 of the License, or (at+;;; your option) any later version.+;;;+;;; GNU Guix is distributed in the hope that it will be useful, but+;;; WITHOUT ANY WARRANTY; without even the implied warranty of+;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+;;; GNU General Public License for more details.+;;;+;;; You should have received a copy of the GNU General Public License+;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.++(define-module (guix substitutes)+ #:use-module (guix i18n)+ #:use-module (guix cache)+ #:use-module (guix store)+ #:use-module (guix utils)+ #:use-module (guix base32)+ #:use-module (guix config)+ #:use-module (guix narinfo)+ #:use-module (guix combinators)+ #:use-module (guix diagnostics)+ #:use-module ((guix build utils) #:select (mkdir-p dump-port))+ #:use-module ((guix build download)+ #:select ((open-connection-for-uri+ . guix:open-connection-for-uri)))+ #:use-module (gcrypt hash)+ #:use-module (ice-9 match)+ #:use-module (ice-9 vlist)+ #:use-module (ice-9 format)+ #:use-module (ice-9 binary-ports)+ #:use-module (rnrs bytevectors)+ #:use-module (srfi srfi-1)+ #:use-module (srfi srfi-11)+ #:use-module (srfi srfi-19)+ #:use-module (srfi srfi-26)+ #:use-module (web uri)+ #:use-module (web http)+ #:use-module (web request)+ #:use-module (web response)+ #:export (%narinfo-cache-directory++ with-cached-connection++ lookup-narinfos+ lookup-narinfos/diverse))++(define %narinfo-cache-directory+ ;; A local cache of narinfos, to avoid going to the network. Most of the+ ;; time, 'guix substitute' is called by guix-daemon as root and stores its+ ;; cached data in /var/guix/…. However, when invoked from 'guix challenge'+ ;; as a user, it stores its cache in ~/.cache.+ (if (zero? (getuid))+ (or (and=> (getenv "XDG_CACHE_HOME")+ (cut string-append <> "/guix/substitute"))+ (string-append %state-directory "/substitute/cache"))+ (string-append (cache-directory #:ensure? #f) "/substitute")))++(define %narinfo-ttl+ ;; Number of seconds during which cached narinfo lookups are considered+ ;; valid for substitute servers that do not advertise a TTL via the+ ;; 'Cache-Control' response header.+ (* 36 3600))++(define %narinfo-negative-ttl+ ;; Likewise, but for negative lookups---i.e., cached lookup failures (404).+ (* 1 3600))++(define %narinfo-transient-error-ttl+ ;; Likewise, but for transient errors such as 504 ("Gateway timeout").+ (* 10 60))++(define %fetch-timeout+ ;; Number of seconds after which networking is considered "slow".+ 5)++(define (narinfo-cache-file cache-url path)+ "Return the name of the local file that contains an entry for PATH. The+entry is stored in a sub-directory specific to CACHE-URL."+ ;; The daemon does not sanitize its input, so PATH could be something like+ ;; "/gnu/store/foo". Gracefully handle that.+ (match (store-path-hash-part path)+ (#f+ (leave (G_ "'~a' does not name a store item~%") path))+ ((? string? hash-part)+ (string-append %narinfo-cache-directory "/"+ (bytevector->base32-string (sha256 (string->utf8 cache-url)))+ "/" hash-part))))++(define (cache-narinfo! cache-url path narinfo ttl)+ "Cache locally NARNIFO for PATH, which originates from CACHE-URL, with the+given TTL (a number of seconds or #f). NARINFO may be #f, in which case it+indicates that PATH is unavailable at CACHE-URL."+ (define now+ (current-time time-monotonic))++ (define (cache-entry cache-uri narinfo)+ `(narinfo (version 2)+ (cache-uri ,cache-uri)+ (date ,(time-second now))+ (ttl ,(or ttl+ (if narinfo %narinfo-ttl %narinfo-negative-ttl)))+ (value ,(and=> narinfo narinfo->string))))++ (let ((file (narinfo-cache-file cache-url path)))+ (mkdir-p (dirname file))+ (with-atomic-file-output file+ (lambda (out)+ (write (cache-entry cache-url narinfo) out))))++ narinfo)++(define %max-cached-connections+ ;; Maximum number of connections kept in cache by+ ;; 'open-connection-for-uri/cached'.+ 16)++(define open-connection-for-uri/cached+ (let ((cache '()))+ (lambda* (uri #:key fresh? timeout verify-certificate?)+ "Return a connection for URI, possibly reusing a cached connection.+When FRESH? is true, delete any cached connections for URI and open a new one.+Return #f if URI's scheme is 'file' or #f.++When true, TIMEOUT is the maximum number of milliseconds to wait for+connection establishment. When VERIFY-CERTIFICATE? is true, verify HTTPS+server certificates."+ (define host (uri-host uri))+ (define scheme (uri-scheme uri))+ (define key (list host scheme (uri-port uri)))++ (and (not (memq scheme '(file #f)))+ (match (assoc-ref cache key)+ (#f+ ;; Open a new connection to URI and evict old entries from+ ;; CACHE, if any.+ (let-values (((socket)+ (guix:open-connection-for-uri+ uri+ #:verify-certificate? verify-certificate?+ #:timeout timeout))+ ((new-cache evicted)+ (at-most (- %max-cached-connections 1) cache)))+ (for-each (match-lambda+ ((_ . port)+ (false-if-exception (close-port port))))+ evicted)+ (set! cache (alist-cons key socket new-cache))+ socket))+ (socket+ (if (or fresh? (port-closed? socket))+ (begin+ (false-if-exception (close-port socket))+ (set! cache (alist-delete key cache))+ (open-connection-for-uri/cached uri #:timeout timeout+ #:verify-certificate?+ verify-certificate?))+ (begin+ ;; Drain input left from the previous use.+ (drain-input socket)+ socket))))))))++(define* (call-with-cached-connection uri proc+ #:optional+ (open-connection+ open-connection-for-uri/cached))+ (let ((port (open-connection uri)))+ (catch #t+ (lambda ()+ (proc port))+ (lambda (key . args)+ ;; If PORT was cached and the server closed the connection in the+ ;; meantime, we get EPIPE. In that case, open a fresh connection and+ ;; retry. We might also get 'bad-response or a similar exception from+ ;; (web response) later on, once we've sent the request.+ (if (or (and (eq? key 'system-error)+ (= EPIPE (system-error-errno `(,key ,@args))))+ (memq key '(bad-response bad-header bad-header-component)))+ (proc (open-connection uri #:fresh? #t))+ (apply throw key args))))))++(define-syntax-rule (with-cached-connection uri port exp ...)+ "Bind PORT with EXP... to a socket connected to URI."+ (call-with-cached-connection uri (lambda (port) exp ...)))++(define (at-most max-length lst)+ "If LST is shorter than MAX-LENGTH, return it and the empty list; otherwise+return its MAX-LENGTH first elements and its tail."+ (let loop ((len 0)+ (lst lst)+ (result '()))+ (match lst+ (()+ (values (reverse result) '()))+ ((head . tail)+ (if (>= len max-length)+ (values (reverse result) lst)+ (loop (+ 1 len) tail (cons head result)))))))++(define* (http-multiple-get base-uri proc seed requests+ #:key port (verify-certificate? #t)+ (open-connection guix:open-connection-for-uri)+ (keep-alive? #t)+ (batch-size 1000))+ "Send all of REQUESTS to the server at BASE-URI. Call PROC for each+response, passing it the request object, the response, a port from which to+read the response body, and the previous result, starting with SEED, à la+'fold'. Return the final result.++When PORT is specified, use it as the initial connection on which HTTP+requests are sent; otherwise call OPEN-CONNECTION to open a new connection for+a URI. When KEEP-ALIVE? is false, close the connection port before+returning."+ (let connect ((port port)+ (requests requests)+ (result seed))+ (define batch+ (at-most batch-size requests))++ ;; (format (current-error-port) "connecting (~a requests left)..."+ ;; (length requests))+ (let ((p (or port (open-connection base-uri+ #:verify-certificate?+ verify-certificate?))))+ ;; For HTTPS, P is not a file port and does not support 'setvbuf'.+ (when (file-port? p)+ (setvbuf p 'block (expt 2 16)))++ ;; Send BATCH in a row.+ ;; XXX: Do our own caching to work around inefficiencies when+ ;; communicating over TLS: <http://bugs.gnu.org/22966>.+ (let-values (((buffer get) (open-bytevector-output-port)))+ ;; Inherit the HTTP proxying property from P.+ (set-http-proxy-port?! buffer (http-proxy-port? p))++ (for-each (cut write-request <> buffer)+ batch)+ (put-bytevector p (get))+ (force-output p))++ ;; Now start processing responses.+ (let loop ((sent batch)+ (processed 0)+ (result result))+ (match sent+ (()+ (match (drop requests processed)+ (()+ (unless keep-alive?+ (close-port p))+ (reverse result))+ (remainder+ (connect p remainder result))))+ ((head tail ...)+ (let* ((resp (read-response p))+ (body (response-body-port resp))+ (result (proc head resp body result)))+ ;; The server can choose to stop responding at any time, in which+ ;; case we have to try again. Check whether that is the case.+ ;; Note that even upon "Connection: close", we can read from BODY.+ (match (assq 'connection (response-headers resp))+ (('connection 'close)+ (close-port p)+ (connect #f ;try again+ (drop requests (+ 1 processed))+ result))+ (_+ (loop tail (+ 1 processed) result)))))))))) ;keep going++(define %unreachable-hosts+ ;; Set of names of unreachable hosts.+ (make-hash-table))++(define* (open-connection-for-uri/maybe uri+ #:key+ fresh?+ (time %fetch-timeout))+ "Open a connection to URI via 'open-connection-for-uri/cached' and return a+port to it, or, if connection failed, print a warning and return #f. Pass+#:fresh? to 'open-connection-for-uri/cached'."+ (define host+ (uri-host uri))++ (catch #t+ (lambda ()+ (open-connection-for-uri/cached uri #:timeout time+ #:fresh? fresh?))+ (match-lambda*+ (('getaddrinfo-error error)+ (unless (hash-ref %unreachable-hosts host)+ (hash-set! %unreachable-hosts host #t) ;warn only once+ (warning (G_ "~a: host not found: ~a~%")+ host (gai-strerror error)))+ #f)+ (('system-error . args)+ (unless (hash-ref %unreachable-hosts host)+ (hash-set! %unreachable-hosts host #t)+ (warning (G_ "~a: connection failed: ~a~%") host+ (strerror+ (system-error-errno `(system-error ,@args)))))+ #f)+ (args+ (apply throw args)))))++(define (read-to-eof port)+ "Read from PORT until EOF is reached. The data are discarded."+ (dump-port port (%make-void-port "w")))++(define (narinfo-request cache-url path)+ "Return an HTTP request for the narinfo of PATH at CACHE-URL."+ (let ((url (string-append cache-url "/" (store-path-hash-part path)+ ".narinfo"))+ (headers '((User-Agent . "GNU Guile"))))+ (build-request (string->uri url) #:method 'GET #:headers headers)))++(define (narinfo-from-file file url)+ "Attempt to read a narinfo from FILE, using URL as the cache URL. Return #f+if file doesn't exist, and the narinfo otherwise."+ (catch 'system-error+ (lambda ()+ (call-with-input-file file+ (cut read-narinfo <> url)))+ (lambda args+ (if (= ENOENT (system-error-errno args))+ #f+ (apply throw args)))))++(define (fetch-narinfos url paths)+ "Retrieve all the narinfos for PATHS from the cache at URL and return them."+ (define update-progress!+ (let ((done 0)+ (total (length paths)))+ (lambda ()+ (display "\r\x1b[K" (current-error-port)) ;erase current line+ (force-output (current-error-port))+ (format (current-error-port)+ (G_ "updating substitutes from '~a'... ~5,1f%")+ url (* 100. (/ done total)))+ (set! done (+ 1 done)))))++ (define hash-part->path+ (let ((mapping (fold (lambda (path result)+ (vhash-cons (store-path-hash-part path) path+ result))+ vlist-null+ paths)))+ (lambda (hash)+ (match (vhash-assoc hash mapping)+ (#f #f)+ ((_ . path) path)))))++ (define (handle-narinfo-response request response port result)+ (let* ((code (response-code response))+ (len (response-content-length response))+ (cache (response-cache-control response))+ (ttl (and cache (assoc-ref cache 'max-age))))+ (update-progress!)++ ;; Make sure to read no more than LEN bytes since subsequent bytes may+ ;; belong to the next response.+ (if (= code 200) ; hit+ (let ((narinfo (read-narinfo port url #:size len)))+ (if (string=? (dirname (narinfo-path narinfo))+ (%store-prefix))+ (begin+ (cache-narinfo! url (narinfo-path narinfo) narinfo ttl)+ (cons narinfo result))+ result))+ (let* ((path (uri-path (request-uri request)))+ (hash-part (basename+ (string-drop-right path 8)))) ;drop ".narinfo"+ (if len+ (get-bytevector-n port len)+ (read-to-eof port))+ (cache-narinfo! url (hash-part->path hash-part) #f+ (if (or (= 404 code) (= 202 code))+ ttl+ %narinfo-transient-error-ttl))+ result))))++ (define (do-fetch uri)+ (case (and=> uri uri-scheme)+ ((http https)+ ;; Note: Do not check HTTPS server certificates to avoid depending+ ;; on the X.509 PKI. We can do it because we authenticate+ ;; narinfos, which provides a much stronger guarantee.+ (let* ((requests (map (cut narinfo-request url <>) paths))+ (result (call-with-cached-connection uri+ (lambda (port)+ (if port+ (begin+ (update-progress!)+ (http-multiple-get uri+ handle-narinfo-response '()+ requests+ #:open-connection+ open-connection-for-uri/cached+ #:verify-certificate? #f+ #:port port))+ '()))+ open-connection-for-uri/maybe)))+ (newline (current-error-port))+ result))+ ((file #f)+ (let* ((base (string-append (uri-path uri) "/"))+ (files (map (compose (cut string-append base <> ".narinfo")+ store-path-hash-part)+ paths)))+ (filter-map (cut narinfo-from-file <> url) files)))+ (else+ (leave (G_ "~s: unsupported server URI scheme~%")+ (if uri (uri-scheme uri) url)))))++ (do-fetch (string->uri url)))++(define (cached-narinfo cache-url path)+ "Check locally if we have valid info about PATH coming from CACHE-URL.+Return two values: a Boolean indicating whether we have valid cached info, and+that info, which may be either #f (when PATH is unavailable) or the narinfo+for PATH."+ (define now+ (current-time time-monotonic))++ (define cache-file+ (narinfo-cache-file cache-url path))++ (catch 'system-error+ (lambda ()+ (call-with-input-file cache-file+ (lambda (p)+ (match (read p)+ (('narinfo ('version 2)+ ('cache-uri cache-uri)+ ('date date) ('ttl ttl) ('value #f))+ ;; A cached negative lookup.+ (if (obsolete? date now ttl)+ (values #f #f)+ (values #t #f)))+ (('narinfo ('version 2)+ ('cache-uri cache-uri)+ ('date date) ('ttl ttl) ('value value))+ ;; A cached positive lookup+ (if (obsolete? date now ttl)+ (values #f #f)+ (values #t (string->narinfo value cache-uri))))+ (('narinfo ('version v) _ ...)+ (values #f #f))))))+ (lambda _+ (values #f #f))))++(define (lookup-narinfos cache paths)+ "Return the narinfos for PATHS, invoking the server at CACHE when no+information is available locally."+ (let-values (((cached missing)+ (fold2 (lambda (path cached missing)+ (let-values (((valid? value)+ (cached-narinfo cache path)))+ (if valid?+ (if value+ (values (cons value cached) missing)+ (values cached missing))+ (values cached (cons path missing)))))+ '()+ '()+ paths)))+ (if (null? missing)+ cached+ (let ((missing (fetch-narinfos cache missing)))+ (append cached (or missing '()))))))++(define (lookup-narinfos/diverse caches paths authorized?)+ "Look up narinfos for PATHS on all of CACHES, a list of URLS, in that order.+That is, when a cache lacks an AUTHORIZED? narinfo, look it up in the next+cache, and so on.++Return a list of narinfos for PATHS or a subset thereof. The returned+narinfos are either AUTHORIZED?, or they claim a hash that matches an+AUTHORIZED? narinfo."+ (define (select-hit result)+ (lambda (path)+ (match (vhash-fold* cons '() path result)+ ((one)+ one)+ ((several ..1)+ (let ((authorized (find authorized? (reverse several))))+ (and authorized+ (find (cut equivalent-narinfo? <> authorized)+ several)))))))++ (let loop ((caches caches)+ (paths paths)+ (result vlist-null) ;path->narinfo vhash+ (hits '())) ;paths+ (match paths+ (() ;we're done+ ;; Now iterate on all the HITS, and return exactly one match for each+ ;; hit: the first narinfo that is authorized, or that has the same hash+ ;; as an authorized narinfo, in the order of CACHES.+ (filter-map (select-hit result) hits))+ (_+ (match caches+ ((cache rest ...)+ (let* ((narinfos (lookup-narinfos cache paths))+ (definite (map narinfo-path (filter authorized? narinfos)))+ (missing (lset-difference string=? paths definite))) ;XXX: perf+ (loop rest missing+ (fold vhash-cons result+ (map narinfo-path narinfos) narinfos)+ (append definite hits))))+ (() ;that's it+ (filter-map (select-hit result) hits)))))))++;;; Local Variables:+;;; eval: (put 'with-timeout 'scheme-indent-function 1)+;;; eval: (put 'with-cached-connection 'scheme-indent-function 2)+;;; eval: (put 'call-with-cached-connection 'scheme-indent-function 1)+;;; End:++;;; substitutes.scm ends herediff --git a/po/guix/POTFILES.in b/po/guix/POTFILES.inindex 666e630adf..fa397d7969 100644--- a/po/guix/POTFILES.in+++ b/po/guix/POTFILES.in@@ -88,6 +88,7 @@ guix/status.scm guix/http-client.scm guix/nar.scm guix/narinfo.scm+guix/substitutes.scm guix/channels.scm guix/profiles.scm guix/git.scm-- 2.29.2
C
C
Christopher Baines wrote on 3 Jan 19:16 +0100
Re: [bug#45409] [PATCH 1/3] guix: Move narinfo code from substitute script to module.
(name . Ludovic Courtès)(address . ludo@gnu.org)(address . 45409@debbugs.gnu.org)
87turx998y.fsf@cbaines.net
Ludovic Courtès <ludo@gnu.org> writes:
Toggle quote (24 lines)> Christopher Baines <mail@cbaines.net> skribis:>>> This separation between the code for dealing with narinfos from the code doing>> that for a purpose should make things clearer, and better support components>> other that the substitute script in using this code.>>>> This is just moving the code around, no code should have been significantly>> changed.>>>> * guix/scripts/substitute.scm (<narinfo>): Move record type to (guix narinfo).>> (fields->alist, narinfo-hash-algorithm+value, narinfo-hash->sha256,>> narinfo-signature->canonical-sexp, narinfo-maker, read-narinfo,>> narinfo-sha256, valid-narinfo?, write-narinfo, narinfo->string,>> string->narinfo, equivalent-narinfo?, supported-compression?,>> compresses-better?, narinfo-best-uri): Move procedures to (guix narinfo).>> (%compression-methods): Move variable to (guix narinfo).>> * guix/narinfo.scm: New file.>> * Makefile.am (MODULES): Add it.>> That’s a good idea!>> Please add guix/narinfo.scm to po/guix/POTFILES.in so it can be> translated.
I've sent some updated patches now, and I've fixed this in them.
Toggle quote (5 lines)>> +(define-module (guix narinfo)>> + #:use-module (guix ui)>> We should try and avoid (guix ui); is (guix diagnostics) enough?
Yep, that seems to work fine.
Toggle quote (9 lines)>> + #:use-module (guix scripts substitute)>> (guix …) modules must not depend on (guix scripts …).>> Perhaps that’s just for ‘%allow-unauthenticated-substitutes?’, no? If> so, let’s just not refer to ‘%allow-unauthenticated-substitutes?’ here.> It’s a hack to allow for tests, so better keep it local to (guix scripts> substitute).
I've moved the commit where I fix this to be the first one, so thisshould be clearer now.
Toggle quote (14 lines)>> +(define* (valid-narinfo? narinfo #:optional (acl (current-acl))>> + #:key verbose?)>> + "Return #t if NARINFO's signature is not valid.">> + (or (%allow-unauthenticated-substitutes?)>> Yeah, let’s remove it from here. At worst, we can always use ‘mock’ in> tests to make ‘valid-narinfo?’ return #t unconditionally.>> OK with these changes.>> After the change, please make sure “make check” and “make as-derivation”> still pass. For “make as-derivation”, we should also make sure> ‘guix-core’ doesn’t pull in everything via (guix scripts substitute).
Both seem to work for me.
Toggle quote (3 lines)> (The zstd patches will conflict with this series but I’ll take care of> it once it’s applied.)
Sounds good.
-----BEGIN PGP SIGNATURE-----
iQKlBAEBCgCPFiEEPonu50WOcg2XVOCyXiijOwuE9XcFAl/yCe1fFIAAAAAALgAoaXNzdWVyLWZwckBub3RhdGlvbnMub3BlbnBncC5maWZ0aGhvcnNlbWFuLm5ldDNFODlFRUU3NDU4RTcyMEQ5NzU0RTBCMjVFMjhBMzNCMEI4NEY1NzcRHG1haWxAY2JhaW5lcy5uZXQACgkQXiijOwuE9XdFeBAAgOEpwej4smaUvF8TdgtTLG1W90vw0FONxGsSRoznjwaFwiSeaT/RhJ7Fzq2T9Kn1ypt+Uz+KVDamYzxF++pjszkbS4YkNORLS6Tm2vmTktSZ71/dssEwmW+X+a+VvOkExvv0AKif+5zFELn4Tu9vZ5I9gz6JB0yuSGvD2VeNYuKIrnOOKFiNaoLuxhRMLcz3MpqUkSdgGm1mnqKAuzmHB3alROICSVNAPaYys23uumiFSWqbYh/i2EPC1yhL/+mkm5sivctDoTPyNJX6sl15zDdnbPiuGEEoMhSIPw/RK6iHz2Q0IiF4kvf7yK3UQq9WTBDZngX2u4zUe8UzmdN2xB3/y7JA0efVTBvYsfuqFwL0Iq2vp57MqmgNlf5Pv7PWDAqJ151cl80+oMNMvJcGethJj0ZwhXcxnYHzTBenJQ3JyBoN3AOoweVmGF1ES3zXDRnlGN/V4jON+wZn7EloHkvL24uN0lSu/1Smpe7cBMXc0CfEjC0NX5KNriKUX0+0lEB0v6Y5uDZfOocGYloMlMIjWDzubrFYb5O2I90OSZxu1/U62eciz1rDmx3m2GpK9bIS0Nh3CeQMulKI6D53jw5a4TmBJoIirYL+PO4Vq+taC3UmlDcWXWsrREAvCyJwjs30iE6flEkrlSX2LMRA+umTsRGL9xtkYsh0xm/ugXs==banI-----END PGP SIGNATURE-----
C
C
Christopher Baines wrote on 3 Jan 19:19 +0100
Re: [bug#45409] [PATCH 3/3] guix: Split (guix substitute) from (guix scripts substitute).
(name . Ludovic Courtès)(address . ludo@gnu.org)(address . 45409@debbugs.gnu.org)
87r1n1993l.fsf@cbaines.net
Ludovic Courtès <ludo@gnu.org> writes:
Toggle quote (20 lines)> Hi,>> Christopher Baines <mail@cbaines.net> skribis:>>> This means there's a module for working with substitutes, rather than all the>> code sitting in the script. The need for this can be seen with the weather and>> challenge scripts, that now don't have to use code from the substitute script,>> but can instead use the substitute module.>>>> The separation here between the actual functionality of the substitute script>> and the underlying functionality used both there and elsewhere should make>> maintenance easier moving forward.>>>> This commit just moves code, none of the code should have been changed>> significantly.>> It would still be nice to list the identifiers that were moved in the> commit log, it’s boring :-) but it can be helpful when browsing the> history.
Sure, I've done that now, I'd got bored by this point before.
Toggle quote (3 lines)> As for the split, I wouldn’t put as much into (guix substitutes) (I’d> use “substitutes”, plural, for consistency with most other modules.)
Done.
Toggle quote (7 lines)> As a rule of thumb, I would keep in (guix scripts substitute) anything> that’s very much biased towards a single short-lived process: connection> cache, host name resolution failure cache, etc. These things are a bit> hacky and not designed for use as a library. They’re also very much> policy rather than mechanism, and as such they don’t belong in a proper> library IMO.
I think that's fine, but it's harder said than done. I think theconnection caching and host name resolution failure caching code wouldneed unpicking from the general substitute fetching code, and I haven'tattempted to do that yet.
Toggle quote (9 lines)>> -(define* (http-multiple-get base-uri proc seed requests>> - #:key port (verify-certificate? #t)>> - (open-connection guix:open-connection-for-uri)>> - (keep-alive? #t)>> - (batch-size 1000))>> How about moving this one to (guix http-client), as a separate patch?> I think it’s a better fit and could be useful elsewhere.
Sure, that sounds good, I'll look at it later with a separate patch.
-----BEGIN PGP SIGNATURE-----
iQKlBAEBCgCPFiEEPonu50WOcg2XVOCyXiijOwuE9XcFAl/yCq5fFIAAAAAALgAoaXNzdWVyLWZwckBub3RhdGlvbnMub3BlbnBncC5maWZ0aGhvcnNlbWFuLm5ldDNFODlFRUU3NDU4RTcyMEQ5NzU0RTBCMjVFMjhBMzNCMEI4NEY1NzcRHG1haWxAY2JhaW5lcy5uZXQACgkQXiijOwuE9Xfoig//S4ZjMTWa03WY4nJMp7mDcZyARD4fFm4ckv68rqYN5Ye011fQYZdTl3gGzUOc2/cR0da95OnRcM7j5P/8C6LBssMEVgJdiodue6QYA8fo6GSBsg73AZ2PjnivQy5HTPwUOIJfsUQAWIYZPb1xpgQFN2CBO2EnjphODEdwAHBpLua2Y63euLoteuLK1/pMA6yqMxXxz5BlYRNKsdVsfWkkBXOE8oFU339/zlBh30AMYfXDhd+ty2988JaoCXYj1jiLfBH4yohV33v79UbLEoNQxKGbTGWQcG/lqWDNJy9sJDBlhqPOT70eSxm0/4VBbLaBOcRk1eG4zSMm/aikCB1MUnHfz9aZcwsVGIFwRo+vk7WJ3ZLpFQVHW9QoH3p4oXIKrL/SEkYabya50zLZqW8cPqQC9amvnruXJWImOtwQ1qikTufyVOp92970atxUGkID6P/kqDm+yNOVYHc6vI1p/xwpAaFIrv0LxZQmt13flLbt/ECFDTnEDFJBhjIxYAPCbwsgByEymEgngBTVWvLuum48x+74oI+ITh+v8+q3/AFg1744PS8cebY3Ao+xEz806kgqqT9B6dkKRdSM860znHQNF7ls/ugRaG2Otl6qj3aLDhqIH+4mrP0uhMGFAoPIv+ED3giJNWsmlv9R2rsYI/0cth+NP2FMCEKtZD/upj8==TZRo-----END PGP SIGNATURE-----
C
C
Christopher Baines wrote on 4 Jan 22:19 +0100
[PATCH v3 1/3] substitute: Untangle skipping authentication from valid-narinfo?.
(address . 45409@debbugs.gnu.org)
20210104211927.14959-1-mail@cbaines.net
Rather than having valid-narinfo? evaluate to #t if%allow-unauthenticated-substitutes? is set to #t, just use (const #t) forvalid-narinfo? when %allow-unauthenticated-substitutes? is set to #t. Thiswill allow moving valid-narinfo? in to a (guix substitutes) module.
* guix/scripts/substitute.scm (process-query, process-substitution): Changethe authorized? argument to lookup-narinfo and lookup-narinfos/diverse basedon %allow-unauthenticated-substitutes?.(valid-narinfo?): Remove use of %allow-unauthenticated-substitutes?.--- guix/scripts/substitute.scm | 77 ++++++++++++++++++++----------------- 1 file changed, 41 insertions(+), 36 deletions(-)
Toggle diff (113 lines)diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex e53de8c304..14fb848880 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -2,6 +2,7 @@ ;;; Copyright © 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org> ;;; Copyright © 2014 Nikita Karetnikov <nikita@karetnikov.org> ;;; Copyright © 2018 Kyle Meyer <kyle@kyleam.com>+;;; Copyright © 2020 Christopher Baines <mail@cbaines.net> ;;; ;;; This file is part of GNU Guix. ;;;@@ -375,38 +376,37 @@ No authentication and authorization checks are performed here!" (define* (valid-narinfo? narinfo #:optional (acl (current-acl)) #:key verbose?) "Return #t if NARINFO's signature is not valid."- (or (%allow-unauthenticated-substitutes?)- (let ((hash (narinfo-sha256 narinfo))- (signature (narinfo-signature narinfo))- (uri (uri->string (first (narinfo-uris narinfo)))))- (and hash signature- (signature-case (signature hash acl)- (valid-signature #t)- (invalid-signature- (when verbose?- (format (current-error-port)- "invalid signature for substitute at '~a'~%"- uri))- #f)- (hash-mismatch- (when verbose?- (format (current-error-port)- "hash mismatch for substitute at '~a'~%"- uri))- #f)- (unauthorized-key- (when verbose?- (format (current-error-port)- "substitute at '~a' is signed by an \+ (let ((hash (narinfo-sha256 narinfo))+ (signature (narinfo-signature narinfo))+ (uri (uri->string (first (narinfo-uris narinfo)))))+ (and hash signature+ (signature-case (signature hash acl)+ (valid-signature #t)+ (invalid-signature+ (when verbose?+ (format (current-error-port)+ "invalid signature for substitute at '~a'~%"+ uri))+ #f)+ (hash-mismatch+ (when verbose?+ (format (current-error-port)+ "hash mismatch for substitute at '~a'~%"+ uri))+ #f)+ (unauthorized-key+ (when verbose?+ (format (current-error-port)+ "substitute at '~a' is signed by an \ unauthorized party~%"- uri))- #f)- (corrupt-signature- (when verbose?- (format (current-error-port)- "corrupt signature for substitute at '~a'~%"- uri))- #f))))))+ uri))+ #f)+ (corrupt-signature+ (when verbose?+ (format (current-error-port)+ "corrupt signature for substitute at '~a'~%"+ uri))+ #f))))) (define (write-narinfo narinfo port) "Write NARINFO to PORT."@@ -918,11 +918,14 @@ expected by the daemon." "Reply to COMMAND, a query as written by the daemon to this process's standard input. Use ACL as the access-control list against which to check authorized substitutes."- (define (valid? obj)- (valid-narinfo? obj acl))+ (define valid?+ (if (%allow-unauthenticated-substitutes?)+ (begin+ (warn-about-missing-authentication) - (when (%allow-unauthenticated-substitutes?)- (warn-about-missing-authentication))+ (const #t))+ (lambda (obj)+ (valid-narinfo? obj acl)))) (match (string-tokenize command) (("have" paths ..1)@@ -1079,7 +1082,9 @@ DESTINATION is in the store, deduplicate its files. Print a status line on the current output port." (define narinfo (lookup-narinfo cache-urls store-item- (cut valid-narinfo? <> acl)))+ (if (%allow-unauthenticated-substitutes?)+ (const #t)+ (cut valid-narinfo? <> acl)))) (define destination-in-store? (string-prefix? (string-append (%store-prefix) "/")-- 2.29.2
C
C
Christopher Baines wrote on 4 Jan 22:19 +0100
[PATCH v3 2/3] guix: Move narinfo code from substitute script to module.
(address . 45409@debbugs.gnu.org)
20210104211927.14959-2-mail@cbaines.net
This separation between the code for dealing with narinfos from the code doingthat for a purpose should make things clearer, and better support componentsother that the substitute script in using this code.
This is just moving the code around, no code should have been significantlychanged.
* guix/scripts/substitute.scm (<narinfo>): Move record type to (guix narinfo).(fields->alist, narinfo-hash-algorithm+value, narinfo-hash->sha256,narinfo-signature->canonical-sexp, narinfo-maker, read-narinfo,narinfo-sha256, valid-narinfo?, write-narinfo, narinfo->string,string->narinfo, equivalent-narinfo?, supported-compression?,compresses-better?, narinfo-best-uri): Move procedures to (guix narinfo).(%compression-methods): Move variable to (guix narinfo).* guix/narinfo.scm: New file.* Makefile.am (MODULES): Add it.* po/guix/POTFILES.in: Add 'guix/narinfo.scm'.--- Makefile.am | 1 + guix/narinfo.scm | 324 ++++++++++++++++++++++++++++++++++++ guix/scripts/challenge.scm | 1 + guix/scripts/substitute.scm | 281 +------------------------------ guix/scripts/weather.scm | 1 + po/guix/POTFILES.in | 1 + tests/challenge.scm | 2 +- tests/substitute.scm | 1 + 8 files changed, 332 insertions(+), 280 deletions(-) create mode 100644 guix/narinfo.scm
Toggle diff (734 lines)diff --git a/Makefile.am b/Makefile.amindex aec2bb1474..69166a2ea1 100644--- a/Makefile.am+++ b/Makefile.am@@ -103,6 +103,7 @@ MODULES = \ guix/profiles.scm \ guix/serialization.scm \ guix/nar.scm \+ guix/narinfo.scm \ guix/derivations.scm \ guix/grafts.scm \ guix/repl.scm \diff --git a/guix/narinfo.scm b/guix/narinfo.scmnew file mode 100644index 0000000000..5965758bff--- /dev/null+++ b/guix/narinfo.scm@@ -0,0 +1,324 @@+;;; GNU Guix --- Functional package management for GNU+;;; Copyright © 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>+;;; Copyright © 2014 Nikita Karetnikov <nikita@karetnikov.org>+;;; Copyright © 2018 Kyle Meyer <kyle@kyleam.com>+;;;+;;; This file is part of GNU Guix.+;;;+;;; GNU Guix is free software; you can redistribute it and/or modify it+;;; under the terms of the GNU General Public License as published by+;;; the Free Software Foundation; either version 3 of the License, or (at+;;; your option) any later version.+;;;+;;; GNU Guix is distributed in the hope that it will be useful, but+;;; WITHOUT ANY WARRANTY; without even the implied warranty of+;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+;;; GNU General Public License for more details.+;;;+;;; You should have received a copy of the GNU General Public License+;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.++(define-module (guix narinfo)+ #:use-module (guix pki)+ #:use-module (guix i18n)+ #:use-module (guix base32)+ #:use-module (guix base64)+ #:use-module (guix records)+ #:use-module (guix diagnostics)+ #:use-module (guix scripts substitute)+ #:use-module (gcrypt hash)+ #:use-module (gcrypt pk-crypto)+ #:use-module (rnrs bytevectors)+ #:use-module (srfi srfi-1)+ #:use-module (srfi srfi-9)+ #:use-module (srfi srfi-26)+ #:use-module (ice-9 match)+ #:use-module (ice-9 binary-ports)+ #:use-module (web uri)+ #:export (narinfo-signature->canonical-sexp++ narinfo?+ narinfo-path+ narinfo-uris+ narinfo-uri-base+ narinfo-compressions+ narinfo-file-hashes+ narinfo-file-sizes+ narinfo-hash+ narinfo-size+ narinfo-references+ narinfo-deriver+ narinfo-system+ narinfo-signature++ narinfo-hash-algorithm+value++ narinfo-hash->sha256+ narinfo-best-uri++ valid-narinfo?++ read-narinfo+ write-narinfo++ string->narinfo+ narinfo->string++ equivalent-narinfo?))++(define-record-type <narinfo>+ (%make-narinfo path uri-base uris compressions file-sizes file-hashes+ nar-hash nar-size references deriver system+ signature contents)+ narinfo?+ (path narinfo-path)+ (uri-base narinfo-uri-base) ;URI of the cache it originates from+ (uris narinfo-uris) ;list of strings+ (compressions narinfo-compressions) ;list of strings+ (file-sizes narinfo-file-sizes) ;list of (integers | #f)+ (file-hashes narinfo-file-hashes)+ (nar-hash narinfo-hash)+ (nar-size narinfo-size)+ (references narinfo-references)+ (deriver narinfo-deriver)+ (system narinfo-system)+ (signature narinfo-signature) ; canonical sexp+ ;; The original contents of a narinfo file. This field is needed because we+ ;; want to preserve the exact textual representation for verification purposes.+ ;; See <https://lists.gnu.org/archive/html/guix-devel/2014-02/msg00340.html>+ ;; for more information.+ (contents narinfo-contents))++(define (narinfo-hash-algorithm+value narinfo)+ "Return two values: the hash algorithm used by NARINFO and its value as a+bytevector."+ (match (string-tokenize (narinfo-hash narinfo)+ (char-set-complement (char-set #\:)))+ ((algorithm base32)+ (values (lookup-hash-algorithm (string->symbol algorithm))+ (nix-base32-string->bytevector base32)))+ (_+ (raise (formatted-message+ (G_ "invalid narinfo hash: ~s") (narinfo-hash narinfo))))))++(define (narinfo-hash->sha256 hash)+ "If the string HASH denotes a sha256 hash, return it as a bytevector.+Otherwise return #f."+ (and (string-prefix? "sha256:" hash)+ (nix-base32-string->bytevector (string-drop hash 7))))++(define (narinfo-signature->canonical-sexp str)+ "Return the value of a narinfo's 'Signature' field as a canonical sexp."+ (match (string-split str #\;)+ ((version host-name sig)+ (let ((maybe-number (string->number version)))+ (cond ((not (number? maybe-number))+ (leave (G_ "signature version must be a number: ~s~%")+ version))+ ;; Currently, there are no other versions.+ ((not (= 1 maybe-number))+ (leave (G_ "unsupported signature version: ~a~%")+ maybe-number))+ (else+ (let ((signature (utf8->string (base64-decode sig))))+ (catch 'gcry-error+ (lambda ()+ (string->canonical-sexp signature))+ (lambda (key proc err)+ (leave (G_ "signature is not a valid \+s-expression: ~s~%")+ signature))))))))+ (x+ (leave (G_ "invalid format of the signature field: ~a~%") x))))++(define (narinfo-maker str cache-url)+ "Return a narinfo constructor for narinfos originating from CACHE-URL. STR+must contain the original contents of a narinfo file."+ (lambda (path urls compressions file-hashes file-sizes+ nar-hash nar-size references deriver system+ signature)+ "Return a new <narinfo> object."+ (define len (length urls))+ (%make-narinfo path cache-url+ ;; Handle the case where URL is a relative URL.+ (map (lambda (url)+ (or (string->uri url)+ (string->uri+ (string-append cache-url "/" url))))+ urls)+ compressions+ (match file-sizes+ (() (make-list len #f))+ ((lst ...) (map string->number lst)))+ (match file-hashes+ (() (make-list len #f))+ ((lst ...) (map string->number lst)))+ nar-hash+ (and=> nar-size string->number)+ (string-tokenize references)+ (match deriver+ ((or #f "") #f)+ (_ deriver))+ system+ (false-if-exception+ (and=> signature narinfo-signature->canonical-sexp))+ str)))++(define fields->alist+ ;; The narinfo format is really just like recutils.+ recutils->alist)++(define* (read-narinfo port #:optional url+ #:key size)+ "Read a narinfo from PORT. If URL is true, it must be a string used to+build full URIs from relative URIs found while reading PORT. When SIZE is+true, read at most SIZE bytes from PORT; otherwise, read as much as possible.++No authentication and authorization checks are performed here!"+ (let ((str (utf8->string (if size+ (get-bytevector-n port size)+ (get-bytevector-all port)))))+ (alist->record (call-with-input-string str fields->alist)+ (narinfo-maker str url)+ '("StorePath" "URL" "Compression"+ "FileHash" "FileSize" "NarHash" "NarSize"+ "References" "Deriver" "System"+ "Signature")+ '("URL" "Compression" "FileSize" "FileHash"))))++(define (narinfo-sha256 narinfo)+ "Return the sha256 hash of NARINFO as a bytevector, or #f if NARINFO lacks a+'Signature' field."+ (define %mandatory-fields+ ;; List of fields that must be signed. If they are not signed, the+ ;; narinfo is considered unsigned.+ '("StorePath" "NarHash" "References"))++ (let ((contents (narinfo-contents narinfo)))+ (match (string-contains contents "Signature:")+ (#f #f)+ (index+ (let* ((above-signature (string-take contents index))+ (signed-fields (match (call-with-input-string above-signature+ fields->alist)+ (((fields . values) ...) fields))))+ (and (every (cut member <> signed-fields) %mandatory-fields)+ (sha256 (string->utf8 above-signature))))))))++(define* (valid-narinfo? narinfo #:optional (acl (current-acl))+ #:key verbose?)+ "Return #t if NARINFO's signature is not valid."+ (let ((hash (narinfo-sha256 narinfo))+ (signature (narinfo-signature narinfo))+ (uri (uri->string (first (narinfo-uris narinfo)))))+ (and hash signature+ (signature-case (signature hash acl)+ (valid-signature #t)+ (invalid-signature+ (when verbose?+ (format (current-error-port)+ "invalid signature for substitute at '~a'~%"+ uri))+ #f)+ (hash-mismatch+ (when verbose?+ (format (current-error-port)+ "hash mismatch for substitute at '~a'~%"+ uri))+ #f)+ (unauthorized-key+ (when verbose?+ (format (current-error-port)+ "substitute at '~a' is signed by an \+unauthorized party~%"+ uri))+ #f)+ (corrupt-signature+ (when verbose?+ (format (current-error-port)+ "corrupt signature for substitute at '~a'~%"+ uri))+ #f)))))++(define (write-narinfo narinfo port)+ "Write NARINFO to PORT."+ (put-bytevector port (string->utf8 (narinfo-contents narinfo))))++(define (narinfo->string narinfo)+ "Return the external representation of NARINFO."+ (call-with-output-string (cut write-narinfo narinfo <>)))++(define (string->narinfo str cache-uri)+ "Return the narinfo represented by STR. Assume CACHE-URI as the base URI of+the cache STR originates form."+ (call-with-input-string str (cut read-narinfo <> cache-uri)))++(define (equivalent-narinfo? narinfo1 narinfo2)+ "Return true if NARINFO1 and NARINFO2 are equivalent--i.e., if they describe+the same store item. This ignores unnecessary metadata such as the Nar URL."+ (and (string=? (narinfo-hash narinfo1)+ (narinfo-hash narinfo2))++ ;; The following is not needed if all we want is to download a valid+ ;; nar, but it's necessary if we want valid narinfo.+ (string=? (narinfo-path narinfo1)+ (narinfo-path narinfo2))+ (equal? (narinfo-references narinfo1)+ (narinfo-references narinfo2))++ (= (narinfo-size narinfo1)+ (narinfo-size narinfo2))))++(define %compression-methods+ ;; Known compression methods and a thunk to determine whether they're+ ;; supported. See 'decompressed-port' in (guix utils).+ `(("gzip" . ,(const #t))+ ("lzip" . ,(const #t))+ ("xz" . ,(const #t))+ ("bzip2" . ,(const #t))+ ("none" . ,(const #t))))++(define (supported-compression? compression)+ "Return true if COMPRESSION, a string, denotes a supported compression+method."+ (match (assoc-ref %compression-methods compression)+ (#f #f)+ (supported? (supported?))))++(define (compresses-better? compression1 compression2)+ "Return true if COMPRESSION1 generally compresses better than COMPRESSION2;+this is a rough approximation."+ (match compression1+ ("none" #f)+ ("gzip" (string=? compression2 "none"))+ (_ (or (string=? compression2 "none")+ (string=? compression2 "gzip")))))++(define (narinfo-best-uri narinfo)+ "Select the \"best\" URI to download NARINFO's nar, and return three values:+the URI, its compression method (a string), and the compressed file size."+ (define choices+ (filter (match-lambda+ ((uri compression file-size)+ (supported-compression? compression)))+ (zip (narinfo-uris narinfo)+ (narinfo-compressions narinfo)+ (narinfo-file-sizes narinfo))))++ (define (file-size<? c1 c2)+ (match c1+ ((uri1 compression1 (? integer? file-size1))+ (match c2+ ((uri2 compression2 (? integer? file-size2))+ (< file-size1 file-size2))+ (_ #t)))+ ((uri compression1 #f)+ (match c2+ ((uri2 compression2 _)+ (compresses-better? compression1 compression2))))+ (_ #f))) ;we can't tell++ (match (sort choices file-size<?)+ (((uri compression file-size) _ ...)+ (values uri compression file-size))))+diff --git a/guix/scripts/challenge.scm b/guix/scripts/challenge.scmindex d0a456ac1d..cc9cbe6f27 100644--- a/guix/scripts/challenge.scm+++ b/guix/scripts/challenge.scm@@ -28,6 +28,7 @@ #:use-module ((guix progress) #:hide (dump-port*)) #:use-module (guix serialization) #:use-module (guix scripts substitute)+ #:use-module (guix narinfo) #:use-module (rnrs bytevectors) #:autoload (guix http-client) (http-fetch) #:use-module ((guix build syscalls) #:select (terminal-columns))diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex 14fb848880..f9bcead045 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -22,6 +22,7 @@ (define-module (guix scripts substitute) #:use-module (guix ui) #:use-module (guix scripts)+ #:use-module (guix narinfo) #:use-module (guix store) #:use-module (guix utils) #:use-module (guix combinators)@@ -68,29 +69,8 @@ #:use-module (web request) #:use-module (web response) #:use-module (guix http-client)- #:export (narinfo-signature->canonical-sexp-- narinfo?- narinfo-path- narinfo-uris- narinfo-uri-base- narinfo-compressions- narinfo-file-hashes- narinfo-file-sizes- narinfo-hash- narinfo-size- narinfo-references- narinfo-deriver- narinfo-system- narinfo-signature-- narinfo-hash->sha256- narinfo-best-uri-- lookup-narinfos+ #:export (lookup-narinfos lookup-narinfos/diverse- read-narinfo- write-narinfo %allow-unauthenticated-substitutes? %error-to-file-descriptor-4?@@ -150,10 +130,6 @@ disabled!~%")) ;; How often we want to remove files corresponding to expired cache entries. (* 7 24 3600)) -(define fields->alist- ;; The narinfo format is really just like recutils.- recutils->alist)- (define %fetch-timeout ;; Number of seconds after which networking is considered "slow". 5)@@ -237,190 +213,6 @@ connection (typically PORT) is kept open once data has been fetched from URI." (leave (G_ "unsupported substitute URI scheme: ~a~%") (uri->string uri))))) - -(define-record-type <narinfo>- (%make-narinfo path uri-base uris compressions file-sizes file-hashes- nar-hash nar-size references deriver system- signature contents)- narinfo?- (path narinfo-path)- (uri-base narinfo-uri-base) ;URI of the cache it originates from- (uris narinfo-uris) ;list of strings- (compressions narinfo-compressions) ;list of strings- (file-sizes narinfo-file-sizes) ;list of (integers | #f)- (file-hashes narinfo-file-hashes)- (nar-hash narinfo-hash)- (nar-size narinfo-size)- (references narinfo-references)- (deriver narinfo-deriver)- (system narinfo-system)- (signature narinfo-signature) ; canonical sexp- ;; The original contents of a narinfo file. This field is needed because we- ;; want to preserve the exact textual representation for verification purposes.- ;; See <https://lists.gnu.org/archive/html/guix-devel/2014-02/msg00340.html>- ;; for more information.- (contents narinfo-contents))--(define (narinfo-hash-algorithm+value narinfo)- "Return two values: the hash algorithm used by NARINFO and its value as a-bytevector."- (match (string-tokenize (narinfo-hash narinfo)- (char-set-complement (char-set #\:)))- ((algorithm base32)- (values (lookup-hash-algorithm (string->symbol algorithm))- (nix-base32-string->bytevector base32)))- (_- (raise (formatted-message- (G_ "invalid narinfo hash: ~s") (narinfo-hash narinfo))))))--(define (narinfo-hash->sha256 hash)- "If the string HASH denotes a sha256 hash, return it as a bytevector.-Otherwise return #f."- (and (string-prefix? "sha256:" hash)- (nix-base32-string->bytevector (string-drop hash 7))))--(define (narinfo-signature->canonical-sexp str)- "Return the value of a narinfo's 'Signature' field as a canonical sexp."- (match (string-split str #\;)- ((version host-name sig)- (let ((maybe-number (string->number version)))- (cond ((not (number? maybe-number))- (leave (G_ "signature version must be a number: ~s~%")- version))- ;; Currently, there are no other versions.- ((not (= 1 maybe-number))- (leave (G_ "unsupported signature version: ~a~%")- maybe-number))- (else- (let ((signature (utf8->string (base64-decode sig))))- (catch 'gcry-error- (lambda ()- (string->canonical-sexp signature))- (lambda (key proc err)- (leave (G_ "signature is not a valid \-s-expression: ~s~%")- signature))))))))- (x- (leave (G_ "invalid format of the signature field: ~a~%") x))))--(define (narinfo-maker str cache-url)- "Return a narinfo constructor for narinfos originating from CACHE-URL. STR-must contain the original contents of a narinfo file."- (lambda (path urls compressions file-hashes file-sizes- nar-hash nar-size references deriver system- signature)- "Return a new <narinfo> object."- (define len (length urls))- (%make-narinfo path cache-url- ;; Handle the case where URL is a relative URL.- (map (lambda (url)- (or (string->uri url)- (string->uri- (string-append cache-url "/" url))))- urls)- compressions- (match file-sizes- (() (make-list len #f))- ((lst ...) (map string->number lst)))- (match file-hashes- (() (make-list len #f))- ((lst ...) (map string->number lst)))- nar-hash- (and=> nar-size string->number)- (string-tokenize references)- (match deriver- ((or #f "") #f)- (_ deriver))- system- (false-if-exception- (and=> signature narinfo-signature->canonical-sexp))- str)))--(define* (read-narinfo port #:optional url- #:key size)- "Read a narinfo from PORT. If URL is true, it must be a string used to-build full URIs from relative URIs found while reading PORT. When SIZE is-true, read at most SIZE bytes from PORT; otherwise, read as much as possible.--No authentication and authorization checks are performed here!"- (let ((str (utf8->string (if size- (get-bytevector-n port size)- (get-bytevector-all port)))))- (alist->record (call-with-input-string str fields->alist)- (narinfo-maker str url)- '("StorePath" "URL" "Compression"- "FileHash" "FileSize" "NarHash" "NarSize"- "References" "Deriver" "System"- "Signature")- '("URL" "Compression" "FileSize" "FileHash"))))--(define (narinfo-sha256 narinfo)- "Return the sha256 hash of NARINFO as a bytevector, or #f if NARINFO lacks a-'Signature' field."- (define %mandatory-fields- ;; List of fields that must be signed. If they are not signed, the- ;; narinfo is considered unsigned.- '("StorePath" "NarHash" "References"))-- (let ((contents (narinfo-contents narinfo)))- (match (string-contains contents "Signature:")- (#f #f)- (index- (let* ((above-signature (string-take contents index))- (signed-fields (match (call-with-input-string above-signature- fields->alist)- (((fields . values) ...) fields))))- (and (every (cut member <> signed-fields) %mandatory-fields)- (sha256 (string->utf8 above-signature))))))))--(define* (valid-narinfo? narinfo #:optional (acl (current-acl))- #:key verbose?)- "Return #t if NARINFO's signature is not valid."- (let ((hash (narinfo-sha256 narinfo))- (signature (narinfo-signature narinfo))- (uri (uri->string (first (narinfo-uris narinfo)))))- (and hash signature- (signature-case (signature hash acl)- (valid-signature #t)- (invalid-signature- (when verbose?- (format (current-error-port)- "invalid signature for substitute at '~a'~%"- uri))- #f)- (hash-mismatch- (when verbose?- (format (current-error-port)- "hash mismatch for substitute at '~a'~%"- uri))- #f)- (unauthorized-key- (when verbose?- (format (current-error-port)- "substitute at '~a' is signed by an \-unauthorized party~%"- uri))- #f)- (corrupt-signature- (when verbose?- (format (current-error-port)- "corrupt signature for substitute at '~a'~%"- uri))- #f)))))--(define (write-narinfo narinfo port)- "Write NARINFO to PORT."- (put-bytevector port (string->utf8 (narinfo-contents narinfo))))--(define (narinfo->string narinfo)- "Return the external representation of NARINFO."- (call-with-output-string (cut write-narinfo narinfo <>)))--(define (string->narinfo str cache-uri)- "Return the narinfo represented by STR. Assume CACHE-URI as the base URI of-the cache STR originates form."- (call-with-input-string str (cut read-narinfo <> cache-uri)))- (define (narinfo-cache-file cache-url path) "Return the name of the local file that contains an entry for PATH. The entry is stored in a sub-directory specific to CACHE-URL."@@ -742,22 +534,6 @@ information is available locally." (let ((missing (fetch-narinfos cache missing))) (append cached (or missing '())))))) -(define (equivalent-narinfo? narinfo1 narinfo2)- "Return true if NARINFO1 and NARINFO2 are equivalent--i.e., if they describe-the same store item. This ignores unnecessary metadata such as the Nar URL."- (and (string=? (narinfo-hash narinfo1)- (narinfo-hash narinfo2))-- ;; The following is not needed if all we want is to download a valid- ;; nar, but it's necessary if we want valid narinfo.- (string=? (narinfo-path narinfo1)- (narinfo-path narinfo2))- (equal? (narinfo-references narinfo1)- (narinfo-references narinfo2))-- (= (narinfo-size narinfo1)- (narinfo-size narinfo2))))- (define (lookup-narinfos/diverse caches paths authorized?) "Look up narinfos for PATHS on all of CACHES, a list of URLS, in that order. That is, when a cache lacks an AUTHORIZED? narinfo, look it up in the next@@ -943,59 +719,6 @@ authorized substitutes." (wtf (error "unknown `--query' command" wtf)))) -(define %compression-methods- ;; Known compression methods and a thunk to determine whether they're- ;; supported. See 'decompressed-port' in (guix utils).- `(("gzip" . ,(const #t))- ("lzip" . ,(const #t))- ("xz" . ,(const #t))- ("bzip2" . ,(const #t))- ("none" . ,(const #t))))--(define (supported-compression? compression)- "Return true if COMPRESSION, a string, denotes a supported compression-method."- (match (assoc-ref %compression-methods compression)- (#f #f)- (supported? (supported?))))--(define (compresses-better? compression1 compression2)- "Return true if COMPRESSION1 generally compresses better than COMPRESSION2;-this is a rough approximation."- (match compression1- ("none" #f)- ("gzip" (string=? compression2 "none"))- (_ (or (string=? compression2 "none")- (string=? compression2 "gzip")))))--(define (narinfo-best-uri narinfo)- "Select the \"best\" URI to download NARINFO's nar, and return three values:-the URI, its compression method (a string), and the compressed file size."- (define choices- (filter (match-lambda- ((uri compression file-size)- (supported-compression? compression)))- (zip (narinfo-uris narinfo)- (narinfo-compressions narinfo)- (narinfo-file-sizes narinfo))))-- (define (file-size<? c1 c2)- (match c1- ((uri1 compression1 (? integer? file-size1))- (match c2- ((uri2 compression2 (? integer? file-size2))- (< file-size1 file-size2))- (_ #t)))- ((uri compression1 #f)- (match c2- ((uri2 compression2 _)- (compresses-better? compression1 compression2))))- (_ #f))) ;we can't tell-- (match (sort choices file-size<?)- (((uri compression file-size) _ ...)- (values uri compression file-size))))- (define %max-cached-connections ;; Maximum number of connections kept in cache by ;; 'open-connection-for-uri/cached'.diff --git a/guix/scripts/weather.scm b/guix/scripts/weather.scmindex f28070ddc4..97e4a73802 100644--- a/guix/scripts/weather.scm+++ b/guix/scripts/weather.scm@@ -33,6 +33,7 @@ #:use-module ((guix build syscalls) #:select (terminal-columns)) #:use-module ((guix build utils) #:select (every*)) #:use-module (guix scripts substitute)+ #:use-module (guix narinfo) #:use-module (guix http-client) #:use-module (guix ci) #:use-module (guix sets)diff --git a/po/guix/POTFILES.in b/po/guix/POTFILES.inindex 1aec3bef3c..666e630adf 100644--- a/po/guix/POTFILES.in+++ b/po/guix/POTFILES.in@@ -87,6 +87,7 @@ guix/ui.scm guix/status.scm guix/http-client.scm guix/nar.scm+guix/narinfo.scm guix/channels.scm guix/profiles.scm guix/git.scmdiff --git a/tests/challenge.scm b/tests/challenge.scmindex 9c6d6e0d58..fdd5fd238e 100644--- a/tests/challenge.scm+++ b/tests/challenge.scm@@ -27,8 +27,8 @@ #:use-module (guix packages) #:use-module (guix gexp) #:use-module (guix base32)+ #:use-module (guix narinfo) #:use-module (guix scripts challenge)- #:use-module (guix scripts substitute) #:use-module ((guix build utils) #:select (find-files)) #:use-module (gnu packages bootstrap) #:use-module (srfi srfi-1)diff --git a/tests/substitute.scm b/tests/substitute.scmindex 542aaf603f..697abc4684 100644--- a/tests/substitute.scm+++ b/tests/substitute.scm@@ -19,6 +19,7 @@ (define-module (test-substitute) #:use-module (guix scripts substitute)+ #:use-module (guix narinfo) #:use-module (guix base64) #:use-module (gcrypt hash) #:use-module (guix serialization)-- 2.29.2
C
C
Christopher Baines wrote on 4 Jan 22:19 +0100
[PATCH v3 3/3] guix: Split (guix substitutes) from (guix scripts substitute).
(address . 45409@debbugs.gnu.org)
20210104211927.14959-3-mail@cbaines.net
This means there's a module for working with substitutes, rather than all thecode sitting in the script. The need for this can be seen with the weather andchallenge scripts, that now don't have to use code from the substitute script,but can instead use the substitute module.
The separation here between the actual functionality of the substitute scriptand the underlying functionality used both there and elsewhere should makemaintenance easier moving forward.
This commit just moves code, none of the code should have been changedsignificantly.
* guix/scripts/substitute.scm (%narinfo-cache-directory, %narinfo-ttl,%narinfo-negative-ttl, %narinfo-transient-error-ttl, %unreachable-hosts,%max-cached-connections): Move variables to (guix substitutes).(narinfo-cache-file, cached-narinfo, cache-narinfo!, narinfo-request, at-most,http-multiple-get, read-to-eof, narinfo-from-file,open-connection-for-uri/maybe, fetch-narinfos, lookup-narinfos,lookup-narinfos/diverse, open-connection-for-uri/cached,call-with-cached-connection): Move procedures to (guix substitutes).(with-cached-connection): Move syntax rule to (guix substitutes).* guix/substitutes.scm: New file.* Makefile.am (MODULES): Add it.* po/guix/POTFILES.in: Add 'guix/substitutes.scm'.--- Makefile.am | 1 + guix/scripts/challenge.scm | 2 +- guix/scripts/substitute.scm | 486 +-------------------------------- guix/scripts/weather.scm | 2 +- guix/substitutes.scm | 531 ++++++++++++++++++++++++++++++++++++ po/guix/POTFILES.in | 1 + 6 files changed, 540 insertions(+), 483 deletions(-) create mode 100644 guix/substitutes.scm
Toggle diff (1143 lines)diff --git a/Makefile.am b/Makefile.amindex 69166a2ea1..fe39eae53c 100644--- a/Makefile.am+++ b/Makefile.am@@ -89,6 +89,7 @@ MODULES = \ guix/memoization.scm \ guix/utils.scm \ guix/sets.scm \+ guix/substitutes.scm \ guix/modules.scm \ guix/download.scm \ guix/discovery.scm \diff --git a/guix/scripts/challenge.scm b/guix/scripts/challenge.scmindex cc9cbe6f27..74cf163937 100644--- a/guix/scripts/challenge.scm+++ b/guix/scripts/challenge.scm@@ -27,8 +27,8 @@ #:use-module (guix packages) #:use-module ((guix progress) #:hide (dump-port*)) #:use-module (guix serialization)- #:use-module (guix scripts substitute) #:use-module (guix narinfo)+ #:use-module (guix substitutes) #:use-module (rnrs bytevectors) #:autoload (guix http-client) (http-fetch) #:use-module ((guix build syscalls) #:select (terminal-columns))diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex f9bcead045..45c07b1038 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -23,39 +23,30 @@ #:use-module (guix ui) #:use-module (guix scripts) #:use-module (guix narinfo)+ #:use-module (guix substitutes) #:use-module (guix store) #:use-module (guix utils)- #:use-module (guix combinators)- #:use-module (guix config)- #:use-module (guix records)- #:use-module (guix diagnostics) #:use-module (guix i18n) #:use-module ((guix serialization) #:select (restore-file dump-file)) #:autoload (guix store deduplication) (dump-file/deduplicate) #:autoload (guix scripts discover) (read-substitute-urls) #:use-module (gcrypt hash) #:use-module (guix base32)- #:use-module (guix base64) #:use-module (guix cache) #:use-module (gcrypt pk-crypto) #:use-module (guix pki)- #:use-module ((guix build utils) #:select (mkdir-p dump-port))+ #:use-module ((guix build utils) #:select (mkdir-p)) #:use-module ((guix build download)- #:select (uri-abbreviation nar-uri-abbreviation+ #:select (nar-uri-abbreviation (open-connection-for-uri- . guix:open-connection-for-uri)- store-path-abbreviation byte-count->string))- #:autoload (gnutls) (error/invalid-session)+ . guix:open-connection-for-uri))) #:use-module (guix progress) #:use-module ((guix build syscalls) #:select (set-thread-name)) #:use-module (ice-9 rdelim)- #:use-module (ice-9 regex) #:use-module (ice-9 match) #:use-module (ice-9 format) #:use-module (ice-9 ftw)- #:use-module (ice-9 binary-ports)- #:use-module (ice-9 vlist) #:use-module (rnrs bytevectors) #:use-module (srfi srfi-1) #:use-module (srfi srfi-9)@@ -69,10 +60,7 @@ #:use-module (web request) #:use-module (web response) #:use-module (guix http-client)- #:export (lookup-narinfos- lookup-narinfos/diverse-- %allow-unauthenticated-substitutes?+ #:export (%allow-unauthenticated-substitutes? %error-to-file-descriptor-4? substitute-urls@@ -89,17 +77,6 @@ ;;; ;;; Code: -(define %narinfo-cache-directory- ;; A local cache of narinfos, to avoid going to the network. Most of the- ;; time, 'guix substitute' is called by guix-daemon as root and stores its- ;; cached data in /var/guix/…. However, when invoked from 'guix challenge'- ;; as a user, it stores its cache in ~/.cache.- (if (zero? (getuid))- (or (and=> (getenv "XDG_CACHE_HOME")- (cut string-append <> "/guix/substitute"))- (string-append %state-directory "/substitute/cache"))- (string-append (cache-directory #:ensure? #f) "/substitute")))- (define (warn-about-missing-authentication) (warning (G_ "authentication and authorization of substitutes \ disabled!~%"))@@ -112,20 +89,6 @@ disabled!~%")) (and=> (getenv "GUIX_ALLOW_UNAUTHENTICATED_SUBSTITUTES") (cut string-ci=? <> "yes")))) -(define %narinfo-ttl- ;; Number of seconds during which cached narinfo lookups are considered- ;; valid for substitute servers that do not advertise a TTL via the- ;; 'Cache-Control' response header.- (* 36 3600))--(define %narinfo-negative-ttl- ;; Likewise, but for negative lookups---i.e., cached lookup failures (404).- (* 1 3600))--(define %narinfo-transient-error-ttl- ;; Likewise, but for transient errors such as 504 ("Gateway timeout").- (* 10 60))- (define %narinfo-expired-cache-entry-removal-delay ;; How often we want to remove files corresponding to expired cache entries. (* 7 24 3600))@@ -213,369 +176,6 @@ connection (typically PORT) is kept open once data has been fetched from URI." (leave (G_ "unsupported substitute URI scheme: ~a~%") (uri->string uri))))) -(define (narinfo-cache-file cache-url path)- "Return the name of the local file that contains an entry for PATH. The-entry is stored in a sub-directory specific to CACHE-URL."- ;; The daemon does not sanitize its input, so PATH could be something like- ;; "/gnu/store/foo". Gracefully handle that.- (match (store-path-hash-part path)- (#f- (leave (G_ "'~a' does not name a store item~%") path))- ((? string? hash-part)- (string-append %narinfo-cache-directory "/"- (bytevector->base32-string (sha256 (string->utf8 cache-url)))- "/" hash-part))))--(define (cached-narinfo cache-url path)- "Check locally if we have valid info about PATH coming from CACHE-URL.-Return two values: a Boolean indicating whether we have valid cached info, and-that info, which may be either #f (when PATH is unavailable) or the narinfo-for PATH."- (define now- (current-time time-monotonic))-- (define cache-file- (narinfo-cache-file cache-url path))-- (catch 'system-error- (lambda ()- (call-with-input-file cache-file- (lambda (p)- (match (read p)- (('narinfo ('version 2)- ('cache-uri cache-uri)- ('date date) ('ttl ttl) ('value #f))- ;; A cached negative lookup.- (if (obsolete? date now ttl)- (values #f #f)- (values #t #f)))- (('narinfo ('version 2)- ('cache-uri cache-uri)- ('date date) ('ttl ttl) ('value value))- ;; A cached positive lookup- (if (obsolete? date now ttl)- (values #f #f)- (values #t (string->narinfo value cache-uri))))- (('narinfo ('version v) _ ...)- (values #f #f))))))- (lambda _- (values #f #f))))--(define (cache-narinfo! cache-url path narinfo ttl)- "Cache locally NARNIFO for PATH, which originates from CACHE-URL, with the-given TTL (a number of seconds or #f). NARINFO may be #f, in which case it-indicates that PATH is unavailable at CACHE-URL."- (define now- (current-time time-monotonic))-- (define (cache-entry cache-uri narinfo)- `(narinfo (version 2)- (cache-uri ,cache-uri)- (date ,(time-second now))- (ttl ,(or ttl- (if narinfo %narinfo-ttl %narinfo-negative-ttl)))- (value ,(and=> narinfo narinfo->string))))-- (let ((file (narinfo-cache-file cache-url path)))- (mkdir-p (dirname file))- (with-atomic-file-output file- (lambda (out)- (write (cache-entry cache-url narinfo) out))))-- narinfo)--(define (narinfo-request cache-url path)- "Return an HTTP request for the narinfo of PATH at CACHE-URL."- (let ((url (string-append cache-url "/" (store-path-hash-part path)- ".narinfo"))- (headers '((User-Agent . "GNU Guile"))))- (build-request (string->uri url) #:method 'GET #:headers headers)))--(define (at-most max-length lst)- "If LST is shorter than MAX-LENGTH, return it and the empty list; otherwise-return its MAX-LENGTH first elements and its tail."- (let loop ((len 0)- (lst lst)- (result '()))- (match lst- (()- (values (reverse result) '()))- ((head . tail)- (if (>= len max-length)- (values (reverse result) lst)- (loop (+ 1 len) tail (cons head result)))))))--(define* (http-multiple-get base-uri proc seed requests- #:key port (verify-certificate? #t)- (open-connection guix:open-connection-for-uri)- (keep-alive? #t)- (batch-size 1000))- "Send all of REQUESTS to the server at BASE-URI. Call PROC for each-response, passing it the request object, the response, a port from which to-read the response body, and the previous result, starting with SEED, à la-'fold'. Return the final result.--When PORT is specified, use it as the initial connection on which HTTP-requests are sent; otherwise call OPEN-CONNECTION to open a new connection for-a URI. When KEEP-ALIVE? is false, close the connection port before-returning."- (let connect ((port port)- (requests requests)- (result seed))- (define batch- (at-most batch-size requests))-- ;; (format (current-error-port) "connecting (~a requests left)..."- ;; (length requests))- (let ((p (or port (open-connection base-uri- #:verify-certificate?- verify-certificate?))))- ;; For HTTPS, P is not a file port and does not support 'setvbuf'.- (when (file-port? p)- (setvbuf p 'block (expt 2 16)))-- ;; Send BATCH in a row.- ;; XXX: Do our own caching to work around inefficiencies when- ;; communicating over TLS: <http://bugs.gnu.org/22966>.- (let-values (((buffer get) (open-bytevector-output-port)))- ;; Inherit the HTTP proxying property from P.- (set-http-proxy-port?! buffer (http-proxy-port? p))-- (for-each (cut write-request <> buffer)- batch)- (put-bytevector p (get))- (force-output p))-- ;; Now start processing responses.- (let loop ((sent batch)- (processed 0)- (result result))- (match sent- (()- (match (drop requests processed)- (()- (unless keep-alive?- (close-port p))- (reverse result))- (remainder- (connect p remainder result))))- ((head tail ...)- (let* ((resp (read-response p))- (body (response-body-port resp))- (result (proc head resp body result)))- ;; The server can choose to stop responding at any time, in which- ;; case we have to try again. Check whether that is the case.- ;; Note that even upon "Connection: close", we can read from BODY.- (match (assq 'connection (response-headers resp))- (('connection 'close)- (close-port p)- (connect #f ;try again- (drop requests (+ 1 processed))- result))- (_- (loop tail (+ 1 processed) result)))))))))) ;keep going--(define (read-to-eof port)- "Read from PORT until EOF is reached. The data are discarded."- (dump-port port (%make-void-port "w")))--(define (narinfo-from-file file url)- "Attempt to read a narinfo from FILE, using URL as the cache URL. Return #f-if file doesn't exist, and the narinfo otherwise."- (catch 'system-error- (lambda ()- (call-with-input-file file- (cut read-narinfo <> url)))- (lambda args- (if (= ENOENT (system-error-errno args))- #f- (apply throw args)))))--(define %unreachable-hosts- ;; Set of names of unreachable hosts.- (make-hash-table))--(define* (open-connection-for-uri/maybe uri- #:key- fresh?- (time %fetch-timeout))- "Open a connection to URI via 'open-connection-for-uri/cached' and return a-port to it, or, if connection failed, print a warning and return #f. Pass-#:fresh? to 'open-connection-for-uri/cached'."- (define host- (uri-host uri))-- (catch #t- (lambda ()- (open-connection-for-uri/cached uri #:timeout time- #:fresh? fresh?))- (match-lambda*- (('getaddrinfo-error error)- (unless (hash-ref %unreachable-hosts host)- (hash-set! %unreachable-hosts host #t) ;warn only once- (warning (G_ "~a: host not found: ~a~%")- host (gai-strerror error)))- #f)- (('system-error . args)- (unless (hash-ref %unreachable-hosts host)- (hash-set! %unreachable-hosts host #t)- (warning (G_ "~a: connection failed: ~a~%") host- (strerror- (system-error-errno `(system-error ,@args)))))- #f)- (args- (apply throw args)))))--(define (fetch-narinfos url paths)- "Retrieve all the narinfos for PATHS from the cache at URL and return them."- (define update-progress!- (let ((done 0)- (total (length paths)))- (lambda ()- (display "\r\x1b[K" (current-error-port)) ;erase current line- (force-output (current-error-port))- (format (current-error-port)- (G_ "updating substitutes from '~a'... ~5,1f%")- url (* 100. (/ done total)))- (set! done (+ 1 done)))))-- (define hash-part->path- (let ((mapping (fold (lambda (path result)- (vhash-cons (store-path-hash-part path) path- result))- vlist-null- paths)))- (lambda (hash)- (match (vhash-assoc hash mapping)- (#f #f)- ((_ . path) path)))))-- (define (handle-narinfo-response request response port result)- (let* ((code (response-code response))- (len (response-content-length response))- (cache (response-cache-control response))- (ttl (and cache (assoc-ref cache 'max-age))))- (update-progress!)-- ;; Make sure to read no more than LEN bytes since subsequent bytes may- ;; belong to the next response.- (if (= code 200) ; hit- (let ((narinfo (read-narinfo port url #:size len)))- (if (string=? (dirname (narinfo-path narinfo))- (%store-prefix))- (begin- (cache-narinfo! url (narinfo-path narinfo) narinfo ttl)- (cons narinfo result))- result))- (let* ((path (uri-path (request-uri request)))- (hash-part (basename- (string-drop-right path 8)))) ;drop ".narinfo"- (if len- (get-bytevector-n port len)- (read-to-eof port))- (cache-narinfo! url (hash-part->path hash-part) #f- (if (or (= 404 code) (= 202 code))- ttl- %narinfo-transient-error-ttl))- result))))-- (define (do-fetch uri)- (case (and=> uri uri-scheme)- ((http https)- ;; Note: Do not check HTTPS server certificates to avoid depending- ;; on the X.509 PKI. We can do it because we authenticate- ;; narinfos, which provides a much stronger guarantee.- (let* ((requests (map (cut narinfo-request url <>) paths))- (result (call-with-cached-connection uri- (lambda (port)- (if port- (begin- (update-progress!)- (http-multiple-get uri- handle-narinfo-response '()- requests- #:open-connection- open-connection-for-uri/cached- #:verify-certificate? #f- #:port port))- '()))- open-connection-for-uri/maybe)))- (newline (current-error-port))- result))- ((file #f)- (let* ((base (string-append (uri-path uri) "/"))- (files (map (compose (cut string-append base <> ".narinfo")- store-path-hash-part)- paths)))- (filter-map (cut narinfo-from-file <> url) files)))- (else- (leave (G_ "~s: unsupported server URI scheme~%")- (if uri (uri-scheme uri) url)))))-- (do-fetch (string->uri url)))--(define (lookup-narinfos cache paths)- "Return the narinfos for PATHS, invoking the server at CACHE when no-information is available locally."- (let-values (((cached missing)- (fold2 (lambda (path cached missing)- (let-values (((valid? value)- (cached-narinfo cache path)))- (if valid?- (if value- (values (cons value cached) missing)- (values cached missing))- (values cached (cons path missing)))))- '()- '()- paths)))- (if (null? missing)- cached- (let ((missing (fetch-narinfos cache missing)))- (append cached (or missing '()))))))--(define (lookup-narinfos/diverse caches paths authorized?)- "Look up narinfos for PATHS on all of CACHES, a list of URLS, in that order.-That is, when a cache lacks an AUTHORIZED? narinfo, look it up in the next-cache, and so on.--Return a list of narinfos for PATHS or a subset thereof. The returned-narinfos are either AUTHORIZED?, or they claim a hash that matches an-AUTHORIZED? narinfo."- (define (select-hit result)- (lambda (path)- (match (vhash-fold* cons '() path result)- ((one)- one)- ((several ..1)- (let ((authorized (find authorized? (reverse several))))- (and authorized- (find (cut equivalent-narinfo? <> authorized)- several)))))))-- (let loop ((caches caches)- (paths paths)- (result vlist-null) ;path->narinfo vhash- (hits '())) ;paths- (match paths- (() ;we're done- ;; Now iterate on all the HITS, and return exactly one match for each- ;; hit: the first narinfo that is authorized, or that has the same hash- ;; as an authorized narinfo, in the order of CACHES.- (filter-map (select-hit result) hits))- (_- (match caches- ((cache rest ...)- (let* ((narinfos (lookup-narinfos cache paths))- (definite (map narinfo-path (filter authorized? narinfos)))- (missing (lset-difference string=? paths definite))) ;XXX: perf- (loop rest missing- (fold vhash-cons result- (map narinfo-path narinfos) narinfos)- (append definite hits))))- (() ;that's it- (filter-map (select-hit result) hits)))))))- (define (lookup-narinfo caches path authorized?) "Return the narinfo for PATH in CACHES, or #f when no substitute for PATH was found."@@ -719,82 +319,6 @@ authorized substitutes." (wtf (error "unknown `--query' command" wtf)))) -(define %max-cached-connections- ;; Maximum number of connections kept in cache by- ;; 'open-connection-for-uri/cached'.- 16)--(define open-connection-for-uri/cached- (let ((cache '()))- (lambda* (uri #:key fresh? timeout verify-certificate?)- "Return a connection for URI, possibly reusing a cached connection.-When FRESH? is true, delete any cached connections for URI and open a new one.-Return #f if URI's scheme is 'file' or #f.--When true, TIMEOUT is the maximum number of milliseconds to wait for-connection establishment. When VERIFY-CERTIFICATE? is true, verify HTTPS-server certificates."- (define host (uri-host uri))- (define scheme (uri-scheme uri))- (define key (list host scheme (uri-port uri)))-- (and (not (memq scheme '(file #f)))- (match (assoc-ref cache key)- (#f- ;; Open a new connection to URI and evict old entries from- ;; CACHE, if any.- (let-values (((socket)- (guix:open-connection-for-uri- uri- #:verify-certificate? verify-certificate?- #:timeout timeout))- ((new-cache evicted)- (at-most (- %max-cached-connections 1) cache)))- (for-each (match-lambda- ((_ . port)- (false-if-exception (close-port port))))- evicted)- (set! cache (alist-cons key socket new-cache))- socket))- (socket- (if (or fresh? (port-closed? socket))- (begin- (false-if-exception (close-port socket))- (set! cache (alist-delete key cache))- (open-connection-for-uri/cached uri #:timeout timeout- #:verify-certificate?- verify-certificate?))- (begin- ;; Drain input left from the previous use.- (drain-input socket)- socket))))))))--(define* (call-with-cached-connection uri proc- #:optional- (open-connection- open-connection-for-uri/cached))- (let ((port (open-connection uri)))- (catch #t- (lambda ()- (proc port))- (lambda (key . args)- ;; If PORT was cached and the server closed the connection in the- ;; meantime, we get EPIPE. In that case, open a fresh connection and- ;; retry. We might also get 'bad-response or a similar exception from- ;; (web response) later on, once we've sent the request, or a- ;; ERROR/INVALID-SESSION from GnuTLS.- (if (or (and (eq? key 'system-error)- (= EPIPE (system-error-errno `(,key ,@args))))- (and (eq? key 'gnutls-error)- (eq? (first args) error/invalid-session))- (memq key '(bad-response bad-header bad-header-component)))- (proc (open-connection uri #:fresh? #t))- (apply throw key args))))))--(define-syntax-rule (with-cached-connection uri port exp ...)- "Bind PORT with EXP... to a socket connected to URI."- (call-with-cached-connection uri (lambda (port) exp ...)))- (define* (process-substitution store-item destination #:key cache-urls acl deduplicate? print-build-trace?)diff --git a/guix/scripts/weather.scm b/guix/scripts/weather.scmindex 97e4a73802..527a63560d 100644--- a/guix/scripts/weather.scm+++ b/guix/scripts/weather.scm@@ -32,8 +32,8 @@ #:use-module (guix gexp) #:use-module ((guix build syscalls) #:select (terminal-columns)) #:use-module ((guix build utils) #:select (every*))- #:use-module (guix scripts substitute) #:use-module (guix narinfo)+ #:use-module (guix substitutes) #:use-module (guix http-client) #:use-module (guix ci) #:use-module (guix sets)diff --git a/guix/substitutes.scm b/guix/substitutes.scmnew file mode 100644index 0000000000..7c2012d307--- /dev/null+++ b/guix/substitutes.scm@@ -0,0 +1,531 @@+;;; GNU Guix --- Functional package management for GNU+;;; Copyright © 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>+;;; Copyright © 2014 Nikita Karetnikov <nikita@karetnikov.org>+;;; Copyright © 2018 Kyle Meyer <kyle@kyleam.com>+;;;+;;; This file is part of GNU Guix.+;;;+;;; GNU Guix is free software; you can redistribute it and/or modify it+;;; under the terms of the GNU General Public License as published by+;;; the Free Software Foundation; either version 3 of the License, or (at+;;; your option) any later version.+;;;+;;; GNU Guix is distributed in the hope that it will be useful, but+;;; WITHOUT ANY WARRANTY; without even the implied warranty of+;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+;;; GNU General Public License for more details.+;;;+;;; You should have received a copy of the GNU General Public License+;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.++(define-module (guix substitutes)+ #:use-module (guix i18n)+ #:use-module (guix cache)+ #:use-module (guix store)+ #:use-module (guix utils)+ #:use-module (guix base32)+ #:use-module (guix config)+ #:use-module (guix narinfo)+ #:use-module (guix combinators)+ #:use-module (guix diagnostics)+ #:use-module ((guix build utils) #:select (mkdir-p dump-port))+ #:use-module ((guix build download)+ #:select ((open-connection-for-uri+ . guix:open-connection-for-uri)))+ #:autoload (gnutls) (error/invalid-session)+ #:use-module (gcrypt hash)+ #:use-module (ice-9 match)+ #:use-module (ice-9 vlist)+ #:use-module (ice-9 format)+ #:use-module (ice-9 binary-ports)+ #:use-module (rnrs bytevectors)+ #:use-module (srfi srfi-1)+ #:use-module (srfi srfi-11)+ #:use-module (srfi srfi-19)+ #:use-module (srfi srfi-26)+ #:use-module (web uri)+ #:use-module (web http)+ #:use-module (web request)+ #:use-module (web response)+ #:export (%narinfo-cache-directory++ with-cached-connection++ lookup-narinfos+ lookup-narinfos/diverse))++(define %narinfo-cache-directory+ ;; A local cache of narinfos, to avoid going to the network. Most of the+ ;; time, 'guix substitute' is called by guix-daemon as root and stores its+ ;; cached data in /var/guix/…. However, when invoked from 'guix challenge'+ ;; as a user, it stores its cache in ~/.cache.+ (if (zero? (getuid))+ (or (and=> (getenv "XDG_CACHE_HOME")+ (cut string-append <> "/guix/substitute"))+ (string-append %state-directory "/substitute/cache"))+ (string-append (cache-directory #:ensure? #f) "/substitute")))++(define %narinfo-ttl+ ;; Number of seconds during which cached narinfo lookups are considered+ ;; valid for substitute servers that do not advertise a TTL via the+ ;; 'Cache-Control' response header.+ (* 36 3600))++(define %narinfo-negative-ttl+ ;; Likewise, but for negative lookups---i.e., cached lookup failures (404).+ (* 1 3600))++(define %narinfo-transient-error-ttl+ ;; Likewise, but for transient errors such as 504 ("Gateway timeout").+ (* 10 60))++(define %fetch-timeout+ ;; Number of seconds after which networking is considered "slow".+ 5)++(define (narinfo-cache-file cache-url path)+ "Return the name of the local file that contains an entry for PATH. The+entry is stored in a sub-directory specific to CACHE-URL."+ ;; The daemon does not sanitize its input, so PATH could be something like+ ;; "/gnu/store/foo". Gracefully handle that.+ (match (store-path-hash-part path)+ (#f+ (leave (G_ "'~a' does not name a store item~%") path))+ ((? string? hash-part)+ (string-append %narinfo-cache-directory "/"+ (bytevector->base32-string (sha256 (string->utf8 cache-url)))+ "/" hash-part))))++(define (cache-narinfo! cache-url path narinfo ttl)+ "Cache locally NARNIFO for PATH, which originates from CACHE-URL, with the+given TTL (a number of seconds or #f). NARINFO may be #f, in which case it+indicates that PATH is unavailable at CACHE-URL."+ (define now+ (current-time time-monotonic))++ (define (cache-entry cache-uri narinfo)+ `(narinfo (version 2)+ (cache-uri ,cache-uri)+ (date ,(time-second now))+ (ttl ,(or ttl+ (if narinfo %narinfo-ttl %narinfo-negative-ttl)))+ (value ,(and=> narinfo narinfo->string))))++ (let ((file (narinfo-cache-file cache-url path)))+ (mkdir-p (dirname file))+ (with-atomic-file-output file+ (lambda (out)+ (write (cache-entry cache-url narinfo) out))))++ narinfo)++(define %max-cached-connections+ ;; Maximum number of connections kept in cache by+ ;; 'open-connection-for-uri/cached'.+ 16)++(define open-connection-for-uri/cached+ (let ((cache '()))+ (lambda* (uri #:key fresh? timeout verify-certificate?)+ "Return a connection for URI, possibly reusing a cached connection.+When FRESH? is true, delete any cached connections for URI and open a new one.+Return #f if URI's scheme is 'file' or #f.++When true, TIMEOUT is the maximum number of milliseconds to wait for+connection establishment. When VERIFY-CERTIFICATE? is true, verify HTTPS+server certificates."+ (define host (uri-host uri))+ (define scheme (uri-scheme uri))+ (define key (list host scheme (uri-port uri)))++ (and (not (memq scheme '(file #f)))+ (match (assoc-ref cache key)+ (#f+ ;; Open a new connection to URI and evict old entries from+ ;; CACHE, if any.+ (let-values (((socket)+ (guix:open-connection-for-uri+ uri+ #:verify-certificate? verify-certificate?+ #:timeout timeout))+ ((new-cache evicted)+ (at-most (- %max-cached-connections 1) cache)))+ (for-each (match-lambda+ ((_ . port)+ (false-if-exception (close-port port))))+ evicted)+ (set! cache (alist-cons key socket new-cache))+ socket))+ (socket+ (if (or fresh? (port-closed? socket))+ (begin+ (false-if-exception (close-port socket))+ (set! cache (alist-delete key cache))+ (open-connection-for-uri/cached uri #:timeout timeout+ #:verify-certificate?+ verify-certificate?))+ (begin+ ;; Drain input left from the previous use.+ (drain-input socket)+ socket))))))))++(define* (call-with-cached-connection uri proc+ #:optional+ (open-connection+ open-connection-for-uri/cached))+ (let ((port (open-connection uri)))+ (catch #t+ (lambda ()+ (proc port))+ (lambda (key . args)+ ;; If PORT was cached and the server closed the connection in the+ ;; meantime, we get EPIPE. In that case, open a fresh connection and+ ;; retry. We might also get 'bad-response or a similar exception from+ ;; (web response) later on, once we've sent the request, or a+ ;; ERROR/INVALID-SESSION from GnuTLS.+ (if (or (and (eq? key 'system-error)+ (= EPIPE (system-error-errno `(,key ,@args))))+ (and (eq? key 'gnutls-error)+ (eq? (first args) error/invalid-session))+ (memq key '(bad-response bad-header bad-header-component)))+ (proc (open-connection uri #:fresh? #t))+ (apply throw key args))))))++(define-syntax-rule (with-cached-connection uri port exp ...)+ "Bind PORT with EXP... to a socket connected to URI."+ (call-with-cached-connection uri (lambda (port) exp ...)))++(define (at-most max-length lst)+ "If LST is shorter than MAX-LENGTH, return it and the empty list; otherwise+return its MAX-LENGTH first elements and its tail."+ (let loop ((len 0)+ (lst lst)+ (result '()))+ (match lst+ (()+ (values (reverse result) '()))+ ((head . tail)+ (if (>= len max-length)+ (values (reverse result) lst)+ (loop (+ 1 len) tail (cons head result)))))))++(define* (http-multiple-get base-uri proc seed requests+ #:key port (verify-certificate? #t)+ (open-connection guix:open-connection-for-uri)+ (keep-alive? #t)+ (batch-size 1000))+ "Send all of REQUESTS to the server at BASE-URI. Call PROC for each+response, passing it the request object, the response, a port from which to+read the response body, and the previous result, starting with SEED, à la+'fold'. Return the final result.++When PORT is specified, use it as the initial connection on which HTTP+requests are sent; otherwise call OPEN-CONNECTION to open a new connection for+a URI. When KEEP-ALIVE? is false, close the connection port before+returning."+ (let connect ((port port)+ (requests requests)+ (result seed))+ (define batch+ (at-most batch-size requests))++ ;; (format (current-error-port) "connecting (~a requests left)..."+ ;; (length requests))+ (let ((p (or port (open-connection base-uri+ #:verify-certificate?+ verify-certificate?))))+ ;; For HTTPS, P is not a file port and does not support 'setvbuf'.+ (when (file-port? p)+ (setvbuf p 'block (expt 2 16)))++ ;; Send BATCH in a row.+ ;; XXX: Do our own caching to work around inefficiencies when+ ;; communicating over TLS: <http://bugs.gnu.org/22966>.+ (let-values (((buffer get) (open-bytevector-output-port)))+ ;; Inherit the HTTP proxying property from P.+ (set-http-proxy-port?! buffer (http-proxy-port? p))++ (for-each (cut write-request <> buffer)+ batch)+ (put-bytevector p (get))+ (force-output p))++ ;; Now start processing responses.+ (let loop ((sent batch)+ (processed 0)+ (result result))+ (match sent+ (()+ (match (drop requests processed)+ (()+ (unless keep-alive?+ (close-port p))+ (reverse result))+ (remainder+ (connect p remainder result))))+ ((head tail ...)+ (let* ((resp (read-response p))+ (body (response-body-port resp))+ (result (proc head resp body result)))+ ;; The server can choose to stop responding at any time, in which+ ;; case we have to try again. Check whether that is the case.+ ;; Note that even upon "Connection: close", we can read from BODY.+ (match (assq 'connection (response-headers resp))+ (('connection 'close)+ (close-port p)+ (connect #f ;try again+ (drop requests (+ 1 processed))+ result))+ (_+ (loop tail (+ 1 processed) result)))))))))) ;keep going++(define %unreachable-hosts+ ;; Set of names of unreachable hosts.+ (make-hash-table))++(define* (open-connection-for-uri/maybe uri+ #:key+ fresh?+ (time %fetch-timeout))+ "Open a connection to URI via 'open-connection-for-uri/cached' and return a+port to it, or, if connection failed, print a warning and return #f. Pass+#:fresh? to 'open-connection-for-uri/cached'."+ (define host+ (uri-host uri))++ (catch #t+ (lambda ()+ (open-connection-for-uri/cached uri #:timeout time+ #:fresh? fresh?))+ (match-lambda*+ (('getaddrinfo-error error)+ (unless (hash-ref %unreachable-hosts host)+ (hash-set! %unreachable-hosts host #t) ;warn only once+ (warning (G_ "~a: host not found: ~a~%")+ host (gai-strerror error)))+ #f)+ (('system-error . args)+ (unless (hash-ref %unreachable-hosts host)+ (hash-set! %unreachable-hosts host #t)+ (warning (G_ "~a: connection failed: ~a~%") host+ (strerror+ (system-error-errno `(system-error ,@args)))))+ #f)+ (args+ (apply throw args)))))++(define (read-to-eof port)+ "Read from PORT until EOF is reached. The data are discarded."+ (dump-port port (%make-void-port "w")))++(define (narinfo-request cache-url path)+ "Return an HTTP request for the narinfo of PATH at CACHE-URL."+ (let ((url (string-append cache-url "/" (store-path-hash-part path)+ ".narinfo"))+ (headers '((User-Agent . "GNU Guile"))))+ (build-request (string->uri url) #:method 'GET #:headers headers)))++(define (narinfo-from-file file url)+ "Attempt to read a narinfo from FILE, using URL as the cache URL. Return #f+if file doesn't exist, and the narinfo otherwise."+ (catch 'system-error+ (lambda ()+ (call-with-input-file file+ (cut read-narinfo <> url)))+ (lambda args+ (if (= ENOENT (system-error-errno args))+ #f+ (apply throw args)))))++(define (fetch-narinfos url paths)+ "Retrieve all the narinfos for PATHS from the cache at URL and return them."+ (define update-progress!+ (let ((done 0)+ (total (length paths)))+ (lambda ()+ (display "\r\x1b[K" (current-error-port)) ;erase current line+ (force-output (current-error-port))+ (format (current-error-port)+ (G_ "updating substitutes from '~a'... ~5,1f%")+ url (* 100. (/ done total)))+ (set! done (+ 1 done)))))++ (define hash-part->path+ (let ((mapping (fold (lambda (path result)+ (vhash-cons (store-path-hash-part path) path+ result))+ vlist-null+ paths)))+ (lambda (hash)+ (match (vhash-assoc hash mapping)+ (#f #f)+ ((_ . path) path)))))++ (define (handle-narinfo-response request response port result)+ (let* ((code (response-code response))+ (len (response-content-length response))+ (cache (response-cache-control response))+ (ttl (and cache (assoc-ref cache 'max-age))))+ (update-progress!)++ ;; Make sure to read no more than LEN bytes since subsequent bytes may+ ;; belong to the next response.+ (if (= code 200) ; hit+ (let ((narinfo (read-narinfo port url #:size len)))+ (if (string=? (dirname (narinfo-path narinfo))+ (%store-prefix))+ (begin+ (cache-narinfo! url (narinfo-path narinfo) narinfo ttl)+ (cons narinfo result))+ result))+ (let* ((path (uri-path (request-uri request)))+ (hash-part (basename+ (string-drop-right path 8)))) ;drop ".narinfo"+ (if len+ (get-bytevector-n port len)+ (read-to-eof port))+ (cache-narinfo! url (hash-part->path hash-part) #f+ (if (or (= 404 code) (= 202 code))+ ttl+ %narinfo-transient-error-ttl))+ result))))++ (define (do-fetch uri)+ (case (and=> uri uri-scheme)+ ((http https)+ ;; Note: Do not check HTTPS server certificates to avoid depending+ ;; on the X.509 PKI. We can do it because we authenticate+ ;; narinfos, which provides a much stronger guarantee.+ (let* ((requests (map (cut narinfo-request url <>) paths))+ (result (call-with-cached-connection uri+ (lambda (port)+ (if port+ (begin+ (update-progress!)+ (http-multiple-get uri+ handle-narinfo-response '()+ requests+ #:open-connection+ open-connection-for-uri/cached+ #:verify-certificate? #f+ #:port port))+ '()))+ open-connection-for-uri/maybe)))+ (newline (current-error-port))+ result))+ ((file #f)+ (let* ((base (string-append (uri-path uri) "/"))+ (files (map (compose (cut string-append base <> ".narinfo")+ store-path-hash-part)+ paths)))+ (filter-map (cut narinfo-from-file <> url) files)))+ (else+ (leave (G_ "~s: unsupported server URI scheme~%")+ (if uri (uri-scheme uri) url)))))++ (do-fetch (string->uri url)))++(define (cached-narinfo cache-url path)+ "Check locally if we have valid info about PATH coming from CACHE-URL.+Return two values: a Boolean indicating whether we have valid cached info, and+that info, which may be either #f (when PATH is unavailable) or the narinfo+for PATH."+ (define now+ (current-time time-monotonic))++ (define cache-file+ (narinfo-cache-file cache-url path))++ (catch 'system-error+ (lambda ()+ (call-with-input-file cache-file+ (lambda (p)+ (match (read p)+ (('narinfo ('version 2)+ ('cache-uri cache-uri)+ ('date date) ('ttl ttl) ('value #f))+ ;; A cached negative lookup.+ (if (obsolete? date now ttl)+ (values #f #f)+ (values #t #f)))+ (('narinfo ('version 2)+ ('cache-uri cache-uri)+ ('date date) ('ttl ttl) ('value value))+ ;; A cached positive lookup+ (if (obsolete? date now ttl)+ (values #f #f)+ (values #t (string->narinfo value cache-uri))))+ (('narinfo ('version v) _ ...)+ (values #f #f))))))+ (lambda _+ (values #f #f))))++(define (lookup-narinfos cache paths)+ "Return the narinfos for PATHS, invoking the server at CACHE when no+information is available locally."+ (let-values (((cached missing)+ (fold2 (lambda (path cached missing)+ (let-values (((valid? value)+ (cached-narinfo cache path)))+ (if valid?+ (if value+ (values (cons value cached) missing)+ (values cached missing))+ (values cached (cons path missing)))))+ '()+ '()+ paths)))+ (if (null? missing)+ cached+ (let ((missing (fetch-narinfos cache missing)))+ (append cached (or missing '()))))))++(define (lookup-narinfos/diverse caches paths authorized?)+ "Look up narinfos for PATHS on all of CACHES, a list of URLS, in that order.+That is, when a cache lacks an AUTHORIZED? narinfo, look it up in the next+cache, and so on.++Return a list of narinfos for PATHS or a subset thereof. The returned+narinfos are either AUTHORIZED?, or they claim a hash that matches an+AUTHORIZED? narinfo."+ (define (select-hit result)+ (lambda (path)+ (match (vhash-fold* cons '() path result)+ ((one)+ one)+ ((several ..1)+ (let ((authorized (find authorized? (reverse several))))+ (and authorized+ (find (cut equivalent-narinfo? <> authorized)+ several)))))))++ (let loop ((caches caches)+ (paths paths)+ (result vlist-null) ;path->narinfo vhash+ (hits '())) ;paths+ (match paths+ (() ;we're done+ ;; Now iterate on all the HITS, and return exactly one match for each+ ;; hit: the first narinfo that is authorized, or that has the same hash+ ;; as an authorized narinfo, in the order of CACHES.+ (filter-map (select-hit result) hits))+ (_+ (match caches+ ((cache rest ...)+ (let* ((narinfos (lookup-narinfos cache paths))+ (definite (map narinfo-path (filter authorized? narinfos)))+ (missing (lset-difference string=? paths definite))) ;XXX: perf+ (loop rest missing+ (fold vhash-cons result+ (map narinfo-path narinfos) narinfos)+ (append definite hits))))+ (() ;that's it+ (filter-map (select-hit result) hits)))))))++;;; Local Variables:+;;; eval: (put 'with-timeout 'scheme-indent-function 1)+;;; eval: (put 'with-cached-connection 'scheme-indent-function 2)+;;; eval: (put 'call-with-cached-connection 'scheme-indent-function 1)+;;; End:++;;; substitutes.scm ends herediff --git a/po/guix/POTFILES.in b/po/guix/POTFILES.inindex 666e630adf..fa397d7969 100644--- a/po/guix/POTFILES.in+++ b/po/guix/POTFILES.in@@ -88,6 +88,7 @@ guix/status.scm guix/http-client.scm guix/nar.scm guix/narinfo.scm+guix/substitutes.scm guix/channels.scm guix/profiles.scm guix/git.scm-- 2.29.2
C
C
Christopher Baines wrote on 4 Jan 22:24 +0100
Re: [bug#45409] [PATCH 1/3] guix: Move narinfo code from substitute script to module.
(name . Ludovic Courtès)(address . ludo@gnu.org)(address . 45409@debbugs.gnu.org)
87k0ssjszy.fsf@cbaines.net
I've sent a v3 now that fixes some conflicts and should apply once moreupon master.
-----BEGIN PGP SIGNATURE-----
iQKlBAEBCgCPFiEEPonu50WOcg2XVOCyXiijOwuE9XcFAl/zh3FfFIAAAAAALgAoaXNzdWVyLWZwckBub3RhdGlvbnMub3BlbnBncC5maWZ0aGhvcnNlbWFuLm5ldDNFODlFRUU3NDU4RTcyMEQ5NzU0RTBCMjVFMjhBMzNCMEI4NEY1NzcRHG1haWxAY2JhaW5lcy5uZXQACgkQXiijOwuE9Xc++BAAl2/jjzbTcEXRq2eJjWUGIrhq18+b5vC7hKkhx+FLYK8WzMH99wHDkPV1QBv98LFaCSF8WSr/jcufvi4PJlDQQZRRKsK/XH2OJneQIeOOElspDFDjpJqCErmjTYmMfXifkputuDGCnA565Nhf9yc/DNlkUPje628JJS9hCrMV1wq1d8zFBx1eK5xRtFk3xCQcwwrNWGZ0ciM9TKhqdSrLxs57vGrdfz46Sj4ce1kdRCwjz9wWmq9lvGFv/sTFcze6G8qaRZo5e+mNGXBIm97+trlnaMVbrP7xXRUXzVuDMO8jrTAJbct6hrsFUaQQR6fFltKSWsG1ZAcl1FX5lpr8JiAueq82bU9HMYGaDlyGt75iogMSAKpTjSZiSjgEPsTRq1/7MreEyos0cy3vYO1KosutPkrpoNX+XsLqtSa/I1KdC/SswH35bP5zHdy+aNTwketfdE827BAFK3RzfPLXmZzWJofQ3sly6UKgCbW6os5U4kLis54uSCJjvTnyFrgygsaq82jRlac5YtBUaGY9fUIK3ziVt3V2lUVm9o6xYKP4WIHJZFInNUNG36gDXhxh4iK+1xYlLJjChry0is1RKUzqWIKd22VF8n6/a0Yr3iYmez+KS7hPfzLRQuXFrM2gEAXi9+8vwINqsneSfYEB+h5H5MTveI1Xwy0zL6jh9WE==dVAY-----END PGP SIGNATURE-----
L
L
Ludovic Courtès wrote on 5 Jan 22:57 +0100
Re: [bug#45409] [PATCH v3 1/3] substitute: Untangle skipping authentication from valid-narinfo?.
(name . Christopher Baines)(address . mail@cbaines.net)(address . 45409@debbugs.gnu.org)
871rezt5cd.fsf@gnu.org
Hi,
Christopher Baines <mail@cbaines.net> skribis:
Toggle quote (10 lines)> Rather than having valid-narinfo? evaluate to #t if> %allow-unauthenticated-substitutes? is set to #t, just use (const #t) for> valid-narinfo? when %allow-unauthenticated-substitutes? is set to #t. This> will allow moving valid-narinfo? in to a (guix substitutes) module.>> * guix/scripts/substitute.scm (process-query, process-substitution): Change> the authorized? argument to lookup-narinfo and lookup-narinfos/diverse based> on %allow-unauthenticated-substitutes?.> (valid-narinfo?): Remove use of %allow-unauthenticated-substitutes?.
Bummer that there are two call sites.
What about doing away with ‘%allow-unauthenticated-substitutes?’ andinstead changing its only user, ‘tests/substitute.scm’, like so:
Toggle diff (19 lines)diff --git a/tests/substitute.scm b/tests/substitute.scmindex 542aaf603f..1827ffe8d4 100644--- a/tests/substitute.scm+++ b/tests/substitute.scm@@ -178,10 +178,10 @@ a file for NARINFO." (call-with-output-file (string-append narinfo-directory "/example.nar") (cute write-file- (string-append narinfo-directory "/example.out") <>))-- (%allow-unauthenticated-substitutes? #f))- thunk+ (string-append narinfo-directory "/example.out") <>)))+ (lambda ()+ (mock ((guix narinfo) valid-narinfo?) (const #t)+ (thunk))) (lambda () (when (file-exists? cache-directory) (delete-file-recursively cache-directory))))))
That change would have to be made in the patch that creates (guixnarinfo).
WDYT?
Ludo’.
L
L
Ludovic Courtès wrote on 5 Jan 22:58 +0100
Re: [bug#45409] [PATCH v3 2/3] guix: Move narinfo code from substitute script to module.
(name . Christopher Baines)(address . mail@cbaines.net)(address . 45409@debbugs.gnu.org)
87wnwrrqpj.fsf@gnu.org
Christopher Baines <mail@cbaines.net> skribis:
Toggle quote (18 lines)> This separation between the code for dealing with narinfos from the code doing> that for a purpose should make things clearer, and better support components> other that the substitute script in using this code.>> This is just moving the code around, no code should have been significantly> changed.>> * guix/scripts/substitute.scm (<narinfo>): Move record type to (guix narinfo).> (fields->alist, narinfo-hash-algorithm+value, narinfo-hash->sha256,> narinfo-signature->canonical-sexp, narinfo-maker, read-narinfo,> narinfo-sha256, valid-narinfo?, write-narinfo, narinfo->string,> string->narinfo, equivalent-narinfo?, supported-compression?,> compresses-better?, narinfo-best-uri): Move procedures to (guix narinfo).> (%compression-methods): Move variable to (guix narinfo).> * guix/narinfo.scm: New file.> * Makefile.am (MODULES): Add it.> * po/guix/POTFILES.in: Add 'guix/narinfo.scm'.
[...]
Toggle quote (2 lines)> +(define-module (guix narinfo)
[...]
Toggle quote (2 lines)> + #:use-module (guix scripts substitute)
This one should be removed.
Otherwise LGTM!
Thanks,Ludo’.
L
L
Ludovic Courtès wrote on 5 Jan 23:03 +0100
Re: [bug#45409] [PATCH v3 3/3] guix: Split (guix substitutes) from (guix scripts substitute).
(name . Christopher Baines)(address . mail@cbaines.net)(address . 45409@debbugs.gnu.org)
87r1mzrqgk.fsf@gnu.org
Christopher Baines <mail@cbaines.net> skribis:
Toggle quote (25 lines)> This means there's a module for working with substitutes, rather than all the> code sitting in the script. The need for this can be seen with the weather and> challenge scripts, that now don't have to use code from the substitute script,> but can instead use the substitute module.>> The separation here between the actual functionality of the substitute script> and the underlying functionality used both there and elsewhere should make> maintenance easier moving forward.>> This commit just moves code, none of the code should have been changed> significantly.>> * guix/scripts/substitute.scm (%narinfo-cache-directory, %narinfo-ttl,> %narinfo-negative-ttl, %narinfo-transient-error-ttl, %unreachable-hosts,> %max-cached-connections): Move variables to (guix substitutes).> (narinfo-cache-file, cached-narinfo, cache-narinfo!, narinfo-request, at-most,> http-multiple-get, read-to-eof, narinfo-from-file,> open-connection-for-uri/maybe, fetch-narinfos, lookup-narinfos,> lookup-narinfos/diverse, open-connection-for-uri/cached,> call-with-cached-connection): Move procedures to (guix substitutes).> (with-cached-connection): Move syntax rule to (guix substitutes).> * guix/substitutes.scm: New file.> * Makefile.am (MODULES): Add it.> * po/guix/POTFILES.in: Add 'guix/substitutes.scm'.
I’m reluctant starting this new module while it still containssingle-short-lived-process assumptions (connection caching & co.).
How about proceeding like this:
1. Move ‘http-multiple-get’ to (guix http-client).
2. Postpone the (guix substitute) bit to a separate patch series to leave us the time to polish things a bit and removes the single-process assumptions, or just move fewer things to (guix substitutes).
You could push (guix narinfo) in the meantime since I think that one isalmost ready.
How does that sound? Am I being too cautious?
Thanks again! :-)
Ludo’.
C
C
Christopher Baines wrote on 5 Jan 23:58 +0100
Re: [bug#45409] [PATCH v3 1/3] substitute: Untangle skipping authentication from valid-narinfo?.
(name . Ludovic Courtès)(address . ludo@gnu.org)(address . 45409@debbugs.gnu.org)
878s97j8ja.fsf@cbaines.net
Ludovic Courtès <ludo@gnu.org> writes:
Toggle quote (44 lines)> Hi,>> Christopher Baines <mail@cbaines.net> skribis:>>> Rather than having valid-narinfo? evaluate to #t if>> %allow-unauthenticated-substitutes? is set to #t, just use (const #t) for>> valid-narinfo? when %allow-unauthenticated-substitutes? is set to #t. This>> will allow moving valid-narinfo? in to a (guix substitutes) module.>>>> * guix/scripts/substitute.scm (process-query, process-substitution): Change>> the authorized? argument to lookup-narinfo and lookup-narinfos/diverse based>> on %allow-unauthenticated-substitutes?.>> (valid-narinfo?): Remove use of %allow-unauthenticated-substitutes?.>> Bummer that there are two call sites.>> What about doing away with ‘%allow-unauthenticated-substitutes?’ and> instead changing its only user, ‘tests/substitute.scm’, like so:>> diff --git a/tests/substitute.scm b/tests/substitute.scm> index 542aaf603f..1827ffe8d4 100644> --- a/tests/substitute.scm> +++ b/tests/substitute.scm> @@ -178,10 +178,10 @@ a file for NARINFO."> (call-with-output-file> (string-append narinfo-directory "/example.nar")> (cute write-file> - (string-append narinfo-directory "/example.out") <>))> -> - (%allow-unauthenticated-substitutes? #f))> - thunk> + (string-append narinfo-directory "/example.out") <>)))> + (lambda ()> + (mock ((guix narinfo) valid-narinfo?) (const #t)> + (thunk)))> (lambda ()> (when (file-exists? cache-directory)> (delete-file-recursively cache-directory))))))>> That change would have to be made in the patch that creates (guix> narinfo).>> WDYT?
I don't know what's up with these tests in particular, adding peek inplaces makes tests fail... not using Guile debugging helpers andoutputting to (current-error-port) seems to not change the resultthough.
I didn't really understand this code, but looking at it more, I'mthinking now that what it actually does is affects all the tests, andfor some tests in the (tests substitute) module, the%allow-unauthenticated-substitutes? behaviour is turned off.
Commenting out the relevant code in the script seems to support this,the substitute tests still pass, but tests in the store, derivation andguix-daemon modules fail. The substitute tests are actually fine, andbreak if you disable substitute authentication. The mock approach isprobably feasible, but it would need to be done in thosemodules/tests. I haven't looked at the details, but I'd be a littleconcerned that it might require mocking in each of the individual 15failing tests, maybe that's good for being explicit though?
Back to the use of %allow-unauthenticated-substitutes? in the code,there are two call sites, for the two separate code paths, but it wouldbe pretty easy to move to one call site. Both process-query andprocess-substitution take an acl, but they could instead take some(valid? obj) procedure. That would either call (valid-narinfo? obj acl)or just evaluate to #t in the allow unauthorized case. This effectivelymoves the logic and call site to the command.
-----BEGIN PGP SIGNATURE-----
iQKlBAEBCgCPFiEEPonu50WOcg2XVOCyXiijOwuE9XcFAl/07wlfFIAAAAAALgAoaXNzdWVyLWZwckBub3RhdGlvbnMub3BlbnBncC5maWZ0aGhvcnNlbWFuLm5ldDNFODlFRUU3NDU4RTcyMEQ5NzU0RTBCMjVFMjhBMzNCMEI4NEY1NzcRHG1haWxAY2JhaW5lcy5uZXQACgkQXiijOwuE9Xf64RAAqQ6xADmqmC1avTCo5hHpSLtLqPInecDxQ4v75eLD2uHXZfCnGbpvdvdIujVdtnBqQjfWSPK432zOAw2o0x+o6KBo3ogtKQ4nCGhx+aKpnUC0MjptbA+bWlXnKnwn/+n5OX4U+WxPjkg5zxiuWVvc9nz6GFdd15EZjzoRz+9Hq/+YfyxPN+rjiw7l48w6T7PgWwpgoprwZZw5u3prLZqXhPWLMYSianf0iYIC5pxqKEhKCKGFoVZOL6ZXjXQT7r73R6GN2t5TsjuaVafhYImetoWPiK5HAyRqsMKu2q7L+VMrOEtUndmjqYukBRw+yUzWYilfqqCKWoy33WuHbj+CP6VD2EUHQ9S4LpIrdJKwdQ7a7tiYYw5O1UWeOvsN8lAMaW+yrUvhK1j79yKrxo0tpq51Qda43kdt+QmTSP3cUVrmyY19UVqNa3QrwDI9h2zzgUV8kD5+g7kAkxZmGe2l16mkhPK+Fg4UuaM6YPY+sod73nc//iaiySQ5orz8Dokza7BnELur2IJnqBh6G6qyfanbRBGoXyIEG4Ne46OZuObFvN2qmSt9r8MQYqOYXFmmnpN0XIvkCsX7ErsCfNGHhEzavdJHqel6y2y5c/CnkLzMnf3jaV+VGWJVDl1+9njPPMX3n9v7uJhCE4zGMWk2ol356JOCb9cjFHKGWJv2trU==wM9k-----END PGP SIGNATURE-----
L
L
Ludovic Courtès wrote on 6 Jan 09:37 +0100
(name . Christopher Baines)(address . mail@cbaines.net)(address . 45409@debbugs.gnu.org)
87im8asbpf.fsf@gnu.org
Hi,
Christopher Baines <mail@cbaines.net> skribis:
Toggle quote (21 lines)> Ludovic Courtès <ludo@gnu.org> writes:>>> Hi,>>>> Christopher Baines <mail@cbaines.net> skribis:>>>>> Rather than having valid-narinfo? evaluate to #t if>>> %allow-unauthenticated-substitutes? is set to #t, just use (const #t) for>>> valid-narinfo? when %allow-unauthenticated-substitutes? is set to #t. This>>> will allow moving valid-narinfo? in to a (guix substitutes) module.>>>>>> * guix/scripts/substitute.scm (process-query, process-substitution): Change>>> the authorized? argument to lookup-narinfo and lookup-narinfos/diverse based>>> on %allow-unauthenticated-substitutes?.>>> (valid-narinfo?): Remove use of %allow-unauthenticated-substitutes?.>>>> Bummer that there are two call sites.>>>> What about doing away with ‘%allow-unauthenticated-substitutes?’ and>> instead changing its only user, ‘tests/substitute.scm’, like so:
My bad, I missed that ‘test-env’ does:
GUIX_ALLOW_UNAUTHENTICATED_SUBSTITUTES=yes
So what I proposed won’t work.
All in all, let’s just take the patch you proposed. Sorry for theconfusion!
Toggle quote (5 lines)> I don't know what's up with these tests in particular, adding peek in> places makes tests fail... not using Guile debugging helpers and> outputting to (current-error-port) seems to not change the result> though.
Yeah that’s because (current-output-port) is used to communicate withthe daemon, so if you inadvertently write things there, it breaks.
Toggle quote (5 lines)> I didn't really understand this code, but looking at it more, I'm> thinking now that what it actually does is affects all the tests, and> for some tests in the (tests substitute) module, the> %allow-unauthenticated-substitutes? behaviour is turned off.
Yeah, I got the logic wrong.
Toggle quote (17 lines)> Commenting out the relevant code in the script seems to support this,> the substitute tests still pass, but tests in the store, derivation and> guix-daemon modules fail. The substitute tests are actually fine, and> break if you disable substitute authentication. The mock approach is> probably feasible, but it would need to be done in those> modules/tests. I haven't looked at the details, but I'd be a little> concerned that it might require mocking in each of the individual 15> failing tests, maybe that's good for being explicit though?>> Back to the use of %allow-unauthenticated-substitutes? in the code,> there are two call sites, for the two separate code paths, but it would> be pretty easy to move to one call site. Both process-query and> process-substitution take an acl, but they could instead take some> (valid? obj) procedure. That would either call (valid-narinfo? obj acl)> or just evaluate to #t in the allow unauthorized case. This effectively> moves the logic and call site to the command.
Yeah but the patch you proposed is fine.
Thanks and apologies for the back-and-forth!
Ludo’.
C
C
Christopher Baines wrote on 7 Jan 23:29 +0100
Re: [bug#45409] [PATCH v3 3/3] guix: Split (guix substitutes) from (guix scripts substitute).
(name . Ludovic Courtès)(address . ludo@gnu.org)(address . 45409@debbugs.gnu.org)
87zh1kidoc.fsf@cbaines.net
Ludovic Courtès <ludo@gnu.org> writes:
Toggle quote (44 lines)> Christopher Baines <mail@cbaines.net> skribis:>>> This means there's a module for working with substitutes, rather than all the>> code sitting in the script. The need for this can be seen with the weather and>> challenge scripts, that now don't have to use code from the substitute script,>> but can instead use the substitute module.>>>> The separation here between the actual functionality of the substitute script>> and the underlying functionality used both there and elsewhere should make>> maintenance easier moving forward.>>>> This commit just moves code, none of the code should have been changed>> significantly.>>>> * guix/scripts/substitute.scm (%narinfo-cache-directory, %narinfo-ttl,>> %narinfo-negative-ttl, %narinfo-transient-error-ttl, %unreachable-hosts,>> %max-cached-connections): Move variables to (guix substitutes).>> (narinfo-cache-file, cached-narinfo, cache-narinfo!, narinfo-request, at-most,>> http-multiple-get, read-to-eof, narinfo-from-file,>> open-connection-for-uri/maybe, fetch-narinfos, lookup-narinfos,>> lookup-narinfos/diverse, open-connection-for-uri/cached,>> call-with-cached-connection): Move procedures to (guix substitutes).>> (with-cached-connection): Move syntax rule to (guix substitutes).>> * guix/substitutes.scm: New file.>> * Makefile.am (MODULES): Add it.>> * po/guix/POTFILES.in: Add 'guix/substitutes.scm'.>> I’m reluctant starting this new module while it still contains> single-short-lived-process assumptions (connection caching & co.).>> How about proceeding like this:>> 1. Move ‘http-multiple-get’ to (guix http-client).>> 2. Postpone the (guix substitute) bit to a separate patch series to> leave us the time to polish things a bit and removes the> single-process assumptions, or just move fewer things to (guix> substitutes).>> You could push (guix narinfo) in the meantime since I think that one is> almost ready.>> How does that sound? Am I being too cautious?
Well, separating out the connection caching might be helpful forcleaning things up in the Guix Build Coordinator, I had to add a mutexcurrently as I'm guessing the caching isn't thread safe.
I think it's possible to separate it out if some of the error handlingis pushed down in to the http procedures, and if when they get an errorindicating the connection is unusable, they close the port.
I've pushed some rough commits for this to this branch:
https://git.cbaines.net/guix/log/?h=prepare-to-move-guix-scripts-substitute-code
I'm still struggling with the tests, currently make check hangs, I thinkon the challenge tests, and I don't currently have a plan to work outwhy the test is hanging.
-----BEGIN PGP SIGNATURE-----
iQKlBAEBCgCPFiEEPonu50WOcg2XVOCyXiijOwuE9XcFAl/3i0NfFIAAAAAALgAoaXNzdWVyLWZwckBub3RhdGlvbnMub3BlbnBncC5maWZ0aGhvcnNlbWFuLm5ldDNFODlFRUU3NDU4RTcyMEQ5NzU0RTBCMjVFMjhBMzNCMEI4NEY1NzcRHG1haWxAY2JhaW5lcy5uZXQACgkQXiijOwuE9XfBUg//QCsNw8UNJ92v+orRrmNP71sDfmC4gAe8BBvwWOuJLKe2mVchYTL4AN5B6Qvmhcob00W3mEdXVet9tb9aW6zdSUI0y0vTcfiJA5MkjI5guOQm2rG/zCrju4pkCPxkxFk/qSju1Q07vR4eAMU4EBCmpiXT06/e0ceTBHvGVY9b7oClCHRMRh3DzMdG3SU978KyVBJxZXD8+q/LwqQ/SAH1cP47Ku/3koHqT9vUq303/f0zPfpU2WE3sky19Sbm710tiiFC2rzW8zM+5pzPr4Pzl1SyRtSCo55El27YaxOAYVW1Jvj2n7eFLdsV5msoUlU2jSg57XdZIKSbDgK3Bs2u+GW6FOwP4mGySysR8ZqQ8RIiQh0cZFmoADhk4FGYIuJevwGgIig5v+mtH1FlpTxbtq90kjhrmdKH4Wdcr2mh5Syvo/saF7eHqKguV48Z9tNN5XC00mWQ2GANv65EPFP3f/eilshiIeFoZR91773aFQ113A6EQvz2Yh2zroODgLjgeXXB7qJAmnl7xy09G9VncXMIBgr52K0s4u4WvOKw2uDvdXPsmeGLR2yDrwG9irHo835bfDFndylsVScdVlgJW+y48co9/ykaflWG4Onh5FThsIWd66rIzoICHrXGNxqW8FjW4fSA7NDhjbK+YV6uEOVQI6LhBlXfrI5LHQrdU7M==gxvx-----END PGP SIGNATURE-----
L
L
Ludovic Courtès wrote on 11 Jan 14:26 +0100
(name . Christopher Baines)(address . mail@cbaines.net)(address . 45409@debbugs.gnu.org)
87im83eha5.fsf@gnu.org
Hi,
Christopher Baines <mail@cbaines.net> skribis:
Toggle quote (21 lines)>> I’m reluctant starting this new module while it still contains>> single-short-lived-process assumptions (connection caching & co.).>>>> How about proceeding like this:>>>> 1. Move ‘http-multiple-get’ to (guix http-client).>>>> 2. Postpone the (guix substitute) bit to a separate patch series to>> leave us the time to polish things a bit and removes the>> single-process assumptions, or just move fewer things to (guix>> substitutes).>>>> You could push (guix narinfo) in the meantime since I think that one is>> almost ready.>>>> How does that sound? Am I being too cautious?>> Well, separating out the connection caching might be helpful for> cleaning things up in the Guix Build Coordinator, I had to add a mutex> currently as I'm guessing the caching isn't thread safe.
Precisely, that’s the kind of reason why it’s currently buried in (guixscripts substitute) rather than exposed as a reusable library. :-)
Toggle quote (4 lines)> I think it's possible to separate it out if some of the error handling> is pushed down in to the http procedures, and if when they get an error> indicating the connection is unusable, they close the port.
Ideally the (web …) modules would do that (that’s what you mean, right?)but then we’d have to wait for Guile proper to implement these things.
Toggle quote (8 lines)> I've pushed some rough commits for this to this branch:>> https://git.cbaines.net/guix/log/?h=prepare-to-move-guix-scripts-substitute-code>> I'm still struggling with the tests, currently make check hangs, I think> on the challenge tests, and I don't currently have a plan to work out> why the test is hanging.
Overall the approach LGTM.
How about first getting (guix narinfo) in ‘master’ (the bits we agreedon), and then tackling the rest so that it’s less daunting?
Also, I’d like to get the zstd patches in. :-)
Thanks,Ludo’.
C
C
Christopher Baines wrote on 16 Jan 14:57 +0100
[PATCH v4 05/13] http-client: Add error handling to http-multiple-get.
(address . 45409@debbugs.gnu.org)
20210116135803.21955-5-mail@cbaines.net
Making sure to close the port if it looks to be unusable. This closing of theport will allow for caching connections, without caching broken connections,as the cache can avoid handing out closed ports.
* guix/http-client.scm (http-multiple-get): Try to catch exceptions thathappen if the port is unusable, this is a adaptation of code within the (guixscripts substitute) module.--- guix/http-client.scm | 74 +++++++++++++++++++++++++++++++++----------- 1 file changed, 56 insertions(+), 18 deletions(-)
Toggle diff (101 lines)diff --git a/guix/http-client.scm b/guix/http-client.scmindex 7ead493633..3aba3b28c1 100644--- a/guix/http-client.scm+++ b/guix/http-client.scm@@ -38,6 +38,7 @@ #:use-module (guix utils) #:use-module (guix base64) #:autoload (gcrypt hash) (sha256)+ #:autoload (gnutls) (error/invalid-session) #:use-module ((guix build utils) #:select (mkdir-p dump-port)) #:use-module ((guix build download)@@ -180,10 +181,25 @@ returning." ;; Inherit the HTTP proxying property from P. (set-http-proxy-port?! buffer (http-proxy-port? p)) - (for-each (cut write-request <> buffer)- batch)- (put-bytevector p (get))- (force-output p))+ (catch #t+ (lambda ()+ (for-each (cut write-request <> buffer)+ batch)+ (put-bytevector p (get))+ (force-output p))+ (lambda (key . args)+ ;; If PORT becomes unusable, open a fresh connection and+ ;; retry.+ (if (or (and (eq? key 'system-error)+ (= EPIPE (system-error-errno `(,key ,@args))))+ (and (eq? key 'gnutls-error)+ (eq? (first args) error/invalid-session)))+ (begin+ (close-port p) ; close the broken port+ (connect #f+ requests+ result))+ (apply throw key args))))) ;; Now start processing responses. (let loop ((sent batch)@@ -199,20 +215,42 @@ returning." (remainder (connect p remainder result)))) ((head tail ...)- (let* ((resp (read-response p))- (body (response-body-port resp))- (result (proc head resp body result)))- ;; The server can choose to stop responding at any time, in which- ;; case we have to try again. Check whether that is the case.- ;; Note that even upon "Connection: close", we can read from BODY.- (match (assq 'connection (response-headers resp))- (('connection 'close)- (close-port p)- (connect #f ;try again- (drop requests (+ 1 processed))- result))- (_- (loop tail (+ 1 processed) result)))))))))) ;keep going+ (catch #t+ (lambda ()+ (let* ((resp (read-response p))+ (body (response-body-port resp))+ (result (proc head resp body result)))+ ;; The server can choose to stop responding at any time,+ ;; in which case we have to try again. Check whether+ ;; that is the case. Note that even upon "Connection:+ ;; close", we can read from BODY.+ (match (assq 'connection (response-headers resp))+ (('connection 'close)+ (close-port p)+ (connect #f ;try again+ (drop requests (+ 1 processed))+ result))+ (_+ (loop tail (+ 1 processed) result))))) ;keep going+ (lambda (key . args)+ ;; If PORT was cached and the server closed the connection+ ;; in the meantime, we get EPIPE. In that case, open a+ ;; fresh connection and retry. We might also get+ ;; 'bad-response or a similar exception from (web response)+ ;; later on, once we've sent the request, or a+ ;; ERROR/INVALID-SESSION from GnuTLS.+ (if (or (and (eq? key 'system-error)+ (= EPIPE (system-error-errno `(,key ,@args))))+ (and (eq? key 'gnutls-error)+ (eq? (first args) error/invalid-session))+ (memq key+ '(bad-response bad-header bad-header-component)))+ (begin+ (close-port p)+ (connect #f ; try again+ (drop requests (+ 1 processed))+ result))+ (apply throw key args)))))))))) ;;;-- 2.30.0
C
C
Christopher Baines wrote on 16 Jan 14:57 +0100
[PATCH v4 02/13] substitute: Remove connection handling from fetch.
(address . 45409@debbugs.gnu.org)
20210116135803.21955-2-mail@cbaines.net
http-fetch does this, so just use that code instead.
* guix/scripts/substitute.scm (fetch): Remove connection handling when theport is closed.--- guix/scripts/substitute.scm | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-)
Toggle diff (25 lines)diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex aaafb5d605..74fce15117 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -200,14 +200,10 @@ connection (typically PORT) is kept open once data has been fetched from URI." (warning (G_ "while fetching ~a: server is somewhat slow~%") (uri->string uri)) (warning (G_ "try `--no-substitutes' if the problem persists~%")))- (begin- (when (or (not port) (port-closed? port))- (set! port (guix:open-connection-for-uri- uri #:verify-certificate? #f)))- (http-fetch uri #:text? #f #:port port- #:keep-alive? keep-alive?- #:buffered? buffered?- #:verify-certificate? #f))))))+ (http-fetch uri #:text? #f #:port port+ #:keep-alive? keep-alive?+ #:buffered? buffered?+ #:verify-certificate? #f))))) (else (leave (G_ "unsupported substitute URI scheme: ~a~%") (uri->string uri)))))-- 2.30.0
C
C
Christopher Baines wrote on 16 Jan 14:57 +0100
[PATCH v4 01/13] substitute: Remove buffer handling from fetch.
(address . 45409@debbugs.gnu.org)
20210116135803.21955-1-mail@cbaines.net
http-fetch does this, so just set the right option.
* guix/scripts/substitute.scm (fetch): Remove buffering code, and pass #:buffered? to http-fetch.--- guix/scripts/substitute.scm | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
Toggle diff (18 lines)diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex 2eefdb79d8..aaafb5d605 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -204,10 +204,9 @@ connection (typically PORT) is kept open once data has been fetched from URI." (when (or (not port) (port-closed? port)) (set! port (guix:open-connection-for-uri uri #:verify-certificate? #f)))- (unless (or buffered? (not (file-port? port)))- (setvbuf port 'none)) (http-fetch uri #:text? #f #:port port #:keep-alive? keep-alive?+ #:buffered? buffered? #:verify-certificate? #f)))))) (else (leave (G_ "unsupported substitute URI scheme: ~a~%")-- 2.30.0
C
C
Christopher Baines wrote on 16 Jan 14:57 +0100
[PATCH v4 03/13] substitute: Remove redundant let block from fetch.
(address . 45409@debbugs.gnu.org)
20210116135803.21955-3-mail@cbaines.net
* guix/scripts/substitute.scm (fetch): Remove redundant let block.--- guix/scripts/substitute.scm | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-)
Toggle diff (36 lines)diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex 74fce15117..ecc2bd9035 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -192,18 +192,17 @@ connection (typically PORT) is kept open once data has been fetched from URI." ;; sudo tc qdisc add dev eth0 root netem delay 1500ms ;; and then cancel with: ;; sudo tc qdisc del dev eth0 root- (let ((port port))- (with-timeout (if timeout?- %fetch-timeout- 0)- (begin- (warning (G_ "while fetching ~a: server is somewhat slow~%")- (uri->string uri))- (warning (G_ "try `--no-substitutes' if the problem persists~%")))- (http-fetch uri #:text? #f #:port port- #:keep-alive? keep-alive?- #:buffered? buffered?- #:verify-certificate? #f)))))+ (with-timeout (if timeout?+ %fetch-timeout+ 0)+ (begin+ (warning (G_ "while fetching ~a: server is somewhat slow~%")+ (uri->string uri))+ (warning (G_ "try `--no-substitutes' if the problem persists~%")))+ (http-fetch uri #:text? #f #:port port+ #:keep-alive? keep-alive?+ #:buffered? buffered?+ #:verify-certificate? #f)))) (else (leave (G_ "unsupported substitute URI scheme: ~a~%") (uri->string uri)))))-- 2.30.0
C
C
Christopher Baines wrote on 16 Jan 14:57 +0100
[PATCH v4 04/13] guix: Move http-multiple-get to (guix http-client).
(address . 45409@debbugs.gnu.org)
20210116135803.21955-4-mail@cbaines.net
From (guix scripts substitute). This will make it easier to reuse this code.
* guix/scripts/substitute.scm (http-multiple-get): Remove, and move to…* guix/http-client.scm (http-multiple-get): …here.--- guix/http-client.scm | 76 +++++++++++++++++++++++++++++++++++++ guix/scripts/substitute.scm | 70 ---------------------------------- 2 files changed, 76 insertions(+), 70 deletions(-)
Toggle diff (186 lines)diff --git a/guix/http-client.scm b/guix/http-client.scmindex 553640fe9e..7ead493633 100644--- a/guix/http-client.scm+++ b/guix/http-client.scm@@ -21,8 +21,11 @@ (define-module (guix http-client) #:use-module (web uri)+ #:use-module (web http) #:use-module ((web client) #:hide (open-socket-for-uri))+ #:use-module (web request) #:use-module (web response)+ #:use-module (srfi srfi-1) #:use-module (srfi srfi-11) #:use-module (srfi srfi-19) #:use-module (srfi srfi-26)@@ -50,6 +53,7 @@ http-get-error-reason http-fetch+ http-multiple-get %http-cache-ttl http-fetch/cached))@@ -138,6 +142,78 @@ Raise an '&http-get-error' condition if downloading fails." (uri->string uri) code (response-reason-phrase resp)))))))))))) +(define* (http-multiple-get base-uri proc seed requests+ #:key port (verify-certificate? #t)+ (open-connection guix:open-connection-for-uri)+ (keep-alive? #t)+ (batch-size 1000))+ "Send all of REQUESTS to the server at BASE-URI. Call PROC for each+response, passing it the request object, the response, a port from which to+read the response body, and the previous result, starting with SEED, à la+'fold'. Return the final result.++When PORT is specified, use it as the initial connection on which HTTP+requests are sent; otherwise call OPEN-CONNECTION to open a new connection for+a URI. When KEEP-ALIVE? is false, close the connection port before+returning."+ (let connect ((port port)+ (requests requests)+ (result seed))+ (define batch+ (if (>= batch-size (length requests))+ requests+ (take requests batch-size)))++ ;; (format (current-error-port) "connecting (~a requests left)..."+ ;; (length requests))+ (let ((p (or port (open-connection base-uri+ #:verify-certificate?+ verify-certificate?))))+ ;; For HTTPS, P is not a file port and does not support 'setvbuf'.+ (when (file-port? p)+ (setvbuf p 'block (expt 2 16)))++ ;; Send BATCH in a row.+ ;; XXX: Do our own caching to work around inefficiencies when+ ;; communicating over TLS: <http://bugs.gnu.org/22966>.+ (let-values (((buffer get) (open-bytevector-output-port)))+ ;; Inherit the HTTP proxying property from P.+ (set-http-proxy-port?! buffer (http-proxy-port? p))++ (for-each (cut write-request <> buffer)+ batch)+ (put-bytevector p (get))+ (force-output p))++ ;; Now start processing responses.+ (let loop ((sent batch)+ (processed 0)+ (result result))+ (match sent+ (()+ (match (drop requests processed)+ (()+ (unless keep-alive?+ (close-port p))+ (reverse result))+ (remainder+ (connect p remainder result))))+ ((head tail ...)+ (let* ((resp (read-response p))+ (body (response-body-port resp))+ (result (proc head resp body result)))+ ;; The server can choose to stop responding at any time, in which+ ;; case we have to try again. Check whether that is the case.+ ;; Note that even upon "Connection: close", we can read from BODY.+ (match (assq 'connection (response-headers resp))+ (('connection 'close)+ (close-port p)+ (connect #f ;try again+ (drop requests (+ 1 processed))+ result))+ (_+ (loop tail (+ 1 processed) result)))))))))) ;keep going+ ;;; ;;; Caching.diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex ecc2bd9035..64b8ae2a15 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -299,76 +299,6 @@ return its MAX-LENGTH first elements and its tail." (values (reverse result) lst) (loop (+ 1 len) tail (cons head result))))))) -(define* (http-multiple-get base-uri proc seed requests- #:key port (verify-certificate? #t)- (open-connection guix:open-connection-for-uri)- (keep-alive? #t)- (batch-size 1000))- "Send all of REQUESTS to the server at BASE-URI. Call PROC for each-response, passing it the request object, the response, a port from which to-read the response body, and the previous result, starting with SEED, à la-'fold'. Return the final result.--When PORT is specified, use it as the initial connection on which HTTP-requests are sent; otherwise call OPEN-CONNECTION to open a new connection for-a URI. When KEEP-ALIVE? is false, close the connection port before-returning."- (let connect ((port port)- (requests requests)- (result seed))- (define batch- (at-most batch-size requests))-- ;; (format (current-error-port) "connecting (~a requests left)..."- ;; (length requests))- (let ((p (or port (open-connection base-uri- #:verify-certificate?- verify-certificate?))))- ;; For HTTPS, P is not a file port and does not support 'setvbuf'.- (when (file-port? p)- (setvbuf p 'block (expt 2 16)))-- ;; Send BATCH in a row.- ;; XXX: Do our own caching to work around inefficiencies when- ;; communicating over TLS: <http://bugs.gnu.org/22966>.- (let-values (((buffer get) (open-bytevector-output-port)))- ;; Inherit the HTTP proxying property from P.- (set-http-proxy-port?! buffer (http-proxy-port? p))-- (for-each (cut write-request <> buffer)- batch)- (put-bytevector p (get))- (force-output p))-- ;; Now start processing responses.- (let loop ((sent batch)- (processed 0)- (result result))- (match sent- (()- (match (drop requests processed)- (()- (unless keep-alive?- (close-port p))- (reverse result))- (remainder- (connect p remainder result))))- ((head tail ...)- (let* ((resp (read-response p))- (body (response-body-port resp))- (result (proc head resp body result)))- ;; The server can choose to stop responding at any time, in which- ;; case we have to try again. Check whether that is the case.- ;; Note that even upon "Connection: close", we can read from BODY.- (match (assq 'connection (response-headers resp))- (('connection 'close)- (close-port p)- (connect #f ;try again- (drop requests (+ 1 processed))- result))- (_- (loop tail (+ 1 processed) result)))))))))) ;keep going- (define (read-to-eof port) "Read from PORT until EOF is reached. The data are discarded." (dump-port port (%make-void-port "w")))-- 2.30.0
C
C
Christopher Baines wrote on 16 Jan 14:57 +0100
[PATCH v4 06/13] substitute: open-connection-for-uri/maybe add #:verify-certificate?.
(address . 45409@debbugs.gnu.org)
20210116135803.21955-6-mail@cbaines.net
As this is used by http-fetch and http-multiple-get when they call thespecified open connection procedure.
* guix/scripts/substitute.scm (open-connection-for-uri/maybe): Support #:verify-certificate?.--- guix/scripts/substitute.scm | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-)
Toggle diff (26 lines)diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex 64b8ae2a15..259b109cc6 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -322,7 +322,8 @@ if file doesn't exist, and the narinfo otherwise." (define* (open-connection-for-uri/maybe uri #:key fresh?- (time %fetch-timeout))+ (time %fetch-timeout)+ verify-certificate?) "Open a connection to URI via 'open-connection-for-uri/cached' and return a port to it, or, if connection failed, print a warning and return #f. Pass #:fresh? to 'open-connection-for-uri/cached'."@@ -332,7 +333,8 @@ port to it, or, if connection failed, print a warning and return #f. Pass (catch #t (lambda () (open-connection-for-uri/cached uri #:timeout time- #:fresh? fresh?))+ #:fresh? fresh?+ #:verify-certificate? verify-certificate?)) (match-lambda* (('getaddrinfo-error error) (unless (hash-ref %unreachable-hosts host)-- 2.30.0
C
C
Christopher Baines wrote on 16 Jan 14:57 +0100
[PATCH v4 08/13] http-client: Accept #:open-connection in http-fetch.
(address . 45409@debbugs.gnu.org)
20210116135803.21955-8-mail@cbaines.net
So that an alternative procedure can be passed in, perhaps to performconnection caching.
* guix/http-client.scm (http-fetch): Add an #:open-connection keywordargument.--- guix/http-client.scm | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-)
Toggle diff (29 lines)diff --git a/guix/http-client.scm b/guix/http-client.scmindex 3aba3b28c1..2d7458a56e 100644--- a/guix/http-client.scm+++ b/guix/http-client.scm@@ -75,6 +75,7 @@ (define* (http-fetch uri #:key port (text? #f) (buffered? #t)+ (open-connection guix:open-connection-for-uri) (keep-alive? #f) (verify-certificate? #t) (headers '((user-agent . "GNU Guile")))@@ -97,10 +98,10 @@ Raise an '&http-get-error' condition if downloading fails." (let loop ((uri (if (string? uri) (string->uri uri) uri)))- (let ((port (or port (guix:open-connection-for-uri uri- #:verify-certificate?- verify-certificate?- #:timeout timeout)))+ (let ((port (or port (open-connection uri+ #:verify-certificate?+ verify-certificate?+ #:timeout timeout))) (headers (match (uri-userinfo uri) ((? string? str) (cons (cons 'Authorization-- 2.30.0
C
C
Christopher Baines wrote on 16 Jan 14:57 +0100
[PATCH v4 07/13] substitute: Stop using call-with-cached-connection in fetch-narinfos.
(address . 45409@debbugs.gnu.org)
20210116135803.21955-7-mail@cbaines.net
Instead, just pass open-connection-for-uri/maybe to http-multiple-get. Thiscode should be functionaly similar to the previous code. The eventual aim ofthis is to make the connection caching not mandatory in fetch-narinfos.
* guix/scripts/substitute.scm (fetch-narinfos): Remove use ofcall-with-cached-connection.--- guix/scripts/substitute.scm | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-)
Toggle diff (35 lines)diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex 259b109cc6..88219ea7f6 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -412,20 +412,14 @@ port to it, or, if connection failed, print a warning and return #f. Pass ;; on the X.509 PKI. We can do it because we authenticate ;; narinfos, which provides a much stronger guarantee. (let* ((requests (map (cut narinfo-request url <>) paths))- (result (call-with-cached-connection uri- (lambda (port)- (if port- (begin- (update-progress!)- (http-multiple-get uri- handle-narinfo-response '()- requests- #:open-connection- open-connection-for-uri/cached- #:verify-certificate? #f- #:port port))- '()))- open-connection-for-uri/maybe)))+ (result (begin+ (update-progress!)+ (http-multiple-get uri+ handle-narinfo-response '()+ requests+ #:open-connection+ open-connection-for-uri/maybe+ #:verify-certificate? #f)))) result)) ((file #f) (let* ((base (string-append (uri-path uri) "/"))-- 2.30.0
C
C
Christopher Baines wrote on 16 Jan 14:57 +0100
[PATCH v4 09/13] substitute: Change connection cache handling in process-substitution.
(address . 45409@debbugs.gnu.org)
20210116135803.21955-9-mail@cbaines.net
Just pass open-connection-for-uri/maybe to http-fetch, this removes the needfor with-cached-connection and passing the port in.
* guix/scripts/substitute.scm (fetch): Don't take a port as an argument, andpass open-connection-for-uri/maybe to http-fetch.(process-substitution): Don't call fetch with with-cached-connection.--- guix/scripts/substitute.scm | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-)
Toggle diff (38 lines)diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex 88219ea7f6..fc5a19124e 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -170,7 +170,7 @@ again." (apply values result))))) (define* (fetch uri #:key (buffered? #t) (timeout? #t)- (keep-alive? #f) (port #f))+ (keep-alive? #f)) "Return a binary input port to URI and the number of bytes it's expected to provide. @@ -199,7 +199,8 @@ connection (typically PORT) is kept open once data has been fetched from URI." (warning (G_ "while fetching ~a: server is somewhat slow~%") (uri->string uri)) (warning (G_ "try `--no-substitutes' if the problem persists~%")))- (http-fetch uri #:text? #f #:port port+ (http-fetch uri #:text? #f+ #:open-connection open-connection-for-uri/maybe #:keep-alive? keep-alive? #:buffered? buffered? #:verify-certificate? #f))))@@ -751,10 +752,8 @@ the current output port." (let*-values (((raw download-size) ;; 'guix publish' without '--cache' doesn't specify a ;; Content-Length, so DOWNLOAD-SIZE is #f in this case.- (with-cached-connection uri port- (fetch uri #:buffered? #f #:timeout? #f- #:port port- #:keep-alive? #t)))+ (fetch uri #:buffered? #f #:timeout? #f+ #:keep-alive? #t)) ((progress) (let* ((dl-size (or download-size (and (equal? compression "none")-- 2.30.0
C
C
Christopher Baines wrote on 16 Jan 14:58 +0100
[PATCH v4 10/13] substitute: Remove now redundant connection caching helpers.
(address . 45409@debbugs.gnu.org)
20210116135803.21955-10-mail@cbaines.net
Failures now should be handled where they occur, and if there's a problemthat's symptomatic of an issue with the connection, the port should be closed.
* guix/scripts/substitute.scm (call-with-cached-connection): Remove procedure.(with-cached-connection): Remove syntax rule.--- guix/scripts/substitute.scm | 28 ---------------------------- 1 file changed, 28 deletions(-)
Toggle diff (48 lines)diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex fc5a19124e..d316bdef15 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -689,32 +689,6 @@ server certificates." (drain-input socket) socket)))))))) -(define* (call-with-cached-connection uri proc- #:optional- (open-connection- open-connection-for-uri/cached))- (let ((port (open-connection uri)))- (catch #t- (lambda ()- (proc port))- (lambda (key . args)- ;; If PORT was cached and the server closed the connection in the- ;; meantime, we get EPIPE. In that case, open a fresh connection and- ;; retry. We might also get 'bad-response or a similar exception from- ;; (web response) later on, once we've sent the request, or a- ;; ERROR/INVALID-SESSION from GnuTLS.- (if (or (and (eq? key 'system-error)- (= EPIPE (system-error-errno `(,key ,@args))))- (and (eq? key 'gnutls-error)- (eq? (first args) error/invalid-session))- (memq key '(bad-response bad-header bad-header-component)))- (proc (open-connection uri #:fresh? #t))- (apply throw key args))))))--(define-syntax-rule (with-cached-connection uri port exp ...)- "Bind PORT with EXP... to a socket connected to URI."- (call-with-cached-connection uri (lambda (port) exp ...)))- (define* (process-substitution store-item destination #:key cache-urls acl deduplicate? print-build-trace?)@@ -1010,8 +984,6 @@ default value." ;;; Local Variables: ;;; eval: (put 'with-timeout 'scheme-indent-function 1)-;;; eval: (put 'with-cached-connection 'scheme-indent-function 2)-;;; eval: (put 'call-with-cached-connection 'scheme-indent-function 1) ;;; End: ;;; substitute.scm ends here-- 2.30.0
C
C
Christopher Baines wrote on 16 Jan 14:58 +0100
[PATCH v4 11/13] substitute: Remove redundant fetch arguments.
(address . 45409@debbugs.gnu.org)
20210116135803.21955-11-mail@cbaines.net
It's just called in one place, with hardcoded argument values, so just inlinethem.
* guix/scripts/substitute.scm (fetch): Remove arguments that don't vary, copythe values from the call site in process-substitution.(process-substitution): Remove unnecessary argument values from fetch call.--- guix/scripts/substitute.scm | 23 +++++++---------------- 1 file changed, 7 insertions(+), 16 deletions(-)
Toggle diff (59 lines)diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex d316bdef15..b5a4c08325 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -169,18 +169,12 @@ again." (sigaction SIGALRM SIG_DFL) (apply values result))))) -(define* (fetch uri #:key (buffered? #t) (timeout? #t)- (keep-alive? #f))+(define (fetch uri) "Return a binary input port to URI and the number of bytes it's expected to-provide.--When PORT is true, use it as the underlying I/O port for HTTP transfers; when-PORT is false, open a new connection for URI. When KEEP-ALIVE? is true, the-connection (typically PORT) is kept open once data has been fetched from URI."+provide." (case (uri-scheme uri) ((file)- (let ((port (open-file (uri-path uri)- (if buffered? "rb" "r0b"))))+ (let ((port (open-file (uri-path uri) "r0b"))) (values port (stat:size (stat port))))) ((http https) (guard (c ((http-get-error? c)@@ -192,17 +186,15 @@ connection (typically PORT) is kept open once data has been fetched from URI." ;; sudo tc qdisc add dev eth0 root netem delay 1500ms ;; and then cancel with: ;; sudo tc qdisc del dev eth0 root- (with-timeout (if timeout?- %fetch-timeout- 0)+ (with-timeout %fetch-timeout (begin (warning (G_ "while fetching ~a: server is somewhat slow~%") (uri->string uri)) (warning (G_ "try `--no-substitutes' if the problem persists~%"))) (http-fetch uri #:text? #f #:open-connection open-connection-for-uri/maybe- #:keep-alive? keep-alive?- #:buffered? buffered?+ #:keep-alive? #t+ #:buffered? #f #:verify-certificate? #f)))) (else (leave (G_ "unsupported substitute URI scheme: ~a~%")@@ -726,8 +718,7 @@ the current output port." (let*-values (((raw download-size) ;; 'guix publish' without '--cache' doesn't specify a ;; Content-Length, so DOWNLOAD-SIZE is #f in this case.- (fetch uri #:buffered? #f #:timeout? #f- #:keep-alive? #t))+ (fetch uri)) ((progress) (let* ((dl-size (or download-size (and (equal? compression "none")-- 2.30.0
C
C
Christopher Baines wrote on 16 Jan 14:58 +0100
[PATCH v4 12/13] substitute: Inline fetch in to process-substitutes.
(address . 45409@debbugs.gnu.org)
20210116135803.21955-12-mail@cbaines.net
As it's only called in one place, and this should make the code easier toread.
* guix/scripts/substitute.scm (fetch): Move procedure inside…(process-substitution): …here.--- guix/scripts/substitute.scm | 60 ++++++++++++++++++------------------- 1 file changed, 29 insertions(+), 31 deletions(-)
Toggle diff (80 lines)diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex b5a4c08325..858ce1dcc4 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -169,37 +169,6 @@ again." (sigaction SIGALRM SIG_DFL) (apply values result))))) -(define (fetch uri)- "Return a binary input port to URI and the number of bytes it's expected to-provide."- (case (uri-scheme uri)- ((file)- (let ((port (open-file (uri-path uri) "r0b")))- (values port (stat:size (stat port)))))- ((http https)- (guard (c ((http-get-error? c)- (leave (G_ "download from '~a' failed: ~a, ~s~%")- (uri->string (http-get-error-uri c))- (http-get-error-code c)- (http-get-error-reason c))))- ;; Test this with:- ;; sudo tc qdisc add dev eth0 root netem delay 1500ms- ;; and then cancel with:- ;; sudo tc qdisc del dev eth0 root- (with-timeout %fetch-timeout- (begin- (warning (G_ "while fetching ~a: server is somewhat slow~%")- (uri->string uri))- (warning (G_ "try `--no-substitutes' if the problem persists~%")))- (http-fetch uri #:text? #f- #:open-connection open-connection-for-uri/maybe- #:keep-alive? #t- #:buffered? #f- #:verify-certificate? #f))))- (else- (leave (G_ "unsupported substitute URI scheme: ~a~%")- (uri->string uri)))))- (define (narinfo-cache-file cache-url path) "Return the name of the local file that contains an entry for PATH. The entry is stored in a sub-directory specific to CACHE-URL."@@ -705,6 +674,35 @@ the current output port." (apply dump-file/deduplicate (append args (list #:store (%store-prefix))))) + (define (fetch uri)+ (case (uri-scheme uri)+ ((file)+ (let ((port (open-file (uri-path uri) "r0b")))+ (values port (stat:size (stat port)))))+ ((http https)+ (guard (c ((http-get-error? c)+ (leave (G_ "download from '~a' failed: ~a, ~s~%")+ (uri->string (http-get-error-uri c))+ (http-get-error-code c)+ (http-get-error-reason c))))+ ;; Test this with:+ ;; sudo tc qdisc add dev eth0 root netem delay 1500ms+ ;; and then cancel with:+ ;; sudo tc qdisc del dev eth0 root+ (with-timeout %fetch-timeout+ (begin+ (warning (G_ "while fetching ~a: server is somewhat slow~%")+ (uri->string uri))+ (warning (G_ "try `--no-substitutes' if the problem persists~%")))+ (http-fetch uri #:text? #f+ #:open-connection open-connection-for-uri/maybe+ #:keep-alive? #t+ #:buffered? #f+ #:verify-certificate? #f))))+ (else+ (leave (G_ "unsupported substitute URI scheme: ~a~%")+ (uri->string uri)))))+ (unless narinfo (leave (G_ "no valid substitute for '~a'~%") store-item))-- 2.30.0
C
C
Christopher Baines wrote on 16 Jan 14:58 +0100
[PATCH v4 13/13] substitute: Remove fetch-narinfos use open-connection-for-uri/maybe.
(address . 45409@debbugs.gnu.org)
20210116135803.21955-13-mail@cbaines.net
At least by default. Instead, make the open-connection procedure a parameter,and make the default guix:open-connection-for-uri. Do so similarly forlookup-narinfos and lookup-narinfos/diverse which work towards callingfetch-narinfos.
This means this code can be moved to a different module, without havinguse/move the connection caching code.
* guix/scripts/substitute.scm (fetch-narinfos): Add #:open-connectionargument, and call http-multiple-get with it.(lookup-narinfos) Add #:open-connection argument, and call fetch-narinfos withit.(lookup-narinfos/diverse): Add #:open-connection argument, and calllookup-narinfos with it.(process-query): Call lookup-narinfos/diverse with #:open-connectionopen-connection-for-uri/maybe.--- guix/scripts/substitute.scm | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-)
Toggle diff (83 lines)diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex 858ce1dcc4..c2a8dd419f 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -314,7 +314,8 @@ port to it, or, if connection failed, print a warning and return #f. Pass (args (apply throw args))))) -(define (fetch-narinfos url paths)+(define* (fetch-narinfos url paths+ #:key (open-connection guix:open-connection-for-uri)) "Retrieve all the narinfos for PATHS from the cache at URL and return them." (define update-progress! (let ((done 0)@@ -379,8 +380,7 @@ port to it, or, if connection failed, print a warning and return #f. Pass (http-multiple-get uri handle-narinfo-response '() requests- #:open-connection- open-connection-for-uri/maybe+ #:open-connection open-connection #:verify-certificate? #f)))) result)) ((file #f)@@ -395,7 +395,8 @@ port to it, or, if connection failed, print a warning and return #f. Pass (do-fetch (string->uri url))) -(define (lookup-narinfos cache paths)+(define* (lookup-narinfos cache paths+ #:key (open-connection guix:open-connection-for-uri)) "Return the narinfos for PATHS, invoking the server at CACHE when no information is available locally." (let-values (((cached missing)@@ -412,10 +413,13 @@ information is available locally." paths))) (if (null? missing) cached- (let ((missing (fetch-narinfos cache missing)))+ (let ((missing (fetch-narinfos cache missing+ #:open-connection open-connection))) (append cached (or missing '())))))) -(define (lookup-narinfos/diverse caches paths authorized?)+(define* (lookup-narinfos/diverse caches paths authorized?+ #:key (open-connection+ guix:open-connection-for-uri)) "Look up narinfos for PATHS on all of CACHES, a list of URLS, in that order. That is, when a cache lacks an AUTHORIZED? narinfo, look it up in the next cache, and so on.@@ -447,7 +451,8 @@ AUTHORIZED? narinfo." (_ (match caches ((cache rest ...)- (let* ((narinfos (lookup-narinfos cache paths))+ (let* ((narinfos (lookup-narinfos cache paths+ #:open-connection open-connection)) (definite (map narinfo-path (filter authorized? narinfos))) (missing (lset-difference string=? paths definite))) ;XXX: perf (loop rest missing@@ -587,14 +592,18 @@ authorized substitutes." (match (string-tokenize command) (("have" paths ..1) ;; Return the subset of PATHS available in CACHE-URLS.- (let ((substitutable (lookup-narinfos/diverse cache-urls paths valid?)))+ (let ((substitutable (lookup-narinfos/diverse+ cache-urls paths valid?+ #:open-connection open-connection-for-uri/maybe))) (for-each (lambda (narinfo) (format #t "~a~%" (narinfo-path narinfo))) substitutable) (newline))) (("info" paths ..1) ;; Reply info about PATHS if it's in CACHE-URLS.- (let ((substitutable (lookup-narinfos/diverse cache-urls paths valid?)))+ (let ((substitutable (lookup-narinfos/diverse+ cache-urls paths valid?+ #:open-connection open-connection-for-uri/maybe))) (for-each display-narinfo-data substitutable) (newline))) (wtf-- 2.30.0
C
C
Christopher Baines wrote on 16 Jan 15:18 +0100
Re: [bug#45409] [PATCH v3 3/3] guix: Split (guix substitutes) from (guix scripts substitute).
(name . Ludovic Courtès)(address . ludo@gnu.org)(address . 45409@debbugs.gnu.org)
87sg717yny.fsf@cbaines.net
Ludovic Courtès <ludo@gnu.org> writes:
Toggle quote (7 lines)>> I think it's possible to separate it out if some of the error handling>> is pushed down in to the http procedures, and if when they get an error>> indicating the connection is unusable, they close the port.>> Ideally the (web …) modules would do that (that’s what you mean, right?)> but then we’d have to wait for Guile proper to implement these things.
Well, I'm unsure, all I'm trying to do at the moment is push theconnection handling down in to http-multiple-get [1].
1: https://issues.guix.info/45409#22
While thinking about this just now, I think there's the possibility ofconnection caching causing issues in process-substitution. I'm guessingthe exceptions could occur anywhere from in http-fetch where it callshttp-get, to back in process-substitution where it finishes reading fromthe port (I'm unsure where, I loose track of where the port is used).
There was a little bit more error handling previously, as the use offetch was wrapped in with-cached-connection, but given that the responsebody hasn't been read by this point, I don't think the previous statewas very safe either.
Toggle quote (13 lines)>> I've pushed some rough commits for this to this branch:>>>> https://git.cbaines.net/guix/log/?h=prepare-to-move-guix-scripts-substitute-code>>>> I'm still struggling with the tests, currently make check hangs, I think>> on the challenge tests, and I don't currently have a plan to work out>> why the test is hanging.>> Overall the approach LGTM.>> How about first getting (guix narinfo) in ‘master’ (the bits we agreed> on), and then tackling the rest so that it’s less daunting?
I've pushed the (guix narinfo) addition now, with the patch that changedthe unauthorized substitute handling.
Toggle quote (2 lines)> Also, I’d like to get the zstd patches in. :-)
I've rebased on master, tweaked the commit messages, and send a set ofv4 patches and while they don't create the (guix substitutes) module, Ithink they unpick the bits I'd like to move out from the code doing theconnection caching.
Thanks,
Chris
-----BEGIN PGP SIGNATURE-----
iQKlBAEBCgCPFiEEPonu50WOcg2XVOCyXiijOwuE9XcFAmAC9cFfFIAAAAAALgAoaXNzdWVyLWZwckBub3RhdGlvbnMub3BlbnBncC5maWZ0aGhvcnNlbWFuLm5ldDNFODlFRUU3NDU4RTcyMEQ5NzU0RTBCMjVFMjhBMzNCMEI4NEY1NzcRHG1haWxAY2JhaW5lcy5uZXQACgkQXiijOwuE9XeKxhAAmRPi9iXgECK2YxEsgNNDOpshCJmL2wsvnp37G3S1c0odAic2Pou95legV6D7zQqSgcknLLdb5Xu2EmRYlixcob3SVMoqIShXkHObumUOBRKsInPX0TU11HDJq1DCeO27IJDYNA0Fs1ZBTWBjR1JIr6VJ8B7qoKLHYnlYACJQvVZo7LA29vuCjrgXM+QEMgykD7TtUBc4940GwHHFtg1KTr92IRulkgPilZsM/dwziNkvJqfZzJzMxVgJrfJOd60F3MG9BPdfkZEe8MlivToOD1uohYbYYnaV27q1rO2+0WUv/5jwkiPA/N1SKiIpobRbtYSwtvzKVgAV7P0gfhrWTvvjGLP9/ynk22XzIPn44/EzCl5DiL2hN11aWLNznDvhVbu1/ixZEnhWz3+5OJMcu4SEjvLo1gGuHXkB6vCNVV/pJPayWup0cG4+zmL6auyUwUolesYSRzdAkMoayClk1Nm3EPlWwgepp9x0f4OJznLUsIrcdvjxFP0tIjAHMQLIqmPpFK3Zb6Jf4iXYkm6S1MEMmtRvwKytiAXyi5w/bhDvTii9gwlA/EPmjCIctPOI6cpv761Z+agFiW3JHc3Cq7tC9wuy4gTCYX5WTvVRh3KZI14pHddETWUP5WzRfdjpKUTf16At0ZSsSaZK6qmnkesRgkb2Ze/I5+4JjbesYps==2OeU-----END PGP SIGNATURE-----
C
C
Christopher Baines wrote on 13 Feb 14:47 +0100
[PATCH v5 01/14] substitute: Remove buffer handling from fetch.
(address . 45409@debbugs.gnu.org)
20210213134719.19625-1-mail@cbaines.net
http-fetch does this, so just set the right option.
* guix/scripts/substitute.scm (fetch): Remove buffering code, and pass #:buffered? to http-fetch.--- guix/scripts/substitute.scm | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
Toggle diff (18 lines)diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex f9bcead045..88610a0781 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -204,10 +204,9 @@ connection (typically PORT) is kept open once data has been fetched from URI." (when (or (not port) (port-closed? port)) (set! port (guix:open-connection-for-uri uri #:verify-certificate? #f)))- (unless (or buffered? (not (file-port? port)))- (setvbuf port 'none)) (http-fetch uri #:text? #f #:port port #:keep-alive? keep-alive?+ #:buffered? buffered? #:verify-certificate? #f)))))) (else (leave (G_ "unsupported substitute URI scheme: ~a~%")-- 2.30.0
C
C
Christopher Baines wrote on 13 Feb 14:47 +0100
[PATCH v5 02/14] substitute: Remove connection handling from fetch.
(address . 45409@debbugs.gnu.org)
20210213134719.19625-2-mail@cbaines.net
http-fetch does this, so just use that code instead.
* guix/scripts/substitute.scm (fetch): Remove connection handling when theport is closed.--- guix/scripts/substitute.scm | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-)
Toggle diff (25 lines)diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex 88610a0781..323957910a 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -200,14 +200,10 @@ connection (typically PORT) is kept open once data has been fetched from URI." (warning (G_ "while fetching ~a: server is somewhat slow~%") (uri->string uri)) (warning (G_ "try `--no-substitutes' if the problem persists~%")))- (begin- (when (or (not port) (port-closed? port))- (set! port (guix:open-connection-for-uri- uri #:verify-certificate? #f)))- (http-fetch uri #:text? #f #:port port- #:keep-alive? keep-alive?- #:buffered? buffered?- #:verify-certificate? #f))))))+ (http-fetch uri #:text? #f #:port port+ #:keep-alive? keep-alive?+ #:buffered? buffered?+ #:verify-certificate? #f))))) (else (leave (G_ "unsupported substitute URI scheme: ~a~%") (uri->string uri)))))-- 2.30.0
C
C
Christopher Baines wrote on 13 Feb 14:47 +0100
[PATCH v5 05/14] http-client: Add error handling to http-multiple-get.
(address . 45409@debbugs.gnu.org)
20210213134719.19625-5-mail@cbaines.net
Making sure to close the port if it looks to be unusable. This closing of theport will allow for caching connections, without caching broken connections,as the cache can avoid handing out closed ports.
* guix/http-client.scm (http-multiple-get): Try to catch exceptions thathappen if the port is unusable, this is a adaptation of code within the (guixscripts substitute) module.--- guix/http-client.scm | 74 +++++++++++++++++++++++++++++++++----------- 1 file changed, 56 insertions(+), 18 deletions(-)
Toggle diff (101 lines)diff --git a/guix/http-client.scm b/guix/http-client.scmindex 7ead493633..3aba3b28c1 100644--- a/guix/http-client.scm+++ b/guix/http-client.scm@@ -38,6 +38,7 @@ #:use-module (guix utils) #:use-module (guix base64) #:autoload (gcrypt hash) (sha256)+ #:autoload (gnutls) (error/invalid-session) #:use-module ((guix build utils) #:select (mkdir-p dump-port)) #:use-module ((guix build download)@@ -180,10 +181,25 @@ returning." ;; Inherit the HTTP proxying property from P. (set-http-proxy-port?! buffer (http-proxy-port? p)) - (for-each (cut write-request <> buffer)- batch)- (put-bytevector p (get))- (force-output p))+ (catch #t+ (lambda ()+ (for-each (cut write-request <> buffer)+ batch)+ (put-bytevector p (get))+ (force-output p))+ (lambda (key . args)+ ;; If PORT becomes unusable, open a fresh connection and+ ;; retry.+ (if (or (and (eq? key 'system-error)+ (= EPIPE (system-error-errno `(,key ,@args))))+ (and (eq? key 'gnutls-error)+ (eq? (first args) error/invalid-session)))+ (begin+ (close-port p) ; close the broken port+ (connect #f+ requests+ result))+ (apply throw key args))))) ;; Now start processing responses. (let loop ((sent batch)@@ -199,20 +215,42 @@ returning." (remainder (connect p remainder result)))) ((head tail ...)- (let* ((resp (read-response p))- (body (response-body-port resp))- (result (proc head resp body result)))- ;; The server can choose to stop responding at any time, in which- ;; case we have to try again. Check whether that is the case.- ;; Note that even upon "Connection: close", we can read from BODY.- (match (assq 'connection (response-headers resp))- (('connection 'close)- (close-port p)- (connect #f ;try again- (drop requests (+ 1 processed))- result))- (_- (loop tail (+ 1 processed) result)))))))))) ;keep going+ (catch #t+ (lambda ()+ (let* ((resp (read-response p))+ (body (response-body-port resp))+ (result (proc head resp body result)))+ ;; The server can choose to stop responding at any time,+ ;; in which case we have to try again. Check whether+ ;; that is the case. Note that even upon "Connection:+ ;; close", we can read from BODY.+ (match (assq 'connection (response-headers resp))+ (('connection 'close)+ (close-port p)+ (connect #f ;try again+ (drop requests (+ 1 processed))+ result))+ (_+ (loop tail (+ 1 processed) result))))) ;keep going+ (lambda (key . args)+ ;; If PORT was cached and the server closed the connection+ ;; in the meantime, we get EPIPE. In that case, open a+ ;; fresh connection and retry. We might also get+ ;; 'bad-response or a similar exception from (web response)+ ;; later on, once we've sent the request, or a+ ;; ERROR/INVALID-SESSION from GnuTLS.+ (if (or (and (eq? key 'system-error)+ (= EPIPE (system-error-errno `(,key ,@args))))+ (and (eq? key 'gnutls-error)+ (eq? (first args) error/invalid-session))+ (memq key+ '(bad-response bad-header bad-header-component)))+ (begin+ (close-port p)+ (connect #f ; try again+ (drop requests (+ 1 processed))+ result))+ (apply throw key args)))))))))) ;;;-- 2.30.0
C
C
Christopher Baines wrote on 13 Feb 14:47 +0100
[PATCH v5 06/14] substitute: open-connection-for-uri/maybe add #:verify-certificate?.
(address . 45409@debbugs.gnu.org)
20210213134719.19625-6-mail@cbaines.net
As this is used by http-fetch and http-multiple-get when they call thespecified open connection procedure.
* guix/scripts/substitute.scm (open-connection-for-uri/maybe): Support #:verify-certificate?.--- guix/scripts/substitute.scm | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-)
Toggle diff (26 lines)diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex fc6bb54301..f01c11b020 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -322,7 +322,8 @@ if file doesn't exist, and the narinfo otherwise." (define* (open-connection-for-uri/maybe uri #:key fresh?- (time %fetch-timeout))+ (time %fetch-timeout)+ verify-certificate?) "Open a connection to URI via 'open-connection-for-uri/cached' and return a port to it, or, if connection failed, print a warning and return #f. Pass #:fresh? to 'open-connection-for-uri/cached'."@@ -332,7 +333,8 @@ port to it, or, if connection failed, print a warning and return #f. Pass (catch #t (lambda () (open-connection-for-uri/cached uri #:timeout time- #:fresh? fresh?))+ #:fresh? fresh?+ #:verify-certificate? verify-certificate?)) (match-lambda* (('getaddrinfo-error error) (unless (hash-ref %unreachable-hosts host)-- 2.30.0
C
C
Christopher Baines wrote on 13 Feb 14:47 +0100
[PATCH v5 07/14] substitute: Stop using call-with-cached-connection in fetch-narinfos.
(address . 45409@debbugs.gnu.org)
20210213134719.19625-7-mail@cbaines.net
Instead, just pass open-connection-for-uri/maybe to http-multiple-get. Thiscode should be functionaly similar to the previous code. The eventual aim ofthis is to make the connection caching not mandatory in fetch-narinfos.
* guix/scripts/substitute.scm (fetch-narinfos): Remove use ofcall-with-cached-connection.--- guix/scripts/substitute.scm | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-)
Toggle diff (35 lines)diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex f01c11b020..cd52ad747e 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -412,20 +412,14 @@ port to it, or, if connection failed, print a warning and return #f. Pass ;; on the X.509 PKI. We can do it because we authenticate ;; narinfos, which provides a much stronger guarantee. (let* ((requests (map (cut narinfo-request url <>) paths))- (result (call-with-cached-connection uri- (lambda (port)- (if port- (begin- (update-progress!)- (http-multiple-get uri- handle-narinfo-response '()- requests- #:open-connection- open-connection-for-uri/cached- #:verify-certificate? #f- #:port port))- '()))- open-connection-for-uri/maybe)))+ (result (begin+ (update-progress!)+ (http-multiple-get uri+ handle-narinfo-response '()+ requests+ #:open-connection+ open-connection-for-uri/maybe+ #:verify-certificate? #f)))) (newline (current-error-port)) result)) ((file #f)-- 2.30.0
C
C
Christopher Baines wrote on 13 Feb 14:47 +0100
[PATCH v5 04/14] guix: Move http-multiple-get to (guix http-client).
(address . 45409@debbugs.gnu.org)
20210213134719.19625-4-mail@cbaines.net
From (guix scripts substitute). This will make it easier to reuse this code.
* guix/scripts/substitute.scm (http-multiple-get): Remove, and move to…* guix/http-client.scm (http-multiple-get): …here.--- guix/http-client.scm | 76 +++++++++++++++++++++++++++++++++++++ guix/scripts/substitute.scm | 70 ---------------------------------- 2 files changed, 76 insertions(+), 70 deletions(-)
Toggle diff (186 lines)diff --git a/guix/http-client.scm b/guix/http-client.scmindex 553640fe9e..7ead493633 100644--- a/guix/http-client.scm+++ b/guix/http-client.scm@@ -21,8 +21,11 @@ (define-module (guix http-client) #:use-module (web uri)+ #:use-module (web http) #:use-module ((web client) #:hide (open-socket-for-uri))+ #:use-module (web request) #:use-module (web response)+ #:use-module (srfi srfi-1) #:use-module (srfi srfi-11) #:use-module (srfi srfi-19) #:use-module (srfi srfi-26)@@ -50,6 +53,7 @@ http-get-error-reason http-fetch+ http-multiple-get %http-cache-ttl http-fetch/cached))@@ -138,6 +142,78 @@ Raise an '&http-get-error' condition if downloading fails." (uri->string uri) code (response-reason-phrase resp)))))))))))) +(define* (http-multiple-get base-uri proc seed requests+ #:key port (verify-certificate? #t)+ (open-connection guix:open-connection-for-uri)+ (keep-alive? #t)+ (batch-size 1000))+ "Send all of REQUESTS to the server at BASE-URI. Call PROC for each+response, passing it the request object, the response, a port from which to+read the response body, and the previous result, starting with SEED, à la+'fold'. Return the final result.++When PORT is specified, use it as the initial connection on which HTTP+requests are sent; otherwise call OPEN-CONNECTION to open a new connection for+a URI. When KEEP-ALIVE? is false, close the connection port before+returning."+ (let connect ((port port)+ (requests requests)+ (result seed))+ (define batch+ (if (>= batch-size (length requests))+ requests+ (take requests batch-size)))++ ;; (format (current-error-port) "connecting (~a requests left)..."+ ;; (length requests))+ (let ((p (or port (open-connection base-uri+ #:verify-certificate?+ verify-certificate?))))+ ;; For HTTPS, P is not a file port and does not support 'setvbuf'.+ (when (file-port? p)+ (setvbuf p 'block (expt 2 16)))++ ;; Send BATCH in a row.+ ;; XXX: Do our own caching to work around inefficiencies when+ ;; communicating over TLS: <http://bugs.gnu.org/22966>.+ (let-values (((buffer get) (open-bytevector-output-port)))+ ;; Inherit the HTTP proxying property from P.+ (set-http-proxy-port?! buffer (http-proxy-port? p))++ (for-each (cut write-request <> buffer)+ batch)+ (put-bytevector p (get))+ (force-output p))++ ;; Now start processing responses.+ (let loop ((sent batch)+ (processed 0)+ (result result))+ (match sent+ (()+ (match (drop requests processed)+ (()+ (unless keep-alive?+ (close-port p))+ (reverse result))+ (remainder+ (connect p remainder result))))+ ((head tail ...)+ (let* ((resp (read-response p))+ (body (response-body-port resp))+ (result (proc head resp body result)))+ ;; The server can choose to stop responding at any time, in which+ ;; case we have to try again. Check whether that is the case.+ ;; Note that even upon "Connection: close", we can read from BODY.+ (match (assq 'connection (response-headers resp))+ (('connection 'close)+ (close-port p)+ (connect #f ;try again+ (drop requests (+ 1 processed))+ result))+ (_+ (loop tail (+ 1 processed) result)))))))))) ;keep going+ ;;; ;;; Caching.diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex f01892776e..fc6bb54301 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -299,76 +299,6 @@ return its MAX-LENGTH first elements and its tail." (values (reverse result) lst) (loop (+ 1 len) tail (cons head result))))))) -(define* (http-multiple-get base-uri proc seed requests- #:key port (verify-certificate? #t)- (open-connection guix:open-connection-for-uri)- (keep-alive? #t)- (batch-size 1000))- "Send all of REQUESTS to the server at BASE-URI. Call PROC for each-response, passing it the request object, the response, a port from which to-read the response body, and the previous result, starting with SEED, à la-'fold'. Return the final result.--When PORT is specified, use it as the initial connection on which HTTP-requests are sent; otherwise call OPEN-CONNECTION to open a new connection for-a URI. When KEEP-ALIVE? is false, close the connection port before-returning."- (let connect ((port port)- (requests requests)- (result seed))- (define batch- (at-most batch-size requests))-- ;; (format (current-error-port) "connecting (~a requests left)..."- ;; (length requests))- (let ((p (or port (open-connection base-uri- #:verify-certificate?- verify-certificate?))))- ;; For HTTPS, P is not a file port and does not support 'setvbuf'.- (when (file-port? p)- (setvbuf p 'block (expt 2 16)))-- ;; Send BATCH in a row.- ;; XXX: Do our own caching to work around inefficiencies when- ;; communicating over TLS: <http://bugs.gnu.org/22966>.- (let-values (((buffer get) (open-bytevector-output-port)))- ;; Inherit the HTTP proxying property from P.- (set-http-proxy-port?! buffer (http-proxy-port? p))-- (for-each (cut write-request <> buffer)- batch)- (put-bytevector p (get))- (force-output p))-- ;; Now start processing responses.- (let loop ((sent batch)- (processed 0)- (result result))- (match sent- (()- (match (drop requests processed)- (()- (unless keep-alive?- (close-port p))- (reverse result))- (remainder- (connect p remainder result))))- ((head tail ...)- (let* ((resp (read-response p))- (body (response-body-port resp))- (result (proc head resp body result)))- ;; The server can choose to stop responding at any time, in which- ;; case we have to try again. Check whether that is the case.- ;; Note that even upon "Connection: close", we can read from BODY.- (match (assq 'connection (response-headers resp))- (('connection 'close)- (close-port p)- (connect #f ;try again- (drop requests (+ 1 processed))- result))- (_- (loop tail (+ 1 processed) result)))))))))) ;keep going- (define (read-to-eof port) "Read from PORT until EOF is reached. The data are discarded." (dump-port port (%make-void-port "w")))-- 2.30.0
C
C
Christopher Baines wrote on 13 Feb 14:47 +0100
[PATCH v5 08/14] http-client: Accept #:open-connection in http-fetch.
(address . 45409@debbugs.gnu.org)
20210213134719.19625-8-mail@cbaines.net
So that an alternative procedure can be passed in, perhaps to performconnection caching.
* guix/http-client.scm (http-fetch): Add an #:open-connection keywordargument.--- guix/http-client.scm | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-)
Toggle diff (29 lines)diff --git a/guix/http-client.scm b/guix/http-client.scmindex 3aba3b28c1..2d7458a56e 100644--- a/guix/http-client.scm+++ b/guix/http-client.scm@@ -75,6 +75,7 @@ (define* (http-fetch uri #:key port (text? #f) (buffered? #t)+ (open-connection guix:open-connection-for-uri) (keep-alive? #f) (verify-certificate? #t) (headers '((user-agent . "GNU Guile")))@@ -97,10 +98,10 @@ Raise an '&http-get-error' condition if downloading fails." (let loop ((uri (if (string? uri) (string->uri uri) uri)))- (let ((port (or port (guix:open-connection-for-uri uri- #:verify-certificate?- verify-certificate?- #:timeout timeout)))+ (let ((port (or port (open-connection uri+ #:verify-certificate?+ verify-certificate?+ #:timeout timeout))) (headers (match (uri-userinfo uri) ((? string? str) (cons (cons 'Authorization-- 2.30.0
C
C
Christopher Baines wrote on 13 Feb 14:47 +0100
[PATCH v5 09/14] substitute: Change connection cache handling in process-substitution.
(address . 45409@debbugs.gnu.org)
20210213134719.19625-9-mail@cbaines.net
Just pass open-connection-for-uri/maybe to http-fetch, this removes the needfor with-cached-connection and passing the port in.
* guix/scripts/substitute.scm (fetch): Don't take a port as an argument, andpass open-connection-for-uri/maybe to http-fetch.(process-substitution): Don't call fetch with with-cached-connection.--- guix/scripts/substitute.scm | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-)
Toggle diff (38 lines)diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex cd52ad747e..5d4884a7db 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -170,7 +170,7 @@ again." (apply values result))))) (define* (fetch uri #:key (buffered? #t) (timeout? #t)- (keep-alive? #f) (port #f))+ (keep-alive? #f)) "Return a binary input port to URI and the number of bytes it's expected to provide. @@ -199,7 +199,8 @@ connection (typically PORT) is kept open once data has been fetched from URI." (warning (G_ "while fetching ~a: server is somewhat slow~%") (uri->string uri)) (warning (G_ "try `--no-substitutes' if the problem persists~%")))- (http-fetch uri #:text? #f #:port port+ (http-fetch uri #:text? #f+ #:open-connection open-connection-for-uri/maybe #:keep-alive? keep-alive? #:buffered? buffered? #:verify-certificate? #f))))@@ -752,10 +753,8 @@ the current output port." (let*-values (((raw download-size) ;; 'guix publish' without '--cache' doesn't specify a ;; Content-Length, so DOWNLOAD-SIZE is #f in this case.- (with-cached-connection uri port- (fetch uri #:buffered? #f #:timeout? #f- #:port port- #:keep-alive? #t)))+ (fetch uri #:buffered? #f #:timeout? #f+ #:keep-alive? #t)) ((progress) (let* ((dl-size (or download-size (and (equal? compression "none")-- 2.30.0
C
C
Christopher Baines wrote on 13 Feb 14:47 +0100
[PATCH v5 03/14] substitute: Remove redundant let block from fetch.
(address . 45409@debbugs.gnu.org)
20210213134719.19625-3-mail@cbaines.net
* guix/scripts/substitute.scm (fetch): Remove redundant let block.--- guix/scripts/substitute.scm | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-)
Toggle diff (36 lines)diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex 323957910a..f01892776e 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -192,18 +192,17 @@ connection (typically PORT) is kept open once data has been fetched from URI." ;; sudo tc qdisc add dev eth0 root netem delay 1500ms ;; and then cancel with: ;; sudo tc qdisc del dev eth0 root- (let ((port port))- (with-timeout (if timeout?- %fetch-timeout- 0)- (begin- (warning (G_ "while fetching ~a: server is somewhat slow~%")- (uri->string uri))- (warning (G_ "try `--no-substitutes' if the problem persists~%")))- (http-fetch uri #:text? #f #:port port- #:keep-alive? keep-alive?- #:buffered? buffered?- #:verify-certificate? #f)))))+ (with-timeout (if timeout?+ %fetch-timeout+ 0)+ (begin+ (warning (G_ "while fetching ~a: server is somewhat slow~%")+ (uri->string uri))+ (warning (G_ "try `--no-substitutes' if the problem persists~%")))+ (http-fetch uri #:text? #f #:port port+ #:keep-alive? keep-alive?+ #:buffered? buffered?+ #:verify-certificate? #f)))) (else (leave (G_ "unsupported substitute URI scheme: ~a~%") (uri->string uri)))))-- 2.30.0
C
C
Christopher Baines wrote on 13 Feb 14:47 +0100
[PATCH v5 12/14] substitute: Inline fetch in to process-substitutes.
(address . 45409@debbugs.gnu.org)
20210213134719.19625-12-mail@cbaines.net
As it's only called in one place, and this should make the code easier toread.
* guix/scripts/substitute.scm (fetch): Move procedure inside…(process-substitution): …here.--- guix/scripts/substitute.scm | 60 ++++++++++++++++++------------------- 1 file changed, 29 insertions(+), 31 deletions(-)
Toggle diff (80 lines)diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex 26fd05429f..717c232633 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -169,37 +169,6 @@ again." (sigaction SIGALRM SIG_DFL) (apply values result))))) -(define (fetch uri)- "Return a binary input port to URI and the number of bytes it's expected to-provide."- (case (uri-scheme uri)- ((file)- (let ((port (open-file (uri-path uri) "r0b")))- (values port (stat:size (stat port)))))- ((http https)- (guard (c ((http-get-error? c)- (leave (G_ "download from '~a' failed: ~a, ~s~%")- (uri->string (http-get-error-uri c))- (http-get-error-code c)- (http-get-error-reason c))))- ;; Test this with:- ;; sudo tc qdisc add dev eth0 root netem delay 1500ms- ;; and then cancel with:- ;; sudo tc qdisc del dev eth0 root- (with-timeout %fetch-timeout- (begin- (warning (G_ "while fetching ~a: server is somewhat slow~%")- (uri->string uri))- (warning (G_ "try `--no-substitutes' if the problem persists~%")))- (http-fetch uri #:text? #f- #:open-connection open-connection-for-uri/maybe- #:keep-alive? #t- #:buffered? #f- #:verify-certificate? #f))))- (else- (leave (G_ "unsupported substitute URI scheme: ~a~%")- (uri->string uri)))))- (define (narinfo-cache-file cache-url path) "Return the name of the local file that contains an entry for PATH. The entry is stored in a sub-directory specific to CACHE-URL."@@ -706,6 +675,35 @@ the current output port." (apply dump-file/deduplicate (append args (list #:store (%store-prefix))))) + (define (fetch uri)+ (case (uri-scheme uri)+ ((file)+ (let ((port (open-file (uri-path uri) "r0b")))+ (values port (stat:size (stat port)))))+ ((http https)+ (guard (c ((http-get-error? c)+ (leave (G_ "download from '~a' failed: ~a, ~s~%")+ (uri->string (http-get-error-uri c))+ (http-get-error-code c)+ (http-get-error-reason c))))+ ;; Test this with:+ ;; sudo tc qdisc add dev eth0 root netem delay 1500ms+ ;; and then cancel with:+ ;; sudo tc qdisc del dev eth0 root+ (with-timeout %fetch-timeout+ (begin+ (warning (G_ "while fetching ~a: server is somewhat slow~%")+ (uri->string uri))+ (warning (G_ "try `--no-substitutes' if the problem persists~%")))+ (http-fetch uri #:text? #f+ #:open-connection open-connection-for-uri/maybe+ #:keep-alive? #t+ #:buffered? #f+ #:verify-certificate? #f))))+ (else+ (leave (G_ "unsupported substitute URI scheme: ~a~%")+ (uri->string uri)))))+ (unless narinfo (leave (G_ "no valid substitute for '~a'~%") store-item))-- 2.30.0
C
C
Christopher Baines wrote on 13 Feb 14:47 +0100
[PATCH v5 10/14] substitute: Remove now redundant connection caching helpers.
(address . 45409@debbugs.gnu.org)
20210213134719.19625-10-mail@cbaines.net
Failures now should be handled where they occur, and if there's a problemthat's symptomatic of an issue with the connection, the port should be closed.
* guix/scripts/substitute.scm (call-with-cached-connection): Remove procedure.(with-cached-connection): Remove syntax rule.--- guix/scripts/substitute.scm | 28 ---------------------------- 1 file changed, 28 deletions(-)
Toggle diff (48 lines)diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex 5d4884a7db..a2b1526cc6 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -690,32 +690,6 @@ server certificates." (drain-input socket) socket)))))))) -(define* (call-with-cached-connection uri proc- #:optional- (open-connection- open-connection-for-uri/cached))- (let ((port (open-connection uri)))- (catch #t- (lambda ()- (proc port))- (lambda (key . args)- ;; If PORT was cached and the server closed the connection in the- ;; meantime, we get EPIPE. In that case, open a fresh connection and- ;; retry. We might also get 'bad-response or a similar exception from- ;; (web response) later on, once we've sent the request, or a- ;; ERROR/INVALID-SESSION from GnuTLS.- (if (or (and (eq? key 'system-error)- (= EPIPE (system-error-errno `(,key ,@args))))- (and (eq? key 'gnutls-error)- (eq? (first args) error/invalid-session))- (memq key '(bad-response bad-header bad-header-component)))- (proc (open-connection uri #:fresh? #t))- (apply throw key args))))))--(define-syntax-rule (with-cached-connection uri port exp ...)- "Bind PORT with EXP... to a socket connected to URI."- (call-with-cached-connection uri (lambda (port) exp ...)))- (define* (process-substitution store-item destination #:key cache-urls acl deduplicate? print-build-trace?)@@ -1011,8 +985,6 @@ default value." ;;; Local Variables: ;;; eval: (put 'with-timeout 'scheme-indent-function 1)-;;; eval: (put 'with-cached-connection 'scheme-indent-function 2)-;;; eval: (put 'call-with-cached-connection 'scheme-indent-function 1) ;;; End: ;;; substitute.scm ends here-- 2.30.0
C
C
Christopher Baines wrote on 13 Feb 14:47 +0100
[PATCH v5 13/14] substitute: Remove fetch-narinfos use open-connection-for-uri/maybe.
(address . 45409@debbugs.gnu.org)
20210213134719.19625-13-mail@cbaines.net
At least by default. Instead, make the open-connection procedure a parameter,and make the default guix:open-connection-for-uri. Do so similarly forlookup-narinfos and lookup-narinfos/diverse which work towards callingfetch-narinfos.
This means this code can be moved to a different module, without havinguse/move the connection caching code.
* guix/scripts/substitute.scm (fetch-narinfos): Add #:open-connectionargument, and call http-multiple-get with it.(lookup-narinfos) Add #:open-connection argument, and call fetch-narinfos withit.(lookup-narinfos/diverse): Add #:open-connection argument, and calllookup-narinfos with it.(process-query): Call lookup-narinfos/diverse with #:open-connectionopen-connection-for-uri/maybe.--- guix/scripts/substitute.scm | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-)
Toggle diff (83 lines)diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex 717c232633..fea2cecef0 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -314,7 +314,8 @@ port to it, or, if connection failed, print a warning and return #f. Pass (args (apply throw args))))) -(define (fetch-narinfos url paths)+(define* (fetch-narinfos url paths+ #:key (open-connection guix:open-connection-for-uri)) "Retrieve all the narinfos for PATHS from the cache at URL and return them." (define update-progress! (let ((done 0)@@ -379,8 +380,7 @@ port to it, or, if connection failed, print a warning and return #f. Pass (http-multiple-get uri handle-narinfo-response '() requests- #:open-connection- open-connection-for-uri/maybe+ #:open-connection open-connection #:verify-certificate? #f)))) (newline (current-error-port)) result))@@ -396,7 +396,8 @@ port to it, or, if connection failed, print a warning and return #f. Pass (do-fetch (string->uri url))) -(define (lookup-narinfos cache paths)+(define* (lookup-narinfos cache paths+ #:key (open-connection guix:open-connection-for-uri)) "Return the narinfos for PATHS, invoking the server at CACHE when no information is available locally." (let-values (((cached missing)@@ -413,10 +414,13 @@ information is available locally." paths))) (if (null? missing) cached- (let ((missing (fetch-narinfos cache missing)))+ (let ((missing (fetch-narinfos cache missing+ #:open-connection open-connection))) (append cached (or missing '())))))) -(define (lookup-narinfos/diverse caches paths authorized?)+(define* (lookup-narinfos/diverse caches paths authorized?+ #:key (open-connection+ guix:open-connection-for-uri)) "Look up narinfos for PATHS on all of CACHES, a list of URLS, in that order. That is, when a cache lacks an AUTHORIZED? narinfo, look it up in the next cache, and so on.@@ -448,7 +452,8 @@ AUTHORIZED? narinfo." (_ (match caches ((cache rest ...)- (let* ((narinfos (lookup-narinfos cache paths))+ (let* ((narinfos (lookup-narinfos cache paths+ #:open-connection open-connection)) (definite (map narinfo-path (filter authorized? narinfos))) (missing (lset-difference string=? paths definite))) ;XXX: perf (loop rest missing@@ -588,14 +593,18 @@ authorized substitutes." (match (string-tokenize command) (("have" paths ..1) ;; Return the subset of PATHS available in CACHE-URLS.- (let ((substitutable (lookup-narinfos/diverse cache-urls paths valid?)))+ (let ((substitutable (lookup-narinfos/diverse+ cache-urls paths valid?+ #:open-connection open-connection-for-uri/maybe))) (for-each (lambda (narinfo) (format #t "~a~%" (narinfo-path narinfo))) substitutable) (newline))) (("info" paths ..1) ;; Reply info about PATHS if it's in CACHE-URLS.- (let ((substitutable (lookup-narinfos/diverse cache-urls paths valid?)))+ (let ((substitutable (lookup-narinfos/diverse+ cache-urls paths valid?+ #:open-connection open-connection-for-uri/maybe))) (for-each display-narinfo-data substitutable) (newline))) (wtf-- 2.30.0
C
C
Christopher Baines wrote on 13 Feb 14:47 +0100
[PATCH v5 11/14] substitute: Remove redundant fetch arguments.
(address . 45409@debbugs.gnu.org)
20210213134719.19625-11-mail@cbaines.net
It's just called in one place, with hardcoded argument values, so just inlinethem.
* guix/scripts/substitute.scm (fetch): Remove arguments that don't vary, copythe values from the call site in process-substitution.(process-substitution): Remove unnecessary argument values from fetch call.--- guix/scripts/substitute.scm | 23 +++++++---------------- 1 file changed, 7 insertions(+), 16 deletions(-)
Toggle diff (59 lines)diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex a2b1526cc6..26fd05429f 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -169,18 +169,12 @@ again." (sigaction SIGALRM SIG_DFL) (apply values result))))) -(define* (fetch uri #:key (buffered? #t) (timeout? #t)- (keep-alive? #f))+(define (fetch uri) "Return a binary input port to URI and the number of bytes it's expected to-provide.--When PORT is true, use it as the underlying I/O port for HTTP transfers; when-PORT is false, open a new connection for URI. When KEEP-ALIVE? is true, the-connection (typically PORT) is kept open once data has been fetched from URI."+provide." (case (uri-scheme uri) ((file)- (let ((port (open-file (uri-path uri)- (if buffered? "rb" "r0b"))))+ (let ((port (open-file (uri-path uri) "r0b"))) (values port (stat:size (stat port))))) ((http https) (guard (c ((http-get-error? c)@@ -192,17 +186,15 @@ connection (typically PORT) is kept open once data has been fetched from URI." ;; sudo tc qdisc add dev eth0 root netem delay 1500ms ;; and then cancel with: ;; sudo tc qdisc del dev eth0 root- (with-timeout (if timeout?- %fetch-timeout- 0)+ (with-timeout %fetch-timeout (begin (warning (G_ "while fetching ~a: server is somewhat slow~%") (uri->string uri)) (warning (G_ "try `--no-substitutes' if the problem persists~%"))) (http-fetch uri #:text? #f #:open-connection open-connection-for-uri/maybe- #:keep-alive? keep-alive?- #:buffered? buffered?+ #:keep-alive? #t+ #:buffered? #f #:verify-certificate? #f)))) (else (leave (G_ "unsupported substitute URI scheme: ~a~%")@@ -727,8 +719,7 @@ the current output port." (let*-values (((raw download-size) ;; 'guix publish' without '--cache' doesn't specify a ;; Content-Length, so DOWNLOAD-SIZE is #f in this case.- (fetch uri #:buffered? #f #:timeout? #f- #:keep-alive? #t))+ (fetch uri)) ((progress) (let* ((dl-size (or download-size (and (equal? compression "none")-- 2.30.0
C
C
Christopher Baines wrote on 13 Feb 14:47 +0100
[PATCH v5 14/14] substitute: Rework connection error handling.
(address . 45409@debbugs.gnu.org)
20210213134719.19625-14-mail@cbaines.net
This is part of trying to reduce the interdependency of code within thesubstitute module.
This commit addresses some of the error handling that was performed throughopen-connection-for-uri/maybe. The new approach is to usecall-with-connection-error-handling, and wrap calls to http-multiple-get andhttp-fetch with that procedure, which takes care of handling connectionerrors.
I think this is even slightly more rigerous than the previous setup, becausethis approach handles connection errors that occur when http-multiple-getreconnects to a host.
* guix/scripts/substitute.scm (open-connection-for-uri/maybe): Transform in tocall-with-connection-error-handling.(fetch-narinfos): Use call-with-connection-error-handling.(process-query): Replace open-connection-for-uri/maybe withopen-connection-for-uri/cached.(open-connection-for-uri/cached): Set a default timeout, matching thebehaviour in open-connection-for-uri/maybe.(process-substitution): Use call-with-connection-error-handling.--- guix/scripts/substitute.scm | 47 +++++++++++++++++-------------------- 1 file changed, 22 insertions(+), 25 deletions(-)
Toggle diff (99 lines)diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex fea2cecef0..a3a0349530 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -281,22 +281,13 @@ if file doesn't exist, and the narinfo otherwise." ;; Set of names of unreachable hosts. (make-hash-table)) -(define* (open-connection-for-uri/maybe uri- #:key- fresh?- (time %fetch-timeout)- verify-certificate?)- "Open a connection to URI via 'open-connection-for-uri/cached' and return a-port to it, or, if connection failed, print a warning and return #f. Pass-#:fresh? to 'open-connection-for-uri/cached'."+(define* (call-with-connection-error-handling uri proc)+ "Call PROC, and catch if a connection fails, print a warning and return #f." (define host (uri-host uri)) (catch #t- (lambda ()- (open-connection-for-uri/cached uri #:timeout time- #:fresh? fresh?- #:verify-certificate? verify-certificate?))+ proc (match-lambda* (('getaddrinfo-error error) (unless (hash-ref %unreachable-hosts host)@@ -377,11 +368,14 @@ port to it, or, if connection failed, print a warning and return #f. Pass (let* ((requests (map (cut narinfo-request url <>) paths)) (result (begin (update-progress!)- (http-multiple-get uri- handle-narinfo-response '()- requests- #:open-connection open-connection- #:verify-certificate? #f))))+ (call-with-connection-error-handling+ uri+ (lambda ()+ (http-multiple-get uri+ handle-narinfo-response '()+ requests+ #:open-connection open-connection+ #:verify-certificate? #f)))))) (newline (current-error-port)) result)) ((file #f)@@ -595,7 +589,7 @@ authorized substitutes." ;; Return the subset of PATHS available in CACHE-URLS. (let ((substitutable (lookup-narinfos/diverse cache-urls paths valid?- #:open-connection open-connection-for-uri/maybe)))+ #:open-connection open-connection-for-uri/cached))) (for-each (lambda (narinfo) (format #t "~a~%" (narinfo-path narinfo))) substitutable)@@ -604,7 +598,7 @@ authorized substitutes." ;; Reply info about PATHS if it's in CACHE-URLS. (let ((substitutable (lookup-narinfos/diverse cache-urls paths valid?- #:open-connection open-connection-for-uri/maybe)))+ #:open-connection open-connection-for-uri/cached))) (for-each display-narinfo-data substitutable) (newline))) (wtf@@ -617,7 +611,7 @@ authorized substitutes." (define open-connection-for-uri/cached (let ((cache '()))- (lambda* (uri #:key fresh? timeout verify-certificate?)+ (lambda* (uri #:key fresh? (timeout %fetch-timeout) verify-certificate?) "Return a connection for URI, possibly reusing a cached connection. When FRESH? is true, delete any cached connections for URI and open a new one. Return #f if URI's scheme is 'file' or #f.@@ -704,11 +698,14 @@ the current output port." (warning (G_ "while fetching ~a: server is somewhat slow~%") (uri->string uri)) (warning (G_ "try `--no-substitutes' if the problem persists~%")))- (http-fetch uri #:text? #f- #:open-connection open-connection-for-uri/maybe- #:keep-alive? #t- #:buffered? #f- #:verify-certificate? #f))))+ (call-with-connection-error-handling+ uri+ (lambda ()+ (http-fetch uri #:text? #f+ #:open-connection open-connection-for-uri/cached+ #:keep-alive? #t+ #:buffered? #f+ #:verify-certificate? #f)))))) (else (leave (G_ "unsupported substitute URI scheme: ~a~%") (uri->string uri)))))-- 2.30.0
C
C
Christopher Baines wrote on 13 Feb 14:56 +0100
Re: [bug#45409] [PATCH v3 3/3] guix: Split (guix substitutes) from (guix scripts substitute).
(name . Ludovic Courtès)(address . ludo@gnu.org)(address . 45409@debbugs.gnu.org)
87zh08jckw.fsf@cbaines.net
Christopher Baines <mail@cbaines.net> writes:
Toggle quote (5 lines)> I've rebased on master, tweaked the commit messages, and send a set of> v4 patches and while they don't create the (guix substitutes) module, I> think they unpick the bits I'd like to move out from the code doing the> connection caching.
I did some more testing today, and while it turns out the tests passedwhen run with network access, one test failed when building the guixpackage.
I've now rebased, and added an addition patch to address this, and senta v5 series. My testing locally seems to suggest this works, so I'd liketo merge it soon so I can push on with moving code out of the scriptmodule.
One other thing, while trying to debug the test failure, I was hittingthe rather topical substituter "Backtrace:" issue [1][2], and of course,this is more an issue with error handling than anything else. I hackedsomething in to send backtraces to (current-error-port), which isspecifically handled in the substituter script, and I think that wouldbe a good thing to do properly?
1: https://issues.guix.gnu.org/458282: https://issues.guix.gnu.org/46362
Thanks,
Chris
-----BEGIN PGP SIGNATURE-----
iQKlBAEBCgCPFiEEPonu50WOcg2XVOCyXiijOwuE9XcFAmAn2o9fFIAAAAAALgAoaXNzdWVyLWZwckBub3RhdGlvbnMub3BlbnBncC5maWZ0aGhvcnNlbWFuLm5ldDNFODlFRUU3NDU4RTcyMEQ5NzU0RTBCMjVFMjhBMzNCMEI4NEY1NzcRHG1haWxAY2JhaW5lcy5uZXQACgkQXiijOwuE9XfAnQ//TuDZuYYtQWGGFBt0N5MJn071Xaygo0542bJJSQfW5/70BRUcbD69zDsn/B4pE3j6dzK8sN+UFNG81QEyjTo7bAP7iCftvuYiSir0aZOqyEZSam0R05ja5pUTkA9R5Dv8oxOML5B2vik+R0F2KBWrNdU10z81gaEW+2KE1hFYP+xBdvoloJ8BQJdhepBoeOXJKVaqIxdxDT8ZPU33wyoGop0dofoMiJdUJ8OkUl5E4Ov2T312W5my800wnUsIbilx3Yk5VPaXRI/0RI3KwBqHCNgy+cY4X11VbYD1emxqbVYcgyockiR6D6WTk2R7/ARoqhIsnWZ1PuRJHFZeSFNSqQc+efk66JVBW5eajHXQnx/JVpnDQ4/hjtqAy+JXZlz3fHONw1/gwgG+OxJD7VKPTLiKPOsc/IITQT7ijoC2HsXoL0n86OWcqWG7yVk+2rLsqhykwUTx/otNY5CEZ+BrUw6Zf39tHdcrR6yU/loUcgCxfmxXtqwdOnV97uHKctPA5e9FCb3pg33qnTXXNoAcBEL5zwxKDQA+iNkXJ5WWk6pwrkNZ9ZRXA/OesyEDwTpePRTXT917nUFekfTzPQZ7/5PmSUZOgS6oGK2Ml1qJQuEUvj9Pcb82a+cqms6NEshjaxJsfGNUjyD54/JcWNjqkv9Pr1xp7inL47eNS89jXAU==NA07-----END PGP SIGNATURE-----
C
C
Christopher Baines wrote on 22 Feb 23:21 +0100
(address . 45409@debbugs.gnu.org)
87h7m3n3pz.fsf@cbaines.net
Christopher Baines <mail@cbaines.net> writes:
Toggle quote (16 lines)> Christopher Baines <mail@cbaines.net> writes:>>> I've rebased on master, tweaked the commit messages, and send a set of>> v4 patches and while they don't create the (guix substitutes) module, I>> think they unpick the bits I'd like to move out from the code doing the>> connection caching.>> I did some more testing today, and while it turns out the tests passed> when run with network access, one test failed when building the guix> package.>> I've now rebased, and added an addition patch to address this, and sent> a v5 series. My testing locally seems to suggest this works, so I'd like> to merge it soon so I can push on with moving code out of the script> module.
I've gone ahead and pushed these patches as5c7874adb00c834e55e58a9b964ebc5fd1bb872c. I'll send some more patches tomake the remaining changes shortly.
-----BEGIN PGP SIGNATURE-----
iQKlBAEBCgCPFiEEPonu50WOcg2XVOCyXiijOwuE9XcFAmA0LmhfFIAAAAAALgAoaXNzdWVyLWZwckBub3RhdGlvbnMub3BlbnBncC5maWZ0aGhvcnNlbWFuLm5ldDNFODlFRUU3NDU4RTcyMEQ5NzU0RTBCMjVFMjhBMzNCMEI4NEY1NzcRHG1haWxAY2JhaW5lcy5uZXQACgkQXiijOwuE9XdjWg/8CeIifn8tlqqoS3kOjpR/5n+Yisd1j6Yg5TObmc8qrkUvXlgkkzdbUxYmTRV7cKtl/Alx1hwk9Wh5N/m+qeOR6C5ie+4+qmL6m2ntFXPxuzJ/z6PkgZ840DqJeoLTnZyK06tzzRKK3fljwjrI2sUW1xpvk9eNLGMFUKMWkjo4w3NbtYUzutrN1HbVt9Z9d35uh1ArEzZuufjmgpE8nckLGi8QieyDHYn55FU2o+MymH1GF/TCNuJrywI0vf2OXkUK8PP1kt5kpTB3DY0UyN/P4w3MnWKMzp2c03TVZcmGR55wKLyMzBXavJfg2hqHaYsYI4wNZtWoXrYOObRZrC4nelformNvHVE0zzWwlLTg3slQWWS5BOn27So30bJd7/Kb6aPYiRBBrxw2F0CKrjAETki6STT4JnxnIYDixm9Ep3LYpuYrbC5BVWXARyDjyOYeY3o5N8b2UutPdjiUvE42d+PetZqJmdBNJQOAG20ZafEYHE1KwotoNNaSGbbJ+yT/cH78Wcz0D07itkFBL1k77WlMaO/JbCXjSddSh5ZBLAAS96NnpqmoNouxnhMh9nfC92FZVtIG8ZgvfeRKfDlGUsMlNbbA3j59hbDElSnlG5JhWKqeW/F26PqnwF/bz9mkqQiAoTzpli+QxgW3YdT3nLdPjaVPe2MvHByEefjykXY==PWEh-----END PGP SIGNATURE-----
C
C
Christopher Baines wrote on 23 Feb 20:59 +0100
[PATCH 2/2] substitute: Print backtraces to (current-error-port).
(address . 45409@debbugs.gnu.org)
20210223195944.26871-2-mail@cbaines.net
Otherwise, I believe the backtraces come out in a way that upsets theguix-daemon. This makes it more difficult to determine what's causing theissue, see [1] and [2].
1: https://issues.guix.gnu.org/458282: https://issues.guix.gnu.org/46362
I'm looking at this now as part of refactoring the code, as just in caseissues crop up, I want it to be clearer where the problem is.
* guix/scripts/substitute.scm (with-exception-handling): New syntax.(guix-substitute): Wrap main part with with-exception-handling.--- guix/scripts/substitute.scm | 83 +++++++++++++++++++++---------------- 1 file changed, 48 insertions(+), 35 deletions(-)
Toggle diff (103 lines)diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex f98ec8e0d3..ed19e67531 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -226,6 +226,18 @@ was found." (args (apply throw args))))))) +(define-syntax with-exception-handling+ (syntax-rules ()+ "Print the backtrace to the current-error-port and exit"+ ((_ exp ...)+ (with-throw-handler #t+ (lambda () exp ...)+ (lambda (key . args)+ (report-error (G_ "substitute: exception raised: ~A: ~A~%") key args)+ (display-backtrace (make-stack #t) (current-error-port))+ (newline (current-error-port))+ (exit 1))))))+ ;;; ;;; Help.@@ -644,41 +656,42 @@ default value." (set-thread-name "guix substitute")) (const #t)) ;GNU/Hurd lacks 'prctl' - (with-networking- (with-error-handling ; for signature errors- (match args- (("--query")- (let ((acl (current-acl)))- (let loop ((command (read-line)))- (or (eof-object? command)- (begin- (process-query command- #:cache-urls (substitute-urls)- #:acl acl)- (loop (read-line)))))))- (("--substitute")- ;; Download STORE-PATH and store it as a Nar in file DESTINATION.- ;; Specify the number of columns of the terminal so the progress- ;; report displays nicely.- (parameterize ((current-terminal-columns (client-terminal-columns)))- (let loop ()- (match (read-line)- ((? eof-object?)- #t)- ((= string-tokenize ("substitute" store-path destination))- (process-substitution store-path destination- #:cache-urls (substitute-urls)- #:acl (current-acl)- #:deduplicate? deduplicate?- #:print-build-trace?- print-build-trace?)- (loop))))))- ((or ("-V") ("--version"))- (show-version-and-exit "guix substitute"))- (("--help")- (show-help))- (opts- (leave (G_ "~a: unrecognized options~%") opts)))))))+ (with-exception-handling+ (with-networking+ (with-error-handling ; for signature errors+ (match args+ (("--query")+ (let ((acl (current-acl)))+ (let loop ((command (read-line)))+ (or (eof-object? command)+ (begin+ (process-query command+ #:cache-urls (substitute-urls)+ #:acl acl)+ (loop (read-line)))))))+ (("--substitute")+ ;; Download STORE-PATH and store it as a Nar in file DESTINATION.+ ;; Specify the number of columns of the terminal so the progress+ ;; report displays nicely.+ (parameterize ((current-terminal-columns (client-terminal-columns)))+ (let loop ()+ (match (read-line)+ ((? eof-object?)+ #t)+ ((= string-tokenize ("substitute" store-path destination))+ (process-substitution store-path destination+ #:cache-urls (substitute-urls)+ #:acl (current-acl)+ #:deduplicate? deduplicate?+ #:print-build-trace?+ print-build-trace?)+ (loop))))))+ ((or ("-V") ("--version"))+ (show-version-and-exit "guix substitute"))+ (("--help")+ (show-help))+ (opts+ (leave (G_ "~a: unrecognized options~%") opts)))))))) ;;; Local Variables: ;;; eval: (put 'with-timeout 'scheme-indent-function 1)-- 2.30.0
C
C
Christopher Baines wrote on 23 Feb 20:59 +0100
[PATCH 1/2] guix: Split (guix substitutes) from (guix scripts substitute).
(address . 45409@debbugs.gnu.org)
20210223195944.26871-1-mail@cbaines.net
This means there's a module for working with substitutes, rather than all thecode sitting in the script. The need for this can be seen with the weather andchallenge scripts, that now don't have to use code from the substitute script,but can instead use the substitute module.
The separation here between the actual functionality of the substitute scriptand the underlying functionality used both there and elsewhere should makemaintenance easier moving forward.
This commit just moves code, none of the code should have been changedsignificantly.
* guix/scripts/substitute.scm (%narinfo-cache-directory, %narinfo-ttl,%narinfo-negative-ttl, %narinfo-transient-error-ttl, %unreachable-hosts): Movevariables to guix/substitutes.scm.(narinfo-cache-file, cached-narinfo, cache-narinfo!, narinfo-request,read-to-eof, call-with-connection-error-handling, fetch-narinfos,lookup-narinfos, lookup-narinfos/diverse): Move procedures toguix/substitutes.scm.* guix/substitutes.scm: New file.* Makefile.am: Add it.* guix/narinfo.scm: Remove redundant module.* guix/scripts/challenge.scm: Change (guix scripts substitute) to (guixsubstitutes).* guix/scripts/weather.scm: Change (guix scripts substitute) to (guixsubstitutes).--- Makefile.am | 1 + guix/narinfo.scm | 1 - guix/scripts/challenge.scm | 2 +- guix/scripts/substitute.scm | 312 +----------------------------- guix/scripts/weather.scm | 2 +- guix/substitutes.scm | 366 ++++++++++++++++++++++++++++++++++++ 6 files changed, 376 insertions(+), 308 deletions(-) create mode 100644 guix/substitutes.scm
Toggle diff (808 lines)diff --git a/Makefile.am b/Makefile.amindex 394d2ef75e..bb27297096 100644--- a/Makefile.am+++ b/Makefile.am@@ -114,6 +114,7 @@ MODULES = \ guix/channels.scm \ guix/gnu-maintenance.scm \ guix/self.scm \+ guix/substitutes.scm \ guix/upstream.scm \ guix/licenses.scm \ guix/lint.scm \diff --git a/guix/narinfo.scm b/guix/narinfo.scmindex d3deba28bd..2d06124017 100644--- a/guix/narinfo.scm+++ b/guix/narinfo.scm@@ -25,7 +25,6 @@ #:use-module (guix base64) #:use-module (guix records) #:use-module (guix diagnostics)- #:use-module (guix scripts substitute) #:use-module (gcrypt hash) #:use-module (gcrypt pk-crypto) #:use-module (rnrs bytevectors)diff --git a/guix/scripts/challenge.scm b/guix/scripts/challenge.scmindex cc9cbe6f27..4ec3be99ca 100644--- a/guix/scripts/challenge.scm+++ b/guix/scripts/challenge.scm@@ -27,7 +27,7 @@ #:use-module (guix packages) #:use-module ((guix progress) #:hide (dump-port*)) #:use-module (guix serialization)- #:use-module (guix scripts substitute)+ #:use-module (guix substitutes) #:use-module (guix narinfo) #:use-module (rnrs bytevectors) #:autoload (guix http-client) (http-fetch)diff --git a/guix/scripts/substitute.scm b/guix/scripts/substitute.scmindex a3a0349530..f98ec8e0d3 100755--- a/guix/scripts/substitute.scm+++ b/guix/scripts/substitute.scm@@ -24,6 +24,7 @@ #:use-module (guix scripts) #:use-module (guix narinfo) #:use-module (guix store)+ #:use-module (guix substitutes) #:use-module (guix utils) #:use-module (guix combinators) #:use-module (guix config)@@ -39,40 +40,28 @@ #:use-module (guix cache) #:use-module (gcrypt pk-crypto) #:use-module (guix pki)- #:use-module ((guix build utils) #:select (mkdir-p dump-port))+ #:use-module ((guix build utils) #:select (mkdir-p)) #:use-module ((guix build download) #:select (uri-abbreviation nar-uri-abbreviation (open-connection-for-uri- . guix:open-connection-for-uri)- store-path-abbreviation byte-count->string))- #:autoload (gnutls) (error/invalid-session)+ . guix:open-connection-for-uri))) #:use-module (guix progress) #:use-module ((guix build syscalls) #:select (set-thread-name)) #:use-module (ice-9 rdelim)- #:use-module (ice-9 regex) #:use-module (ice-9 match) #:use-module (ice-9 format) #:use-module (ice-9 ftw)- #:use-module (ice-9 binary-ports)- #:use-module (ice-9 vlist) #:use-module (rnrs bytevectors) #:use-module (srfi srfi-1)- #:use-module (srfi srfi-9) #:use-module (srfi srfi-11) #:use-module (srfi srfi-19) #:use-module (srfi srfi-26) #:use-module (srfi srfi-34) #:use-module (srfi srfi-35) #:use-module (web uri)- #:use-module (web http)- #:use-module (web request)- #:use-module (web response) #:use-module (guix http-client)- #:export (lookup-narinfos- lookup-narinfos/diverse-- %allow-unauthenticated-substitutes?+ #:export (%allow-unauthenticated-substitutes? %error-to-file-descriptor-4? substitute-urls@@ -89,16 +78,9 @@ ;;; ;;; Code: -(define %narinfo-cache-directory- ;; A local cache of narinfos, to avoid going to the network. Most of the- ;; time, 'guix substitute' is called by guix-daemon as root and stores its- ;; cached data in /var/guix/…. However, when invoked from 'guix challenge'- ;; as a user, it stores its cache in ~/.cache.- (if (zero? (getuid))- (or (and=> (getenv "XDG_CACHE_HOME")- (cut string-append <> "/guix/substitute"))- (string-append %state-directory "/substitute/cache"))- (string-append (cache-directory #:ensure? #f) "/substitute")))+(define %narinfo-expired-cache-entry-removal-delay+ ;; How often we want to remove files corresponding to expired cache entries.+ (* 7 24 3600)) (define (warn-about-missing-authentication) (warning (G_ "authentication and authorization of substitutes \@@ -112,24 +94,6 @@ disabled!~%")) (and=> (getenv "GUIX_ALLOW_UNAUTHENTICATED_SUBSTITUTES") (cut string-ci=? <> "yes")))) -(define %narinfo-ttl- ;; Number of seconds during which cached narinfo lookups are considered- ;; valid for substitute servers that do not advertise a TTL via the- ;; 'Cache-Control' response header.- (* 36 3600))--(define %narinfo-negative-ttl- ;; Likewise, but for negative lookups---i.e., cached lookup failures (404).- (* 1 3600))--(define %narinfo-transient-error-ttl- ;; Likewise, but for transient errors such as 504 ("Gateway timeout").- (* 10 60))--(define %narinfo-expired-cache-entry-removal-delay- ;; How often we want to remove files corresponding to expired cache entries.- (* 7 24 3600))- (define %fetch-timeout ;; Number of seconds after which networking is considered "slow". 5)@@ -169,84 +133,6 @@ again." (sigaction SIGALRM SIG_DFL) (apply values result))))) -(define (narinfo-cache-file cache-url path)- "Return the name of the local file that contains an entry for PATH. The-entry is stored in a sub-directory specific to CACHE-URL."- ;; The daemon does not sanitize its input, so PATH could be something like- ;; "/gnu/store/foo". Gracefully handle that.- (match (store-path-hash-part path)- (#f- (leave (G_ "'~a' does not name a store item~%") path))- ((? string? hash-part)- (string-append %narinfo-cache-directory "/"- (bytevector->base32-string (sha256 (string->utf8 cache-url)))- "/" hash-part))))--(define (cached-narinfo cache-url path)- "Check locally if we have valid info about PATH coming from CACHE-URL.-Return two values: a Boolean indicating whether we have valid cached info, and-that info, which may be either #f (when PATH is unavailable) or the narinfo-for PATH."- (define now- (current-time time-monotonic))-- (define cache-file- (narinfo-cache-file cache-url path))-- (catch 'system-error- (lambda ()- (call-with-input-file cache-file- (lambda (p)- (match (read p)- (('narinfo ('version 2)- ('cache-uri cache-uri)- ('date date) ('ttl ttl) ('value #f))- ;; A cached negative lookup.- (if (obsolete? date now ttl)- (values #f #f)- (values #t #f)))- (('narinfo ('version 2)- ('cache-uri cache-uri)- ('date date) ('ttl ttl) ('value value))- ;; A cached positive lookup- (if (obsolete? date now ttl)- (values #f #f)- (values #t (string->narinfo value cache-uri))))- (('narinfo ('version v) _ ...)- (values #f #f))))))- (lambda _- (values #f #f))))--(define (cache-narinfo! cache-url path narinfo ttl)- "Cache locally NARNIFO for PATH, which originates from CACHE-URL, with the-given TTL (a number of seconds or #f). NARINFO may be #f, in which case it-indicates that PATH is unavailable at CACHE-URL."- (define now- (current-time time-monotonic))-- (define (cache-entry cache-uri narinfo)- `(narinfo (version 2)- (cache-uri ,cache-uri)- (date ,(time-second now))- (ttl ,(or ttl- (if narinfo %narinfo-ttl %narinfo-negative-ttl)))- (value ,(and=> narinfo narinfo->string))))-- (let ((file (narinfo-cache-file cache-url path)))- (mkdir-p (dirname file))- (with-atomic-file-output file- (lambda (out)- (write (cache-entry cache-url narinfo) out))))-- narinfo)--(define (narinfo-request cache-url path)- "Return an HTTP request for the narinfo of PATH at CACHE-URL."- (let ((url (string-append cache-url "/" (store-path-hash-part path)- ".narinfo"))- (headers '((User-Agent . "GNU Guile"))))- (build-request (string->uri url) #:method 'GET #:headers headers)))- (define (at-most max-length lst) "If LST is shorter than MAX-LENGTH, return it and the empty list; otherwise return its MAX-LENGTH first elements and its tail."@@ -261,10 +147,6 @@ return its MAX-LENGTH first elements and its tail." (values (reverse result) lst) (loop (+ 1 len) tail (cons head result))))))) -(define (read-to-eof port)- "Read from PORT until EOF is reached. The data are discarded."- (dump-port port (%make-void-port "w")))- (define (narinfo-from-file file url) "Attempt to read a narinfo from FILE, using URL as the cache URL. Return #f if file doesn't exist, and the narinfo otherwise."@@ -277,186 +159,6 @@ if file doesn't exist, and the narinfo otherwise." #f (apply throw args))))) -(define %unreachable-hosts- ;; Set of names of unreachable hosts.- (make-hash-table))--(define* (call-with-connection-error-handling uri proc)- "Call PROC, and catch if a connection fails, print a warning and return #f."- (define host- (uri-host uri))-- (catch #t- proc- (match-lambda*- (('getaddrinfo-error error)- (unless (hash-ref %unreachable-hosts host)- (hash-set! %unreachable-hosts host #t) ;warn only once- (warning (G_ "~a: host not found: ~a~%")- host (gai-strerror error)))- #f)- (('system-error . args)- (unless (hash-ref %unreachable-hosts host)- (hash-set! %unreachable-hosts host #t)- (warning (G_ "~a: connection failed: ~a~%") host- (strerror- (system-error-errno `(system-error ,@args)))))- #f)- (args- (apply throw args)))))--(define* (fetch-narinfos url paths- #:key (open-connection guix:open-connection-for-uri))- "Retrieve all the narinfos for PATHS from the cache at URL and return them."- (define update-progress!- (let ((done 0)- (total (length paths)))- (lambda ()- (display "\r\x1b[K" (current-error-port)) ;erase current line- (force-output (current-error-port))- (format (current-error-port)- (G_ "updating substitutes from '~a'... ~5,1f%")- url (* 100. (/ done total)))- (set! done (+ 1 done)))))-- (define hash-part->path- (let ((mapping (fold (lambda (path result)- (vhash-cons (store-path-hash-part path) path- result))- vlist-null- paths)))- (lambda (hash)- (match (vhash-assoc hash mapping)- (#f #f)- ((_ . path) path)))))-- (define (handle-narinfo-response request response port result)- (let* ((code (response-code response))- (len (response-content-length response))- (cache (response-cache-control response))- (ttl (and cache (assoc-ref cache 'max-age))))- (update-progress!)-- ;; Make sure to read no more than LEN bytes since subsequent bytes may- ;; belong to the next response.- (if (= code 200) ; hit- (let ((narinfo (read-narinfo port url #:size len)))- (if (string=? (dirname (narinfo-path narinfo))- (%store-prefix))- (begin- (cache-narinfo! url (narinfo-path narinfo) narinfo ttl)- (cons narinfo result))- result))- (let* ((path (uri-path (request-uri request)))- (hash-part (basename- (string-drop-right path 8)))) ;drop ".narinfo"- (if len- (get-bytevector-n port len)- (read-to-eof port))- (cache-narinfo! url (hash-part->path hash-part) #f- (if (or (= 404 code) (= 202 code))- ttl- %narinfo-transient-error-ttl))- result))))-- (define (do-fetch uri)- (case (and=> uri uri-scheme)- ((http https)- ;; Note: Do not check HTTPS server certificates to avoid depending- ;; on the X.509 PKI. We can do it because we authenticate- ;; narinfos, which provides a much stronger guarantee.- (let* ((requests (map (cut narinfo-request url <>) paths))- (result (begin- (update-progress!)- (call-with-connection-error-handling- uri- (lambda ()- (http-multiple-get uri- handle-narinfo-response '()- requests- #:open-connection open-connection- #:verify-certificate? #f))))))- (newline (current-error-port))- result))- ((file #f)- (let* ((base (string-append (uri-path uri) "/"))- (files (map (compose (cut string-append base <> ".narinfo")- store-path-hash-part)- paths)))- (filter-map (cut narinfo-from-file <> url) files)))- (else- (leave (G_ "~s: unsupported server URI scheme~%")- (if uri (uri-scheme uri) url)))))-- (do-fetch (string->uri url)))--(define* (lookup-narinfos cache paths- #:key (open-connection guix:open-connection-for-uri))- "Return the narinfos for PATHS, invoking the server at CACHE when no-information is available locally."- (let-values (((cached missing)- (fold2 (lambda (path cached missing)- (let-values (((valid? value)- (cached-narinfo cache path)))- (if valid?- (if value- (values (cons value cached) missing)- (values cached missing))- (values cached (cons path missing)))))- '()- '()- paths)))- (if (null? missing)- cached- (let ((missing (fetch-narinfos cache missing- #:open-connection open-connection)))- (append cached (or missing '()))))))--(define* (lookup-narinfos/diverse caches paths authorized?- #:key (open-connection- guix:open-connection-for-uri))- "Look up narinfos for PATHS on all of CACHES, a list of URLS, in that order.-That is, when a cache lacks an AUTHORIZED? narinfo, look it up in the next-cache, and so on.--Return a list of narinfos for PATHS or a subset thereof. The returned-narinfos are either AUTHORIZED?, or they claim a hash that matches an-AUTHORIZED? narinfo."- (define (select-hit result)- (lambda (path)- (match (vhash-fold* cons '() path result)- ((one)- one)- ((several ..1)- (let ((authorized (find authorized? (reverse several))))- (and authorized- (find (cut equivalent-narinfo? <> authorized)- several)))))))-- (let loop ((caches caches)- (paths paths)- (result vlist-null) ;path->narinfo vhash- (hits '())) ;paths- (match paths- (() ;we're done- ;; Now iterate on all the HITS, and return exactly one match for each- ;; hit: the first narinfo that is authorized, or that has the same hash- ;; as an authorized narinfo, in the order of CACHES.- (filter-map (select-hit result) hits))- (_- (match caches- ((cache rest ...)- (let* ((narinfos (lookup-narinfos cache paths- #:open-connection open-connection))- (definite (map narinfo-path (filter authorized? narinfos)))- (missing (lset-difference string=? paths definite))) ;XXX: perf- (loop rest missing- (fold vhash-cons result- (map narinfo-path narinfos) narinfos)- (append definite hits))))- (() ;that's it- (filter-map (select-hit result) hits)))))))- (define (lookup-narinfo caches path authorized?) "Return the narinfo for PATH in CACHES, or #f when no substitute for PATH was found."diff --git a/guix/scripts/weather.scm b/guix/scripts/weather.scmindex 97e4a73802..9e94bff5a3 100644--- a/guix/scripts/weather.scm+++ b/guix/scripts/weather.scm@@ -32,7 +32,7 @@ #:use-module (guix gexp) #:use-module ((guix build syscalls) #:select (terminal-columns)) #:use-module ((guix build utils) #:select (every*))- #:use-module (guix scripts substitute)+ #:use-module (guix substitutes) #:use-module (guix narinfo) #:use-module (guix http-client) #:use-module (guix ci)diff --git a/guix/substitutes.scm b/guix/substitutes.scmnew file mode 100644index 0000000000..dc94ccc8e4--- /dev/null+++ b/guix/substitutes.scm@@ -0,0 +1,366 @@+;;; GNU Guix --- Functional package management for GNU+;;; Copyright © 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>+;;; Copyright © 2014 Nikita Karetnikov <nikita@karetnikov.org>+;;; Copyright © 2018 Kyle Meyer <kyle@kyleam.com>+;;; Copyright © 2020 Christopher Baines <mail@cbaines.net>+;;;+;;; This file is part of GNU Guix.+;;;+;;; GNU Guix is free software; you can redistribute it and/or modify it+;;; under the terms of the GNU General Public License as published by+;;; the Free Software Foundation; either version 3 of the License, or (at+;;; your option) any later version.+;;;+;;; GNU Guix is distributed in the hope that it will be useful, but+;;; WITHOUT ANY WARRANTY; without even the implied warranty of+;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+;;; GNU General Public License for more details.+;;;+;;; You should have received a copy of the GNU General Public License+;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.++(define-module (guix substitutes)+ #:use-module (guix narinfo)+ #:use-module (guix store)+ #:use-module (guix utils)+ #:use-module (guix combinators)+ #:use-module (guix config)+ #:use-module (guix records)+ #:use-module (guix diagnostics)+ #:use-module (guix i18n)+ #:use-module (gcrypt hash)+ #:use-module (guix base32)+ #:use-module (guix base64)+ #:use-module (guix cache)+ #:use-module (gcrypt pk-crypto)+ #:use-module (guix pki)+ #:use-module ((guix build utils) #:select (mkdir-p dump-port))+ #:use-module ((guix build download)+ #:select ((open-connection-for-uri+ . guix:open-connection-for-uri)))+ #:use-module (guix progress)+ #:use-module (ice-9 rdelim)+ #:use-module (ice-9 regex)+ #:use-module (ice-9 match)+ #:use-module (ice-9 format)+ #:use-module (ice-9 ftw)+ #:use-module (ice-9 binary-ports)+ #:use-module (ice-9 vlist)+ #:use-module (rnrs bytevectors)+ #:use-module (srfi srfi-1)+ #:use-module (srfi srfi-11)+ #:use-module (srfi srfi-19)+ #:use-module (srfi srfi-26)+ #:use-module (srfi srfi-34)+ #:use-module (srfi srfi-35)+ #:use-module (web uri)+ #:use-module (web request)+ #:use-module (web response)+ #:use-module (guix http-client)+ #:export (%narinfo-cache-directory++ call-with-connection-error-handling++ lookup-narinfos+ lookup-narinfos/diverse))++(define %narinfo-ttl+ ;; Number of seconds during which cached narinfo lookups are considered+ ;; valid for substitute servers that do not advertise a TTL via the+ ;; 'Cache-Control' response header.+ (* 36 3600))++(define %narinfo-negative-ttl+ ;; Likewise, but for negative lookups---i.e., cached lookup failures (404).+ (* 1 3600))++(define %narinfo-transient-error-ttl+ ;; Likewise, but for transient errors such as 504 ("Gateway timeout").+ (* 10 60))++(define %narinfo-cache-directory+ ;; A local cache of narinfos, to avoid going to the network. Most of the+ ;; time, 'guix substitute' is called by guix-daemon as root and stores its+ ;; cached data in /var/guix/…. However, when invoked from 'guix challenge'+ ;; as a user, it stores its cache in ~/.cache.+ (if (zero? (getuid))+ (or (and=> (getenv "XDG_CACHE_HOME")+ (cut string-append <> "/guix/substitute"))+ (string-append %state-directory "/substitute/cache"))+ (string-append (cache-directory #:ensure? #f) "/substitute")))++(define (narinfo-cache-file cache-url path)+ "Return the name of the local file that contains an entry for PATH. The+entry is stored in a sub-directory specific to CACHE-URL."+ ;; The daemon does not sanitize its input, so PATH could be something like+ ;; "/gnu/store/foo". Gracefully handle that.+ (match (store-path-hash-part path)+ (#f+ (leave (G_ "'~a' does not name a store item~%") path))+ ((? string? hash-part)+ (string-append %narinfo-cache-directory "/"+ (bytevector->base32-string (sha256 (string->utf8 cache-url)))+ "/" hash-part))))++(define (cache-narinfo! cache-url path narinfo ttl)+ "Cache locally NARNIFO for PATH, which originates from CACHE-URL, with the+given TTL (a number of seconds or #f). NARINFO may be #f, in which case it+indicates that PATH is unavailable at CACHE-URL."+ (define now+ (current-time time-monotonic))++ (define (cache-entry cache-uri narinfo)+ `(narinfo (version 2)+ (cache-uri ,cache-uri)+ (date ,(time-second now))+ (ttl ,(or ttl+ (if narinfo %narinfo-ttl %narinfo-negative-ttl)))+ (value ,(and=> narinfo narinfo->string))))++ (let ((file (narinfo-cache-file cache-url path)))+ (mkdir-p (dirname file))+ (with-atomic-file-output file+ (lambda (out)+ (write (cache-entry cache-url narinfo) out))))++ narinfo)++(define %unreachable-hosts+ ;; Set of names of unreachable hosts.+ (make-hash-table))++(define* (call-with-connection-error-handling uri proc)+ "Call PROC, and catch if a connection fails, print a warning and return #f."+ (define host+ (uri-host uri))++ (catch #t+ proc+ (match-lambda*+ (('getaddrinfo-error error)+ (unless (hash-ref %unreachable-hosts host)+ (hash-set! %unreachable-hosts host #t) ;warn only once+ (warning (G_ "~a: host not found: ~a~%")+ host (gai-strerror error)))+ #f)+ (('system-error . args)+ (unless (hash-ref %unreachable-hosts host)+ (hash-set! %unreachable-hosts host #t)+ (warning (G_ "~a: connection failed: ~a~%") host+ (strerror+ (system-error-errno `(system-error ,@args)))))+ #f)+ (args+ (apply throw args)))))++(define (narinfo-request cache-url path)+ "Return an HTTP request for the narinfo of PATH at CACHE-URL."+ (let ((url (string-append cache-url "/" (store-path-hash-part path)+ ".narinfo"))+ (headers '((User-Agent . "GNU Guile"))))+ (build-request (string->uri url) #:method 'GET #:headers headers)))++(define (narinfo-from-file file url)+ "Attempt to read a narinfo from FILE, using URL as the cache URL. Return #f+if file doesn't exist, and the narinfo otherwise."+ (catch 'system-error+ (lambda ()+ (call-with-input-file file+ (cut read-narinfo <> url)))+ (lambda args+ (if (= ENOENT (system-error-errno args))+ #f+ (apply throw args)))))++(define* (fetch-narinfos url paths+ #:key (open-connection guix:open-connection-for-uri))+ "Retrieve all the narinfos for PATHS from the cache at URL and return them."+ (define update-progress!+ (let ((done 0)+ (total (length paths)))+ (lambda ()+ (display "\r\x1b[K" (current-error-port)) ;erase current line+ (force-output (current-error-port))+ (format (current-error-port)+ (G_ "updating substitutes from '~a'... ~5,1f%")+ url (* 100. (/ done total)))+ (set! done (+ 1 done)))))++ (define hash-part->path+ (let ((mapping (fold (lambda (path result)+ (vhash-cons (store-path-hash-part path) path+ result))+ vlist-null+ paths)))+ (lambda (hash)+ (match (vhash-assoc hash mapping)+ (#f #f)+ ((_ . path) path)))))++ (define (read-to-eof port)+ "Read from PORT until EOF is reached. The data are discarded."+ (dump-port port (%make-void-port "w")))++ (define (handle-narinfo-response request response port result)+ (let* ((code (response-code response))+ (len (response-content-length response))+ (cache (response-cache-control response))+ (ttl (and cache (assoc-ref cache 'max-age))))+ (update-progress!)++ ;; Make sure to read no more than LEN bytes since subsequent bytes may+ ;; belong to the next response.+ (if (= code 200) ; hit+ (let ((narinfo (read-narinfo port url #:size len)))+ (if (string=? (dirname (narinfo-path narinfo))+ (%store-prefix))+ (begin+ (cache-narinfo! url (narinfo-path narinfo) narinfo ttl)+ (cons narinfo result))+ result))+ (let* ((path (uri-path (request-uri request)))+ (hash-part (basename+ (string-drop-right path 8)))) ;drop ".narinfo"+ (if len+ (get-bytevector-n port len)+ (read-to-eof port))+ (cache-narinfo! url (hash-part->path hash-part) #f+ (if (or (= 404 code) (= 202 code))+ ttl+ %narinfo-transient-error-ttl))+ result))))++ (define (do-fetch uri)+ (case (and=> uri uri-scheme)+ ((http https)+ ;; Note: Do not check HTTPS server certificates to avoid depending+ ;; on the X.509 PKI. We can do it because we authenticate+ ;; narinfos, which provides a much stronger guarantee.+ (let* ((requests (map (cut narinfo-request url <>) paths))+ (result (begin+ (update-progress!)+ (call-with-connection-error-handling+ uri+ (lambda ()+ (http-multiple-get uri+ handle-narinfo-response '()+ requests+ #:open-connection open-connection+ #:verify-certificate? #f))))))+ (newline (current-error-port))+ result))+ ((file #f)+ (let* ((base (string-append (uri-path uri) "/"))+ (files (map (compose (cut string-append base <> ".narinfo")+ store-path-hash-part)+ paths)))+ (filter-map (cut narinfo-from-file <> url) files)))+ (else+ (leave (G_ "~s: unsupported server URI scheme~%")+ (if uri (uri-scheme uri) url)))))++ (do-fetch (string->uri url)))++(define (cached-narinfo cache-url path)+ "Check locally if we have valid info about PATH coming from CACHE-URL.+Return two values: a Boolean indicating whether we have valid cached info, and+that info, which may be either #f (when PATH is unavailable) or the narinfo+for PATH."+ (define now+ (current-time time-monotonic))++ (define cache-file+ (narinfo-cache-file cache-url path))++ (catch 'system-error+ (lambda ()+ (call-with-input-file cache-file+ (lambda (p)+ (match (read p)+ (('narinfo ('version 2)+ ('cache-uri cache-uri)+ ('date date) ('ttl ttl) ('value #f))+ ;; A cached negative lookup.+ (if (obsolete? date now ttl)+ (values #f #f)+ (values #t #f)))+ (('narinfo ('version 2)+ ('cache-uri cache-uri)+ ('date date) ('ttl ttl) ('value value))+ ;; A cached positive lookup+ (if (obsolete? date now ttl)+ (values #f #f)+ (values #t (string->narinfo value cache-uri))))+ (('narinfo ('version v) _ ...)+ (values #f #f))))))+ (lambda _+ (values #f #f))))++(define* (lookup-narinfos cache paths+ #:key (open-connection guix:open-connection-for-uri))+ "Return the narinfos for PATHS, invoking the server at CACHE when no+information is available locally."+ (let-values (((cached missing)+ (fold2 (lambda (path cached missing)+ (let-values (((valid? value)+ (cached-narinfo cache path)))+ (if valid?+ (if value+ (values (cons value cached) missing)+ (values cached missing))+ (values cached (cons path missing)))))+ '()+ '()+ paths)))+ (if (null? missing)+ cached+ (let ((missing (fetch-narinfos cache missing+ #:open-connection open-connection)))+ (append cached (or missing '()))))))++(define* (lookup-narinfos/diverse caches paths authorized?+ #:key (open-connection+ guix:open-connection-for-uri))+ "Look up narinfos for PATHS on all of CACHES, a list of URLS, in that order.+That is, when a cache lacks an AUTHORIZED? narinfo, look it up in the next+cache, and so on.++Return a list of narinfos for PATHS or a subset thereof. The returned+narinfos are either AUTHORIZED?, or they claim a hash that matches an+AUTHORIZED? narinfo."+ (define (select-hit result)+ (lambda (path)+ (match (vhash-fold* cons '() path result)+ ((one)+ one)+ ((several ..1)+ (let ((authorized (find authorized? (reverse several))))+ (and authorized+ (find (cut equivalent-narinfo? <> authorized)+ several)))))))++ (let loop ((caches caches)+ (paths paths)+ (result vlist-null) ;path->narinfo vhash+ (hits '())) ;paths+ (match paths+ (() ;we're done+ ;; Now iterate on all the HITS, and return exactly one match for each+ ;; hit: the first narinfo that is authorized, or that has the same hash+ ;; as an authorized narinfo, in the order of CACHES.+ (filter-map (select-hit result) hits))+ (_+ (match caches+ ((cache rest ...)+ (let* ((narinfos (lookup-narinfos cache paths+ #:open-connection open-connection))+ (definite (map narinfo-path (filter authorized? narinfos)))+ (missing (lset-difference string=? paths definite))) ;XXX: perf+ (loop rest missing+ (fold vhash-cons result+ (map narinfo-path narinfos) narinfos)+ (append definite hits))))+ (() ;that's it+ (filter-map (select-hit result) hits)))))))++;;; substitutes.scm ends here-- 2.30.0
C
C
Christopher Baines wrote on 23 Feb 21:46 +0100
Re: [bug#45409] [PATCH v3 3/3] guix: Split (guix substitutes) from (guix scripts substitute).
(address . 45409@debbugs.gnu.org)
87wnuyldgm.fsf@cbaines.net
Christopher Baines <mail@cbaines.net> writes:
Toggle quote (22 lines)> Christopher Baines <mail@cbaines.net> writes:>>> Christopher Baines <mail@cbaines.net> writes:>>>>> I've rebased on master, tweaked the commit messages, and send a set of>>> v4 patches and while they don't create the (guix substitutes) module, I>>> think they unpick the bits I'd like to move out from the code doing the>>> connection caching.>>>> I did some more testing today, and while it turns out the tests passed>> when run with network access, one test failed when building the guix>> package.>>>> I've now rebased, and added an addition patch to address this, and sent>> a v5 series. My testing locally seems to suggest this works, so I'd like>> to merge it soon so I can push on with moving code out of the script>> module.>> I've gone ahead and pushed these patches as> 5c7874adb00c834e55e58a9b964ebc5fd1bb872c. I'll send some more patches to> make the remaining changes shortly.
I've sent more patches now.
One creates the (guix substitutes) module, and the other mostlyindependent patch looks to make backtraces appear in full.
-----BEGIN PGP SIGNATURE-----
iQKlBAEBCgCPFiEEPonu50WOcg2XVOCyXiijOwuE9XcFAmA1aZpfFIAAAAAALgAoaXNzdWVyLWZwckBub3RhdGlvbnMub3BlbnBncC5maWZ0aGhvcnNlbWFuLm5ldDNFODlFRUU3NDU4RTcyMEQ5NzU0RTBCMjVFMjhBMzNCMEI4NEY1NzcRHG1haWxAY2JhaW5lcy5uZXQACgkQXiijOwuE9XeRmw/+IkdQBBZCr9vhW3UY+1z+zdmNrG+pjhOTPPIP+pPCxN55uK7TIS8JMCa2Tf/liT8xDswpATpi32UlULP8AWaJGCyqFNK35rRIyWtqOFbpL14KwjD4oqnUmGDKRCHhxchoU52vcP11hkXJIUv4yBXBpqi9lgFX8ydAKhtm/Cvy35CPwGC1FnOQPvI2IBU43uMRlRzS1AOf4BM4dXkWM2XxCAnJS3+IlqJx0dIrFGgLXPaUax8jZzN/gGfp4mW4u8WnKWClWE+xD1pn1hk4gi3oJHCcEQodL8hdkSueRjiaFzSP1yQWDcfHA0UeR+SUrqgUcA4ceNP5lidAdoBxIgJXtAF1LWOnykl2L2UN7jGngVK6ccCx8NqbIl11SQtruKfB40XHAJ6zHLIUS2V85aN+HtEOc6hZxGz3N0mzdD39R6zxb0rA23Q23eUEWO+YSMZofv41DT7eQf3CJwEej69otYRkkn8KvH0p4r4DKK1jSq8vL+QEy7sV2IBj9fCl04avNv+H0cPJXc8Mk71tXfGPlEOVkLJImTaDkLlUofUFRB2vGILePELnK68FWZpsgZlOqxyfgNv7zF6Mv4qkKk6jbvbaWoKs3x76rE4dJR5RohfUMABFY2dlAVEvS0tITI/CWpDFf0WLpAyaD16Ns4RxkAgs+DAS5KNTum6bv47PxbU==9RNQ-----END PGP SIGNATURE-----
C
C
Christopher Baines wrote on 6 Mar 01:57 +0100
Re: [bug#45409] [PATCH 0/3] Move some (guix scripts substitute) code to two new modules
(address . 45409-done@debbugs.gnu.org)
87h7lpnlpe.fsf@cbaines.net
I pushed the creation of the (guix substitutes) module as112692c0d546d35cd67c5dc70dbd1dc609b18f64, so hopefully now it'll beeasier to improve substitute related things in Guix and things like theGuix Build Coordinator that use this code.
-----BEGIN PGP SIGNATURE-----
iQKlBAEBCgCPFiEEPonu50WOcg2XVOCyXiijOwuE9XcFAmBC015fFIAAAAAALgAoaXNzdWVyLWZwckBub3RhdGlvbnMub3BlbnBncC5maWZ0aGhvcnNlbWFuLm5ldDNFODlFRUU3NDU4RTcyMEQ5NzU0RTBCMjVFMjhBMzNCMEI4NEY1NzcRHG1haWxAY2JhaW5lcy5uZXQACgkQXiijOwuE9XcNYhAAqv6uiYBJpfLzTza2rD7IfaeGWJBgGJZh4HZjXWUv7xEyVoMMLEkRhdjtqIbIPzF9xeTRVs9hCzqSfgas6yU13q4zUmVC8PSQSQ63Ek4cta9UElMEuBk3F6wgo82PouWqVyRCyZs4/5MduCgVg1aQtGh11mNV8WoZaPKSsgPEIphMuW+1FV7iUIM6iUwMVKCO/aJ1S+IDT2ohYaGyGPcurFkIGXeyioyrjesxYcDr0M7+ZOZDREaZFx/ThwtRKLkB9yGaM81h2VCsakV06rFoLQk+F1cbfIqOQ7IhPXxdLcVs6v5NaG+H//FnDocbcgg4Vc7qy6HgkJ3EZG8F0hpa74zanSh1lCu+IjbS31VmRl/vqzdwfYXHeGylK3eimWJQAxkBO4jQmQYF354bv3o7mawxqze9ls0USWVpEI0im2XEHK1oBCzkGzt4/8yusYhz8s4C4qSfjLqHG0/quUK1EsqWo2ciTpGl8iTkxTAHHEwe6gsrjL1DciI20e5zeAw2iKoqJBKSt36qj/uGjiIAQPc8bBQ9c0sZqQNHUVQ1MX0IpK6qW4YGFCBe3jCwCQAlUf7dQPQi2A2Yc8HLocZdqDvFhxLONQQhbgaUmaYZrWR8PGsQ11oNV7dGkYPysaL6SvRcjg9tQ72F/9B4iNcMM8Tgp7h0C+yeBRFdirS4JLE==zCPM-----END PGP SIGNATURE-----
Closed
?