docker.scm 12 KB

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