Merge branch 'master' into core-updates
[jackhill/guix/guix.git] / guix / docker.scm
1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2017 Ricardo Wurmus <rekado@elephly.net>
3 ;;; Copyright © 2017, 2018 Ludovic Courtès <ludo@gnu.org>
4 ;;; Copyright © 2018 Chris Marusich <cmmarusich@gmail.com>
5 ;;;
6 ;;; This file is part of GNU Guix.
7 ;;;
8 ;;; GNU Guix is free software; you can redistribute it and/or modify it
9 ;;; under the terms of the GNU General Public License as published by
10 ;;; the Free Software Foundation; either version 3 of the License, or (at
11 ;;; your option) any later version.
12 ;;;
13 ;;; GNU Guix is distributed in the hope that it will be useful, but
14 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 ;;; GNU General Public License for more details.
17 ;;;
18 ;;; You should have received a copy of the GNU General Public License
19 ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
20
21 (define-module (guix docker)
22 #:use-module (gcrypt hash)
23 #:use-module (guix base16)
24 #:use-module ((guix build utils)
25 #:select (mkdir-p
26 delete-file-recursively
27 with-directory-excursion
28 invoke))
29 #:use-module (gnu build install)
30 #:use-module (json) ;guile-json
31 #:use-module (srfi srfi-19)
32 #:use-module (srfi srfi-26)
33 #:use-module ((texinfo string-utils)
34 #:select (escape-special-chars))
35 #:use-module (rnrs bytevectors)
36 #:use-module (ice-9 match)
37 #:export (build-docker-image))
38
39 ;; Generate a 256-bit identifier in hexadecimal encoding for the Docker image.
40 (define docker-id
41 (compose bytevector->base16-string sha256 string->utf8))
42
43 (define (layer-diff-id layer)
44 "Generate a layer DiffID for the given LAYER archive."
45 (string-append "sha256:" (bytevector->base16-string (file-sha256 layer))))
46
47 ;; This is the semantic version of the JSON metadata schema according to
48 ;; https://github.com/docker/docker/blob/master/image/spec/v1.2.md
49 ;; It is NOT the version of the image specification.
50 (define schema-version "1.0")
51
52 (define (image-description id time)
53 "Generate a simple image description."
54 `((id . ,id)
55 (created . ,time)
56 (container_config . #nil)))
57
58 (define (generate-tag path)
59 "Generate an image tag for the given PATH."
60 (match (string-split (basename path) #\-)
61 ((hash name . rest) (string-append name ":" hash))))
62
63 (define (manifest path id)
64 "Generate a simple image manifest."
65 `(((Config . "config.json")
66 (RepoTags . (,(generate-tag path)))
67 (Layers . (,(string-append id "/layer.tar"))))))
68
69 ;; According to the specifications this is required for backwards
70 ;; compatibility. It duplicates information provided by the manifest.
71 (define (repositories path id)
72 "Generate a repositories file referencing PATH and the image ID."
73 `((,(generate-tag path) . ((latest . ,id)))))
74
75 ;; See https://github.com/opencontainers/image-spec/blob/master/config.md
76 (define (config layer time arch)
77 "Generate a minimal image configuration for the given LAYER file."
78 ;; "architecture" must be values matching "platform.arch" in the
79 ;; runtime-spec at
80 ;; https://github.com/opencontainers/runtime-spec/blob/v1.0.0-rc2/config.md#platform
81 `((architecture . ,arch)
82 (comment . "Generated by GNU Guix")
83 (created . ,time)
84 (config . #nil)
85 (container_config . #nil)
86 (os . "linux")
87 (rootfs . ((type . "layers")
88 (diff_ids . (,(layer-diff-id layer)))))))
89
90 (define %tar-determinism-options
91 ;; GNU tar options to produce archives deterministically.
92 '("--sort=name" "--mtime=@1"
93 "--owner=root:0" "--group=root:0"))
94
95 (define symlink-source
96 (match-lambda
97 ((source '-> target)
98 (string-trim source #\/))))
99
100 (define (topmost-component file)
101 "Return the topmost component of FILE. For instance, if FILE is \"/a/b/c\",
102 return \"a\"."
103 (match (string-tokenize file (char-set-complement (char-set #\/)))
104 ((first rest ...)
105 first)))
106
107 (define* (build-docker-image image paths prefix
108 #:key
109 (symlinks '())
110 (transformations '())
111 (system (utsname:machine (uname)))
112 database
113 compressor
114 (creation-time (current-time time-utc)))
115 "Write to IMAGE a Docker image archive containing the given PATHS. PREFIX
116 must be a store path that is a prefix of any store paths in PATHS.
117
118 When DATABASE is true, copy it to /var/guix/db in the image and create
119 /var/guix/gcroots and friends.
120
121 SYMLINKS must be a list of (SOURCE -> TARGET) tuples describing symlinks to be
122 created in the image, where each TARGET is relative to PREFIX.
123 TRANSFORMATIONS must be a list of (OLD -> NEW) tuples describing how to
124 transform the PATHS. Any path in PATHS that begins with OLD will be rewritten
125 in the Docker image so that it begins with NEW instead. If a path is a
126 non-empty directory, then its contents will be recursively added, as well.
127
128 SYSTEM is a GNU triplet (or prefix thereof) of the system the binaries in
129 PATHS are for; it is used to produce metadata in the image. Use COMPRESSOR, a
130 command such as '(\"gzip\" \"-9n\"), to compress IMAGE. Use CREATION-TIME, a
131 SRFI-19 time-utc object, as the creation time in metadata."
132 (define (sanitize path-fragment)
133 (escape-special-chars
134 ;; GNU tar strips the leading slash off of absolute paths before applying
135 ;; the transformations, so we need to do the same, or else our
136 ;; replacements won't match any paths.
137 (string-trim path-fragment #\/)
138 ;; Escape the basic regexp special characters (see: "(sed) BRE syntax").
139 ;; We also need to escape "/" because we use it as a delimiter.
140 "/*.^$[]\\"
141 #\\))
142 (define transformation->replacement
143 (match-lambda
144 ((old '-> new)
145 ;; See "(tar) transform" for details on the expression syntax.
146 (string-append "s/^" (sanitize old) "/" (sanitize new) "/"))))
147 (define (transformations->expression transformations)
148 (let ((replacements (map transformation->replacement transformations)))
149 (string-append
150 ;; Avoid transforming link targets, since that would break some links
151 ;; (e.g., symlinks that point to an absolute store path).
152 "flags=rSH;"
153 (string-join replacements ";")
154 ;; Some paths might still have a leading path delimiter even after tar
155 ;; transforms them (e.g., "/a/b" might be transformed into "/b"), so
156 ;; strip any leading path delimiters that remain.
157 ";s,^//*,,")))
158 (define transformation-options
159 (if (eq? '() transformations)
160 '()
161 `("--transform" ,(transformations->expression transformations))))
162 (let* ((directory "/tmp/docker-image") ;temporary working directory
163 (id (docker-id prefix))
164 (time (date->string (time-utc->date creation-time) "~4"))
165 (arch (let-syntax ((cond* (syntax-rules ()
166 ((_ (pattern clause) ...)
167 (cond ((string-prefix? pattern system)
168 clause)
169 ...
170 (else
171 (error "unsupported system"
172 system)))))))
173 (cond* ("x86_64" "amd64")
174 ("i686" "386")
175 ("arm" "arm")
176 ("mips64" "mips64le")))))
177 ;; Make sure we start with a fresh, empty working directory.
178 (mkdir directory)
179 (with-directory-excursion directory
180 (mkdir id)
181 (with-directory-excursion id
182 (with-output-to-file "VERSION"
183 (lambda () (display schema-version)))
184 (with-output-to-file "json"
185 (lambda () (scm->json (image-description id time))))
186
187 ;; Create SYMLINKS.
188 (for-each (match-lambda
189 ((source '-> target)
190 (let ((source (string-trim source #\/)))
191 (mkdir-p (dirname source))
192 (symlink (string-append prefix "/" target)
193 source))))
194 symlinks)
195
196 (when database
197 ;; Initialize /var/guix, assuming PREFIX points to a profile.
198 (install-database-and-gc-roots "." database prefix))
199
200 (apply invoke "tar" "-cf" "layer.tar"
201 `(,@transformation-options
202 ,@%tar-determinism-options
203 ,@paths
204 ,@(if database '("var") '())
205 ,@(map symlink-source symlinks)))
206 ;; It is possible for "/" to show up in the archive, especially when
207 ;; applying transformations. For example, the transformation
208 ;; "s,^/a,," will (perhaps surprisingly) cause GNU tar to transform
209 ;; the path "/a" into "/". The presence of "/" in the archive is
210 ;; probably benign, but it is definitely safe to remove it, so let's
211 ;; do that. This fails when "/" is not in the archive, so use system*
212 ;; instead of invoke to avoid an exception in that case, and redirect
213 ;; stderr to the bit bucket to avoid "Exiting with failure status"
214 ;; error messages.
215 (with-error-to-port (%make-void-port "w")
216 (lambda ()
217 (system* "tar" "--delete" "/" "-f" "layer.tar")))
218
219 (for-each delete-file-recursively
220 (map (compose topmost-component symlink-source)
221 symlinks))
222
223 ;; Delete /var/guix.
224 (when database
225 (delete-file-recursively "var")))
226
227 (with-output-to-file "config.json"
228 (lambda ()
229 (scm->json (config (string-append id "/layer.tar")
230 time arch))))
231 (with-output-to-file "manifest.json"
232 (lambda ()
233 (scm->json (manifest prefix id))))
234 (with-output-to-file "repositories"
235 (lambda ()
236 (scm->json (repositories prefix id)))))
237
238 (apply invoke "tar" "-cf" image "-C" directory
239 `(,@%tar-determinism-options
240 ,@(if compressor
241 (list "-I" (string-join compressor))
242 '())
243 "."))
244 (delete-file-recursively directory)))