environment.scm 34 KB

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