docker.scm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2017 Ricardo Wurmus <rekado@elephly.net>
  3. ;;; Copyright © 2017, 2018, 2019, 2021 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. (define-module (guix docker)
  21. #:use-module (gcrypt hash)
  22. #:use-module (guix base16)
  23. #:use-module ((guix build utils)
  24. #:select (mkdir-p
  25. delete-file-recursively
  26. with-directory-excursion
  27. invoke))
  28. #:use-module (gnu build install)
  29. #:use-module (json) ;guile-json
  30. #:use-module (srfi srfi-1)
  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 ftw)
  37. #:use-module (ice-9 match)
  38. #:export (build-docker-image))
  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. (define (layer-diff-id layer)
  43. "Generate a layer DiffID for the given LAYER archive."
  44. (string-append "sha256:" (bytevector->base16-string (file-sha256 layer))))
  45. ;; This is the semantic version of the JSON metadata schema according to
  46. ;; https://github.com/docker/docker/blob/master/image/spec/v1.2.md
  47. ;; It is NOT the version of the image specification.
  48. (define schema-version "1.0")
  49. (define (image-description id time)
  50. "Generate a simple image description."
  51. `((id . ,id)
  52. (created . ,time)
  53. (container_config . #nil)))
  54. (define (canonicalize-repository-name name)
  55. "\"Repository\" names are restricted to roughtl [a-z0-9_.-].
  56. Return a version of TAG that follows these rules."
  57. (define ascii-letters
  58. (string->char-set "abcdefghijklmnopqrstuvwxyz"))
  59. (define separators
  60. (string->char-set "_-."))
  61. (define repo-char-set
  62. (char-set-union char-set:digit ascii-letters separators))
  63. (string-map (lambda (chr)
  64. (if (char-set-contains? repo-char-set chr)
  65. chr
  66. #\.))
  67. (string-trim (string-downcase name) separators)))
  68. (define* (manifest path id #:optional (tag "guix"))
  69. "Generate a simple image manifest."
  70. (let ((tag (canonicalize-repository-name tag)))
  71. `#(((Config . "config.json")
  72. (RepoTags . #(,(string-append tag ":latest")))
  73. (Layers . #(,(string-append id "/layer.tar")))))))
  74. ;; According to the specifications this is required for backwards
  75. ;; compatibility. It duplicates information provided by the manifest.
  76. (define* (repositories path id #:optional (tag "guix"))
  77. "Generate a repositories file referencing PATH and the image ID."
  78. `((,(canonicalize-repository-name tag) . ((latest . ,id)))))
  79. ;; See https://github.com/opencontainers/image-spec/blob/master/config.md
  80. (define* (config layer time arch #:key entry-point (environment '()))
  81. "Generate a minimal image configuration for the given LAYER file."
  82. ;; "architecture" must be values matching "platform.arch" in the
  83. ;; runtime-spec at
  84. ;; https://github.com/opencontainers/runtime-spec/blob/v1.0.0-rc2/config.md#platform
  85. `((architecture . ,arch)
  86. (comment . "Generated by GNU Guix")
  87. (created . ,time)
  88. (config . ,`((env . ,(list->vector
  89. (map (match-lambda
  90. ((name . value)
  91. (string-append name "=" value)))
  92. environment)))
  93. ,@(if entry-point
  94. `((entrypoint . ,(list->vector entry-point)))
  95. '())))
  96. (container_config . #nil)
  97. (os . "linux")
  98. (rootfs . ((type . "layers")
  99. (diff_ids . #(,(layer-diff-id layer)))))))
  100. (define %tar-determinism-options
  101. ;; GNU tar options to produce archives deterministically.
  102. '("--sort=name" "--mtime=@1"
  103. "--owner=root:0" "--group=root:0"
  104. ;; When 'build-docker-image' is passed store items, the 'nlink' of the
  105. ;; files therein leads tar to store hard links instead of actual copies.
  106. ;; However, the 'nlink' count depends on deduplication in the store; it's
  107. ;; an "implicit input" to the build process. '--hard-dereference'
  108. ;; eliminates it.
  109. "--hard-dereference"))
  110. (define directive-file
  111. ;; Return the file or directory created by a 'evaluate-populate-directive'
  112. ;; directive.
  113. (match-lambda
  114. ((source '-> target)
  115. (string-trim source #\/))
  116. (('directory name _ ...)
  117. (string-trim name #\/))))
  118. (define* (build-docker-image image paths prefix
  119. #:key
  120. (repository "guix")
  121. (extra-files '())
  122. (transformations '())
  123. (system (utsname:machine (uname)))
  124. database
  125. entry-point
  126. (environment '())
  127. compressor
  128. (creation-time (current-time time-utc)))
  129. "Write to IMAGE a Docker image archive containing the given PATHS. PREFIX
  130. must be a store path that is a prefix of any store paths in PATHS. REPOSITORY
  131. is a descriptive name that will show up in \"REPOSITORY\" column of the output
  132. of \"docker images\".
  133. When DATABASE is true, copy it to /var/guix/db in the image and create
  134. /var/guix/gcroots and friends.
  135. When ENTRY-POINT is true, it must be a list of strings; it is stored as the
  136. entry point in the Docker image JSON structure.
  137. ENVIRONMENT must be a list of name/value pairs. It specifies the environment
  138. variables that must be defined in the resulting image.
  139. EXTRA-FILES must be a list of directives for 'evaluate-populate-directive'
  140. describing non-store files that must be created in the image.
  141. TRANSFORMATIONS must be a list of (OLD -> NEW) tuples describing how to
  142. transform the PATHS. Any path in PATHS that begins with OLD will be rewritten
  143. in the Docker image so that it begins with NEW instead. If a path is a
  144. non-empty directory, then its contents will be recursively added, as well.
  145. SYSTEM is a GNU triplet (or prefix thereof) of the system the binaries in
  146. PATHS are for; it is used to produce metadata in the image. Use COMPRESSOR, a
  147. command such as '(\"gzip\" \"-9n\"), to compress IMAGE. Use CREATION-TIME, a
  148. SRFI-19 time-utc object, as the creation time in metadata."
  149. (define (sanitize path-fragment)
  150. (escape-special-chars
  151. ;; GNU tar strips the leading slash off of absolute paths before applying
  152. ;; the transformations, so we need to do the same, or else our
  153. ;; replacements won't match any paths.
  154. (string-trim path-fragment #\/)
  155. ;; Escape the basic regexp special characters (see: "(sed) BRE syntax").
  156. ;; We also need to escape "/" because we use it as a delimiter.
  157. "/*.^$[]\\"
  158. #\\))
  159. (define transformation->replacement
  160. (match-lambda
  161. ((old '-> new)
  162. ;; See "(tar) transform" for details on the expression syntax.
  163. (string-append "s/^" (sanitize old) "/" (sanitize new) "/"))))
  164. (define (transformations->expression transformations)
  165. (let ((replacements (map transformation->replacement transformations)))
  166. (string-append
  167. ;; Avoid transforming link targets, since that would break some links
  168. ;; (e.g., symlinks that point to an absolute store path).
  169. "flags=rSH;"
  170. (string-join replacements ";")
  171. ;; Some paths might still have a leading path delimiter even after tar
  172. ;; transforms them (e.g., "/a/b" might be transformed into "/b"), so
  173. ;; strip any leading path delimiters that remain.
  174. ";s,^//*,,")))
  175. (define transformation-options
  176. (if (eq? '() transformations)
  177. '()
  178. `("--transform" ,(transformations->expression transformations))))
  179. (let* ((directory "/tmp/docker-image") ;temporary working directory
  180. (id (docker-id prefix))
  181. (time (date->string (time-utc->date creation-time) "~4"))
  182. (arch (let-syntax ((cond* (syntax-rules ()
  183. ((_ (pattern clause) ...)
  184. (cond ((string-prefix? pattern system)
  185. clause)
  186. ...
  187. (else
  188. (error "unsupported system"
  189. system)))))))
  190. (cond* ("x86_64" "amd64")
  191. ("i686" "386")
  192. ("arm" "arm")
  193. ("mips64" "mips64le")))))
  194. ;; Make sure we start with a fresh, empty working directory.
  195. (mkdir directory)
  196. (with-directory-excursion directory
  197. (mkdir id)
  198. (with-directory-excursion id
  199. (with-output-to-file "VERSION"
  200. (lambda () (display schema-version)))
  201. (with-output-to-file "json"
  202. (lambda () (scm->json (image-description id time))))
  203. ;; Create a directory for the non-store files that need to go into the
  204. ;; archive.
  205. (mkdir "extra")
  206. (with-directory-excursion "extra"
  207. ;; Create non-store files.
  208. (for-each (cut evaluate-populate-directive <> "./")
  209. extra-files)
  210. (when database
  211. ;; Initialize /var/guix, assuming PREFIX points to a profile.
  212. (install-database-and-gc-roots "." database prefix))
  213. (apply invoke "tar" "-cf" "../layer.tar"
  214. `(,@transformation-options
  215. ,@%tar-determinism-options
  216. ,@paths
  217. ,@(scandir "."
  218. (lambda (file)
  219. (not (member file '("." ".."))))))))
  220. ;; It is possible for "/" to show up in the archive, especially when
  221. ;; applying transformations. For example, the transformation
  222. ;; "s,^/a,," will (perhaps surprisingly) cause GNU tar to transform
  223. ;; the path "/a" into "/". The presence of "/" in the archive is
  224. ;; probably benign, but it is definitely safe to remove it, so let's
  225. ;; do that. This fails when "/" is not in the archive, so use system*
  226. ;; instead of invoke to avoid an exception in that case, and redirect
  227. ;; stderr to the bit bucket to avoid "Exiting with failure status"
  228. ;; error messages.
  229. (with-error-to-port (%make-void-port "w")
  230. (lambda ()
  231. (system* "tar" "--delete" "/" "-f" "layer.tar")))
  232. (delete-file-recursively "extra"))
  233. (with-output-to-file "config.json"
  234. (lambda ()
  235. (scm->json (config (string-append id "/layer.tar")
  236. time arch
  237. #:environment environment
  238. #:entry-point entry-point))))
  239. (with-output-to-file "manifest.json"
  240. (lambda ()
  241. (scm->json (manifest prefix id repository))))
  242. (with-output-to-file "repositories"
  243. (lambda ()
  244. (scm->json (repositories prefix id repository)))))
  245. (apply invoke "tar" "-cf" image "-C" directory
  246. `(,@%tar-determinism-options
  247. ,@(if compressor
  248. (list "-I" (string-join compressor))
  249. '())
  250. "."))
  251. (delete-file-recursively directory)))