environment.scm 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  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 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 (gnu system linux-container)
  37. #:use-module (gnu system file-systems)
  38. #:use-module (gnu packages)
  39. #:use-module (gnu packages bash)
  40. #:use-module (gnu packages commencement)
  41. #:use-module (gnu packages guile)
  42. #:use-module ((gnu packages bootstrap)
  43. #:select (bootstrap-executable %bootstrap-guile))
  44. #:use-module (ice-9 format)
  45. #:use-module (ice-9 match)
  46. #:use-module (ice-9 rdelim)
  47. #:use-module (srfi srfi-1)
  48. #:use-module (srfi srfi-11)
  49. #:use-module (srfi srfi-26)
  50. #:use-module (srfi srfi-37)
  51. #:use-module (srfi srfi-98)
  52. #:export (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 (alist-cons 'graft? #f 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* (build-environment derivations opts)
  345. "Build the DERIVATIONS required by the environment using the build options
  346. in OPTS."
  347. (let ((substitutes? (assoc-ref opts 'substitutes?))
  348. (dry-run? (assoc-ref opts 'dry-run?)))
  349. (mbegin %store-monad
  350. (show-what-to-build* derivations
  351. #:use-substitutes? substitutes?
  352. #:dry-run? dry-run?)
  353. (if dry-run?
  354. (return #f)
  355. (built-derivations derivations)))))
  356. (define (manifest->derivation manifest system bootstrap?)
  357. "Return the derivation for a profile of MANIFEST.
  358. BOOTSTRAP? specifies whether to use the bootstrap Guile to build the profile."
  359. (profile-derivation manifest
  360. #:system system
  361. ;; Packages can have conflicting inputs, or explicit
  362. ;; inputs that conflict with implicit inputs (e.g., gcc,
  363. ;; gzip, etc.). Thus, do not error out when we
  364. ;; encounter collision.
  365. #:allow-collisions? #t
  366. #:hooks (if bootstrap?
  367. '()
  368. %default-profile-hooks)
  369. #:locales? (not bootstrap?)))
  370. (define requisites* (store-lift requisites))
  371. (define (inputs->requisites inputs)
  372. "Convert INPUTS, a list of input tuples or store path strings, into a set of
  373. requisite store items i.e. the union closure of all the inputs."
  374. (define (input->requisites input)
  375. (requisites*
  376. (match input
  377. ((drv output)
  378. (list (derivation->output-path drv output)))
  379. ((drv)
  380. (list (derivation->output-path drv)))
  381. ((? direct-store-path? path)
  382. (list path)))))
  383. (mlet %store-monad ((reqs (mapm %store-monad
  384. input->requisites inputs)))
  385. (return (delete-duplicates (concatenate reqs)))))
  386. (define (status->exit-code status)
  387. "Compute the exit code made from STATUS, a value as returned by 'waitpid',
  388. and suitable for 'exit'."
  389. ;; See <bits/waitstatus.h>.
  390. (or (status:exit-val status)
  391. (logior #x80 (status:term-sig status))))
  392. (define exit/status (compose exit status->exit-code))
  393. (define primitive-exit/status (compose primitive-exit status->exit-code))
  394. (define* (launch-environment command profile manifest
  395. #:key pure? (white-list '()))
  396. "Run COMMAND in a new environment containing INPUTS, using the native search
  397. paths defined by the list PATHS. When PURE?, pre-existing environment
  398. variables are cleared before setting the new ones, except those matching the
  399. regexps in WHITE-LIST."
  400. ;; Properly handle SIGINT, so pressing C-c in an interactive terminal
  401. ;; application works.
  402. (sigaction SIGINT SIG_DFL)
  403. (create-environment profile manifest
  404. #:pure? pure? #:white-list white-list)
  405. (match command
  406. ((program . args)
  407. (apply execlp program program args))))
  408. (define* (launch-environment/fork command profile manifest
  409. #:key pure? (white-list '()))
  410. "Run COMMAND in a new process with an environment containing PROFILE, with
  411. the search paths specified by MANIFEST. When PURE?, pre-existing environment
  412. variables are cleared before setting the new ones, except those matching the
  413. regexps in WHITE-LIST."
  414. (match (primitive-fork)
  415. (0 (launch-environment command profile manifest
  416. #:pure? pure?
  417. #:white-list white-list))
  418. (pid (match (waitpid pid)
  419. ((_ . status) status)))))
  420. (define* (launch-environment/container #:key command bash user user-mappings
  421. profile manifest link-profile? network?
  422. map-cwd? (white-list '()))
  423. "Run COMMAND within a container that features the software in PROFILE.
  424. Environment variables are set according to the search paths of MANIFEST.
  425. The global shell is BASH, a file name for a GNU Bash binary in the
  426. store. When NETWORK?, access to the host system network is permitted.
  427. USER-MAPPINGS, a list of file system mappings, contains the user-specified
  428. host file systems to mount inside the container. If USER is not #f, each
  429. target of USER-MAPPINGS will be re-written relative to '/home/USER', and USER
  430. will be used for the passwd entry. LINK-PROFILE? creates a symbolic link from
  431. ~/.guix-profile to the environment profile.
  432. Preserve environment variables whose name matches the one of the regexps in
  433. WHILE-LIST."
  434. (define (optional-mapping->fs mapping)
  435. (and (file-exists? (file-system-mapping-source mapping))
  436. (file-system-mapping->bind-mount mapping)))
  437. (mlet %store-monad ((reqs (inputs->requisites
  438. (list (direct-store-path bash) profile))))
  439. (return
  440. (let* ((cwd (getcwd))
  441. (home (getenv "HOME"))
  442. (uid (if user 1000 (getuid)))
  443. (gid (if user 1000 (getgid)))
  444. (passwd (let ((pwd (getpwuid (getuid))))
  445. (password-entry
  446. (name (or user (passwd:name pwd)))
  447. (real-name (if user
  448. ""
  449. (passwd:gecos pwd)))
  450. (uid uid) (gid gid) (shell bash)
  451. (directory (if user
  452. (string-append "/home/" user)
  453. (passwd:dir pwd))))))
  454. (groups (list (group-entry (name "users") (gid gid))
  455. (group-entry (gid 65534) ;the overflow GID
  456. (name "overflow"))))
  457. (home-dir (password-entry-directory passwd))
  458. (environ (filter (match-lambda
  459. ((variable . value)
  460. (find (cut regexp-exec <> variable)
  461. white-list)))
  462. (get-environment-variables)))
  463. ;; Bind-mount all requisite store items, user-specified mappings,
  464. ;; /bin/sh, the current working directory, and possibly networking
  465. ;; configuration files within the container.
  466. (mappings
  467. (append
  468. (override-user-mappings
  469. user home
  470. (append user-mappings
  471. ;; Share current working directory, unless asked not to.
  472. (if map-cwd?
  473. (list (file-system-mapping
  474. (source cwd)
  475. (target cwd)
  476. (writable? #t)))
  477. '())))
  478. ;; Mappings for the union closure of all inputs.
  479. (map (lambda (dir)
  480. (file-system-mapping
  481. (source dir)
  482. (target dir)
  483. (writable? #f)))
  484. reqs)))
  485. (file-systems (append %container-file-systems
  486. (if network?
  487. (filter-map optional-mapping->fs
  488. %network-file-mappings)
  489. '())
  490. (map file-system-mapping->bind-mount
  491. mappings))))
  492. (exit/status
  493. (call-with-container file-systems
  494. (lambda ()
  495. ;; Setup global shell.
  496. (mkdir-p "/bin")
  497. (symlink bash "/bin/sh")
  498. ;; Set a reasonable default PS1.
  499. (setenv "PS1" "\\u@\\h \\w [env]\\$ ")
  500. ;; Setup directory for temporary files.
  501. (mkdir-p "/tmp")
  502. (for-each (lambda (var)
  503. (setenv var "/tmp"))
  504. ;; The same variables as in Nix's 'build.cc'.
  505. '("TMPDIR" "TEMPDIR" "TMP" "TEMP"))
  506. ;; Create a dummy home directory.
  507. (mkdir-p home-dir)
  508. (setenv "HOME" home-dir)
  509. ;; If requested, link $GUIX_ENVIRONMENT to $HOME/.guix-profile;
  510. ;; this allows programs expecting that path to continue working as
  511. ;; expected within a container.
  512. (when link-profile? (link-environment profile home-dir))
  513. ;; Create a dummy /etc/passwd to satisfy applications that demand
  514. ;; to read it, such as 'git clone' over SSH, a valid use-case when
  515. ;; sharing the host's network namespace.
  516. (mkdir-p "/etc")
  517. (write-passwd (list passwd))
  518. (write-group groups)
  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 profile manifest #:pure? #f)))
  533. #:guest-uid uid
  534. #:guest-gid gid
  535. #:namespaces (if network?
  536. (delq 'net %namespaces) ; share host network
  537. %namespaces)))))))
  538. (define (user-override-home user)
  539. "Return home directory for override user USER."
  540. (string-append "/home/" user))
  541. (define (override-user-mappings user home mappings)
  542. "If a username USER is provided, rewrite each HOME prefix in file system
  543. mappings MAPPINGS to a home directory determined by 'override-user-dir';
  544. otherwise, return MAPPINGS."
  545. (if (not user)
  546. mappings
  547. (map (lambda (mapping)
  548. (let ((target (file-system-mapping-target mapping)))
  549. (if (string-prefix? home target)
  550. (file-system-mapping
  551. (source (file-system-mapping-source mapping))
  552. (target (override-user-dir user home target))
  553. (writable? (file-system-mapping-writable? mapping)))
  554. mapping)))
  555. mappings)))
  556. (define (override-user-dir user home dir)
  557. "If username USER is provided, overwrite string prefix HOME in DIR with a
  558. directory determined by 'user-override-home'; otherwise, return DIR."
  559. (if (and user (string-prefix? home dir))
  560. (string-append (user-override-home user)
  561. (substring dir (string-length home)))
  562. dir))
  563. (define (link-environment profile home-dir)
  564. "Create a symbolic link from HOME-DIR/.guix-profile to PROFILE."
  565. (let ((profile-dir (string-append home-dir "/.guix-profile")))
  566. (catch 'system-error
  567. (lambda ()
  568. (symlink profile profile-dir))
  569. (lambda args
  570. (if (= EEXIST (system-error-errno args))
  571. (leave (G_ "cannot link profile: '~a' already exists within container~%")
  572. profile-dir)
  573. (apply throw args))))))
  574. (define (environment-bash container? bootstrap? system)
  575. "Return a monadic value in the store monad for the version of GNU Bash
  576. needed in the environment for SYSTEM, if any. If CONTAINER? is #f, return #f.
  577. If CONTAINER? and BOOTSTRAP?, return the store path for the bootstrap Bash.
  578. Otherwise, return the derivation for the Bash package."
  579. (with-monad %store-monad
  580. (cond
  581. ((and container? (not bootstrap?))
  582. (package->derivation bash))
  583. ;; Use the bootstrap Bash instead.
  584. ((and container? bootstrap?)
  585. (lower-object (bootstrap-executable "bash" system)))
  586. (else
  587. (return #f)))))
  588. (define (parse-args args)
  589. "Parse the list of command line arguments ARGS."
  590. (define (handle-argument arg result)
  591. (alist-cons 'package (tag-package-arg result arg) result))
  592. ;; The '--' token is used to separate the command to run from the rest of
  593. ;; the operands.
  594. (let-values (((args command) (break (cut string=? "--" <>) args)))
  595. (let ((opts (parse-command-line args %options (list %default-options)
  596. #:argument-handler handle-argument)))
  597. (match command
  598. (() opts)
  599. (("--") opts)
  600. (("--" command ...) (alist-cons 'exec command opts))))))
  601. (define (assert-container-features)
  602. "Check if containers can be created and exit with an informative error
  603. message if any test fails."
  604. (unless (user-namespace-supported?)
  605. (report-error (G_ "cannot create container: user namespaces unavailable\n"))
  606. (leave (G_ "is your kernel version < 3.10?\n")))
  607. (unless (unprivileged-user-namespace-supported?)
  608. (report-error (G_ "cannot create container: unprivileged user cannot create user namespaces\n"))
  609. (leave (G_ "please set /proc/sys/kernel/unprivileged_userns_clone to \"1\"\n")))
  610. (unless (setgroups-supported?)
  611. (report-error (G_ "cannot create container: /proc/self/setgroups does not exist\n"))
  612. (leave (G_ "is your kernel version < 3.19?\n"))))
  613. (define (register-gc-root target root)
  614. "Make ROOT an indirect root to TARGET. This is procedure is idempotent."
  615. (let* ((root (if (string-prefix? "/" root)
  616. root
  617. (string-append (canonicalize-path (dirname root))
  618. "/" root))))
  619. (catch 'system-error
  620. (lambda ()
  621. (symlink target root)
  622. ((store-lift add-indirect-root) root))
  623. (lambda args
  624. (if (and (= EEXIST (system-error-errno args))
  625. (equal? (false-if-exception (readlink root)) target))
  626. (with-monad %store-monad
  627. (return #t))
  628. (apply throw args))))))
  629. ;;;
  630. ;;; Entry point.
  631. ;;;
  632. (define (guix-environment . args)
  633. (with-error-handling
  634. (let* ((opts (parse-args args))
  635. (pure? (assoc-ref opts 'pure))
  636. (container? (assoc-ref opts 'container?))
  637. (link-prof? (assoc-ref opts 'link-profile?))
  638. (network? (assoc-ref opts 'network?))
  639. (no-cwd? (assoc-ref opts 'no-cwd?))
  640. (user (assoc-ref opts 'user))
  641. (bootstrap? (assoc-ref opts 'bootstrap?))
  642. (system (assoc-ref opts 'system))
  643. (command (or (assoc-ref opts 'exec)
  644. ;; Spawn a shell if the user didn't specify
  645. ;; anything in particular.
  646. (if container?
  647. ;; The user's shell is likely not available
  648. ;; within the container.
  649. '("/bin/sh")
  650. (list %default-shell))))
  651. (mappings (pick-all opts 'file-system-mapping))
  652. (white-list (pick-all opts 'inherit-regexp)))
  653. (when container? (assert-container-features))
  654. (when (and (not container?) link-prof?)
  655. (leave (G_ "'--link-profile' cannot be used without '--container'~%")))
  656. (when (and (not container?) user)
  657. (leave (G_ "'--user' cannot be used without '--container'~%")))
  658. (when (and (not container?) no-cwd?)
  659. (leave (G_ "--no-cwd cannot be used without --container~%")))
  660. (with-store store
  661. (with-status-verbosity (assoc-ref opts 'verbosity)
  662. (define manifest
  663. (options/resolve-packages store opts))
  664. (set-build-options-from-command-line store opts)
  665. ;; Use the bootstrap Guile when requested.
  666. (parameterize ((%graft? (assoc-ref opts 'graft?))
  667. (%guile-for-build
  668. (package-derivation
  669. store
  670. (if bootstrap?
  671. %bootstrap-guile
  672. (canonical-package guile-2.2)))))
  673. (run-with-store store
  674. ;; Containers need a Bourne shell at /bin/sh.
  675. (mlet* %store-monad ((bash (environment-bash container?
  676. bootstrap?
  677. system))
  678. (prof-drv (manifest->derivation
  679. manifest system bootstrap?))
  680. (profile -> (derivation->output-path prof-drv))
  681. (gc-root -> (assoc-ref opts 'gc-root)))
  682. ;; First build the inputs. This is necessary even for
  683. ;; --search-paths. Additionally, we might need to build bash for
  684. ;; a container.
  685. (mbegin %store-monad
  686. (build-environment (if (derivation? bash)
  687. (list prof-drv bash)
  688. (list prof-drv))
  689. opts)
  690. (mwhen gc-root
  691. (register-gc-root profile gc-root))
  692. (cond
  693. ((assoc-ref opts 'dry-run?)
  694. (return #t))
  695. ((assoc-ref opts 'search-paths)
  696. (show-search-paths profile manifest #:pure? pure?)
  697. (return #t))
  698. (container?
  699. (let ((bash-binary
  700. (if bootstrap?
  701. (derivation->output-path bash)
  702. (string-append (derivation->output-path bash)
  703. "/bin/sh"))))
  704. (launch-environment/container #:command command
  705. #:bash bash-binary
  706. #:user user
  707. #:user-mappings mappings
  708. #:profile profile
  709. #:manifest manifest
  710. #:white-list white-list
  711. #:link-profile? link-prof?
  712. #:network? network?
  713. #:map-cwd? (not no-cwd?))))
  714. (else
  715. (return
  716. (exit/status
  717. (launch-environment/fork command profile manifest
  718. #:white-list white-list
  719. #:pure? pure?))))))))))))))