environment.scm 33 KB

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