environment.scm 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2014, 2015, 2018 David Thompson <davet@gnu.org>
  3. ;;; Copyright © 2015, 2016, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>
  4. ;;; Copyright © 2018 Mike Gerwitz <mtg@gnu.org>
  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 scripts environment)
  21. #:use-module (guix ui)
  22. #:use-module (guix store)
  23. #:use-module ((guix status) #:select (with-status-verbosity))
  24. #:use-module (guix grafts)
  25. #:use-module (guix derivations)
  26. #:use-module (guix packages)
  27. #:use-module (guix profiles)
  28. #:use-module (guix search-paths)
  29. #:use-module (guix build utils)
  30. #:use-module (guix monads)
  31. #:use-module ((guix gexp) #:select (lower-object))
  32. #:use-module (guix scripts)
  33. #:use-module (guix scripts build)
  34. #:use-module (gnu build linux-container)
  35. #:use-module (gnu build accounts)
  36. #:use-module ((guix build syscalls) #:select (set-network-interface-up))
  37. #:use-module (gnu system linux-container)
  38. #:use-module (gnu system file-systems)
  39. #:use-module (gnu packages)
  40. #:use-module (gnu packages bash)
  41. #:use-module ((gnu packages bootstrap)
  42. #:select (bootstrap-executable %bootstrap-guile))
  43. #:use-module (ice-9 format)
  44. #:use-module (ice-9 match)
  45. #:use-module (ice-9 rdelim)
  46. #:use-module (srfi srfi-1)
  47. #:use-module (srfi srfi-11)
  48. #:use-module (srfi srfi-26)
  49. #:use-module (srfi srfi-37)
  50. #:use-module (srfi srfi-98)
  51. #:export (assert-container-features
  52. guix-environment))
  53. ;; Protect some env vars from purification. Borrowed from nix-shell.
  54. (define %precious-variables
  55. '("HOME" "USER" "LOGNAME" "DISPLAY" "TERM" "TZ" "PAGER"))
  56. (define %default-shell
  57. (or (getenv "SHELL") "/bin/sh"))
  58. (define (purify-environment white-list)
  59. "Unset all environment variables except those that match the regexps in
  60. WHITE-LIST and those listed in %PRECIOUS-VARIABLES. A small number of
  61. variables such as 'HOME' and 'USER' are left untouched."
  62. (for-each unsetenv
  63. (remove (lambda (variable)
  64. (or (member variable %precious-variables)
  65. (find (cut regexp-exec <> variable)
  66. white-list)))
  67. (match (get-environment-variables)
  68. (((names . _) ...)
  69. names)))))
  70. (define* (create-environment profile manifest
  71. #:key pure? (white-list '()))
  72. "Set the environment variables specified by MANIFEST for PROFILE. When
  73. PURE? is #t, unset the variables in the current environment except those that
  74. match the regexps in WHITE-LIST. Otherwise, augment existing environment
  75. variables with additional search paths."
  76. (when pure?
  77. (purify-environment white-list))
  78. (for-each (match-lambda
  79. ((($ <search-path-specification> variable _ separator) . value)
  80. (let ((current (getenv variable)))
  81. (setenv variable
  82. (if (and current (not pure?))
  83. (if separator
  84. (string-append value separator current)
  85. value)
  86. value)))))
  87. (profile-search-paths profile manifest))
  88. ;; Give users a way to know that they're in 'guix environment', so they can
  89. ;; adjust 'PS1' accordingly, for instance. Set it to PROFILE so users can
  90. ;; conveniently access its contents.
  91. (setenv "GUIX_ENVIRONMENT" profile))
  92. (define* (show-search-paths profile manifest #:key pure?)
  93. "Display the search paths of MANIFEST applied to PROFILE. When PURE? is #t,
  94. do not augment existing environment variables with additional search paths."
  95. (for-each (match-lambda
  96. ((search-path . value)
  97. (display
  98. (search-path-definition search-path value
  99. #:kind (if pure? 'exact 'prefix)))
  100. (newline)))
  101. (profile-search-paths profile manifest)))
  102. (define (input->manifest-entry input)
  103. "Return a manifest entry for INPUT, or #f if INPUT does not correspond to a
  104. package."
  105. (match input
  106. ((_ (? package? package))
  107. (package->manifest-entry package))
  108. ((_ (? package? package) output)
  109. (package->manifest-entry package output))
  110. (_
  111. #f)))
  112. (define (package-environment-inputs package)
  113. "Return a list of manifest entries corresponding to the transitive input
  114. packages for PACKAGE."
  115. ;; Remove non-package inputs such as origin records.
  116. (filter-map input->manifest-entry
  117. (bag-transitive-inputs (package->bag package))))
  118. (define (show-help)
  119. (display (G_ "Usage: guix environment [OPTION]... PACKAGE... [-- COMMAND...]
  120. Build an environment that includes the dependencies of PACKAGE and execute
  121. COMMAND or an interactive shell in that environment.\n"))
  122. (display (G_ "
  123. -e, --expression=EXPR create environment for the package that EXPR
  124. evaluates to"))
  125. (display (G_ "
  126. -l, --load=FILE create environment for the package that the code within
  127. FILE evaluates to"))
  128. (display (G_ "
  129. -m, --manifest=FILE create environment with the manifest from FILE"))
  130. (display (G_ "
  131. --ad-hoc include all specified packages in the environment instead
  132. of only their inputs"))
  133. (display (G_ "
  134. --pure unset existing environment variables"))
  135. (display (G_ "
  136. -E, --preserve=REGEXP preserve environment variables that match REGEXP"))
  137. (display (G_ "
  138. --search-paths display needed environment variable definitions"))
  139. (display (G_ "
  140. -s, --system=SYSTEM attempt to build for SYSTEM--e.g., \"i686-linux\""))
  141. (display (G_ "
  142. -r, --root=FILE make FILE a symlink to the result, and register it
  143. as a garbage collector root"))
  144. (display (G_ "
  145. -C, --container run command within an isolated container"))
  146. (display (G_ "
  147. -N, --network allow containers to access the network"))
  148. (display (G_ "
  149. -P, --link-profile link environment profile to ~/.guix-profile within
  150. an isolated container"))
  151. (display (G_ "
  152. -u, --user=USER instead of copying the name and home of the current
  153. user into an isolated container, use the name USER
  154. with home directory /home/USER"))
  155. (display (G_ "
  156. --no-cwd do not share current working directory with an
  157. isolated container"))
  158. (display (G_ "
  159. --share=SPEC for containers, share writable host file system
  160. according to SPEC"))
  161. (display (G_ "
  162. --expose=SPEC for containers, expose read-only host file system
  163. according to SPEC"))
  164. (display (G_ "
  165. -v, --verbosity=LEVEL use the given verbosity LEVEL"))
  166. (display (G_ "
  167. --bootstrap use bootstrap binaries to build the environment"))
  168. (newline)
  169. (show-build-options-help)
  170. (newline)
  171. (show-transformation-options-help)
  172. (newline)
  173. (display (G_ "
  174. -h, --help display this help and exit"))
  175. (display (G_ "
  176. -V, --version display version information and exit"))
  177. (newline)
  178. (show-bug-report-information))
  179. (define %default-options
  180. `((system . ,(%current-system))
  181. (substitutes? . #t)
  182. (offload? . #t)
  183. (graft? . #t)
  184. (print-build-trace? . #t)
  185. (print-extended-build-trace? . #t)
  186. (multiplexed-build-output? . #t)
  187. (debug . 0)
  188. (verbosity . 1)))
  189. (define (tag-package-arg opts arg)
  190. "Return a two-element list with the form (TAG ARG) that tags ARG with either
  191. 'ad-hoc' in OPTS has the 'ad-hoc?' key set to #t, or 'inputs' otherwise."
  192. ;; Normally, the transitive inputs to a package are added to an environment,
  193. ;; but the ad-hoc? flag changes the meaning of a package argument such that
  194. ;; the package itself is added to the environment instead.
  195. (if (assoc-ref opts 'ad-hoc?)
  196. `(ad-hoc-package ,arg)
  197. `(package ,arg)))
  198. (define %options
  199. ;; Specification of the command-line options.
  200. (cons* (option '(#\h "help") #f #f
  201. (lambda args
  202. (show-help)
  203. (exit 0)))
  204. (option '(#\V "version") #f #f
  205. (lambda args
  206. (show-version-and-exit "guix environment")))
  207. (option '("pure") #f #f
  208. (lambda (opt name arg result)
  209. (alist-cons 'pure #t result)))
  210. (option '(#\E "preserve") #t #f
  211. (lambda (opt name arg result)
  212. (alist-cons 'inherit-regexp
  213. (make-regexp* arg)
  214. result)))
  215. (option '("inherit") #t #f ;deprecated
  216. (lambda (opt name arg result)
  217. (warning (G_ "'--inherit' is deprecated, \
  218. use '--preserve' instead~%"))
  219. (alist-cons 'inherit-regexp
  220. (make-regexp* arg)
  221. result)))
  222. (option '("search-paths") #f #f
  223. (lambda (opt name arg result)
  224. (alist-cons 'search-paths #t result)))
  225. (option '(#\l "load") #t #f
  226. (lambda (opt name arg result)
  227. (alist-cons 'load
  228. (tag-package-arg result arg)
  229. result)))
  230. (option '(#\e "expression") #t #f
  231. (lambda (opt name arg result)
  232. (alist-cons 'expression
  233. (tag-package-arg result arg)
  234. result)))
  235. (option '(#\m "manifest") #t #f
  236. (lambda (opt name arg result)
  237. (alist-cons 'manifest
  238. arg
  239. result)))
  240. (option '("ad-hoc") #f #f
  241. (lambda (opt name arg result)
  242. (alist-cons 'ad-hoc? #t result)))
  243. (option '(#\n "dry-run") #f #f
  244. (lambda (opt name arg result)
  245. (alist-cons 'dry-run? #t result)))
  246. (option '(#\s "system") #t #f
  247. (lambda (opt name arg result)
  248. (alist-cons 'system arg
  249. (alist-delete 'system result eq?))))
  250. (option '(#\C "container") #f #f
  251. (lambda (opt name arg result)
  252. (alist-cons 'container? #t result)))
  253. (option '(#\N "network") #f #f
  254. (lambda (opt name arg result)
  255. (alist-cons 'network? #t result)))
  256. (option '(#\P "link-profile") #f #f
  257. (lambda (opt name arg result)
  258. (alist-cons 'link-profile? #t result)))
  259. (option '(#\u "user") #t #f
  260. (lambda (opt name arg result)
  261. (alist-cons 'user arg
  262. (alist-delete 'user result eq?))))
  263. (option '("no-cwd") #f #f
  264. (lambda (opt name arg result)
  265. (alist-cons 'no-cwd? #t result)))
  266. (option '("share") #t #f
  267. (lambda (opt name arg result)
  268. (alist-cons 'file-system-mapping
  269. (specification->file-system-mapping arg #t)
  270. result)))
  271. (option '("expose") #t #f
  272. (lambda (opt name arg result)
  273. (alist-cons 'file-system-mapping
  274. (specification->file-system-mapping arg #f)
  275. result)))
  276. (option '(#\r "root") #t #f
  277. (lambda (opt name arg result)
  278. (alist-cons 'gc-root arg result)))
  279. (option '(#\v "verbosity") #t #f
  280. (lambda (opt name arg result)
  281. (let ((level (string->number* arg)))
  282. (alist-cons 'verbosity level
  283. (alist-delete 'verbosity result)))))
  284. (option '("bootstrap") #f #f
  285. (lambda (opt name arg result)
  286. (alist-cons 'bootstrap? #t result)))
  287. (append %transformation-options
  288. %standard-build-options)))
  289. (define (pick-all alist key)
  290. "Return a list of values in ALIST associated with KEY."
  291. (define same-key? (cut eq? key <>))
  292. (fold (lambda (pair memo)
  293. (match pair
  294. (((? same-key? k) . v)
  295. (cons v memo))
  296. (_ memo)))
  297. '() alist))
  298. (define (options/resolve-packages store opts)
  299. "Return OPTS with package specification strings replaced by manifest entries
  300. for the corresponding packages."
  301. (define (manifest-entry=? e1 e2)
  302. (and (eq? (manifest-entry-item e1) (manifest-entry-item e2))
  303. (string=? (manifest-entry-output e1)
  304. (manifest-entry-output e2))))
  305. (define transform
  306. (cut (options->transformation opts) store <>))
  307. (define* (package->manifest-entry* package #:optional (output "out"))
  308. (package->manifest-entry (transform package) output))
  309. (define (packages->outputs packages mode)
  310. (match packages
  311. ((? package? package)
  312. (if (eq? mode 'ad-hoc-package)
  313. (list (package->manifest-entry* package))
  314. (package-environment-inputs package)))
  315. (((? package? package) (? string? output))
  316. (if (eq? mode 'ad-hoc-package)
  317. (list (package->manifest-entry* package output))
  318. (package-environment-inputs package)))
  319. ((lst ...)
  320. (append-map (cut packages->outputs <> mode) lst))))
  321. (manifest
  322. (delete-duplicates
  323. (append-map (match-lambda
  324. (('package 'ad-hoc-package (? string? spec))
  325. (let-values (((package output)
  326. (specification->package+output spec)))
  327. (list (package->manifest-entry* package output))))
  328. (('package 'package (? string? spec))
  329. (package-environment-inputs
  330. (transform (specification->package+output spec))))
  331. (('expression mode str)
  332. ;; Add all the outputs of the package STR evaluates to.
  333. (packages->outputs (read/eval str) mode))
  334. (('load mode file)
  335. ;; Add all the outputs of the package defined in FILE.
  336. (let ((module (make-user-module '())))
  337. (packages->outputs (load* file module) mode)))
  338. (('manifest . file)
  339. (let ((module (make-user-module '((guix profiles) (gnu)))))
  340. (manifest-entries (load* file module))))
  341. (_ '()))
  342. opts)
  343. manifest-entry=?)))
  344. (define (manifest->derivation manifest system bootstrap?)
  345. "Return the derivation for a profile of MANIFEST.
  346. BOOTSTRAP? specifies whether to use the bootstrap Guile to build the profile."
  347. (profile-derivation manifest
  348. #:system system
  349. ;; Packages can have conflicting inputs, or explicit
  350. ;; inputs that conflict with implicit inputs (e.g., gcc,
  351. ;; gzip, etc.). Thus, do not error out when we
  352. ;; encounter collision.
  353. #:allow-collisions? #t
  354. #:hooks (if bootstrap?
  355. '()
  356. %default-profile-hooks)
  357. #:locales? (not bootstrap?)))
  358. (define requisites* (store-lift requisites))
  359. (define (inputs->requisites inputs)
  360. "Convert INPUTS, a list of input tuples or store path strings, into a set of
  361. requisite store items i.e. the union closure of all the inputs."
  362. (define (input->requisites input)
  363. (requisites*
  364. (match input
  365. ((drv output)
  366. (list (derivation->output-path drv output)))
  367. ((drv)
  368. (list (derivation->output-path drv)))
  369. ((? direct-store-path? path)
  370. (list path)))))
  371. (mlet %store-monad ((reqs (mapm %store-monad
  372. input->requisites inputs)))
  373. (return (delete-duplicates (concatenate reqs)))))
  374. (define (status->exit-code status)
  375. "Compute the exit code made from STATUS, a value as returned by 'waitpid',
  376. and suitable for 'exit'."
  377. ;; See <bits/waitstatus.h>.
  378. (or (status:exit-val status)
  379. (logior #x80 (status:term-sig status))))
  380. (define exit/status (compose exit status->exit-code))
  381. (define primitive-exit/status (compose primitive-exit status->exit-code))
  382. (define* (launch-environment command profile manifest
  383. #:key pure? (white-list '()))
  384. "Run COMMAND in a new environment containing INPUTS, using the native search
  385. paths defined by the list PATHS. When PURE?, pre-existing environment
  386. variables are cleared before setting the new ones, except those matching the
  387. regexps in WHITE-LIST."
  388. ;; Properly handle SIGINT, so pressing C-c in an interactive terminal
  389. ;; application works.
  390. (sigaction SIGINT SIG_DFL)
  391. (create-environment profile manifest
  392. #:pure? pure? #:white-list white-list)
  393. (match command
  394. ((program . args)
  395. (apply execlp program program args))))
  396. (define* (launch-environment/fork command profile manifest
  397. #:key pure? (white-list '()))
  398. "Run COMMAND in a new process with an environment containing PROFILE, with
  399. the search paths specified by MANIFEST. When PURE?, pre-existing environment
  400. variables are cleared before setting the new ones, except those matching the
  401. regexps in WHITE-LIST."
  402. (match (primitive-fork)
  403. (0 (launch-environment command profile manifest
  404. #:pure? pure?
  405. #:white-list white-list))
  406. (pid (match (waitpid pid)
  407. ((_ . status) status)))))
  408. (define* (launch-environment/container #:key command bash user user-mappings
  409. profile manifest link-profile? network?
  410. map-cwd? (white-list '()))
  411. "Run COMMAND within a container that features the software in PROFILE.
  412. Environment variables are set according to the search paths of MANIFEST.
  413. The global shell is BASH, a file name for a GNU Bash binary in the
  414. store. When NETWORK?, access to the host system network is permitted.
  415. USER-MAPPINGS, a list of file system mappings, contains the user-specified
  416. host file systems to mount inside the container. If USER is not #f, each
  417. target of USER-MAPPINGS will be re-written relative to '/home/USER', and USER
  418. will be used for the passwd entry. LINK-PROFILE? creates a symbolic link from
  419. ~/.guix-profile to the environment profile.
  420. Preserve environment variables whose name matches the one of the regexps in
  421. WHILE-LIST."
  422. (define (optional-mapping->fs mapping)
  423. (and (file-exists? (file-system-mapping-source mapping))
  424. (file-system-mapping->bind-mount mapping)))
  425. (mlet %store-monad ((reqs (inputs->requisites
  426. (list (direct-store-path bash) profile))))
  427. (return
  428. (let* ((cwd (getcwd))
  429. (home (getenv "HOME"))
  430. (uid (if user 1000 (getuid)))
  431. (gid (if user 1000 (getgid)))
  432. (passwd (let ((pwd (getpwuid (getuid))))
  433. (password-entry
  434. (name (or user (passwd:name pwd)))
  435. (real-name (if user
  436. ""
  437. (passwd:gecos pwd)))
  438. (uid uid) (gid gid) (shell bash)
  439. (directory (if user
  440. (string-append "/home/" user)
  441. (passwd:dir pwd))))))
  442. (groups (list (group-entry (name "users") (gid gid))
  443. (group-entry (gid 65534) ;the overflow GID
  444. (name "overflow"))))
  445. (home-dir (password-entry-directory passwd))
  446. (logname (password-entry-name passwd))
  447. (environ (filter (match-lambda
  448. ((variable . value)
  449. (find (cut regexp-exec <> variable)
  450. white-list)))
  451. (get-environment-variables)))
  452. ;; Bind-mount all requisite store items, user-specified mappings,
  453. ;; /bin/sh, the current working directory, and possibly networking
  454. ;; configuration files within the container.
  455. (mappings
  456. (append
  457. (override-user-mappings
  458. user home
  459. (append user-mappings
  460. ;; Share current working directory, unless asked not to.
  461. (if map-cwd?
  462. (list (file-system-mapping
  463. (source cwd)
  464. (target cwd)
  465. (writable? #t)))
  466. '())))
  467. ;; Mappings for the union closure of all inputs.
  468. (map (lambda (dir)
  469. (file-system-mapping
  470. (source dir)
  471. (target dir)
  472. (writable? #f)))
  473. reqs)))
  474. (file-systems (append %container-file-systems
  475. (if network?
  476. (filter-map optional-mapping->fs
  477. %network-file-mappings)
  478. '())
  479. (map file-system-mapping->bind-mount
  480. mappings))))
  481. (exit/status
  482. (call-with-container file-systems
  483. (lambda ()
  484. ;; Setup global shell.
  485. (mkdir-p "/bin")
  486. (symlink bash "/bin/sh")
  487. ;; Set a reasonable default PS1.
  488. (setenv "PS1" "\\u@\\h \\w [env]\\$ ")
  489. ;; Setup directory for temporary files.
  490. (mkdir-p "/tmp")
  491. (for-each (lambda (var)
  492. (setenv var "/tmp"))
  493. ;; The same variables as in Nix's 'build.cc'.
  494. '("TMPDIR" "TEMPDIR" "TMP" "TEMP"))
  495. ;; Some programs expect USER and/or LOGNAME to be set.
  496. (setenv "LOGNAME" logname)
  497. (setenv "USER" logname)
  498. ;; Create a dummy home directory.
  499. (mkdir-p home-dir)
  500. (setenv "HOME" home-dir)
  501. ;; If requested, link $GUIX_ENVIRONMENT to $HOME/.guix-profile;
  502. ;; this allows programs expecting that path to continue working as
  503. ;; expected within a container.
  504. (when link-profile? (link-environment profile home-dir))
  505. ;; Create a dummy /etc/passwd to satisfy applications that demand
  506. ;; to read it, such as 'git clone' over SSH, a valid use-case when
  507. ;; sharing the host's network namespace.
  508. (mkdir-p "/etc")
  509. (write-passwd (list passwd))
  510. (write-group groups)
  511. (unless network?
  512. ;; When isolated from the network, provide a minimal /etc/hosts
  513. ;; to resolve "localhost".
  514. (call-with-output-file "/etc/hosts"
  515. (lambda (port)
  516. (display "127.0.0.1 localhost\n" port)))
  517. ;; Allow local AF_INET communications.
  518. (set-network-interface-up "lo"))
  519. ;; For convenience, start in the user's current working
  520. ;; directory or, if unmapped, the home directory.
  521. (chdir (if map-cwd?
  522. (override-user-dir user home cwd)
  523. home-dir))
  524. ;; Set environment variables that match WHITE-LIST.
  525. (for-each (match-lambda
  526. ((variable . value)
  527. (setenv variable value)))
  528. environ)
  529. (primitive-exit/status
  530. ;; A container's environment is already purified, so no need to
  531. ;; request it be purified again.
  532. (launch-environment command
  533. (if link-profile?
  534. (string-append home-dir "/.guix-profile")
  535. profile)
  536. manifest #:pure? #f)))
  537. #:guest-uid uid
  538. #:guest-gid gid
  539. #:namespaces (if network?
  540. (delq 'net %namespaces) ; share host network
  541. %namespaces)))))))
  542. (define (user-override-home user)
  543. "Return home directory for override user USER."
  544. (string-append "/home/" user))
  545. (define (override-user-mappings user home mappings)
  546. "If a username USER is provided, rewrite each HOME prefix in file system
  547. mappings MAPPINGS to a home directory determined by 'override-user-dir';
  548. otherwise, return MAPPINGS."
  549. (if (not user)
  550. mappings
  551. (map (lambda (mapping)
  552. (let ((target (file-system-mapping-target mapping)))
  553. (if (string-prefix? home target)
  554. (file-system-mapping
  555. (source (file-system-mapping-source mapping))
  556. (target (override-user-dir user home target))
  557. (writable? (file-system-mapping-writable? mapping)))
  558. mapping)))
  559. mappings)))
  560. (define (override-user-dir user home dir)
  561. "If username USER is provided, overwrite string prefix HOME in DIR with a
  562. directory determined by 'user-override-home'; otherwise, return DIR."
  563. (if (and user (string-prefix? home dir))
  564. (string-append (user-override-home user)
  565. (substring dir (string-length home)))
  566. dir))
  567. (define (link-environment profile home-dir)
  568. "Create a symbolic link from HOME-DIR/.guix-profile to PROFILE."
  569. (let ((profile-dir (string-append home-dir "/.guix-profile")))
  570. (catch 'system-error
  571. (lambda ()
  572. (symlink profile profile-dir))
  573. (lambda args
  574. (if (= EEXIST (system-error-errno args))
  575. (leave (G_ "cannot link profile: '~a' already exists within container~%")
  576. profile-dir)
  577. (apply throw args))))))
  578. (define (environment-bash container? bootstrap? system)
  579. "Return a monadic value in the store monad for the version of GNU Bash
  580. needed in the environment for SYSTEM, if any. If CONTAINER? is #f, return #f.
  581. If CONTAINER? and BOOTSTRAP?, return the store path for the bootstrap Bash.
  582. Otherwise, return the derivation for the Bash package."
  583. (with-monad %store-monad
  584. (cond
  585. ((and container? (not bootstrap?))
  586. (package->derivation bash))
  587. ;; Use the bootstrap Bash instead.
  588. ((and container? bootstrap?)
  589. (lower-object (bootstrap-executable "bash" system)))
  590. (else
  591. (return #f)))))
  592. (define (parse-args args)
  593. "Parse the list of command line arguments ARGS."
  594. (define (handle-argument arg result)
  595. (alist-cons 'package (tag-package-arg result arg) result))
  596. ;; The '--' token is used to separate the command to run from the rest of
  597. ;; the operands.
  598. (let-values (((args command) (break (cut string=? "--" <>) args)))
  599. (let ((opts (parse-command-line args %options (list %default-options)
  600. #:argument-handler handle-argument)))
  601. (match command
  602. (() opts)
  603. (("--") opts)
  604. (("--" command ...) (alist-cons 'exec command opts))))))
  605. (define (assert-container-features)
  606. "Check if containers can be created and exit with an informative error
  607. message if any test fails."
  608. (unless (user-namespace-supported?)
  609. (report-error (G_ "cannot create container: user namespaces unavailable\n"))
  610. (leave (G_ "is your kernel version < 3.10?\n")))
  611. (unless (unprivileged-user-namespace-supported?)
  612. (report-error (G_ "cannot create container: unprivileged user cannot create user namespaces\n"))
  613. (leave (G_ "please set /proc/sys/kernel/unprivileged_userns_clone to \"1\"\n")))
  614. (unless (setgroups-supported?)
  615. (report-error (G_ "cannot create container: /proc/self/setgroups does not exist\n"))
  616. (leave (G_ "is your kernel version < 3.19?\n"))))
  617. (define (register-gc-root target root)
  618. "Make ROOT an indirect root to TARGET. This is procedure is idempotent."
  619. (let* ((root (if (string-prefix? "/" root)
  620. root
  621. (string-append (canonicalize-path (dirname root))
  622. "/" root))))
  623. (catch 'system-error
  624. (lambda ()
  625. (symlink target root)
  626. ((store-lift add-indirect-root) root))
  627. (lambda args
  628. (if (and (= EEXIST (system-error-errno args))
  629. (equal? (false-if-exception (readlink root)) target))
  630. (with-monad %store-monad
  631. (return #t))
  632. (apply throw args))))))
  633. ;;;
  634. ;;; Entry point.
  635. ;;;
  636. (define-command (guix-environment . args)
  637. (category development)
  638. (synopsis "spawn one-off software environments")
  639. (with-error-handling
  640. (let* ((opts (parse-args args))
  641. (pure? (assoc-ref opts 'pure))
  642. (container? (assoc-ref opts 'container?))
  643. (link-prof? (assoc-ref opts 'link-profile?))
  644. (network? (assoc-ref opts 'network?))
  645. (no-cwd? (assoc-ref opts 'no-cwd?))
  646. (user (assoc-ref opts 'user))
  647. (bootstrap? (assoc-ref opts 'bootstrap?))
  648. (system (assoc-ref opts 'system))
  649. (command (or (assoc-ref opts 'exec)
  650. ;; Spawn a shell if the user didn't specify
  651. ;; anything in particular.
  652. (if container?
  653. ;; The user's shell is likely not available
  654. ;; within the container.
  655. '("/bin/sh")
  656. (list %default-shell))))
  657. (mappings (pick-all opts 'file-system-mapping))
  658. (white-list (pick-all opts 'inherit-regexp)))
  659. (when container? (assert-container-features))
  660. (when (and (not container?) link-prof?)
  661. (leave (G_ "'--link-profile' cannot be used without '--container'~%")))
  662. (when (and (not container?) user)
  663. (leave (G_ "'--user' cannot be used without '--container'~%")))
  664. (when (and (not container?) no-cwd?)
  665. (leave (G_ "--no-cwd cannot be used without --container~%")))
  666. (with-store store
  667. (with-build-handler (build-notifier #:use-substitutes?
  668. (assoc-ref opts 'substitutes?)
  669. #:verbosity
  670. (assoc-ref opts 'verbosity)
  671. #:dry-run?
  672. (assoc-ref opts 'dry-run?))
  673. (with-status-verbosity (assoc-ref opts 'verbosity)
  674. (define manifest
  675. (options/resolve-packages store opts))
  676. (set-build-options-from-command-line store opts)
  677. ;; Use the bootstrap Guile when requested.
  678. (parameterize ((%graft? (assoc-ref opts 'graft?))
  679. (%guile-for-build
  680. (package-derivation
  681. store
  682. (if bootstrap?
  683. %bootstrap-guile
  684. (default-guile)))))
  685. (run-with-store store
  686. ;; Containers need a Bourne shell at /bin/sh.
  687. (mlet* %store-monad ((bash (environment-bash container?
  688. bootstrap?
  689. system))
  690. (prof-drv (manifest->derivation
  691. manifest system bootstrap?))
  692. (profile -> (derivation->output-path prof-drv))
  693. (gc-root -> (assoc-ref opts 'gc-root)))
  694. ;; First build the inputs. This is necessary even for
  695. ;; --search-paths. Additionally, we might need to build bash for
  696. ;; a container.
  697. (mbegin %store-monad
  698. (built-derivations (if (derivation? bash)
  699. (list prof-drv bash)
  700. (list prof-drv)))
  701. (mwhen gc-root
  702. (register-gc-root profile gc-root))
  703. (cond
  704. ((assoc-ref opts 'search-paths)
  705. (show-search-paths profile manifest #:pure? pure?)
  706. (return #t))
  707. (container?
  708. (let ((bash-binary
  709. (if bootstrap?
  710. (derivation->output-path bash)
  711. (string-append (derivation->output-path bash)
  712. "/bin/sh"))))
  713. (launch-environment/container #:command command
  714. #:bash bash-binary
  715. #:user user
  716. #:user-mappings mappings
  717. #:profile profile
  718. #:manifest manifest
  719. #:white-list white-list
  720. #:link-profile? link-prof?
  721. #:network? network?
  722. #:map-cwd? (not no-cwd?))))
  723. (else
  724. (return
  725. (exit/status
  726. (launch-environment/fork command profile manifest
  727. #:white-list white-list
  728. #:pure? pure?)))))))))))))))