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>
6 ;;; This file is part of GNU Guix.
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.
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.
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/>.
21 (define-module (guix docker)
22 #:use-module (gcrypt hash)
23 #:use-module (guix base16)
24 #:use-module ((guix build utils)
26 delete-file-recursively
27 with-directory-excursion
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))
39 ;; Generate a 256-bit identifier in hexadecimal encoding for the Docker image.
41 (compose bytevector->base16-string sha256 string->utf8))
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))))
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")
52 (define (image-description id time)
53 "Generate a simple image description."
56 (container_config . #nil)))
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))))
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"))))))
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)))))
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
80 ;; https://github.com/opencontainers/runtime-spec/blob/v1.0.0-rc2/config.md#platform
81 `((architecture . ,arch)
82 (comment . "Generated by GNU Guix")
85 (container_config . #nil)
87 (rootfs . ((type . "layers")
88 (diff_ids . (,(layer-diff-id layer)))))))
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"))
95 (define symlink-source
98 (string-trim source #\/))))
100 (define (topmost-component file)
101 "Return the topmost component of FILE. For instance, if FILE is \"/a/b/c\",
103 (match (string-tokenize file (char-set-complement (char-set #\/)))
107 (define* (build-docker-image image paths prefix
110 (transformations '())
111 (system (utsname:machine (uname)))
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.
118 When DATABASE is true, copy it to /var/guix/db in the image and create
119 /var/guix/gcroots and friends.
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.
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.
142 (define transformation->replacement
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)))
150 ;; Avoid transforming link targets, since that would break some links
151 ;; (e.g., symlinks that point to an absolute store path).
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.
158 (define transformation-options
159 (if (eq? '() transformations)
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)
171 (error "unsupported system"
173 (cond* ("x86_64" "amd64")
176 ("mips64" "mips64le")))))
177 ;; Make sure we start with a fresh, empty working directory.
179 (with-directory-excursion directory
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))))
188 (for-each (match-lambda
190 (let ((source (string-trim source #\/)))
191 (mkdir-p (dirname source))
192 (symlink (string-append prefix "/" target)
197 ;; Initialize /var/guix, assuming PREFIX points to a profile.
198 (install-database-and-gc-roots "." database prefix))
200 (apply invoke "tar" "-cf" "layer.tar"
201 `(,@transformation-options
202 ,@%tar-determinism-options
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"
215 (with-error-to-port (%make-void-port "w")
217 (system* "tar" "--delete" "/" "-f" "layer.tar")))
219 (for-each delete-file-recursively
220 (map (compose topmost-component symlink-source)
225 (delete-file-recursively "var")))
227 (with-output-to-file "config.json"
229 (scm->json (config (string-append id "/layer.tar")
231 (with-output-to-file "manifest.json"
233 (scm->json (manifest prefix id))))
234 (with-output-to-file "repositories"
236 (scm->json (repositories prefix id)))))
238 (apply invoke "tar" "-cf" image "-C" directory
239 `(,@%tar-determinism-options
241 (list "-I" (string-join compressor))
244 (delete-file-recursively directory)))