5 @setfilename guix-cookbook.info
6 @documentencoding UTF-8
7 @settitle GNU Guix Cookbook
10 @c Onion service for ci.guix.gnu.org.
11 @set SUBSTITUTE-TOR-URL https://4zwzi66wwdaalbhgnix55ea3ab4pvvw66ll2ow53kjub6se4q2bclcyd.onion
14 Copyright @copyright{} 2019, 2022 Ricardo Wurmus@*
15 Copyright @copyright{} 2019 Efraim Flashner@*
16 Copyright @copyright{} 2019 Pierre Neidhardt@*
17 Copyright @copyright{} 2020 Oleg Pykhalov@*
18 Copyright @copyright{} 2020 Matthew Brooks@*
19 Copyright @copyright{} 2020 Marcin Karpezo@*
20 Copyright @copyright{} 2020 Brice Waegeneire@*
21 Copyright @copyright{} 2020 André Batista@*
22 Copyright @copyright{} 2020 Christine Lemmer-Webber@*
23 Copyright @copyright{} 2021 Joshua Branson@*
25 Permission is granted to copy, distribute and/or modify this document
26 under the terms of the GNU Free Documentation License, Version 1.3 or
27 any later version published by the Free Software Foundation; with no
28 Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A
29 copy of the license is included in the section entitled ``GNU Free
30 Documentation License''.
33 @dircategory System administration
35 * Guix cookbook: (guix-cookbook). Tutorials and examples for GNU Guix.
39 @title GNU Guix Cookbook
40 @subtitle Tutorials and examples for using the GNU Guix Functional Package Manager
41 @author The GNU Guix Developers
44 @vskip 0pt plus 1filll
51 @c *********************************************************************
53 @top GNU Guix Cookbook
55 This document presents tutorials and detailed examples for GNU@tie{}Guix, a
56 functional package management tool written for the GNU system. Please
57 @pxref{Top,,, guix, GNU Guix reference manual} for details about the system,
58 its API, and related concepts.
60 @c TRANSLATORS: You can replace the following paragraph with information on
61 @c how to join your own translation team and how to report issues with the
63 This manual is also available in French (@pxref{Top,,, guix-cookbook.fr,
64 Livre de recettes de GNU Guix}) and German (@pxref{Top,,,
65 guix-cookbook.de, GNU-Guix-Kochbuch}). If you would like to translate
66 this document in your native language, consider joining
67 @uref{https://translate.fedoraproject.org/projects/guix/documentation-cookbook,
68 Weblate} (@pxref{Translating Guix,,, guix, GNU Guix reference manual}).
71 * Scheme tutorials:: Meet your new favorite language!
72 * Packaging:: Packaging tutorials
73 * System Configuration:: Customizing the GNU System
74 * Containers:: Isolated environments and nested systems
75 * Advanced package management:: Power to the users!
76 * Environment management:: Control environment
78 * Acknowledgments:: Thanks!
79 * GNU Free Documentation License:: The license of this document.
80 * Concept Index:: Concepts.
83 --- The Detailed Node Listing ---
87 * A Scheme Crash Course:: Learn the basics of Scheme
91 * Packaging Tutorial:: Let's add a package to Guix!
95 * Auto-Login to a Specific TTY:: Automatically Login a User to a Specific TTY
96 * Customizing the Kernel:: Creating and using a custom Linux kernel on Guix System.
97 * Guix System Image API:: Customizing images to target specific platforms.
98 * Connecting to Wireguard VPN:: Connecting to a Wireguard VPN.
99 * Customizing a Window Manager:: Handle customization of a Window manager on Guix System.
100 * Running Guix on a Linode Server:: Running Guix on a Linode Server. Running Guix on a Linode Server
101 * Setting up a bind mount:: Setting up a bind mount in the file-systems definition.
102 * Getting substitutes from Tor:: Configuring Guix daemon to get substitutes through Tor.
103 * Setting up NGINX with Lua:: Configuring NGINX web-server to load Lua modules.
104 * Music Server with Bluetooth Audio:: Headless music player with Bluetooth output.
109 @c *********************************************************************
110 @node Scheme tutorials
111 @chapter Scheme tutorials
113 GNU@tie{}Guix is written in the general purpose programming language Scheme,
114 and many of its features can be accessed and manipulated programmatically.
115 You can use Scheme to generate package definitions, to modify them, to build
116 them, to deploy whole operating systems, etc.
118 Knowing the basics of how to program in Scheme will unlock many of the
119 advanced features Guix provides --- and you don't even need to be an
120 experienced programmer to use them!
124 @node A Scheme Crash Course
125 @section A Scheme Crash Course
127 @cindex Scheme, crash course
129 Guix uses the Guile implementation of Scheme. To start playing with the
130 language, install it with @code{guix install guile} and start a
131 @dfn{REPL}---short for @uref{https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop,
132 @dfn{read-eval-print loop}}---by running @code{guile} from the command line.
134 Alternatively you can also run @code{guix shell guile -- guile}
135 if you'd rather not have Guile installed in your user profile.
137 In the following examples, lines show what you would type at the REPL;
138 lines starting with ``@result{}'' show evaluation results, while lines
139 starting with ``@print{}'' show things that get printed. @xref{Using Guile
140 Interactively,,, guile, GNU Guile Reference Manual}, for more details on the
145 Scheme syntax boils down to a tree of expressions (or @emph{s-expression} in
146 Lisp lingo). An expression can be a literal such as numbers and strings, or a
147 compound which is a parenthesized list of compounds and literals. @code{#true}
148 and @code{#false} (abbreviated @code{#t} and @code{#f}) stand for the
149 Booleans ``true'' and ``false'', respectively.
151 Examples of valid expressions:
155 @result{} "Hello World!"
160 (display (string-append "Hello " "Guix" "\n"))
162 @result{} #<unspecified>
166 This last example is a function call nested in another function call. When a
167 parenthesized expression is evaluated, the first term is the function and the
168 rest are the arguments passed to the function. Every function returns the
169 last evaluated expression as its return value.
172 Anonymous functions are declared with the @code{lambda} term:
176 @result{} #<procedure 120e348 at <unknown port>:24:0 (x)>
179 The above procedure returns the square of its argument. Since everything is
180 an expression, the @code{lambda} expression returns an anonymous procedure,
181 which can in turn be applied to an argument:
184 ((lambda (x) (* x x)) 3)
189 Anything can be assigned a global name with @code{define}:
193 (define square (lambda (x) (* x x)))
199 Procedures can be defined more concisely with the following syntax:
202 (define (square x) (* x x))
206 A list structure can be created with the @code{list} procedure:
214 The @dfn{quote} disables evaluation of a parenthesized expression: the
215 first term is not called over the other terms (@pxref{Expression Syntax,
216 quote,, guile, GNU Guile Reference Manual}). Thus it effectively
217 returns a list of terms.
220 '(display (string-append "Hello " "Guix" "\n"))
221 @result{} (display (string-append "Hello " "Guix" "\n"))
228 The @dfn{quasiquote} disables evaluation of a parenthesized expression
229 until @dfn{unquote} (a comma) re-enables it. Thus it provides us with
230 fine-grained control over what is evaluated and what is not.
233 `(2 a 5 7 (2 ,a 5 ,(+ a 4)))
234 @result{} (2 a 5 7 (2 3 5 7))
237 Note that the above result is a list of mixed elements: numbers, symbols (here
238 @code{a}) and the last element is a list itself.
241 Multiple variables can be named locally with @code{let} (@pxref{Local
242 Bindings,,, guile, GNU Guile Reference Manual}):
255 @error{} In procedure module-lookup: Unbound variable: y
258 Use @code{let*} to allow later variable declarations to refer to earlier
269 @dfn{Keywords} are typically used to identify the named parameters of a
270 procedure. They are prefixed by @code{#:} (hash, colon) followed by
271 alphanumeric characters: @code{#:like-this}.
272 @xref{Keywords,,, guile, GNU Guile Reference Manual}.
275 The percentage @code{%} is typically used for read-only global variables in
276 the build stage. Note that it is merely a convention, like @code{_} in C.
277 Scheme treats @code{%} exactly the same as any other letter.
280 Modules are created with @code{define-module} (@pxref{Creating Guile
281 Modules,,, guile, GNU Guile Reference Manual}). For instance
284 (define-module (guix build-system ruby)
285 #:use-module (guix store)
290 defines the module @code{guix build-system ruby} which must be located in
291 @file{guix/build-system/ruby.scm} somewhere in the Guile load path. It
292 depends on the @code{(guix store)} module and it exports two variables,
293 @code{ruby-build} and @code{ruby-build-system}.
296 @quotation Going further
297 Scheme is a language that has been widely used to teach programming and
298 you'll find plenty of material using it as a vehicle. Here's a
299 selection of documents to learn more about Scheme:
303 @uref{https://spritely.institute/static/papers/scheme-primer.html, @i{A
304 Scheme Primer}}, by Christine Lemmer-Webber and the Spritely Institute.
307 @uref{http://www.troubleshooters.com/codecorn/scheme_guile/hello.htm,
308 @i{Scheme at a Glance}}, by Steve Litt.
311 @uref{https://mitpress.mit.edu/sites/default/files/sicp/index.html,
312 @i{Structure and Interpretation of Computer Programs}}, by Harold
313 Abelson and Gerald Jay Sussman, with Julie Sussman. Colloquially known
314 as ``SICP'', this book is a reference.
316 You can also install it and read it from your computer:
319 guix install sicp info-reader
323 An @uref{https://sarabander.github.io/sicp/, unofficial ebook} is also
328 You'll find more books, tutorials and other resources at
329 @url{https://schemers.org/}.
333 @c *********************************************************************
339 This chapter is dedicated to teaching you how to add packages to the
340 collection of packages that come with GNU Guix. This involves writing package
341 definitions in Guile Scheme, organizing them in package modules, and building
345 * Packaging Tutorial:: A tutorial on how to add packages to Guix.
348 @node Packaging Tutorial
349 @section Packaging Tutorial
351 GNU Guix stands out as the @emph{hackable} package manager, mostly because it
352 uses @uref{https://www.gnu.org/software/guile/, GNU Guile}, a powerful
353 high-level programming language, one of the
354 @uref{https://en.wikipedia.org/wiki/Scheme_%28programming_language%29, Scheme}
356 @uref{https://en.wikipedia.org/wiki/Lisp_%28programming_language%29, Lisp family}.
358 Package definitions are also written in Scheme, which empowers Guix in some
359 very unique ways, unlike most other package managers that use shell scripts or
364 Use functions, structures, macros and all of Scheme expressiveness for your
368 Inheritance makes it easy to customize a package by inheriting from it and
369 modifying only what is needed.
372 Batch processing: the whole package collection can be parsed, filtered and
373 processed. Building a headless server with all graphical interfaces stripped
374 out? It's possible. Want to rebuild everything from source using specific
375 compiler optimization flags? Pass the @code{#:make-flags "..."} argument to
376 the list of packages. It wouldn't be a stretch to think
377 @uref{https://wiki.gentoo.org/wiki/USE_flag, Gentoo USE flags} here, but this
378 goes even further: the changes don't have to be thought out beforehand by the
379 packager, they can be @emph{programmed} by the user!
382 The following tutorial covers all the basics around package creation with Guix.
383 It does not assume much knowledge of the Guix system nor of the Lisp language.
384 The reader is only expected to be familiar with the command line and to have some
385 basic programming knowledge.
387 @node A ``Hello World'' package
388 @subsection A ``Hello World'' package
390 The ``Defining Packages'' section of the manual introduces the basics of Guix
391 packaging (@pxref{Defining Packages,,, guix, GNU Guix Reference Manual}). In
392 the following section, we will partly go over those basics again.
394 GNU@tie{}Hello is a dummy project that serves as an idiomatic example for
395 packaging. It uses the GNU build system (@code{./configure && make && make
396 install}). Guix already provides a package definition which is a perfect
397 example to start with. You can look up its declaration with @code{guix edit
398 hello} from the command line. Let's see how it looks:
407 (uri (string-append "mirror://gnu/hello/hello-" version
411 "0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i"))))
412 (build-system gnu-build-system)
413 (synopsis "Hello, GNU world: An example GNU package")
415 "GNU Hello prints the message \"Hello, world!\" and then exits. It
416 serves as an example of standard GNU coding practices. As such, it supports
417 command-line arguments, multiple languages, and so on.")
418 (home-page "https://www.gnu.org/software/hello/")
422 As you can see, most of it is rather straightforward. But let's review the
427 The project name. Using Scheme conventions, we prefer to keep it
428 lower case, without underscore and using dash-separated words.
431 This field contains a description of the source code origin. The
432 @code{origin} record contains these fields:
435 @item The method, here @code{url-fetch} to download via HTTP/FTP, but other methods
436 exist, such as @code{git-fetch} for Git repositories.
437 @item The URI, which is typically some @code{https://} location for @code{url-fetch}. Here
438 the special `mirror://gnu` refers to a set of well known locations, all of
439 which can be used by Guix to fetch the source, should some of them fail.
440 @item The @code{sha256} checksum of the requested file. This is essential to ensure
441 the source is not corrupted. Note that Guix works with base32 strings,
442 hence the call to the @code{base32} function.
447 This is where the power of abstraction provided by the Scheme language really
448 shines: in this case, the @code{gnu-build-system} abstracts away the famous
449 @code{./configure && make && make install} shell invocations. Other build
450 systems include the @code{trivial-build-system} which does not do anything and
451 requires from the packager to program all the build steps, the
452 @code{python-build-system}, the @code{emacs-build-system}, and many more
453 (@pxref{Build Systems,,, guix, GNU Guix Reference Manual}).
456 It should be a concise summary of what the package does. For many packages a
457 tagline from the project's home page can be used as the synopsis.
460 Same as for the synopsis, it's fine to re-use the project description from the
461 homepage. Note that Guix uses Texinfo syntax.
464 Use HTTPS if available.
467 See @code{guix/licenses.scm} in the project source for a full list of
471 Time to build our first package! Nothing fancy here for now: we will stick to a
472 dummy @code{my-hello}, a copy of the above declaration.
474 As with the ritualistic ``Hello World'' taught with most programming languages,
475 this will possibly be the most ``manual'' approach. We will work out an ideal
476 setup later; for now we will go the simplest route.
478 Save the following to a file @file{my-hello.scm}.
481 (use-modules (guix packages)
483 (guix build-system gnu)
491 (uri (string-append "mirror://gnu/hello/hello-" version
495 "0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i"))))
496 (build-system gnu-build-system)
497 (synopsis "Hello, Guix world: An example custom Guix package")
499 "GNU Hello prints the message \"Hello, world!\" and then exits. It
500 serves as an example of standard GNU coding practices. As such, it supports
501 command-line arguments, multiple languages, and so on.")
502 (home-page "https://www.gnu.org/software/hello/")
506 We will explain the extra code in a moment.
508 Feel free to play with the different values of the various fields. If you
509 change the source, you'll need to update the checksum. Indeed, Guix refuses to
510 build anything if the given checksum does not match the computed checksum of the
511 source code. To obtain the correct checksum of the package declaration, we
512 need to download the source, compute the sha256 checksum and convert it to
515 Thankfully, Guix can automate this task for us; all we need is to provide the
518 @c TRANSLATORS: This is example shell output.
520 $ guix download mirror://gnu/hello/hello-2.10.tar.gz
522 Starting download of /tmp/guix-file.JLYgL7
523 From https://ftpmirror.gnu.org/gnu/hello/hello-2.10.tar.gz...
524 following redirection to `https://mirror.ibcp.fr/pub/gnu/hello/hello-2.10.tar.gz'...
525 …10.tar.gz 709KiB 2.5MiB/s 00:00 [##################] 100.0%
526 /gnu/store/hbdalsf5lpf01x4dcknwx6xbn6n5km6k-hello-2.10.tar.gz
527 0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i
530 In this specific case the output tells us which mirror was chosen.
531 If the result of the above command is not the same as in the above snippet,
532 update your @code{my-hello} declaration accordingly.
534 Note that GNU package tarballs come with an OpenPGP signature, so you
535 should definitely check the signature of this tarball with `gpg` to
536 authenticate it before going further:
538 @c TRANSLATORS: This is example shell output.
540 $ guix download mirror://gnu/hello/hello-2.10.tar.gz.sig
542 Starting download of /tmp/guix-file.03tFfb
543 From https://ftpmirror.gnu.org/gnu/hello/hello-2.10.tar.gz.sig...
544 following redirection to `https://ftp.igh.cnrs.fr/pub/gnu/hello/hello-2.10.tar.gz.sig'...
545 ….tar.gz.sig 819B 1.2MiB/s 00:00 [##################] 100.0%
546 /gnu/store/rzs8wba9ka7grrmgcpfyxvs58mly0sx6-hello-2.10.tar.gz.sig
547 0q0v86n3y38z17rl146gdakw9xc4mcscpk8dscs412j22glrv9jf
548 $ gpg --verify /gnu/store/rzs8wba9ka7grrmgcpfyxvs58mly0sx6-hello-2.10.tar.gz.sig /gnu/store/hbdalsf5lpf01x4dcknwx6xbn6n5km6k-hello-2.10.tar.gz
549 gpg: Signature made Sun 16 Nov 2014 01:08:37 PM CET
550 gpg: using RSA key A9553245FDE9B739
551 gpg: Good signature from "Sami Kerola <kerolasa@@iki.fi>" [unknown]
552 gpg: aka "Sami Kerola (http://www.iki.fi/kerolasa/) <kerolasa@@iki.fi>" [unknown]
553 gpg: WARNING: This key is not certified with a trusted signature!
554 gpg: There is no indication that the signature belongs to the owner.
555 Primary key fingerprint: 8ED3 96E3 7E38 D471 A005 30D3 A955 3245 FDE9 B739
558 You can then happily run
560 @c TRANSLATORS: Do not translate this command
562 $ guix package --install-from-file=my-hello.scm
565 You should now have @code{my-hello} in your profile!
567 @c TRANSLATORS: Do not translate this command
569 $ guix package --list-installed=my-hello
571 /gnu/store/f1db2mfm8syb8qvc357c53slbvf1g9m9-my-hello-2.10
574 We've gone as far as we could without any knowledge of Scheme. Before moving
575 on to more complex packages, now is the right time to brush up on your Scheme
576 knowledge. @pxref{A Scheme Crash Course} to get up to speed.
581 In the rest of this chapter we will rely on some basic Scheme
582 programming knowledge. Now let's detail the different possible setups
583 for working on Guix packages.
585 There are several ways to set up a Guix packaging environment.
587 We recommend you work directly on the Guix source checkout since it makes it
588 easier for everyone to contribute to the project.
590 But first, let's look at other possibilities.
593 @subsubsection Local file
595 This is what we previously did with @samp{my-hello}. With the Scheme basics we've
596 covered, we are now able to explain the leading chunks. As stated in @code{guix
600 -f, --install-from-file=FILE
601 install the package that the code within FILE
605 Thus the last expression @emph{must} return a package, which is the case in our
608 The @code{use-modules} expression tells which of the modules we need in the file.
609 Modules are a collection of values and procedures. They are commonly called
610 ``libraries'' or ``packages'' in other programming languages.
612 @node @samp{GUIX_PACKAGE_PATH}
613 @subsubsection @samp{GUIX_PACKAGE_PATH}
615 @emph{Note: Starting from Guix 0.16, the more flexible Guix @dfn{channels} are the
616 preferred way and supersede @samp{GUIX_PACKAGE_PATH}. See next section.}
618 It can be tedious to specify the file from the command line instead of simply
619 calling @code{guix package --install my-hello} as you would do with the official
622 Guix makes it possible to streamline the process by adding as many ``package
623 declaration directories'' as you want.
625 Create a directory, say @file{~/guix-packages} and add it to the @samp{GUIX_PACKAGE_PATH}
626 environment variable:
629 $ mkdir ~/guix-packages
630 $ export GUIX_PACKAGE_PATH=~/guix-packages
633 To add several directories, separate them with a colon (@code{:}).
635 Our previous @samp{my-hello} needs some adjustments though:
638 (define-module (my-hello)
639 #:use-module (guix licenses)
640 #:use-module (guix packages)
641 #:use-module (guix build-system gnu)
642 #:use-module (guix download))
644 (define-public my-hello
650 (uri (string-append "mirror://gnu/hello/hello-" version
654 "0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i"))))
655 (build-system gnu-build-system)
656 (synopsis "Hello, Guix world: An example custom Guix package")
658 "GNU Hello prints the message \"Hello, world!\" and then exits. It
659 serves as an example of standard GNU coding practices. As such, it supports
660 command-line arguments, multiple languages, and so on.")
661 (home-page "https://www.gnu.org/software/hello/")
665 Note that we have assigned the package value to an exported variable name with
666 @code{define-public}. This is effectively assigning the package to the @code{my-hello}
667 variable so that it can be referenced, among other as dependency of other
670 If you use @code{guix package --install-from-file=my-hello.scm} on the above file, it
671 will fail because the last expression, @code{define-public}, does not return a
672 package. If you want to use @code{define-public} in this use-case nonetheless, make
673 sure the file ends with an evaluation of @code{my-hello}:
677 (define-public my-hello
684 This last example is not very typical.
686 Now @samp{my-hello} should be part of the package collection like all other official
687 packages. You can verify this with:
690 $ guix package --show=my-hello
694 @subsubsection Guix channels
696 Guix 0.16 features channels, which is very similar to @samp{GUIX_PACKAGE_PATH} but
697 provides better integration and provenance tracking. Channels are not
698 necessarily local, they can be maintained as a public Git repository for
699 instance. Of course, several channels can be used at the same time.
701 @xref{Channels,,, guix, GNU Guix Reference Manual} for setup details.
703 @node Direct checkout hacking
704 @subsubsection Direct checkout hacking
706 Working directly on the Guix project is recommended: it reduces the friction
707 when the time comes to submit your changes upstream to let the community benefit
710 Unlike most software distributions, the Guix repository holds in one place both
711 the tooling (including the package manager) and the package definitions. This
712 choice was made so that it would give developers the flexibility to modify the
713 API without breakage by updating all packages at the same time. This reduces
716 Check out the official @uref{https://git-scm.com/, Git} repository:
719 $ git clone https://git.savannah.gnu.org/git/guix.git
722 In the rest of this article, we use @samp{$GUIX_CHECKOUT} to refer to the location of
726 Follow the instructions in the manual (@pxref{Contributing,,, guix, GNU Guix
727 Reference Manual}) to set up the repository environment.
729 Once ready, you should be able to use the package definitions from the
730 repository environment.
732 Feel free to edit package definitions found in @samp{$GUIX_CHECKOUT/gnu/packages}.
734 The @samp{$GUIX_CHECKOUT/pre-inst-env} script lets you use @samp{guix} over the package
735 collection of the repository (@pxref{Running Guix Before It Is
736 Installed,,, guix, GNU Guix Reference Manual}).
740 Search packages, such as Ruby:
744 $ ./pre-inst-env guix package --list-available=ruby
745 ruby 1.8.7-p374 out gnu/packages/ruby.scm:119:2
746 ruby 2.1.6 out gnu/packages/ruby.scm:91:2
747 ruby 2.2.2 out gnu/packages/ruby.scm:39:2
751 Build a package, here Ruby version 2.1:
754 $ ./pre-inst-env guix build --keep-failed ruby@@2.1
755 /gnu/store/c13v73jxmj2nir2xjqaz5259zywsa9zi-ruby-2.1.6
759 Install it to your user profile:
762 $ ./pre-inst-env guix package --install ruby@@2.1
766 Check for common mistakes:
769 $ ./pre-inst-env guix lint ruby@@2.1
773 Guix strives at maintaining a high packaging standard; when contributing to the
774 Guix project, remember to
778 follow the coding style (@pxref{Coding Style,,, guix, GNU Guix Reference Manual}),
780 and review the check list from the manual (@pxref{Submitting Patches,,, guix, GNU Guix Reference Manual}).
783 Once you are happy with the result, you are welcome to send your contribution to
784 make it part of Guix. This process is also detailed in the manual. (@pxref{Contributing,,, guix, GNU Guix Reference Manual})
787 It's a community effort so the more join in, the better Guix becomes!
789 @node Extended example
790 @subsection Extended example
792 The above ``Hello World'' example is as simple as it goes. Packages can be more
793 complex than that and Guix can handle more advanced scenarios. Let's look at
794 another, more sophisticated package (slightly modified from the source):
797 (define-module (gnu packages version-control)
798 #:use-module ((guix licenses) #:prefix license:)
799 #:use-module (guix utils)
800 #:use-module (guix packages)
801 #:use-module (guix git-download)
802 #:use-module (guix build-system cmake)
803 #:use-module (gnu packages ssh)
804 #:use-module (gnu packages web)
805 #:use-module (gnu packages pkg-config)
806 #:use-module (gnu packages python)
807 #:use-module (gnu packages compression)
808 #:use-module (gnu packages tls))
810 (define-public my-libgit2
811 (let ((commit "e98d0a37c93574d2c6107bf7f31140b548c6a7bf")
815 (version (git-version "0.26.6" revision commit))
819 (url "https://github.com/libgit2/libgit2/")
821 (file-name (git-file-name name version))
824 "17pjvprmdrx4h6bb1hhc98w9qi6ki7yl57f090n9kbhswxqfs7s3"))
825 (patches (search-patches "libgit2-mtime-0.patch"))
826 (modules '((guix build utils)))
827 ;; Remove bundled software.
828 (snippet '(delete-file-recursively "deps"))))
829 (build-system cmake-build-system)
830 (outputs '("out" "debug"))
832 `(#:tests? #true ; Run the test suite (this is the default)
833 #:configure-flags '("-DUSE_SHA1DC=ON") ; SHA-1 collision detection
835 (modify-phases %standard-phases
836 (add-after 'unpack 'fix-hardcoded-paths
838 (substitute* "tests/repo/init.c"
839 (("#!/bin/sh") (string-append "#!" (which "sh"))))
840 (substitute* "tests/clar/fs.h"
841 (("/bin/cp") (which "cp"))
842 (("/bin/rm") (which "rm")))))
843 ;; Run checks more verbosely.
845 (lambda _ (invoke "./libgit2_clar" "-v" "-Q")))
846 (add-after 'unpack 'make-files-writable-for-tests
847 (lambda _ (for-each make-file-writable (find-files "." ".*")))))))
849 (list libssh2 http-parser python-wrapper))
853 ;; These two libraries are in 'Requires.private' in libgit2.pc.
855 (home-page "https://libgit2.github.com/")
856 (synopsis "Library providing Git core methods")
858 "Libgit2 is a portable, pure C implementation of the Git core methods
859 provided as a re-entrant linkable library with a solid API, allowing you to
860 write native speed custom Git applications in any language with bindings.")
861 ;; GPLv2 with linking exception
862 (license license:gpl2))))
865 (In those cases were you only want to tweak a few fields from a package
866 definition, you should rely on inheritance instead of copy-pasting everything.
869 Let's discuss those fields in depth.
871 @subsubsection @code{git-fetch} method
873 Unlike the @code{url-fetch} method, @code{git-fetch} expects a @code{git-reference} which takes
874 a Git repository and a commit. The commit can be any Git reference such as
875 tags, so if the @code{version} is tagged, then it can be used directly. Sometimes
876 the tag is prefixed with a @code{v}, in which case you'd use @code{(commit (string-append
879 To ensure that the source code from the Git repository is stored in a
880 directory with a descriptive name, we use @code{(file-name (git-file-name name
883 The @code{git-version} procedure can be used to derive the
884 version when packaging programs for a specific commit, following the
885 Guix contributor guidelines (@pxref{Version Numbers,,, guix, GNU Guix
888 How does one obtain the @code{sha256} hash that's in there, you ask? By
889 invoking @command{guix hash} on a checkout of the desired commit, along
893 git clone https://github.com/libgit2/libgit2/
899 @command{guix hash -rx} computes a SHA256 hash over the whole directory,
900 excluding the @file{.git} sub-directory (@pxref{Invoking guix hash,,,
901 guix, GNU Guix Reference Manual}).
903 In the future, @command{guix download} will hopefully be able to do
904 these steps for you, just like it does for regular downloads.
906 @subsubsection Snippets
908 Snippets are quoted (i.e. non-evaluated) Scheme code that are a means of patching
909 the source. They are a Guix-y alternative to the traditional @file{.patch} files.
910 Because of the quote, the code in only evaluated when passed to the Guix daemon
911 for building. There can be as many snippets as needed.
913 Snippets might need additional Guile modules which can be imported from the
914 @code{modules} field.
916 @subsubsection Inputs
918 There are 3 different input types. In short:
922 Required for building but not runtime -- installing a package
923 through a substitute won't install these inputs.
925 Installed in the store but not in the profile, as well as being
926 present at build time.
927 @item propagated-inputs
928 Installed in the store and in the profile, as well as
929 being present at build time.
932 @xref{package Reference,,, guix, GNU Guix Reference Manual} for more details.
934 The distinction between the various inputs is important: if a dependency can be
935 handled as an @emph{input} instead of a @emph{propagated input}, it should be done so, or
936 else it ``pollutes'' the user profile for no good reason.
938 For instance, a user installing a graphical program that depends on a
939 command line tool might only be interested in the graphical part, so there is no
940 need to force the command line tool into the user profile. The dependency is a
941 concern to the package, not to the user. @emph{Inputs} make it possible to handle
942 dependencies without bugging the user by adding undesired executable files (or
943 libraries) to their profile.
945 Same goes for @emph{native-inputs}: once the program is installed, build-time
946 dependencies can be safely garbage-collected.
947 It also matters when a substitute is available, in which case only the @emph{inputs}
948 and @emph{propagated inputs} will be fetched: the @emph{native inputs} are not required to
949 install a package from a substitute.
952 You may see here and there snippets where package inputs are written
953 quite differently, like so:
956 ;; The "old style" for inputs.
958 `(("libssh2" ,libssh2)
959 ("http-parser" ,http-parser)
960 ("python" ,python-wrapper)))
963 This is the ``old style'', where each input in the list is explicitly
964 given a label (a string). It is still supported but we recommend using
965 the style above instead. @xref{package Reference,,, guix, GNU Guix
966 Reference Manual}, for more info.
969 @subsubsection Outputs
971 Just like how a package can have multiple inputs, it can also produce multiple
974 Each output corresponds to a separate directory in the store.
976 The user can choose which output to install; this is useful to save space or
977 to avoid polluting the user profile with unwanted executables or libraries.
979 Output separation is optional. When the @code{outputs} field is left out, the
980 default and only output (the complete package) is referred to as @code{"out"}.
982 Typical separate output names include @code{debug} and @code{doc}.
984 It's advised to separate outputs only when you've shown it's worth it: if the
985 output size is significant (compare with @code{guix size}) or in case the package is
988 @subsubsection Build system arguments
990 The @code{arguments} is a keyword-value list used to configure the build process.
992 The simplest argument @code{#:tests?} can be used to disable the test suite when
993 building the package. This is mostly useful when the package does not feature
994 any test suite. It's strongly recommended to keep the test suite on if there is
997 Another common argument is @code{:make-flags}, which specifies a list of flags to
998 append when running make, as you would from the command line. For instance, the
1002 #:make-flags (list (string-append "prefix=" (assoc-ref %outputs "out"))
1009 $ make CC=gcc prefix=/gnu/store/...-<out>
1012 This sets the C compiler to @code{gcc} and the @code{prefix} variable (the installation
1013 directory in Make parlance) to @code{(assoc-ref %outputs "out")}, which is a build-stage
1014 global variable pointing to the destination directory in the store (something like
1015 @file{/gnu/store/...-my-libgit2-20180408}).
1017 Similarly, it's possible to set the configure flags:
1020 #:configure-flags '("-DUSE_SHA1DC=ON")
1023 The @code{%build-inputs} variable is also generated in scope. It's an association
1024 table that maps the input names to their store directories.
1026 The @code{phases} keyword lists the sequential steps of the build system. Typically
1027 phases include @code{unpack}, @code{configure}, @code{build}, @code{install} and @code{check}. To know
1028 more about those phases, you need to work out the appropriate build system
1029 definition in @samp{$GUIX_CHECKOUT/guix/build/gnu-build-system.scm}:
1032 (define %standard-phases
1033 ;; Standard build phases, as a list of symbol/procedure pairs.
1034 (let-syntax ((phases (syntax-rules ()
1035 ((_ p ...) `((p . ,p) ...)))))
1036 (phases set-SOURCE-DATE-EPOCH set-paths install-locale unpack
1039 patch-source-shebangs configure patch-generated-file-shebangs
1041 patch-shebangs strip
1043 validate-documentation-location
1044 delete-info-dir-file
1045 patch-dot-desktop-files
1046 install-license-files
1047 reset-gzip-timestamps
1048 compress-documentation)))
1054 (add-to-load-path "/path/to/guix/checkout")
1055 ,use (guix build gnu-build-system)
1056 (map first %standard-phases)
1057 @result{} (set-SOURCE-DATE-EPOCH set-paths install-locale unpack bootstrap patch-usr-bin-file patch-source-shebangs configure patch-generated-file-shebangs build check install patch-shebangs strip validate-runpath validate-documentation-location delete-info-dir-file patch-dot-desktop-files install-license-files reset-gzip-timestamps compress-documentation)
1060 If you want to know more about what happens during those phases, consult the
1061 associated procedures.
1063 For instance, as of this writing the definition of @code{unpack} for the GNU build
1067 (define* (unpack #:key source #:allow-other-keys)
1068 "Unpack SOURCE in the working directory, and change directory within the
1069 source. When SOURCE is a directory, copy it in a sub-directory of the current
1071 (if (file-is-directory? source)
1076 ;; Preserve timestamps (set to the Epoch) on the copied tree so that
1077 ;; things work deterministically.
1078 (copy-recursively source "."
1079 #:keep-mtime? #true))
1081 (if (string-suffix? ".zip" source)
1082 (invoke "unzip" source)
1083 (invoke "tar" "xvf" source))
1084 (chdir (first-subdirectory "."))))
1088 Note the @code{chdir} call: it changes the working directory to where the source was
1090 Thus every phase following the @code{unpack} will use the source as a working
1091 directory, which is why we can directly work on the source files.
1092 That is to say, unless a later phase changes the working directory to something
1095 We modify the list of @code{%standard-phases} of the build system with the
1096 @code{modify-phases} macro as per the list of specified modifications, which may have
1097 the following forms:
1101 @code{(add-before @var{phase} @var{new-phase} @var{procedure})}: Run @var{procedure} named @var{new-phase} before @var{phase}.
1103 @code{(add-after @var{phase} @var{new-phase} @var{procedure})}: Same, but afterwards.
1105 @code{(replace @var{phase} @var{procedure})}.
1107 @code{(delete @var{phase})}.
1110 The @var{procedure} supports the keyword arguments @code{inputs} and @code{outputs}. Each
1111 input (whether @emph{native}, @emph{propagated} or not) and output directory is referenced
1112 by their name in those variables. Thus @code{(assoc-ref outputs "out")} is the store
1113 directory of the main output of the package. A phase procedure may look like
1117 (lambda* (#:key inputs outputs #:allow-other-keys)
1118 (let ((bash-directory (assoc-ref inputs "bash"))
1119 (output-directory (assoc-ref outputs "out"))
1120 (doc-directory (assoc-ref outputs "doc")))
1125 The procedure must return @code{#true} on success. It's brittle to rely on the return
1126 value of the last expression used to tweak the phase because there is no
1127 guarantee it would be a @code{#true}. Hence the trailing @code{#true} to ensure the right value
1128 is returned on success.
1130 @subsubsection Code staging
1132 The astute reader may have noticed the quasi-quote and comma syntax in the
1133 argument field. Indeed, the build code in the package declaration should not be
1134 evaluated on the client side, but only when passed to the Guix daemon. This
1135 mechanism of passing code around two running processes is called @uref{https://arxiv.org/abs/1709.00833, code staging}.
1137 @subsubsection Utility functions
1139 When customizing @code{phases}, we often need to write code that mimics the
1140 equivalent system invocations (@code{make}, @code{mkdir}, @code{cp}, etc.)@: commonly used during
1141 regular ``Unix-style'' installations.
1143 Some like @code{chmod} are native to Guile.
1144 @xref{,,, guile, Guile reference manual} for a complete list.
1146 Guix provides additional helper functions which prove especially handy in the
1147 context of package management.
1149 Some of those functions can be found in
1150 @samp{$GUIX_CHECKOUT/guix/guix/build/utils.scm}. Most of them mirror the behaviour
1151 of the traditional Unix system commands:
1155 Like the @samp{which} system command.
1157 Akin to the @samp{find} system command.
1159 Like @samp{mkdir -p}, which creates all parents as needed.
1161 Similar to @samp{install} when installing a file to a (possibly
1162 non-existing) directory. Guile has @code{copy-file} which works
1164 @item copy-recursively
1166 @item delete-file-recursively
1169 Run an executable. This should be used instead of @code{system*}.
1170 @item with-directory-excursion
1171 Run the body in a different working directory,
1172 then restore the previous working directory.
1174 A ``@command{sed}-like'' function.
1177 @xref{Build Utilities,,, guix, GNU Guix Reference Manual}, for more
1178 information on these utilities.
1180 @subsubsection Module prefix
1182 The license in our last example needs a prefix: this is because of how the
1183 @code{license} module was imported in the package, as @code{#:use-module ((guix licenses)
1184 #:prefix license:)}. The Guile module import mechanism
1185 (@pxref{Using Guile Modules,,, guile, Guile reference manual})
1186 gives the user full control over namespacing: this is needed to avoid
1187 clashes between, say, the
1188 @samp{zlib} variable from @samp{licenses.scm} (a @emph{license} value) and the @samp{zlib} variable
1189 from @samp{compression.scm} (a @emph{package} value).
1191 @node Other build systems
1192 @subsection Other build systems
1194 What we've seen so far covers the majority of packages using a build system
1195 other than the @code{trivial-build-system}. The latter does not automate anything
1196 and leaves you to build everything manually. This can be more demanding and we
1197 won't cover it here for now, but thankfully it is rarely necessary to fall back
1200 For the other build systems, such as ASDF, Emacs, Perl, Ruby and many more, the
1201 process is very similar to the GNU build system except for a few specialized
1204 @xref{Build Systems,,, guix, GNU Guix Reference Manual}, for more
1205 information on build systems, or check the source code in the
1206 @samp{$GUIX_CHECKOUT/guix/build} and
1207 @samp{$GUIX_CHECKOUT/guix/build-system} directories.
1209 @node Programmable and automated package definition
1210 @subsection Programmable and automated package definition
1212 We can't repeat it enough: having a full-fledged programming language at hand
1213 empowers us in ways that reach far beyond traditional package management.
1215 Let's illustrate this with some awesome features of Guix!
1217 @node Recursive importers
1218 @subsubsection Recursive importers
1220 You might find some build systems good enough that there is little to do at all
1221 to write a package, to the point that it becomes repetitive and tedious after a
1222 while. A @emph{raison d'être} of computers is to replace human beings at those
1223 boring tasks. So let's tell Guix to do this for us and create the package
1224 definition of an R package from CRAN (the output is trimmed for conciseness):
1227 $ guix import cran --recursive walrus
1229 (define-public r-mc2d
1233 (define-public r-jmvcore
1237 (define-public r-wrs2
1241 (define-public r-walrus
1248 (uri (cran-uri "walrus" version))
1251 "1nk2glcvy4hyksl5ipq2mz8jy4fss90hx6cq98m3w96kzjni6jjj"))))
1252 (build-system r-build-system)
1254 (list r-ggplot2 r-jmvcore r-r6 r-wrs2))
1255 (home-page "https://github.com/jamovi/walrus")
1256 (synopsis "Robust Statistical Methods")
1258 "This package provides a toolbox of common robust statistical
1259 tests, including robust descriptives, robust t-tests, and robust ANOVA.
1260 It is also available as a module for 'jamovi' (see
1261 <https://www.jamovi.org> for more information). Walrus is based on the
1262 WRS2 package by Patrick Mair, which is in turn based on the scripts and
1263 work of Rand Wilcox. These analyses are described in depth in the book
1264 'Introduction to Robust Estimation & Hypothesis Testing'.")
1268 The recursive importer won't import packages for which Guix already has package
1269 definitions, except for the very first.
1271 Not all applications can be packaged this way, only those relying on a select
1272 number of supported systems. Read about the full list of importers in
1273 the guix import section of the manual
1274 (@pxref{Invoking guix import,,, guix, GNU Guix Reference Manual}).
1276 @node Automatic update
1277 @subsubsection Automatic update
1279 Guix can be smart enough to check for updates on systems it knows. It can
1280 report outdated package definitions with
1283 $ guix refresh hello
1286 In most cases, updating a package to a newer version requires little more than
1287 changing the version number and the checksum. Guix can do that automatically as
1291 $ guix refresh hello --update
1295 @subsubsection Inheritance
1297 If you've started browsing the existing package definitions, you might have
1298 noticed that a significant number of them have a @code{inherit} field:
1301 (define-public adwaita-icon-theme
1302 (package (inherit gnome-icon-theme)
1303 (name "adwaita-icon-theme")
1307 (uri (string-append "mirror://gnome/sources/" name "/"
1308 (version-major+minor version) "/"
1309 name "-" version ".tar.xz"))
1312 "17fpahgh5dyckgz7rwqvzgnhx53cx9kr2xw0szprc6bnqy977fi8"))))
1313 (native-inputs (list `(,gtk+ "bin")))))
1316 All unspecified fields are inherited from the parent package. This is very
1317 convenient to create alternative packages, for instance with different source,
1318 version or compilation options.
1321 @subsection Getting help
1323 Sadly, some applications can be tough to package. Sometimes they need a patch to
1324 work with the non-standard file system hierarchy enforced by the store.
1325 Sometimes the tests won't run properly. (They can be skipped but this is not
1326 recommended.) Other times the resulting package won't be reproducible.
1328 Should you be stuck, unable to figure out how to fix any sort of packaging
1329 issue, don't hesitate to ask the community for help.
1331 See the @uref{https://www.gnu.org/software/guix/contact/, Guix homepage} for information on the mailing lists, IRC, etc.
1334 @subsection Conclusion
1336 This tutorial was a showcase of the sophisticated package management that Guix
1337 boasts. At this point we have mostly restricted this introduction to the
1338 @code{gnu-build-system} which is a core abstraction layer on which more advanced
1339 abstractions are based.
1341 Where do we go from here? Next we ought to dissect the innards of the build
1342 system by removing all abstractions, using the @code{trivial-build-system}: this
1343 should give us a thorough understanding of the process before investigating some
1344 more advanced packaging techniques and edge cases.
1346 Other features worth exploring are the interactive editing and debugging
1347 capabilities of Guix provided by the Guile REPL@.
1349 Those fancy features are completely optional and can wait; now is a good time
1350 to take a well-deserved break. With what we've introduced here you should be
1351 well armed to package lots of programs. You can get started right away and
1352 hopefully we will see your contributions soon!
1355 @subsection References
1359 The @uref{https://www.gnu.org/software/guix/manual/en/html_node/Defining-Packages.html, package reference in the manual}
1362 @uref{https://gitlab.com/pjotrp/guix-notes/blob/master/HACKING.org, Pjotr’s hacking guide to GNU Guix}
1365 @uref{https://www.gnu.org/software/guix/guix-ghm-andreas-20130823.pdf, ``GNU Guix: Package without a scheme!''}, by Andreas Enge
1368 @c *********************************************************************
1369 @node System Configuration
1370 @chapter System Configuration
1372 Guix offers a flexible language for declaratively configuring your Guix
1373 System. This flexibility can at times be overwhelming. The purpose of this
1374 chapter is to demonstrate some advanced configuration concepts.
1376 @pxref{System Configuration,,, guix, GNU Guix Reference Manual} for a complete
1380 * Auto-Login to a Specific TTY:: Automatically Login a User to a Specific TTY
1381 * Customizing the Kernel:: Creating and using a custom Linux kernel on Guix System.
1382 * Guix System Image API:: Customizing images to target specific platforms.
1383 * Connecting to Wireguard VPN:: Connecting to a Wireguard VPN.
1384 * Customizing a Window Manager:: Handle customization of a Window manager on Guix System.
1385 * Running Guix on a Linode Server:: Running Guix on a Linode Server
1386 * Setting up a bind mount:: Setting up a bind mount in the file-systems definition.
1387 * Getting substitutes from Tor:: Configuring Guix daemon to get substitutes through Tor.
1388 * Setting up NGINX with Lua:: Configuring NGINX web-server to load Lua modules.
1389 * Music Server with Bluetooth Audio:: Headless music player with Bluetooth output.
1392 @node Auto-Login to a Specific TTY
1393 @section Auto-Login to a Specific TTY
1395 While the Guix manual explains auto-login one user to @emph{all} TTYs (
1396 @pxref{auto-login to TTY,,, guix, GNU Guix Reference Manual}), some
1397 might prefer a situation, in which one user is logged into one TTY with
1398 the other TTYs either configured to login different users or no one at
1399 all. Note that one can auto-login one user to any TTY, but it is
1400 usually advisable to avoid @code{tty1}, which, by default, is used to
1401 log warnings and errors.
1403 Here is how one might set up auto login for one user to one tty:
1406 (define (auto-login-to-tty config tty user)
1407 (if (string=? tty (mingetty-configuration-tty config))
1408 (mingetty-configuration
1413 (define %my-services
1414 (modify-services %base-services
1416 (mingetty-service-type config =>
1418 config "tty3" "alice"))))
1422 (services %my-services))
1425 One could also @code{compose} (@pxref{Higher-Order Functions,,, guile,
1426 The Guile Reference Manual}) @code{auto-login-to-tty} to login multiple
1427 users to multiple ttys.
1429 Finally, here is a note of caution. Setting up auto login to a TTY,
1430 means that anyone can turn on your computer and run commands as your
1432 However, if you have an encrypted root partition, and thus already need
1433 to enter a passphrase when the system boots, auto-login might be a
1437 @node Customizing the Kernel
1438 @section Customizing the Kernel
1440 Guix is, at its core, a source based distribution with substitutes
1441 (@pxref{Substitutes,,, guix, GNU Guix Reference Manual}), and as such building
1442 packages from their source code is an expected part of regular package
1443 installations and upgrades. Given this starting point, it makes sense that
1444 efforts are made to reduce the amount of time spent compiling packages, and
1445 recent changes and upgrades to the building and distribution of substitutes
1446 continues to be a topic of discussion within Guix.
1448 The kernel, while not requiring an overabundance of RAM to build, does take a
1449 rather long time on an average machine. The official kernel configuration, as
1450 is the case with many GNU/Linux distributions, errs on the side of
1451 inclusiveness, and this is really what causes the build to take such a long
1452 time when the kernel is built from source.
1454 The Linux kernel, however, can also just be described as a regular old
1455 package, and as such can be customized just like any other package. The
1456 procedure is a little bit different, although this is primarily due to the
1457 nature of how the package definition is written.
1459 The @code{linux-libre} kernel package definition is actually a procedure which
1463 (define* (make-linux-libre* version gnu-revision source supported-systems
1466 ;; A function that takes an arch and a variant.
1467 ;; See kernel-config for an example.
1468 (configuration-file #f)
1469 (defconfig "defconfig")
1470 (extra-options %default-extra-linux-options))
1474 The current @code{linux-libre} package is for the 5.15.x series, and is
1478 (define-public linux-libre-5.15
1479 (make-linux-libre* linux-libre-5.15-version
1480 linux-libre-5.15-gnu-revision
1481 linux-libre-5.15-source
1482 '("x86_64-linux" "i686-linux" "armhf-linux" "aarch64-linux" "riscv64-linux")
1483 #:configuration-file kernel-config))
1486 Any keys which are not assigned values inherit their default value from the
1487 @code{make-linux-libre} definition. When comparing the two snippets above,
1488 notice the code comment that refers to @code{#:configuration-file}. Because of
1489 this, it is not actually easy to include a custom kernel configuration from the
1490 definition, but don't worry, there are other ways to work with what we do have.
1492 There are two ways to create a kernel with a custom kernel configuration. The
1493 first is to provide a standard @file{.config} file during the build process by
1494 including an actual @file{.config} file as a native input to our custom
1495 kernel. The following is a snippet from the custom @code{'configure} phase of
1496 the @code{make-linux-libre} package definition:
1499 (let ((build (assoc-ref %standard-phases 'build))
1500 (config (assoc-ref (or native-inputs inputs) "kconfig")))
1502 ;; Use a custom kernel configuration file or a default
1503 ;; configuration file.
1506 (copy-file config ".config")
1507 (chmod ".config" #o666))
1508 (invoke "make" ,defconfig)))
1511 Below is a sample kernel package. The @code{linux-libre} package is nothing
1512 special and can be inherited from and have its fields overridden like any
1516 (define-public linux-libre/E2140
1518 (inherit linux-libre)
1520 `(("kconfig" ,(local-file "E2140.config"))
1521 ,@@(alist-delete "kconfig"
1522 (package-native-inputs linux-libre))))))
1525 In the same directory as the file defining @code{linux-libre-E2140} is a file
1526 named @file{E2140.config}, which is an actual kernel configuration file. The
1527 @code{defconfig} keyword of @code{make-linux-libre} is left blank here, so the
1528 only kernel configuration in the package is the one which was included in the
1529 @code{native-inputs} field.
1531 The second way to create a custom kernel is to pass a new value to the
1532 @code{extra-options} keyword of the @code{make-linux-libre} procedure. The
1533 @code{extra-options} keyword works with another function defined right below
1537 (define %default-extra-linux-options
1538 `(;; https://lists.gnu.org/archive/html/guix-devel/2014-04/msg00039.html
1539 ("CONFIG_DEVPTS_MULTIPLE_INSTANCES" . #true)
1540 ;; Modules required for initrd:
1541 ("CONFIG_NET_9P" . m)
1542 ("CONFIG_NET_9P_VIRTIO" . m)
1543 ("CONFIG_VIRTIO_BLK" . m)
1544 ("CONFIG_VIRTIO_NET" . m)
1545 ("CONFIG_VIRTIO_PCI" . m)
1546 ("CONFIG_VIRTIO_BALLOON" . m)
1547 ("CONFIG_VIRTIO_MMIO" . m)
1548 ("CONFIG_FUSE_FS" . m)
1550 ("CONFIG_9P_FS" . m)))
1552 (define (config->string options)
1553 (string-join (map (match-lambda
1555 (string-append option "=m"))
1557 (string-append option "=y"))
1559 (string-append option "=n")))
1564 And in the custom configure script from the `make-linux-libre` package:
1567 ;; Appending works even when the option wasn't in the
1568 ;; file. The last one prevails if duplicated.
1569 (let ((port (open-file ".config" "a"))
1570 (extra-configuration ,(config->string extra-options)))
1571 (display extra-configuration port)
1574 (invoke "make" "oldconfig")
1577 So by not providing a configuration-file the @file{.config} starts blank, and
1578 then we write into it the collection of flags that we want. Here's another
1582 (define %macbook41-full-config
1583 (append %macbook41-config-options
1587 (@@@@ (gnu packages linux) %default-extra-linux-options)))
1589 (define-public linux-libre-macbook41
1590 ;; XXX: Access the internal 'make-linux-libre*' procedure, which is
1591 ;; private and unexported, and is liable to change in the future.
1592 ((@@@@ (gnu packages linux) make-linux-libre*)
1593 (@@@@ (gnu packages linux) linux-libre-version)
1594 (@@@@ (gnu packages linux) linux-libre-gnu-revision)
1595 (@@@@ (gnu packages linux) linux-libre-source)
1597 #:extra-version "macbook41"
1598 #:extra-options %macbook41-config-options))
1601 In the above example @code{%file-systems} is a collection of flags enabling
1602 different file system support, @code{%efi-support} enables EFI support and
1603 @code{%emulation} enables a x86_64-linux machine to act in 32-bit mode also.
1604 @code{%default-extra-linux-options} are the ones quoted above, which had to be
1605 added in since they were replaced in the @code{extra-options} keyword.
1607 This all sounds like it should be doable, but how does one even know which
1608 modules are required for a particular system? Two places that can be helpful
1609 in trying to answer this question is the
1610 @uref{https://wiki.gentoo.org/wiki/Handbook:AMD64/Installation/Kernel, Gentoo
1612 @uref{https://www.kernel.org/doc/html/latest/admin-guide/README.html?highlight=localmodconfig,
1613 documentation from the kernel itself}. From the kernel documentation, it
1614 seems that @code{make localmodconfig} is the command we want.
1616 In order to actually run @code{make localmodconfig} we first need to get and
1617 unpack the kernel source code:
1620 tar xf $(guix build linux-libre --source)
1623 Once inside the directory containing the source code run @code{touch .config}
1624 to create an initial, empty @file{.config} to start with. @code{make
1625 localmodconfig} works by seeing what you already have in @file{.config} and
1626 letting you know what you're missing. If the file is blank then you're
1627 missing everything. The next step is to run:
1630 guix shell -D linux-libre -- make localmodconfig
1633 and note the output. Do note that the @file{.config} file is still empty.
1634 The output generally contains two types of warnings. The first start with
1635 "WARNING" and can actually be ignored in our case. The second read:
1638 module pcspkr did not have configs CONFIG_INPUT_PCSPKR
1641 For each of these lines, copy the @code{CONFIG_XXXX_XXXX} portion into the
1642 @file{.config} in the directory, and append @code{=m}, so in the end it looks
1646 CONFIG_INPUT_PCSPKR=m
1650 After copying all the configuration options, run @code{make localmodconfig}
1651 again to make sure that you don't have any output starting with ``module''.
1652 After all of these machine specific modules there are a couple more left that
1653 are also needed. @code{CONFIG_MODULES} is necessary so that you can build and
1654 load modules separately and not have everything built into the kernel.
1655 @code{CONFIG_BLK_DEV_SD} is required for reading from hard drives. It is
1656 possible that there are other modules which you will need.
1658 This post does not aim to be a guide to configuring your own kernel however,
1659 so if you do decide to build a custom kernel you'll have to seek out other
1660 guides to create a kernel which is just right for your needs.
1662 The second way to setup the kernel configuration makes more use of Guix's
1663 features and allows you to share configuration segments between different
1664 kernels. For example, all machines using EFI to boot have a number of EFI
1665 configuration flags that they need. It is likely that all the kernels will
1666 share a list of file systems to support. By using variables it is easier to
1667 see at a glance what features are enabled and to make sure you don't have
1668 features in one kernel but missing in another.
1670 Left undiscussed however, is Guix's initrd and its customization. It is
1671 likely that you'll need to modify the initrd on a machine using a custom
1672 kernel, since certain modules which are expected to be built may not be
1673 available for inclusion into the initrd.
1675 @node Guix System Image API
1676 @section Guix System Image API
1678 Historically, Guix System is centered around an @code{operating-system}
1679 structure. This structure contains various fields ranging from the
1680 bootloader and kernel declaration to the services to install.
1682 Depending on the target machine, that can go from a standard
1683 @code{x86_64} machine to a small ARM single board computer such as the
1684 Pine64, the image constraints can vary a lot. The hardware
1685 manufacturers will impose different image formats with various partition
1688 To create images suitable for all those machines, a new abstraction is
1689 necessary: that's the goal of the @code{image} record. This record
1690 contains all the required information to be transformed into a
1691 standalone image, that can be directly booted on any target machine.
1694 (define-record-type* <image>
1697 (name image-name ;symbol
1699 (format image-format) ;symbol
1700 (target image-target
1702 (size image-size ;size in bytes as integer
1704 (operating-system image-operating-system ;<operating-system>
1706 (partitions image-partitions ;list of <partition>
1708 (compression? image-compression? ;boolean
1710 (volatile-root? image-volatile-root? ;boolean
1712 (substitutable? image-substitutable? ;boolean
1716 This record contains the operating-system to instantiate. The
1717 @code{format} field defines the image type and can be @code{efi-raw},
1718 @code{qcow2} or @code{iso9660} for instance. In the future, it could be
1719 extended to @code{docker} or other image types.
1721 A new directory in the Guix sources is dedicated to images definition. For now
1722 there are four files:
1725 @item @file{gnu/system/images/hurd.scm}
1726 @item @file{gnu/system/images/pine64.scm}
1727 @item @file{gnu/system/images/novena.scm}
1728 @item @file{gnu/system/images/pinebook-pro.scm}
1731 Let's have a look to @file{pine64.scm}. It contains the
1732 @code{pine64-barebones-os} variable which is a minimal definition of an
1733 operating-system dedicated to the @b{Pine A64 LTS} board.
1736 (define pine64-barebones-os
1738 (host-name "vignemale")
1739 (timezone "Europe/Paris")
1740 (locale "en_US.utf8")
1741 (bootloader (bootloader-configuration
1742 (bootloader u-boot-pine64-lts-bootloader)
1743 (targets '("/dev/vda"))))
1744 (initrd-modules '())
1745 (kernel linux-libre-arm64-generic)
1746 (file-systems (cons (file-system
1747 (device (file-system-label "my-root"))
1750 %base-file-systems))
1751 (services (cons (service agetty-service-type
1752 (agetty-configuration
1753 (extra-options '("-L")) ; no carrier detect
1754 (baud-rate "115200")
1760 The @code{kernel} and @code{bootloader} fields are pointing to packages
1761 dedicated to this board.
1763 Right below, the @code{pine64-image-type} variable is also defined.
1766 (define pine64-image-type
1769 (constructor (cut image-with-os arm64-disk-image <>))))
1772 It's using a record we haven't talked about yet, the @code{image-type} record,
1776 (define-record-type* <image-type>
1777 image-type make-image-type
1779 (name image-type-name) ;symbol
1780 (constructor image-type-constructor)) ;<operating-system> -> <image>
1783 The main purpose of this record is to associate a name to a procedure
1784 transforming an @code{operating-system} to an image. To understand why
1785 it is necessary, let's have a look to the command producing an image
1786 from an @code{operating-system} configuration file:
1789 guix system image my-os.scm
1792 This command expects an @code{operating-system} configuration but how
1793 should we indicate that we want an image targeting a Pine64 board? We
1794 need to provide an extra information, the @code{image-type}, by passing
1795 the @code{--image-type} or @code{-t} flag, this way:
1798 guix system image --image-type=pine64-raw my-os.scm
1801 This @code{image-type} parameter points to the @code{pine64-image-type}
1802 defined above. Hence, the @code{operating-system} declared in
1803 @code{my-os.scm} will be applied the @code{(cut image-with-os
1804 arm64-disk-image <>)} procedure to turn it into an image.
1806 The resulting image looks like:
1810 (format 'disk-image)
1811 (target "aarch64-linux-gnu")
1812 (operating-system my-os)
1815 (inherit root-partition)
1816 (offset root-offset)))))
1819 which is the aggregation of the @code{operating-system} defined in
1820 @code{my-os.scm} to the @code{arm64-disk-image} record.
1822 But enough Scheme madness. What does this image API bring to the Guix user?
1827 mathieu@@cervin:~$ guix system --list-image-types
1828 The available image types are:
1836 - uncompressed-iso9660
1843 and by writing an @code{operating-system} file based on
1844 @code{pine64-barebones-os}, you can customize your image to your
1845 preferences in a file (@file{my-pine-os.scm}) like this:
1848 (use-modules (gnu services linux)
1849 (gnu system images pine64))
1851 (let ((base-os pine64-barebones-os))
1854 (timezone "America/Indiana/Indianapolis")
1857 (service earlyoom-service-type
1858 (earlyoom-configuration
1859 (prefer-regexp "icecat|chromium")))
1860 (operating-system-user-services base-os)))))
1866 guix system image --image-type=pine64-raw my-pine-os.scm
1872 guix system image --image-type=hurd-raw my-hurd-os.scm
1875 to get an image that can be written directly to a hard drive and booted
1878 Without changing anything to @code{my-hurd-os.scm}, calling:
1881 guix system image --image-type=hurd-qcow2 my-hurd-os.scm
1884 will instead produce a Hurd QEMU image.
1886 @node Connecting to Wireguard VPN
1887 @section Connecting to Wireguard VPN
1889 To connect to a Wireguard VPN server you need the kernel module to be
1890 loaded in memory and a package providing networking tools that support
1891 it (e.g. @code{wireguard-tools} or @code{network-manager}).
1893 Here is a configuration example for Linux-Libre < 5.6, where the module
1894 is out of tree and need to be loaded manually---following revisions of
1895 the kernel have it built-in and so don't need such configuration:
1899 (use-service-modules desktop)
1900 (use-package-modules vpn)
1904 (services (cons (simple-service 'wireguard-module
1905 kernel-module-loader-service-type
1908 (packages (cons wireguard-tools %base-packages))
1909 (kernel-loadable-modules (list wireguard-linux-compat)))
1912 After reconfiguring and restarting your system you can either use
1913 Wireguard tools or NetworkManager to connect to a VPN server.
1915 @subsection Using Wireguard tools
1917 To test your Wireguard setup it is convenient to use @command{wg-quick}.
1918 Just give it a configuration file @command{wg-quick up ./wg0.conf}; or
1919 put that file in @file{/etc/wireguard} and run @command{wg-quick up wg0}
1923 Be warned that the author described this command as a: “[…] very quick
1924 and dirty bash script […]”.
1927 @subsection Using NetworkManager
1929 Thanks to NetworkManager support for Wireguard we can connect to our VPN
1930 using @command{nmcli} command. Up to this point this guide assumes that
1931 you're using Network Manager service provided by
1932 @code{%desktop-services}. Ortherwise you need to adjust your services
1933 list to load @code{network-manager-service-type} and reconfigure your
1936 To import your VPN configuration execute nmcli import command:
1939 # nmcli connection import type wireguard file wg0.conf
1940 Connection 'wg0' (edbee261-aa5a-42db-b032-6c7757c60fde) successfully added
1943 This will create a configuration file in
1944 @file{/etc/NetworkManager/wg0.nmconnection}. Next connect to the
1948 $ nmcli connection up wg0
1949 Connection successfully activated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/6)
1952 By default NetworkManager will connect automatically on system boot. To
1953 change that behaviour you need to edit your config:
1956 # nmcli connection modify wg0 connection.autoconnect no
1959 For more specific information about NetworkManager and wireguard
1960 @uref{https://blogs.gnome.org/thaller/2019/03/15/wireguard-in-networkmanager/,see
1961 this post by thaller}.
1963 @node Customizing a Window Manager
1964 @section Customizing a Window Manager
1971 You could install StumpWM with a Guix system by adding
1972 @code{stumpwm} and optionally @code{`(,stumpwm "lib")}
1973 packages to a system configuration file, e.g.@: @file{/etc/config.scm}.
1975 An example configuration can look like this:
1979 (use-package-modules wm)
1983 (packages (append (list sbcl stumpwm `(,stumpwm "lib"))
1987 @cindex stumpwm fonts
1988 By default StumpWM uses X11 fonts, which could be small or pixelated on
1989 your system. You could fix this by installing StumpWM contrib Lisp
1990 module @code{sbcl-ttf-fonts}, adding it to Guix system packages:
1994 (use-package-modules fonts wm)
1998 (packages (append (list sbcl stumpwm `(,stumpwm "lib"))
1999 sbcl-ttf-fonts font-dejavu %base-packages)))
2002 Then you need to add the following code to a StumpWM configuration file
2003 @file{~/.stumpwm.d/init.lisp}:
2006 (require :ttf-fonts)
2007 (setf xft:*font-dirs* '("/run/current-system/profile/share/fonts/"))
2008 (setf clx-truetype:+font-cache-filename+ (concat (getenv "HOME") "/.fonts/font-cache.sexp"))
2010 (set-font (make-instance 'xft:font :family "DejaVu Sans Mono" :subfamily "Book" :size 11))
2014 @subsection Session lock
2017 Depending on your environment, locking the screen of your session might come built in
2018 or it might be something you have to set up yourself. If you use a desktop environment
2019 like GNOME or KDE, it's usually built in. If you use a plain window manager like
2020 StumpWM or EXWM, you might have to set it up yourself.
2025 If you use Xorg, you can use the utility
2026 @uref{https://www.mankier.com/1/xss-lock, xss-lock} to lock the screen of your session.
2027 xss-lock is triggered by DPMS which since Xorg 1.8 is auto-detected and enabled if
2028 ACPI is also enabled at kernel runtime.
2030 To use xss-lock, you can simple execute it and put it into the background before
2031 you start your window manager from e.g. your @file{~/.xsession}:
2038 In this example, xss-lock uses @code{slock} to do the actual locking of the screen when
2039 it determines it's appropriate, like when you suspend your device.
2041 For slock to be allowed to be a screen locker for the graphical session, it needs to
2042 be made setuid-root so it can authenticate users, and it needs a PAM service. This
2043 can be achieved by adding the following service to your @file{config.scm}:
2046 (screen-locker-service slock)
2049 If you manually lock your screen, e.g. by directly calling slock when you want to lock
2050 your screen but not suspend it, it's a good idea to notify xss-lock about this so no
2051 confusion occurs. This can be done by executing @code{xset s activate} immediately
2052 before you execute slock.
2054 @node Running Guix on a Linode Server
2055 @section Running Guix on a Linode Server
2056 @cindex linode, Linode
2058 To run Guix on a server hosted by @uref{https://www.linode.com, Linode},
2059 start with a recommended Debian server. We recommend using the default
2060 distro as a way to bootstrap Guix. Create your SSH keys.
2066 Be sure to add your SSH key for easy login to the remote server.
2067 This is trivially done via Linode's graphical interface for adding
2068 SSH keys. Go to your profile and click add SSH Key.
2069 Copy into it the output of:
2072 cat ~/.ssh/<username>_rsa.pub
2075 Power the Linode down.
2077 In the Linode's Storage tab, resize the Debian disk to be smaller.
2078 30 GB free space is recommended. Then click "Add a disk", and fill
2079 out the form with the following:
2089 Set it to the remaining size
2092 In the Configurations tab, press "Edit" on the default Debian profile.
2093 Under "Block Device Assignment" click "Add a Device". It should be
2094 @file{/dev/sdc} and you can select the "Guix" disk. Save Changes.
2096 Now "Add a Configuration", with the following:
2102 Kernel:GRUB 2 (it's at the bottom! This step is @b{IMPORTANT!})
2105 Block device assignment:
2108 @file{/dev/sda}: Guix
2111 @file{/dev/sdb}: swap
2114 Root device: @file{/dev/sda}
2117 Turn off all the filesystem/boot helpers
2120 Now power it back up, booting with the Debian configuration. Once it's
2121 running, ssh to your server via @code{ssh
2122 root@@@var{<your-server-IP-here>}}. (You can find your server IP address in
2123 your Linode Summary section.) Now you can run the "install guix from
2124 @pxref{Binary Installation,,, guix, GNU Guix}" steps:
2127 sudo apt-get install gpg
2128 wget https://sv.gnu.org/people/viewgpg.php?user_id=15145 -qO - | gpg --import -
2129 wget https://git.savannah.gnu.org/cgit/guix.git/plain/etc/guix-install.sh
2130 chmod +x guix-install.sh
2135 Now it's time to write out a config for the server. The key information
2136 is below. Save the resulting file as @file{guix-config.scm}.
2141 (use-service-modules networking
2143 (use-package-modules admin
2150 (host-name "my-server")
2151 (timezone "America/New_York")
2152 (locale "en_US.UTF-8")
2153 ;; This goofy code will generate the grub.cfg
2154 ;; without installing the grub bootloader on disk.
2155 (bootloader (bootloader-configuration
2158 (inherit grub-bootloader)
2159 (installer #~(const #true))))))
2160 (file-systems (cons (file-system
2164 %base-file-systems))
2167 (swap-devices (list "/dev/sdb"))
2170 (initrd-modules (cons "virtio_scsi" ; Needed to find the disk
2171 %base-initrd-modules))
2173 (users (cons (user-account
2176 ;; Adding the account to the "wheel" group
2177 ;; makes it a sudoer.
2178 (supplementary-groups '("wheel"))
2179 (home-directory "/home/janedoe"))
2180 %base-user-accounts))
2182 (packages (cons* nss-certs ;for HTTPS access
2187 (service dhcp-client-service-type)
2188 (service openssh-service-type
2189 (openssh-configuration
2190 (openssh openssh-sans-x)
2191 (password-authentication? #false)
2193 `(("janedoe" ,(local-file "janedoe_rsa.pub"))
2194 ("root" ,(local-file "janedoe_rsa.pub"))))))
2198 Replace the following fields in the above configuration:
2200 (host-name "my-server") ; replace with your server name
2201 ; if you chose a linode server outside the U.S., then
2202 ; use tzselect to find a correct timezone string
2203 (timezone "America/New_York") ; if needed replace timezone
2204 (name "janedoe") ; replace with your username
2205 ("janedoe" ,(local-file "janedoe_rsa.pub")) ; replace with your ssh key
2206 ("root" ,(local-file "janedoe_rsa.pub")) ; replace with your ssh key
2209 The last line in the above example lets you log into the server as root
2210 and set the initial root password (see the note at the end of this
2211 recipe about root login). After you have done this, you may
2212 delete that line from your configuration and reconfigure to prevent root
2215 Copy your ssh public key (eg: @file{~/.ssh/id_rsa.pub}) as
2216 @file{@var{<your-username-here>}_rsa.pub} and put
2217 @file{guix-config.scm} in the same directory. In a new terminal run
2221 sftp root@@<remote server ip address>
2222 put /path/to/files/<username>_rsa.pub .
2223 put /path/to/files/guix-config.scm .
2226 In your first terminal, mount the guix drive:
2230 mount /dev/sdc /mnt/guix
2233 Due to the way we set up the bootloader section of the guix-config.scm,
2234 only the grub configuration file will be installed. So, we need to copy
2235 over some of the other GRUB stuff already installed on the Debian system:
2238 mkdir -p /mnt/guix/boot/grub
2239 cp -r /boot/grub/* /mnt/guix/boot/grub/
2242 Now initialize the Guix installation:
2245 guix system init guix-config.scm /mnt/guix
2249 Now from the Linode console, select boot and select "Guix".
2251 Once it boots, you should be able to log in via SSH! (The server config
2252 will have changed though.) You may encounter an error like:
2255 $ ssh root@@<server ip address>
2256 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
2257 @ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @
2258 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
2259 IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
2260 Someone could be eavesdropping on you right now (man-in-the-middle attack)!
2261 It is also possible that a host key has just been changed.
2262 The fingerprint for the ECDSA key sent by the remote host is
2263 SHA256:0B+wp33w57AnKQuHCvQP0+ZdKaqYrI/kyU7CfVbS7R4.
2264 Please contact your system administrator.
2265 Add correct host key in /home/joshua/.ssh/known_hosts to get rid of this message.
2266 Offending ECDSA key in /home/joshua/.ssh/known_hosts:3
2267 ECDSA host key for 198.58.98.76 has changed and you have requested strict checking.
2268 Host key verification failed.
2271 Either delete @file{~/.ssh/known_hosts} file, or delete the offending line
2272 starting with your server IP address.
2274 Be sure to set your password and root's password.
2277 ssh root@@<remote ip address>
2278 passwd ; for the root password
2279 passwd <username> ; for the user password
2282 You may not be able to run the above commands at this point. If you
2283 have issues remotely logging into your linode box via SSH, then you may
2284 still need to set your root and user password initially by clicking on
2285 the ``Launch Console'' option in your linode. Choose the ``Glish''
2286 instead of ``Weblish''. Now you should be able to ssh into the machine.
2288 Hooray! At this point you can shut down the server, delete the
2289 Debian disk, and resize the Guix to the rest of the size.
2292 By the way, if you save it as a disk image right at this point, you'll
2293 have an easy time spinning up new Guix images! You may need to
2294 down-size the Guix image to 6144MB, to save it as an image. Then you
2295 can resize it again to the max size.
2297 @node Setting up a bind mount
2298 @section Setting up a bind mount
2300 To bind mount a file system, one must first set up some definitions
2301 before the @code{operating-system} section of the system definition. In
2302 this example we will bind mount a folder from a spinning disk drive to
2303 @file{/tmp}, to save wear and tear on the primary SSD, without
2304 dedicating an entire partition to be mounted as @file{/tmp}.
2306 First, the source drive that hosts the folder we wish to bind mount
2307 should be defined, so that the bind mount can depend on it.
2310 (define source-drive ;; "source-drive" can be named anything you want.
2312 (device (uuid "UUID goes here"))
2313 (mount-point "/path-to-spinning-disk-goes-here")
2314 (type "ext4"))) ;; Make sure to set this to the appropriate type for your drive.
2317 The source folder must also be defined, so that guix will know it's not
2318 a regular block device, but a folder.
2320 (define (%source-directory) "/path-to-spinning-disk-goes-here/tmp") ;; "source-directory" can be named any valid variable name.
2323 Finally, inside the @code{file-systems} definition, we must add the
2327 (file-systems (cons*
2329 ...<other drives omitted for clarity>...
2331 source-drive ;; Must match the name you gave the source drive in the earlier definition.
2334 (device (%source-directory)) ;; Make sure "source-directory" matches your earlier definition.
2335 (mount-point "/tmp")
2336 (type "none") ;; We are mounting a folder, not a partition, so this type needs to be "none"
2337 (flags '(bind-mount))
2338 (dependencies (list source-drive)) ;; Ensure "source-drive" matches what you've named the variable for the drive.
2341 ...<other drives omitted for clarity>...
2346 @node Getting substitutes from Tor
2347 @section Getting substitutes from Tor
2349 Guix daemon can use a HTTP proxy to get substitutes, here we are
2350 configuring it to get them via Tor.
2353 @emph{Not all} Guix daemon's traffic will go through Tor! Only
2354 HTTP/HTTPS will get proxied; FTP, Git protocol, SSH, etc connections
2355 will still go through the clearnet. Again, this configuration isn't
2356 foolproof some of your traffic won't get routed by Tor at all. Use it
2359 Also note that the procedure described here applies only to package
2360 substitution. When you update your guix distribution with
2361 @command{guix pull}, you still need to use @command{torsocks} if
2362 you want to route the connection to guix's git repository servers
2366 Guix's substitute server is available as a Onion service, if you want
2367 to use it to get your substitutes through Tor configure your system as
2372 (use-service-module base networking)
2378 (service tor-service-type
2380 (config-file (plain-file "tor-config"
2381 "HTTPTunnelPort 127.0.0.1:9250"))))
2382 (modify-services %base-services
2384 config => (guix-configuration
2386 ;; ci.guix.gnu.org's Onion service
2388 "@value{SUBSTITUTE-TOR-URL}")
2389 (http-proxy "http://localhost:9250")))))))
2392 This will keep a tor process running that provides a HTTP CONNECT tunnel
2393 which will be used by @command{guix-daemon}. The daemon can use other
2394 protocols than HTTP(S) to get remote resources, request using those
2395 protocols won't go through Tor since we are only setting a HTTP tunnel
2396 here. Note that @code{substitutes-urls} is using HTTPS and not HTTP or
2397 it won't work, that's a limitation of Tor's tunnel; you may want to use
2398 @command{privoxy} instead to avoid such limitations.
2400 If you don't want to always get substitutes through Tor but using it just
2401 some of the times, then skip the @code{guix-configuration}. When you
2402 want to get a substitute from the Tor tunnel run:
2405 sudo herd set-http-proxy guix-daemon http://localhost:9250
2407 --substitute-urls=@value{SUBSTITUTE-TOR-URL} @dots{}
2410 @node Setting up NGINX with Lua
2411 @section Setting up NGINX with Lua
2412 @cindex nginx, lua, openresty, resty
2414 NGINX could be extended with Lua scripts.
2416 Guix provides NGINX service with ability to load Lua module and specific
2417 Lua packages, and reply to requests by evaluating Lua scripts.
2419 The following example demonstrates system definition with configuration
2420 to evaluate @file{index.lua} Lua script on HTTP request to
2421 @uref{http://localhost/hello} endpoint:
2424 local shell = require "resty.shell"
2427 local timeout = 1000 -- ms
2428 local max_size = 4096 -- byte
2430 local ok, stdout, stderr, reason, status =
2431 shell.run([[/run/current-system/profile/bin/ls /tmp]], stdin, timeout, max_size)
2438 (use-service-modules #;… web)
2439 (use-package-modules #;… lua)
2444 (service nginx-service-type
2445 (nginx-configuration
2448 (file-append nginx-lua-module "/etc/nginx/modules/ngx_http_lua_module.so")))
2449 (lua-package-path (list lua-resty-core
2454 (lua-package-cpath (list lua-resty-signal))
2456 (list (nginx-server-configuration
2457 (server-name '("localhost"))
2461 (nginx-location-configuration
2463 (body (list #~(format #f "content_by_lua_file ~s;"
2464 #$(local-file "index.lua"))))))))))))))
2467 @node Music Server with Bluetooth Audio
2468 @section Music Server with Bluetooth Audio
2470 @cindex music server, headless
2471 @cindex bluetooth, ALSA configuration
2473 MPD, the Music Player Daemon, is a flexible server-side application for
2474 playing music. Client programs on different machines on the network ---
2475 a mobile phone, a laptop, a desktop workstation --- can connect to it to
2476 control the playback of audio files from your local music collection.
2477 MPD decodes the audio files and plays them back on one or many outputs.
2479 By default MPD will play to the default audio device. In the example
2480 below we make things a little more interesting by setting up a headless
2481 music server. There will be no graphical user interface, no Pulseaudio
2482 daemon, and no local audio output. Instead we will configure MPD with
2483 two outputs: a bluetooth speaker and a web server to serve audio streams
2484 to any streaming media player.
2486 Bluetooth is often rather frustrating to set up. You will have to pair
2487 your Bluetooth device and make sure that the device is automatically
2488 connected as soon as it powers on. The Bluetooth system service
2489 returned by the @code{bluetooth-service} procedure provides the
2490 infrastructure needed to set this up.
2492 Reconfigure your system with at least the following services and
2498 (packages (cons* bluez bluez-alsa
2502 (dbus-service #:services (list bluez-alsa))
2503 (bluetooth-service #:auto-enable? #t)))
2506 Start the @code{bluetooth} service and then use @command{bluetoothctl}
2507 to scan for Bluetooth devices. Try to identify your Bluetooth speaker
2508 and pick out its device ID from the resulting list of devices that is
2509 indubitably dominated by a baffling smorgasbord of your neighbors' home
2510 automation gizmos. This only needs to be done once:
2514 [NEW] Controller 00:11:22:33:95:7F BlueZ 5.40 [default]
2516 [bluetooth]# power on
2517 [bluetooth]# Changing power on succeeded
2519 [bluetooth]# agent on
2520 [bluetooth]# Agent registered
2522 [bluetooth]# default-agent
2523 [bluetooth]# Default agent request successful
2525 [bluetooth]# scan on
2526 [bluetooth]# Discovery started
2527 [CHG] Controller 00:11:22:33:95:7F Discovering: yes
2528 [NEW] Device AA:BB:CC:A4:AA:CD My Bluetooth Speaker
2529 [NEW] Device 44:44:FF:2A:20:DC My Neighbor's TV
2532 [bluetooth]# pair AA:BB:CC:A4:AA:CD
2533 Attempting to pair with AA:BB:CC:A4:AA:CD
2534 [CHG] Device AA:BB:CC:A4:AA:CD Connected: yes
2536 [My Bluetooth Speaker]# [CHG] Device AA:BB:CC:A4:AA:CD UUIDs: 0000110b-0000-1000-8000-00xxxxxxxxxx
2537 [CHG] Device AA:BB:CC:A4:AA:CD UUIDs: 0000110c-0000-1000-8000-00xxxxxxxxxx
2538 [CHG] Device AA:BB:CC:A4:AA:CD UUIDs: 0000110e-0000-1000-8000-00xxxxxxxxxx
2539 [CHG] Device AA:BB:CC:A4:AA:CD Paired: yes
2542 [CHG] Device AA:BB:CC:A4:AA:CD Connected: no
2545 [bluetooth]# trust AA:BB:CC:A4:AA:CD
2546 [bluetooth]# [CHG] Device AA:BB:CC:A4:AA:CD Trusted: yes
2547 Changing AA:BB:CC:A4:AA:CD trust succeeded
2550 [bluetooth]# connect AA:BB:CC:A4:AA:CD
2551 Attempting to connect to AA:BB:CC:A4:AA:CD
2552 [bluetooth]# [CHG] Device AA:BB:CC:A4:AA:CD RSSI: -63
2553 [CHG] Device AA:BB:CC:A4:AA:CD Connected: yes
2554 Connection successful
2556 [My Bluetooth Speaker]# scan off
2557 [CHG] Device AA:BB:CC:A4:AA:CD RSSI is nil
2559 [CHG] Controller 00:11:22:33:95:7F Discovering: no
2562 Congratulations, you can now automatically connect to your Bluetooth
2565 It is now time to configure ALSA to use the @emph{bluealsa} Bluetooth
2566 module, so that you can define an ALSA pcm device corresponding to your
2567 Bluetooth speaker. For a headless server using @emph{bluealsa} with a
2568 fixed Bluetooth device is likely simpler than configuring Pulseaudio and
2569 its stream switching behavior. We configure ALSA by crafting a custom
2570 @code{alsa-configuration} for the @code{alsa-service-type}. The
2571 configuration will declare a @code{pcm} type @code{bluealsa} from the
2572 @code{bluealsa} module provided by the @code{bluez-alsa} package, and
2573 then define a @code{pcm} device of that type for your Bluetooth speaker.
2575 All that is left then is to make MPD send audio data to this ALSA
2576 device. We also add a secondary MPD output that makes the currently
2577 played audio files available as a stream through a web server on port
2578 8080. When enabled a device on the network could listen to the audio
2579 stream by connecting any capable media player to the HTTP server on port
2580 8080, independent of the status of the Bluetooth speaker.
2582 What follows is the outline of an @code{operating-system} declaration
2583 that should accomplish the above-mentioned tasks:
2587 (use-service-modules audio dbus sound #;… etc)
2588 (use-package-modules audio linux #;… etc)
2591 (packages (cons* bluez bluez-alsa
2595 (service mpd-service-type
2597 (user "your-username")
2598 (music-dir "/path/to/your/music")
2599 (address "192.168.178.20")
2600 (outputs (list (mpd-output
2604 ;; Use the same name as in the ALSA
2605 ;; configuration below.
2606 '((device . "pcm.btspeaker"))))
2615 '((encoder . "vorbis")
2617 (bind-to-address . "192.168.178.20")
2618 (max-clients . "0") ;no limit
2620 (format . "44100:16:1"))))))))
2621 (dbus-service #:services (list bluez-alsa))
2622 (bluetooth-service #:auto-enable? #t)
2623 (service alsa-service-type
2625 (pulseaudio? #false) ;we don't need it
2628 # Declare Bluetooth audio device type \"bluealsa\" from bluealsa module
2629 pcm_type.bluealsa @{
2630 lib \"" #$(file-append bluez-alsa "/lib/alsa-lib/libasound_module_pcm_bluealsa.so") "\"
2633 # Declare control device type \"bluealsa\" from the same module
2634 ctl_type.bluealsa @{
2635 lib \"" #$(file-append bluez-alsa "/lib/alsa-lib/libasound_module_ctl_bluealsa.so") "\"
2638 # Define the actual Bluetooth audio device.
2641 device \"AA:BB:CC:A4:AA:CD\" # unique device identifier
2645 # Define an associated controller.
2652 Enjoy the music with the MPD client of your choice or a media player
2653 capable of streaming via HTTP!
2656 @c *********************************************************************
2660 The kernel Linux provides a number of shared facilities that are
2661 available to processes in the system. These facilities include a shared
2662 view on the file system, other processes, network devices, user and
2663 group identities, and a few others. Since Linux 3.19 a user can choose
2664 to @emph{unshare} some of these shared facilities for selected
2665 processes, providing them (and their child processes) with a different
2668 A process with an unshared @code{mount} namespace, for example, has its
2669 own view on the file system --- it will only be able to see directories
2670 that have been explicitly bound in its mount namespace. A process with
2671 its own @code{proc} namespace will consider itself to be the only
2672 process running on the system, running as PID 1.
2674 Guix uses these kernel features to provide fully isolated environments
2675 and even complete Guix System containers, lightweight virtual machines
2676 that share the host system's kernel. This feature comes in especially
2677 handy when using Guix on a foreign distribution to prevent interference
2678 from foreign libraries or configuration files that are available
2682 * Guix Containers:: Perfectly isolated environments
2683 * Guix System Containers:: A system inside your system
2686 @node Guix Containers
2687 @section Guix Containers
2689 The easiest way to get started is to use @command{guix shell} with the
2690 @option{--container} option. @xref{Invoking guix shell,,, guix, GNU
2691 Guix Reference Manual} for a reference of valid options.
2693 The following snippet spawns a minimal shell process with most
2694 namespaces unshared from the system. The current working directory is
2695 visible to the process, but anything else on the file system is
2696 unavailable. This extreme isolation can be very useful when you want to
2697 rule out any sort of interference from environment variables, globally
2698 installed libraries, or configuration files.
2701 guix shell --container
2704 It is a bleak environment, barren, desolate. You will find that not
2705 even the GNU coreutils are available here, so to explore this deserted
2706 wasteland you need to use built-in shell commands. Even the usually
2707 gigantic @file{/gnu/store} directory is reduced to a faint shadow of
2712 /gnu/store/@dots{}-gcc-10.3.0-lib
2713 /gnu/store/@dots{}-glibc-2.33
2714 /gnu/store/@dots{}-bash-static-5.1.8
2715 /gnu/store/@dots{}-ncurses-6.2.20210619
2716 /gnu/store/@dots{}-bash-5.1.8
2717 /gnu/store/@dots{}-profile
2718 /gnu/store/@dots{}-readline-8.1.1
2721 @cindex exiting a container
2722 There isn't much you can do in an environment like this other than
2723 exiting it. You can use @key{^D} or @command{exit} to terminate this
2724 limited shell environment.
2726 @cindex exposing directories, container
2727 @cindex sharing directories, container
2728 @cindex mapping locations, container
2729 You can make other directories available inside of the container
2730 environment; use @option{--expose=DIRECTORY} to bind-mount the given
2731 directory as a read-only location inside the container, or use
2732 @option{--share=DIRECTORY} to make the location writable. With an
2733 additional mapping argument after the directory name you can control the
2734 name of the directory inside the container. In the following example we
2735 map @file{/etc} on the host system to @file{/the/host/etc} inside a
2736 container in which the GNU coreutils are installed.
2739 $ guix shell --container --share=/etc=/the/host/etc coreutils
2743 Similarly, you can prevent the current working directory from being
2744 mapped into the container with the @option{--no-cwd} option. Another
2745 good idea is to create a dedicated directory that will serve as the
2746 container's home directory, and spawn the container shell from that
2749 @cindex hide system libraries, container
2750 @cindex avoid ABI mismatch, container
2751 On a foreign system a container environment can be used to compile
2752 software that cannot possibly be linked with system libraries or with
2753 the system's compiler toolchain. A common use-case in a research
2754 context is to install packages from within an R session. Outside of a
2755 container environment there is a good chance that the foreign compiler
2756 toolchain and incompatible system libraries are found first, resulting
2757 in incompatible binaries that cannot be used by R. In a container shell
2758 this problem disappears, as system libraries and executables simply
2759 aren't available due to the unshared @code{mount} namespace.
2761 Let's take a comprehensive manifest providing a comfortable development
2762 environment for use with R:
2765 (specifications->manifest
2773 ;; Common command line tools lest the container is too empty.
2783 ;; Toolchain and common libraries for "install.packages"
2785 "gfortran-toolchain"
2800 Let's use this to run R inside a container environment. For convenience
2801 we share the @code{net} namespace to use the host system's network
2802 interfaces. Now we can build R packages from source the traditional way
2803 without having to worry about ABI mismatch or incompatibilities.
2806 $ guix shell --container --network --manifest=manifest.scm -- R
2808 R version 4.2.1 (2022-06-23) -- "Funny-Looking Kid"
2809 Copyright (C) 2022 The R Foundation for Statistical Computing
2811 > e <- Sys.getenv("GUIX_ENVIRONMENT")
2812 > Sys.setenv(GIT_SSL_CAINFO=paste0(e, "/etc/ssl/certs/ca-certificates.crt"))
2813 > Sys.setenv(SSL_CERT_FILE=paste0(e, "/etc/ssl/certs/ca-certificates.crt"))
2814 > Sys.setenv(SSL_CERT_DIR=paste0(e, "/etc/ssl/certs"))
2815 > install.packages("Cairo", lib=paste0(getwd()))
2817 * installing *source* package 'Cairo' ...
2821 The downloaded source packages are in
2822 '/tmp/RtmpCuwdwM/downloaded_packages'
2823 > library("Cairo", lib=getwd())
2827 Using container shells is fun, but they can become a little cumbersome
2828 when you want to go beyond just a single interactive process. Some
2829 tasks become a lot easier when they sit on the rock solid foundation of
2830 a proper Guix System and its rich set of system services. The next
2831 section shows you how to launch a complete Guix System inside of a
2835 @node Guix System Containers
2836 @section Guix System Containers
2838 The Guix System provides a wide array of interconnected system services
2839 that are configured declaratively to form a dependable stateless GNU
2840 System foundation for whatever tasks you throw at it. Even when using
2841 Guix on a foreign distribution you can benefit from the design of Guix
2842 System by running a system instance as a container. Using the same
2843 kernel features of unshared namespaces mentioned in the previous
2844 section, the resulting Guix System instance is isolated from the host
2845 system and only shares file system locations that you explicitly
2848 A Guix System container differs from the shell process created by
2849 @command{guix shell --container} in a number of important ways. While
2850 in a container shell the containerized process is a Bash shell process,
2851 a Guix System container runs the Shepherd as PID 1. In a system
2852 container all system services (@pxref{Services,,, guix, GNU Guix
2853 Reference Manual}) are set up just as they would be on a Guix System in
2854 a virtual machine or on bare metal---this includes daemons managed by
2855 the GNU@tie{}Shepherd (@pxref{Shepherd Services,,, guix, GNU Guix
2856 Reference Manual}) as well as other kinds of extensions to the operating
2857 system (@pxref{Service Composition,,, guix, GNU Guix Reference Manual}).
2859 The perceived increase in complexity of running a Guix System container
2860 is easily justified when dealing with more complex applications that
2861 have higher or just more rigid requirements on their execution
2862 contexts---configuration files, dedicated user accounts, directories for
2863 caches or log files, etc. In Guix System the demands of this kind of
2864 software are satisfied through the deployment of system services.
2867 @node A Database Container
2868 @subsection A Database Container
2870 A good example might be a PostgreSQL database server. Much of the
2871 complexity of setting up such a database server is encapsulated in this
2872 deceptively short service declaration:
2875 (service postgresql-service-type
2876 (postgresql-configuration
2877 (postgresql postgresql-14)))
2880 A complete operating system declaration for use with a Guix System
2881 container would look something like this:
2885 (use-package-modules databases)
2886 (use-service-modules databases)
2889 (host-name "container")
2890 (timezone "Europe/Berlin")
2891 (file-systems (cons (file-system
2892 (device (file-system-label "does-not-matter"))
2895 %base-file-systems))
2896 (bootloader (bootloader-configuration
2897 (bootloader grub-bootloader)
2898 (targets '("/dev/sdX"))))
2900 (cons* (service postgresql-service-type
2901 (postgresql-configuration
2902 (postgresql postgresql-14)
2904 (postgresql-config-file
2905 (log-destination "stderr")
2907 (plain-file "pg_hba.conf"
2910 host all all 10.0.0.1/32 trust"))
2912 '(("listen_addresses" "*")
2913 ("log_directory" "/var/log/postgresql")))))))
2914 (service postgresql-role-service-type
2915 (postgresql-role-configuration
2917 (list (postgresql-role
2919 (create-database? #t))))))
2923 With @code{postgresql-role-service-type} we define a role ``test'' and
2924 create a matching database, so that we can test right away without any
2925 further manual setup. The @code{postgresql-config-file} settings allow
2926 a client from IP address 10.0.0.1 to connect without requiring
2927 authentication---a bad idea in production systems, but convenient for
2930 Let's build a script that will launch an instance of this Guix System as
2931 a container. Write the @code{operating-system} declaration above to a
2932 file @file{os.scm} and then use @command{guix system container} to build
2933 the launcher. (@pxref{Invoking guix system,,, guix, GNU Guix Reference
2937 $ guix system container os.scm
2938 The following derivations will be built:
2939 /gnu/store/@dots{}-run-container.drv
2941 building /gnu/store/@dots{}-run-container.drv...
2942 /gnu/store/@dots{}-run-container
2945 Now that we have a launcher script we can run it to spawn the new system
2946 with a running PostgreSQL service. Note that due to some as yet
2947 unresolved limitations we need to run the launcher as the root user, for
2948 example with @command{sudo}.
2951 $ sudo /gnu/store/@dots{}-run-container
2952 system container is running as PID 5983
2956 Background the process with @key{Ctrl-z} followed by @command{bg}. Note
2957 the process ID in the output; we will need it to connect to the
2958 container later. You know what? Let's try attaching to the container
2959 right now. We will use @command{nsenter}, a tool provided by the
2960 @code{util-linux} package:
2963 $ guix shell util-linux
2964 $ sudo nsenter -a -t 5983
2965 root@@container /# pgrep -a postgres
2966 49 /gnu/store/@dots{}-postgresql-14.4/bin/postgres -D /var/lib/postgresql/data --config-file=/gnu/store/@dots{}-postgresql.conf -p 5432
2967 51 postgres: checkpointer
2968 52 postgres: background writer
2969 53 postgres: walwriter
2970 54 postgres: autovacuum launcher
2971 55 postgres: stats collector
2972 56 postgres: logical replication launcher
2973 root@@container /# exit
2976 The PostgreSQL service is running in the container!
2979 @node Container Networking
2980 @subsection Container Networking
2981 @cindex container networking
2983 What good is a Guix System running a PostgreSQL database service as a
2984 container when we can only talk to it with processes originating in the
2985 container? It would be much better if we could talk to the database
2988 The easiest way to do this is to create a pair of connected virtual
2989 Ethernet devices (known as @code{veth}). We move one of the devices
2990 (@code{ceth-test}) into the @code{net} namespace of the container and
2991 leave the other end (@code{veth-test}) of the connection on the host
3000 # Attach the new net namespace "guix-test" to the container PID.
3001 sudo ip netns attach $ns $pid
3003 # Create the pair of devices
3004 sudo ip link add $host type veth peer name $client
3006 # Move the client device into the container's net namespace
3007 sudo ip link set $client netns $ns
3010 Then we configure the host side:
3013 sudo ip link set $host up
3014 sudo ip addr add 10.0.0.1/24 dev $host
3017 @dots{}and then we configure the client side:
3020 sudo ip netns exec $ns ip link set lo up
3021 sudo ip netns exec $ns ip link set $client up
3022 sudo ip netns exec $ns ip addr add 10.0.0.2/24 dev $client
3025 At this point the host can reach the container at IP address 10.0.0.2,
3026 and the container can reach the host at IP 10.0.0.1. This is all we
3027 need to talk to the database server inside the container from the host
3028 system on the outside.
3031 $ psql -h 10.0.0.2 -U test
3033 Type "help" for help.
3035 test=> CREATE TABLE hello (who TEXT NOT NULL);
3037 test=> INSERT INTO hello (who) VALUES ('world');
3039 test=> SELECT * FROM hello;
3046 Now that we're done with this little demonstration let's clean up:
3050 sudo ip netns del $ns
3051 sudo ip link del $host
3055 @c *********************************************************************
3056 @node Advanced package management
3057 @chapter Advanced package management
3059 Guix is a functional package manager that offers many features beyond
3060 what more traditional package managers can do. To the uninitiated,
3061 those features might not have obvious use cases at first. The purpose
3062 of this chapter is to demonstrate some advanced package management
3065 @pxref{Package Management,,, guix, GNU Guix Reference Manual} for a complete
3069 * Guix Profiles in Practice:: Strategies for multiple profiles and manifests.
3072 @node Guix Profiles in Practice
3073 @section Guix Profiles in Practice
3075 Guix provides a very useful feature that may be quite foreign to newcomers:
3076 @emph{profiles}. They are a way to group package installations together and all users
3077 on the same system are free to use as many profiles as they want.
3079 Whether you're a developer or not, you may find that multiple profiles bring you
3080 great power and flexibility. While they shift the paradigm somewhat compared to
3081 @emph{traditional package managers}, they are very convenient to use once you've
3082 understood how to set them up.
3084 If you are familiar with Python's @samp{virtualenv}, you can think of a profile as a
3085 kind of universal @samp{virtualenv} that can hold any kind of software whatsoever, not
3086 just Python software. Furthermore, profiles are self-sufficient: they capture
3087 all the runtime dependencies which guarantees that all programs within a profile
3088 will always work at any point in time.
3090 Multiple profiles have many benefits:
3094 Clean semantic separation of the various packages a user needs for different contexts.
3097 Multiple profiles can be made available into the environment either on login
3098 or within a dedicated shell.
3101 Profiles can be loaded on demand. For instance, the user can use multiple
3102 shells, each of them running different profiles.
3105 Isolation: Programs from one profile will not use programs from the other, and
3106 the user can even install different versions of the same programs to the two
3107 profiles without conflict.
3110 Deduplication: Profiles share dependencies that happens to be the exact same.
3111 This makes multiple profiles storage-efficient.
3114 Reproducible: when used with declarative manifests, a profile can be fully
3115 specified by the Guix commit that was active when it was set up. This means
3116 that the exact same profile can be
3117 @uref{https://guix.gnu.org/blog/2018/multi-dimensional-transactions-and-rollbacks-oh-my/,
3118 set up anywhere and anytime}, with just the commit information. See the
3119 section on @ref{Reproducible profiles}.
3122 Easier upgrades and maintenance: Multiple profiles make it easy to keep
3123 package listings at hand and make upgrades completely frictionless.
3126 Concretely, here follows some typical profiles:
3130 The dependencies of a project you are working on.
3133 Your favourite programming language libraries.
3136 Laptop-specific programs (like @samp{powertop}) that you don't need on a desktop.
3139 @TeX{}live (this one can be really useful when you need to install just one
3140 package for this one document you've just received over email).
3146 Let's dive in the set up!
3148 @node Basic setup with manifests
3149 @subsection Basic setup with manifests
3151 A Guix profile can be set up @i{via} a @dfn{manifest}. A manifest is a
3152 snippet of Scheme code that specifies the set of packages you want to
3153 have in your profile; it looks like this:
3156 (specifications->manifest
3158 ;; Version 1.3 of package-2.
3160 ;; The "lib" output of package-3.
3166 @xref{Writing Manifests,,, guix, GNU Guix Reference Manual}, for
3167 more information about the syntax.
3169 We can create a manifest specification per profile and install them this way:
3172 GUIX_EXTRA_PROFILES=$HOME/.guix-extra-profiles
3173 mkdir -p "$GUIX_EXTRA_PROFILES"/my-project # if it does not exist yet
3174 guix package --manifest=/path/to/guix-my-project-manifest.scm --profile="$GUIX_EXTRA_PROFILES"/my-project/my-project
3177 Here we set an arbitrary variable @samp{GUIX_EXTRA_PROFILES} to point to the directory
3178 where we will store our profiles in the rest of this article.
3180 Placing all your profiles in a single directory, with each profile getting its
3181 own sub-directory, is somewhat cleaner. This way, each sub-directory will
3182 contain all the symlinks for precisely one profile. Besides, ``looping over
3183 profiles'' becomes obvious from any programming language (e.g.@: a shell script) by
3184 simply looping over the sub-directories of @samp{$GUIX_EXTRA_PROFILES}.
3186 Note that it's also possible to loop over the output of
3189 guix package --list-profiles
3192 although you'll probably have to filter out @file{~/.config/guix/current}.
3194 To enable all profiles on login, add this to your @file{~/.bash_profile} (or similar):
3197 for i in $GUIX_EXTRA_PROFILES/*; do
3198 profile=$i/$(basename "$i")
3199 if [ -f "$profile"/etc/profile ]; then
3200 GUIX_PROFILE="$profile"
3201 . "$GUIX_PROFILE"/etc/profile
3207 Note to Guix System users: the above reflects how your default profile
3208 @file{~/.guix-profile} is activated from @file{/etc/profile}, that latter being loaded by
3209 @file{~/.bashrc} by default.
3211 You can obviously choose to only enable a subset of them:
3214 for i in "$GUIX_EXTRA_PROFILES"/my-project-1 "$GUIX_EXTRA_PROFILES"/my-project-2; do
3215 profile=$i/$(basename "$i")
3216 if [ -f "$profile"/etc/profile ]; then
3217 GUIX_PROFILE="$profile"
3218 . "$GUIX_PROFILE"/etc/profile
3224 When a profile is off, it's straightforward to enable it for an individual shell
3225 without "polluting" the rest of the user session:
3228 GUIX_PROFILE="path/to/my-project" ; . "$GUIX_PROFILE"/etc/profile
3231 The key to enabling a profile is to @emph{source} its @samp{etc/profile} file. This file
3232 contains shell code that exports the right environment variables necessary to
3233 activate the software contained in the profile. It is built automatically by
3234 Guix and meant to be sourced.
3235 It contains the same variables you would get if you ran:
3238 guix package --search-paths=prefix --profile=$my_profile"
3241 Once again, see (@pxref{Invoking guix package,,, guix, GNU Guix Reference Manual})
3242 for the command line options.
3244 To upgrade a profile, simply install the manifest again:
3247 guix package -m /path/to/guix-my-project-manifest.scm -p "$GUIX_EXTRA_PROFILES"/my-project/my-project
3250 To upgrade all profiles, it's easy enough to loop over them. For instance,
3251 assuming your manifest specifications are stored in
3252 @file{~/.guix-manifests/guix-$profile-manifest.scm}, with @samp{$profile} being the name
3253 of the profile (e.g.@: "project1"), you could do the following in Bourne shell:
3256 for profile in "$GUIX_EXTRA_PROFILES"/*; do
3257 guix package --profile="$profile" --manifest="$HOME/.guix-manifests/guix-$profile-manifest.scm"
3261 Each profile has its own generations:
3264 guix package -p "$GUIX_EXTRA_PROFILES"/my-project/my-project --list-generations
3267 You can roll-back to any generation of a given profile:
3270 guix package -p "$GUIX_EXTRA_PROFILES"/my-project/my-project --switch-generations=17
3273 Finally, if you want to switch to a profile without inheriting from the
3274 current environment, you can activate it from an empty shell:
3277 env -i $(which bash) --login --noprofile --norc
3278 . my-project/etc/profile
3281 @node Required packages
3282 @subsection Required packages
3284 Activating a profile essentially boils down to exporting a bunch of
3285 environmental variables. This is the role of the @samp{etc/profile} within the
3288 @emph{Note: Only the environmental variables of the packages that consume them will
3291 For instance, @samp{MANPATH} won't be set if there is no consumer application for man
3292 pages within the profile. So if you need to transparently access man pages once
3293 the profile is loaded, you've got two options:
3297 Either export the variable manually, e.g.
3299 export MANPATH=/path/to/profile$@{MANPATH:+:@}$MANPATH
3303 Or include @samp{man-db} to the profile manifest.
3306 The same is true for @samp{INFOPATH} (you can install @samp{info-reader}),
3307 @samp{PKG_CONFIG_PATH} (install @samp{pkg-config}), etc.
3309 @node Default profile
3310 @subsection Default profile
3312 What about the default profile that Guix keeps in @file{~/.guix-profile}?
3314 You can assign it the role you want. Typically you would install the manifest
3315 of the packages you want to use all the time.
3317 Alternatively, you could keep it ``manifest-less'' for throw-away packages
3318 that you would just use for a couple of days.
3319 This way makes it convenient to run
3322 guix install package-foo
3323 guix upgrade package-bar
3326 without having to specify the path to a profile.
3328 @node The benefits of manifests
3329 @subsection The benefits of manifests
3331 Manifests are a convenient way to keep your package lists around and, say,
3332 to synchronize them across multiple machines using a version control system.
3334 A common complaint about manifests is that they can be slow to install when they
3335 contain large number of packages. This is especially cumbersome when you just
3336 want get an upgrade for one package within a big manifest.
3338 This is one more reason to use multiple profiles, which happen to be just
3339 perfect to break down manifests into multiple sets of semantically connected
3340 packages. Using multiple, small profiles provides more flexibility and
3343 Manifests come with multiple benefits. In particular, they ease maintenance:
3347 When a profile is set up from a manifest, the manifest itself is
3348 self-sufficient to keep a ``package listing'' around and reinstall the profile
3349 later or on a different system. For ad-hoc profiles, we would need to
3350 generate a manifest specification manually and maintain the package versions
3351 for the packages that don't use the default version.
3354 @code{guix package --upgrade} always tries to update the packages that have
3355 propagated inputs, even if there is nothing to do. Guix manifests remove this
3359 When partially upgrading a profile, conflicts may arise (due to diverging
3360 dependencies between the updated and the non-updated packages) and they can be
3361 annoying to resolve manually. Manifests remove this problem altogether since
3362 all packages are always upgraded at once.
3365 As mentioned above, manifests allow for reproducible profiles, while the
3366 imperative @code{guix install}, @code{guix upgrade}, etc. do not, since they produce
3367 different profiles every time even when they hold the same packages. See
3368 @uref{https://issues.guix.gnu.org/issue/33285, the related discussion on the matter}.
3371 Manifest specifications are usable by other @samp{guix} commands. For example, you
3372 can run @code{guix weather -m manifest.scm} to see how many substitutes are
3373 available, which can help you decide whether you want to try upgrading today
3374 or wait a while. Another example: you can run @code{guix pack -m manifest.scm} to
3375 create a pack containing all the packages in the manifest (and their
3376 transitive references).
3379 Finally, manifests have a Scheme representation, the @samp{<manifest>} record type.
3380 They can be manipulated in Scheme and passed to the various Guix @uref{https://en.wikipedia.org/wiki/Api, APIs}.
3383 It's important to understand that while manifests can be used to declare
3384 profiles, they are not strictly equivalent: profiles have the side effect that
3385 they ``pin'' packages in the store, which prevents them from being
3386 garbage-collected (@pxref{Invoking guix gc,,, guix, GNU Guix Reference Manual})
3387 and ensures that they will still be available at any point in
3390 Let's take an example:
3394 We have an environment for hacking on a project for which there isn't a Guix
3395 package yet. We build the environment using a manifest, and then run @code{guix
3396 environment -m manifest.scm}. So far so good.
3399 Many weeks pass and we have run a couple of @code{guix pull} in the mean time.
3400 Maybe a dependency from our manifest has been updated; or we may have run
3401 @code{guix gc} and some packages needed by our manifest have been
3405 Eventually, we set to work on that project again, so we run @code{guix shell
3406 -m manifest.scm}. But now we have to wait for Guix to build and install
3410 Ideally, we could spare the rebuild time. And indeed we can, all we need is to
3411 install the manifest to a profile and use @code{GUIX_PROFILE=/the/profile;
3412 . "$GUIX_PROFILE"/etc/profile} as explained above: this guarantees that our
3413 hacking environment will be available at all times.
3415 @emph{Security warning:} While keeping old profiles around can be convenient, keep in
3416 mind that outdated packages may not have received the latest security fixes.
3418 @node Reproducible profiles
3419 @subsection Reproducible profiles
3421 To reproduce a profile bit-for-bit, we need two pieces of information:
3427 a Guix channel specification.
3430 Indeed, manifests alone might not be enough: different Guix versions (or
3431 different channels) can produce different outputs for a given manifest.
3433 You can output the Guix channel specification with @samp{guix describe
3435 Save this to a file, say @samp{channel-specs.scm}.
3437 On another computer, you can use the channel specification file and the manifest
3438 to reproduce the exact same profile:
3441 GUIX_EXTRA_PROFILES=$HOME/.guix-extra-profiles
3442 GUIX_EXTRA=$HOME/.guix-extra
3444 mkdir "$GUIX_EXTRA"/my-project
3445 guix pull --channels=channel-specs.scm --profile "$GUIX_EXTRA/my-project/guix"
3447 mkdir -p "$GUIX_EXTRA_PROFILES/my-project"
3448 "$GUIX_EXTRA"/my-project/guix/bin/guix package --manifest=/path/to/guix-my-project-manifest.scm --profile="$GUIX_EXTRA_PROFILES"/my-project/my-project
3451 It's safe to delete the Guix channel profile you've just installed with the
3452 channel specification, the project profile does not depend on it.
3454 @c *********************************************************************
3455 @node Environment management
3456 @chapter Environment management
3458 Guix provides multiple tools to manage environment. This chapter
3459 demonstrate such utilities.
3462 * Guix environment via direnv:: Setup Guix environment with direnv
3465 @node Guix environment via direnv
3466 @section Guix environment via direnv
3468 Guix provides a @samp{direnv} package, which could extend shell after
3469 directory change. This tool could be used to prepare a pure Guix
3472 The following example provides a shell function for @file{~/.direnvrc}
3473 file, which could be used from Guix Git repository in
3474 @file{~/src/guix/.envrc} file to setup a build environment similar to
3475 described in @pxref{Building from Git,,, guix, GNU Guix Reference
3478 Create a @file{~/.direnvrc} with a Bash code:
3481 # Thanks <https://github.com/direnv/direnv/issues/73#issuecomment-152284914>
3485 local alias_dir=$PWD/.direnv/aliases
3486 mkdir -p "$alias_dir"
3487 PATH_add "$alias_dir"
3488 local target="$alias_dir/$name"
3489 if declare -f "$name" >/dev/null; then
3490 echo "#!$SHELL" > "$target"
3491 declare -f "$name" >> "$target" 2>/dev/null
3492 # Notice that we add shell variables to the function trigger.
3493 echo "$name \$*" >> "$target"
3501 export GUIX_GITHUB_TOKEN="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
3503 # Unset 'GUIX_PACKAGE_PATH'.
3504 export GUIX_PACKAGE_PATH=""
3506 # Recreate a garbage collector root.
3507 gcroots="$HOME/.config/guix/gcroots"
3509 gcroot="$gcroots/guix"
3515 # Miscellaneous packages.
3516 PACKAGES_MAINTENANCE=(
3530 # Environment packages.
3531 PACKAGES=(help2man guile-sqlite3 guile-gcrypt)
3533 # Thanks <https://lists.gnu.org/archive/html/guix-devel/2016-09/msg00859.html>
3534 eval "$(guix environment --search-paths --root="$gcroot" --pure guix --ad-hoc $@{PACKAGES[@@]@} $@{PACKAGES_MAINTENANCE[@@]@} "$@@")"
3536 # Predefine configure flags.
3539 ./configure --localstatedir=/var --prefix=
3541 export_function configure
3543 # Run make and optionally build something.
3549 ./pre-inst-env guix build "$@@"
3552 export_function build
3554 # Predefine push Git command.
3557 git push --set-upstream origin
3559 export_function push
3561 clear # Clean up the screen.
3562 git-cal --author='Your Name' # Show contributions calendar.
3564 # Show commands help.
3566 build build a package or just a project if no argument provided
3567 configure run ./configure with predefined parameters
3568 push push to upstream Git repository
3573 Every project containing @file{.envrc} with a string @code{use guix}
3574 will have predefined environment variables and procedures.
3576 Run @command{direnv allow} to setup the environment for the first time.
3578 @c *********************************************************************
3579 @node Acknowledgments
3580 @chapter Acknowledgments
3582 Guix is based on the @uref{https://nixos.org/nix/, Nix package manager},
3583 which was designed and
3584 implemented by Eelco Dolstra, with contributions from other people (see
3585 the @file{nix/AUTHORS} file in Guix.) Nix pioneered functional package
3586 management, and promoted unprecedented features, such as transactional
3587 package upgrades and rollbacks, per-user profiles, and referentially
3588 transparent build processes. Without this work, Guix would not exist.
3590 The Nix-based software distributions, Nixpkgs and NixOS, have also been
3591 an inspiration for Guix.
3593 GNU@tie{}Guix itself is a collective work with contributions from a
3594 number of people. See the @file{AUTHORS} file in Guix for more
3595 information on these fine people. The @file{THANKS} file lists people
3596 who have helped by reporting bugs, taking care of the infrastructure,
3597 providing artwork and themes, making suggestions, and more---thank you!
3599 This document includes adapted sections from articles that have previously
3600 been published on the Guix blog at @uref{https://guix.gnu.org/blog}.
3603 @c *********************************************************************
3604 @node GNU Free Documentation License
3605 @appendix GNU Free Documentation License
3606 @cindex license, GNU Free Documentation License
3607 @include fdl-1.3.texi
3609 @c *********************************************************************
3611 @unnumbered Concept Index
3617 @c ispell-local-dictionary: "american";