doc: Refer to the pt_BR translation.
[jackhill/guix/guix.git] / doc / guix-cookbook.texi
1 \input texinfo
2 @c -*-texinfo-*-
3
4 @c %**start of header
5 @setfilename guix-cookbook.info
6 @documentencoding UTF-8
7 @settitle GNU Guix Cookbook
8 @c %**end of header
9
10 @c Onion service for ci.guix.gnu.org.
11 @set SUBSTITUTE-TOR-URL https://4zwzi66wwdaalbhgnix55ea3ab4pvvw66ll2ow53kjub6se4q2bclcyd.onion
12
13 @copying
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@*
24
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''.
31 @end copying
32
33 @dircategory System administration
34 @direntry
35 * Guix cookbook: (guix-cookbook). Tutorials and examples for GNU Guix.
36 @end direntry
37
38 @titlepage
39 @title GNU Guix Cookbook
40 @subtitle Tutorials and examples for using the GNU Guix Functional Package Manager
41 @author The GNU Guix Developers
42
43 @page
44 @vskip 0pt plus 1filll
45
46 @insertcopying
47 @end titlepage
48
49 @contents
50
51 @c *********************************************************************
52 @node Top
53 @top GNU Guix Cookbook
54
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.
59
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
62 @c translation.
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}).
69
70 @menu
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
77
78 * Acknowledgments:: Thanks!
79 * GNU Free Documentation License:: The license of this document.
80 * Concept Index:: Concepts.
81
82 @detailmenu
83 --- The Detailed Node Listing ---
84
85 Scheme tutorials
86
87 * A Scheme Crash Course:: Learn the basics of Scheme
88
89 Packaging
90
91 * Packaging Tutorial:: Let's add a package to Guix!
92
93 System Configuration
94
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.
105
106 @end detailmenu
107 @end menu
108
109 @c *********************************************************************
110 @node Scheme tutorials
111 @chapter Scheme tutorials
112
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.
117
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!
121
122 Let's get started!
123
124 @node A Scheme Crash Course
125 @section A Scheme Crash Course
126
127 @cindex Scheme, crash course
128
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.
133
134 Alternatively you can also run @code{guix shell guile -- guile}
135 if you'd rather not have Guile installed in your user profile.
136
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
141 REPL.
142
143 @itemize
144 @item
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.
150
151 Examples of valid expressions:
152
153 @lisp
154 "Hello World!"
155 @result{} "Hello World!"
156
157 17
158 @result{} 17
159
160 (display (string-append "Hello " "Guix" "\n"))
161 @print{} Hello Guix!
162 @result{} #<unspecified>
163 @end lisp
164
165 @item
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.
170
171 @item
172 Anonymous functions are declared with the @code{lambda} term:
173
174 @lisp
175 (lambda (x) (* x x))
176 @result{} #<procedure 120e348 at <unknown port>:24:0 (x)>
177 @end lisp
178
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:
182
183 @lisp
184 ((lambda (x) (* x x)) 3)
185 @result{} 9
186 @end lisp
187
188 @item
189 Anything can be assigned a global name with @code{define}:
190
191 @lisp
192 (define a 3)
193 (define square (lambda (x) (* x x)))
194 (square a)
195 @result{} 9
196 @end lisp
197
198 @item
199 Procedures can be defined more concisely with the following syntax:
200
201 @lisp
202 (define (square x) (* x x))
203 @end lisp
204
205 @item
206 A list structure can be created with the @code{list} procedure:
207
208 @lisp
209 (list 2 a 5 7)
210 @result{} (2 3 5 7)
211 @end lisp
212
213 @item
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.
218
219 @lisp
220 '(display (string-append "Hello " "Guix" "\n"))
221 @result{} (display (string-append "Hello " "Guix" "\n"))
222
223 '(2 a 5 7)
224 @result{} (2 a 5 7)
225 @end lisp
226
227 @item
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.
231
232 @lisp
233 `(2 a 5 7 (2 ,a 5 ,(+ a 4)))
234 @result{} (2 a 5 7 (2 3 5 7))
235 @end lisp
236
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.
239
240 @item
241 Multiple variables can be named locally with @code{let} (@pxref{Local
242 Bindings,,, guile, GNU Guile Reference Manual}):
243
244 @lisp
245 (define x 10)
246 (let ((x 2)
247 (y 3))
248 (list x y))
249 @result{} (2 3)
250
251 x
252 @result{} 10
253
254 y
255 @error{} In procedure module-lookup: Unbound variable: y
256 @end lisp
257
258 Use @code{let*} to allow later variable declarations to refer to earlier
259 definitions.
260
261 @lisp
262 (let* ((x 2)
263 (y (* x 3)))
264 (list x y))
265 @result{} (2 6)
266 @end lisp
267
268 @item
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}.
273
274 @item
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.
278
279 @item
280 Modules are created with @code{define-module} (@pxref{Creating Guile
281 Modules,,, guile, GNU Guile Reference Manual}). For instance
282
283 @lisp
284 (define-module (guix build-system ruby)
285 #:use-module (guix store)
286 #:export (ruby-build
287 ruby-build-system))
288 @end lisp
289
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}.
294 @end itemize
295
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:
300
301 @itemize
302 @item
303 @uref{https://spritely.institute/static/papers/scheme-primer.html, @i{A
304 Scheme Primer}}, by Christine Lemmer-Webber and the Spritely Institute.
305
306 @item
307 @uref{http://www.troubleshooters.com/codecorn/scheme_guile/hello.htm,
308 @i{Scheme at a Glance}}, by Steve Litt.
309
310 @item
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.
315
316 You can also install it and read it from your computer:
317
318 @example
319 guix install sicp info-reader
320 info sicp
321 @end example
322
323 An @uref{https://sarabander.github.io/sicp/, unofficial ebook} is also
324 available.
325
326 @end itemize
327
328 You'll find more books, tutorials and other resources at
329 @url{https://schemers.org/}.
330 @end quotation
331
332
333 @c *********************************************************************
334 @node Packaging
335 @chapter Packaging
336
337 @cindex packaging
338
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
342 them.
343
344 @menu
345 * Packaging Tutorial:: A tutorial on how to add packages to Guix.
346 @end menu
347
348 @node Packaging Tutorial
349 @section Packaging Tutorial
350
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}
355 dialects from the
356 @uref{https://en.wikipedia.org/wiki/Lisp_%28programming_language%29, Lisp family}.
357
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
360 simple languages.
361
362 @itemize
363 @item
364 Use functions, structures, macros and all of Scheme expressiveness for your
365 package definitions.
366
367 @item
368 Inheritance makes it easy to customize a package by inheriting from it and
369 modifying only what is needed.
370
371 @item
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!
380 @end itemize
381
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.
386
387 @node A ``Hello World'' package
388 @subsection A ``Hello World'' package
389
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.
393
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:
399
400 @lisp
401 (define-public hello
402 (package
403 (name "hello")
404 (version "2.10")
405 (source (origin
406 (method url-fetch)
407 (uri (string-append "mirror://gnu/hello/hello-" version
408 ".tar.gz"))
409 (sha256
410 (base32
411 "0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i"))))
412 (build-system gnu-build-system)
413 (synopsis "Hello, GNU world: An example GNU package")
414 (description
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/")
419 (license gpl3+)))
420 @end lisp
421
422 As you can see, most of it is rather straightforward. But let's review the
423 fields together:
424
425 @table @samp
426 @item name
427 The project name. Using Scheme conventions, we prefer to keep it
428 lower case, without underscore and using dash-separated words.
429
430 @item source
431 This field contains a description of the source code origin. The
432 @code{origin} record contains these fields:
433
434 @enumerate
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.
443 @end enumerate
444
445 @item build-system
446
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}).
454
455 @item synopsis
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.
458
459 @item description
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.
462
463 @item home-page
464 Use HTTPS if available.
465
466 @item license
467 See @code{guix/licenses.scm} in the project source for a full list of
468 available licenses.
469 @end table
470
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.
473
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.
477
478 Save the following to a file @file{my-hello.scm}.
479
480 @lisp
481 (use-modules (guix packages)
482 (guix download)
483 (guix build-system gnu)
484 (guix licenses))
485
486 (package
487 (name "my-hello")
488 (version "2.10")
489 (source (origin
490 (method url-fetch)
491 (uri (string-append "mirror://gnu/hello/hello-" version
492 ".tar.gz"))
493 (sha256
494 (base32
495 "0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i"))))
496 (build-system gnu-build-system)
497 (synopsis "Hello, Guix world: An example custom Guix package")
498 (description
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/")
503 (license gpl3+))
504 @end lisp
505
506 We will explain the extra code in a moment.
507
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
513 base32.
514
515 Thankfully, Guix can automate this task for us; all we need is to provide the
516 URI:
517
518 @c TRANSLATORS: This is example shell output.
519 @example sh
520 $ guix download mirror://gnu/hello/hello-2.10.tar.gz
521
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
528 @end example
529
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.
533
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:
537
538 @c TRANSLATORS: This is example shell output.
539 @example sh
540 $ guix download mirror://gnu/hello/hello-2.10.tar.gz.sig
541
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
556 @end example
557
558 You can then happily run
559
560 @c TRANSLATORS: Do not translate this command
561 @example sh
562 $ guix package --install-from-file=my-hello.scm
563 @end example
564
565 You should now have @code{my-hello} in your profile!
566
567 @c TRANSLATORS: Do not translate this command
568 @example sh
569 $ guix package --list-installed=my-hello
570 my-hello 2.10 out
571 /gnu/store/f1db2mfm8syb8qvc357c53slbvf1g9m9-my-hello-2.10
572 @end example
573
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.
577
578 @node Setup
579 @subsection Setup
580
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.
584
585 There are several ways to set up a Guix packaging environment.
586
587 We recommend you work directly on the Guix source checkout since it makes it
588 easier for everyone to contribute to the project.
589
590 But first, let's look at other possibilities.
591
592 @node Local file
593 @subsubsection Local file
594
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
597 package --help}:
598
599 @example
600 -f, --install-from-file=FILE
601 install the package that the code within FILE
602 evaluates to
603 @end example
604
605 Thus the last expression @emph{must} return a package, which is the case in our
606 earlier example.
607
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.
611
612 @node @samp{GUIX_PACKAGE_PATH}
613 @subsubsection @samp{GUIX_PACKAGE_PATH}
614
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.}
617
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
620 packages.
621
622 Guix makes it possible to streamline the process by adding as many ``package
623 declaration directories'' as you want.
624
625 Create a directory, say @file{~/guix-packages} and add it to the @samp{GUIX_PACKAGE_PATH}
626 environment variable:
627
628 @example
629 $ mkdir ~/guix-packages
630 $ export GUIX_PACKAGE_PATH=~/guix-packages
631 @end example
632
633 To add several directories, separate them with a colon (@code{:}).
634
635 Our previous @samp{my-hello} needs some adjustments though:
636
637 @lisp
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))
643
644 (define-public my-hello
645 (package
646 (name "my-hello")
647 (version "2.10")
648 (source (origin
649 (method url-fetch)
650 (uri (string-append "mirror://gnu/hello/hello-" version
651 ".tar.gz"))
652 (sha256
653 (base32
654 "0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i"))))
655 (build-system gnu-build-system)
656 (synopsis "Hello, Guix world: An example custom Guix package")
657 (description
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/")
662 (license gpl3+)))
663 @end lisp
664
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
668 packages.
669
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}:
674
675 @lisp
676 ; ...
677 (define-public my-hello
678 ; ...
679 )
680
681 my-hello
682 @end lisp
683
684 This last example is not very typical.
685
686 Now @samp{my-hello} should be part of the package collection like all other official
687 packages. You can verify this with:
688
689 @example
690 $ guix package --show=my-hello
691 @end example
692
693 @node Guix channels
694 @subsubsection Guix channels
695
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.
700
701 @xref{Channels,,, guix, GNU Guix Reference Manual} for setup details.
702
703 @node Direct checkout hacking
704 @subsubsection Direct checkout hacking
705
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
708 from your hard work!
709
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
714 development inertia.
715
716 Check out the official @uref{https://git-scm.com/, Git} repository:
717
718 @example
719 $ git clone https://git.savannah.gnu.org/git/guix.git
720 @end example
721
722 In the rest of this article, we use @samp{$GUIX_CHECKOUT} to refer to the location of
723 the checkout.
724
725
726 Follow the instructions in the manual (@pxref{Contributing,,, guix, GNU Guix
727 Reference Manual}) to set up the repository environment.
728
729 Once ready, you should be able to use the package definitions from the
730 repository environment.
731
732 Feel free to edit package definitions found in @samp{$GUIX_CHECKOUT/gnu/packages}.
733
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}).
737
738 @itemize
739 @item
740 Search packages, such as Ruby:
741
742 @example
743 $ cd $GUIX_CHECKOUT
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
748 @end example
749
750 @item
751 Build a package, here Ruby version 2.1:
752
753 @example
754 $ ./pre-inst-env guix build --keep-failed ruby@@2.1
755 /gnu/store/c13v73jxmj2nir2xjqaz5259zywsa9zi-ruby-2.1.6
756 @end example
757
758 @item
759 Install it to your user profile:
760
761 @example
762 $ ./pre-inst-env guix package --install ruby@@2.1
763 @end example
764
765 @item
766 Check for common mistakes:
767
768 @example
769 $ ./pre-inst-env guix lint ruby@@2.1
770 @end example
771 @end itemize
772
773 Guix strives at maintaining a high packaging standard; when contributing to the
774 Guix project, remember to
775
776 @itemize
777 @item
778 follow the coding style (@pxref{Coding Style,,, guix, GNU Guix Reference Manual}),
779 @item
780 and review the check list from the manual (@pxref{Submitting Patches,,, guix, GNU Guix Reference Manual}).
781 @end itemize
782
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})
785
786
787 It's a community effort so the more join in, the better Guix becomes!
788
789 @node Extended example
790 @subsection Extended example
791
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):
795
796 @lisp
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))
809
810 (define-public my-libgit2
811 (let ((commit "e98d0a37c93574d2c6107bf7f31140b548c6a7bf")
812 (revision "1"))
813 (package
814 (name "my-libgit2")
815 (version (git-version "0.26.6" revision commit))
816 (source (origin
817 (method git-fetch)
818 (uri (git-reference
819 (url "https://github.com/libgit2/libgit2/")
820 (commit commit)))
821 (file-name (git-file-name name version))
822 (sha256
823 (base32
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"))
831 (arguments
832 `(#:tests? #true ; Run the test suite (this is the default)
833 #:configure-flags '("-DUSE_SHA1DC=ON") ; SHA-1 collision detection
834 #:phases
835 (modify-phases %standard-phases
836 (add-after 'unpack 'fix-hardcoded-paths
837 (lambda _
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.
844 (replace 'check
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 "." ".*")))))))
848 (inputs
849 (list libssh2 http-parser python-wrapper))
850 (native-inputs
851 (list pkg-config))
852 (propagated-inputs
853 ;; These two libraries are in 'Requires.private' in libgit2.pc.
854 (list openssl zlib))
855 (home-page "https://libgit2.github.com/")
856 (synopsis "Library providing Git core methods")
857 (description
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))))
863 @end lisp
864
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.
867 See below.)
868
869 Let's discuss those fields in depth.
870
871 @subsubsection @code{git-fetch} method
872
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
877 "v" version))}.
878
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
881 version))}.
882
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
886 Reference Manual}).
887
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
890 these lines:
891
892 @example
893 git clone https://github.com/libgit2/libgit2/
894 cd libgit2
895 git checkout v0.26.6
896 guix hash -rx .
897 @end example
898
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}).
902
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.
905
906 @subsubsection Snippets
907
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.
912
913 Snippets might need additional Guile modules which can be imported from the
914 @code{modules} field.
915
916 @subsubsection Inputs
917
918 There are 3 different input types. In short:
919
920 @table @asis
921 @item native-inputs
922 Required for building but not runtime -- installing a package
923 through a substitute won't install these inputs.
924 @item 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.
930 @end table
931
932 @xref{package Reference,,, guix, GNU Guix Reference Manual} for more details.
933
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.
937
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.
944
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.
950
951 @quotation Note
952 You may see here and there snippets where package inputs are written
953 quite differently, like so:
954
955 @lisp
956 ;; The "old style" for inputs.
957 (inputs
958 `(("libssh2" ,libssh2)
959 ("http-parser" ,http-parser)
960 ("python" ,python-wrapper)))
961 @end lisp
962
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.
967 @end quotation
968
969 @subsubsection Outputs
970
971 Just like how a package can have multiple inputs, it can also produce multiple
972 outputs.
973
974 Each output corresponds to a separate directory in the store.
975
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.
978
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"}.
981
982 Typical separate output names include @code{debug} and @code{doc}.
983
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
986 modular.
987
988 @subsubsection Build system arguments
989
990 The @code{arguments} is a keyword-value list used to configure the build process.
991
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
995 one.
996
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
999 following flags
1000
1001 @lisp
1002 #:make-flags (list (string-append "prefix=" (assoc-ref %outputs "out"))
1003 "CC=gcc")
1004 @end lisp
1005
1006 translate into
1007
1008 @example
1009 $ make CC=gcc prefix=/gnu/store/...-<out>
1010 @end example
1011
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}).
1016
1017 Similarly, it's possible to set the configure flags:
1018
1019 @lisp
1020 #:configure-flags '("-DUSE_SHA1DC=ON")
1021 @end lisp
1022
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.
1025
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}:
1030
1031 @lisp
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
1037 bootstrap
1038 patch-usr-bin-file
1039 patch-source-shebangs configure patch-generated-file-shebangs
1040 build check install
1041 patch-shebangs strip
1042 validate-runpath
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)))
1049 @end lisp
1050
1051 Or from the REPL:
1052
1053 @lisp
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)
1058 @end lisp
1059
1060 If you want to know more about what happens during those phases, consult the
1061 associated procedures.
1062
1063 For instance, as of this writing the definition of @code{unpack} for the GNU build
1064 system is:
1065
1066 @lisp
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
1070 working directory."
1071 (if (file-is-directory? source)
1072 (begin
1073 (mkdir "source")
1074 (chdir "source")
1075
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))
1080 (begin
1081 (if (string-suffix? ".zip" source)
1082 (invoke "unzip" source)
1083 (invoke "tar" "xvf" source))
1084 (chdir (first-subdirectory "."))))
1085 #true)
1086 @end lisp
1087
1088 Note the @code{chdir} call: it changes the working directory to where the source was
1089 unpacked.
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
1093 else.
1094
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:
1098
1099 @itemize
1100 @item
1101 @code{(add-before @var{phase} @var{new-phase} @var{procedure})}: Run @var{procedure} named @var{new-phase} before @var{phase}.
1102 @item
1103 @code{(add-after @var{phase} @var{new-phase} @var{procedure})}: Same, but afterwards.
1104 @item
1105 @code{(replace @var{phase} @var{procedure})}.
1106 @item
1107 @code{(delete @var{phase})}.
1108 @end itemize
1109
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
1114 this:
1115
1116 @lisp
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")))
1121 ;; ...
1122 #true))
1123 @end lisp
1124
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.
1129
1130 @subsubsection Code staging
1131
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}.
1136
1137 @subsubsection Utility functions
1138
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.
1142
1143 Some like @code{chmod} are native to Guile.
1144 @xref{,,, guile, Guile reference manual} for a complete list.
1145
1146 Guix provides additional helper functions which prove especially handy in the
1147 context of package management.
1148
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:
1152
1153 @table @code
1154 @item which
1155 Like the @samp{which} system command.
1156 @item find-files
1157 Akin to the @samp{find} system command.
1158 @item mkdir-p
1159 Like @samp{mkdir -p}, which creates all parents as needed.
1160 @item install-file
1161 Similar to @samp{install} when installing a file to a (possibly
1162 non-existing) directory. Guile has @code{copy-file} which works
1163 like @samp{cp}.
1164 @item copy-recursively
1165 Like @samp{cp -r}.
1166 @item delete-file-recursively
1167 Like @samp{rm -rf}.
1168 @item invoke
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.
1173 @item substitute*
1174 A ``@command{sed}-like'' function.
1175 @end table
1176
1177 @xref{Build Utilities,,, guix, GNU Guix Reference Manual}, for more
1178 information on these utilities.
1179
1180 @subsubsection Module prefix
1181
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).
1190
1191 @node Other build systems
1192 @subsection Other build systems
1193
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
1198 on this system.
1199
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
1202 arguments.
1203
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.
1208
1209 @node Programmable and automated package definition
1210 @subsection Programmable and automated package definition
1211
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.
1214
1215 Let's illustrate this with some awesome features of Guix!
1216
1217 @node Recursive importers
1218 @subsubsection Recursive importers
1219
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):
1225
1226 @example
1227 $ guix import cran --recursive walrus
1228
1229 (define-public r-mc2d
1230 ; ...
1231 (license gpl2+)))
1232
1233 (define-public r-jmvcore
1234 ; ...
1235 (license gpl2+)))
1236
1237 (define-public r-wrs2
1238 ; ...
1239 (license gpl3)))
1240
1241 (define-public r-walrus
1242 (package
1243 (name "r-walrus")
1244 (version "1.0.3")
1245 (source
1246 (origin
1247 (method url-fetch)
1248 (uri (cran-uri "walrus" version))
1249 (sha256
1250 (base32
1251 "1nk2glcvy4hyksl5ipq2mz8jy4fss90hx6cq98m3w96kzjni6jjj"))))
1252 (build-system r-build-system)
1253 (propagated-inputs
1254 (list r-ggplot2 r-jmvcore r-r6 r-wrs2))
1255 (home-page "https://github.com/jamovi/walrus")
1256 (synopsis "Robust Statistical Methods")
1257 (description
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'.")
1265 (license gpl3)))
1266 @end example
1267
1268 The recursive importer won't import packages for which Guix already has package
1269 definitions, except for the very first.
1270
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}).
1275
1276 @node Automatic update
1277 @subsubsection Automatic update
1278
1279 Guix can be smart enough to check for updates on systems it knows. It can
1280 report outdated package definitions with
1281
1282 @example
1283 $ guix refresh hello
1284 @end example
1285
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
1288 well:
1289
1290 @example
1291 $ guix refresh hello --update
1292 @end example
1293
1294 @node Inheritance
1295 @subsubsection Inheritance
1296
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:
1299
1300 @lisp
1301 (define-public adwaita-icon-theme
1302 (package (inherit gnome-icon-theme)
1303 (name "adwaita-icon-theme")
1304 (version "3.26.1")
1305 (source (origin
1306 (method url-fetch)
1307 (uri (string-append "mirror://gnome/sources/" name "/"
1308 (version-major+minor version) "/"
1309 name "-" version ".tar.xz"))
1310 (sha256
1311 (base32
1312 "17fpahgh5dyckgz7rwqvzgnhx53cx9kr2xw0szprc6bnqy977fi8"))))
1313 (native-inputs (list `(,gtk+ "bin")))))
1314 @end lisp
1315
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.
1319
1320 @node Getting help
1321 @subsection Getting help
1322
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.
1327
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.
1330
1331 See the @uref{https://www.gnu.org/software/guix/contact/, Guix homepage} for information on the mailing lists, IRC, etc.
1332
1333 @node Conclusion
1334 @subsection Conclusion
1335
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.
1340
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.
1345
1346 Other features worth exploring are the interactive editing and debugging
1347 capabilities of Guix provided by the Guile REPL@.
1348
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!
1353
1354 @node References
1355 @subsection References
1356
1357 @itemize
1358 @item
1359 The @uref{https://www.gnu.org/software/guix/manual/en/html_node/Defining-Packages.html, package reference in the manual}
1360
1361 @item
1362 @uref{https://gitlab.com/pjotrp/guix-notes/blob/master/HACKING.org, Pjotr’s hacking guide to GNU Guix}
1363
1364 @item
1365 @uref{https://www.gnu.org/software/guix/guix-ghm-andreas-20130823.pdf, ``GNU Guix: Package without a scheme!''}, by Andreas Enge
1366 @end itemize
1367
1368 @c *********************************************************************
1369 @node System Configuration
1370 @chapter System Configuration
1371
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.
1375
1376 @pxref{System Configuration,,, guix, GNU Guix Reference Manual} for a complete
1377 reference.
1378
1379 @menu
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.
1390 @end menu
1391
1392 @node Auto-Login to a Specific TTY
1393 @section Auto-Login to a Specific TTY
1394
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.
1402
1403 Here is how one might set up auto login for one user to one tty:
1404
1405 @lisp
1406 (define (auto-login-to-tty config tty user)
1407 (if (string=? tty (mingetty-configuration-tty config))
1408 (mingetty-configuration
1409 (inherit config)
1410 (auto-login user))
1411 config))
1412
1413 (define %my-services
1414 (modify-services %base-services
1415 ;; @dots{}
1416 (mingetty-service-type config =>
1417 (auto-login-to-tty
1418 config "tty3" "alice"))))
1419
1420 (operating-system
1421 ;; @dots{}
1422 (services %my-services))
1423 @end lisp
1424
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.
1428
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
1431 regular user.
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
1434 convenient option.
1435
1436
1437 @node Customizing the Kernel
1438 @section Customizing the Kernel
1439
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.
1447
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.
1453
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.
1458
1459 The @code{linux-libre} kernel package definition is actually a procedure which
1460 creates a package.
1461
1462 @lisp
1463 (define* (make-linux-libre* version gnu-revision source supported-systems
1464 #:key
1465 (extra-version #f)
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))
1471 ...)
1472 @end lisp
1473
1474 The current @code{linux-libre} package is for the 5.15.x series, and is
1475 declared like this:
1476
1477 @lisp
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))
1484 @end lisp
1485
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.
1491
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:
1497
1498 @lisp
1499 (let ((build (assoc-ref %standard-phases 'build))
1500 (config (assoc-ref (or native-inputs inputs) "kconfig")))
1501
1502 ;; Use a custom kernel configuration file or a default
1503 ;; configuration file.
1504 (if config
1505 (begin
1506 (copy-file config ".config")
1507 (chmod ".config" #o666))
1508 (invoke "make" ,defconfig)))
1509 @end lisp
1510
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
1513 other package:
1514
1515 @lisp
1516 (define-public linux-libre/E2140
1517 (package
1518 (inherit linux-libre)
1519 (native-inputs
1520 `(("kconfig" ,(local-file "E2140.config"))
1521 ,@@(alist-delete "kconfig"
1522 (package-native-inputs linux-libre))))))
1523 @end lisp
1524
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.
1530
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
1534 it:
1535
1536 @lisp
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)
1549 ("CONFIG_CIFS" . m)
1550 ("CONFIG_9P_FS" . m)))
1551
1552 (define (config->string options)
1553 (string-join (map (match-lambda
1554 ((option . 'm)
1555 (string-append option "=m"))
1556 ((option . #true)
1557 (string-append option "=y"))
1558 ((option . #false)
1559 (string-append option "=n")))
1560 options)
1561 "\n"))
1562 @end lisp
1563
1564 And in the custom configure script from the `make-linux-libre` package:
1565
1566 @lisp
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)
1572 (close-port port))
1573
1574 (invoke "make" "oldconfig")
1575 @end lisp
1576
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
1579 custom kernel:
1580
1581 @lisp
1582 (define %macbook41-full-config
1583 (append %macbook41-config-options
1584 %file-systems
1585 %efi-support
1586 %emulation
1587 (@@@@ (gnu packages linux) %default-extra-linux-options)))
1588
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)
1596 '("x86_64-linux")
1597 #:extra-version "macbook41"
1598 #:extra-options %macbook41-config-options))
1599 @end lisp
1600
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.
1606
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
1611 Handbook} and the
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.
1615
1616 In order to actually run @code{make localmodconfig} we first need to get and
1617 unpack the kernel source code:
1618
1619 @example shell
1620 tar xf $(guix build linux-libre --source)
1621 @end example
1622
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:
1628
1629 @example shell
1630 guix shell -D linux-libre -- make localmodconfig
1631 @end example
1632
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:
1636
1637 @example shell
1638 module pcspkr did not have configs CONFIG_INPUT_PCSPKR
1639 @end example
1640
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
1643 like this:
1644
1645 @example shell
1646 CONFIG_INPUT_PCSPKR=m
1647 CONFIG_VIRTIO=m
1648 @end example
1649
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.
1657
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.
1661
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.
1669
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.
1674
1675 @node Guix System Image API
1676 @section Guix System Image API
1677
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.
1681
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
1686 sizes and offsets.
1687
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.
1692
1693 @lisp
1694 (define-record-type* <image>
1695 image make-image
1696 image?
1697 (name image-name ;symbol
1698 (default #f))
1699 (format image-format) ;symbol
1700 (target image-target
1701 (default #f))
1702 (size image-size ;size in bytes as integer
1703 (default 'guess))
1704 (operating-system image-operating-system ;<operating-system>
1705 (default #f))
1706 (partitions image-partitions ;list of <partition>
1707 (default '()))
1708 (compression? image-compression? ;boolean
1709 (default #t))
1710 (volatile-root? image-volatile-root? ;boolean
1711 (default #t))
1712 (substitutable? image-substitutable? ;boolean
1713 (default #t)))
1714 @end lisp
1715
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.
1720
1721 A new directory in the Guix sources is dedicated to images definition. For now
1722 there are four files:
1723
1724 @itemize @bullet
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}
1729 @end itemize
1730
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.
1734
1735 @lisp
1736 (define pine64-barebones-os
1737 (operating-system
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"))
1748 (mount-point "/")
1749 (type "ext4"))
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")
1755 (term "vt100")
1756 (tty "ttyS0")))
1757 %base-services))))
1758 @end lisp
1759
1760 The @code{kernel} and @code{bootloader} fields are pointing to packages
1761 dedicated to this board.
1762
1763 Right below, the @code{pine64-image-type} variable is also defined.
1764
1765 @lisp
1766 (define pine64-image-type
1767 (image-type
1768 (name 'pine64-raw)
1769 (constructor (cut image-with-os arm64-disk-image <>))))
1770 @end lisp
1771
1772 It's using a record we haven't talked about yet, the @code{image-type} record,
1773 defined this way:
1774
1775 @lisp
1776 (define-record-type* <image-type>
1777 image-type make-image-type
1778 image-type?
1779 (name image-type-name) ;symbol
1780 (constructor image-type-constructor)) ;<operating-system> -> <image>
1781 @end lisp
1782
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:
1787
1788 @example
1789 guix system image my-os.scm
1790 @end example
1791
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:
1796
1797 @example
1798 guix system image --image-type=pine64-raw my-os.scm
1799 @end example
1800
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.
1805
1806 The resulting image looks like:
1807
1808 @lisp
1809 (image
1810 (format 'disk-image)
1811 (target "aarch64-linux-gnu")
1812 (operating-system my-os)
1813 (partitions
1814 (list (partition
1815 (inherit root-partition)
1816 (offset root-offset)))))
1817 @end lisp
1818
1819 which is the aggregation of the @code{operating-system} defined in
1820 @code{my-os.scm} to the @code{arm64-disk-image} record.
1821
1822 But enough Scheme madness. What does this image API bring to the Guix user?
1823
1824 One can run:
1825
1826 @example
1827 mathieu@@cervin:~$ guix system --list-image-types
1828 The available image types are:
1829
1830 - pinebook-pro-raw
1831 - pine64-raw
1832 - novena-raw
1833 - hurd-raw
1834 - hurd-qcow2
1835 - qcow2
1836 - uncompressed-iso9660
1837 - efi-raw
1838 - arm64-raw
1839 - arm32-raw
1840 - iso9660
1841 @end example
1842
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:
1846
1847 @lisp
1848 (use-modules (gnu services linux)
1849 (gnu system images pine64))
1850
1851 (let ((base-os pine64-barebones-os))
1852 (operating-system
1853 (inherit base-os)
1854 (timezone "America/Indiana/Indianapolis")
1855 (services
1856 (cons
1857 (service earlyoom-service-type
1858 (earlyoom-configuration
1859 (prefer-regexp "icecat|chromium")))
1860 (operating-system-user-services base-os)))))
1861 @end lisp
1862
1863 run:
1864
1865 @example
1866 guix system image --image-type=pine64-raw my-pine-os.scm
1867 @end example
1868
1869 or,
1870
1871 @example
1872 guix system image --image-type=hurd-raw my-hurd-os.scm
1873 @end example
1874
1875 to get an image that can be written directly to a hard drive and booted
1876 from.
1877
1878 Without changing anything to @code{my-hurd-os.scm}, calling:
1879
1880 @example
1881 guix system image --image-type=hurd-qcow2 my-hurd-os.scm
1882 @end example
1883
1884 will instead produce a Hurd QEMU image.
1885
1886 @node Connecting to Wireguard VPN
1887 @section Connecting to Wireguard VPN
1888
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}).
1892
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:
1896
1897 @lisp
1898 (use-modules (gnu))
1899 (use-service-modules desktop)
1900 (use-package-modules vpn)
1901
1902 (operating-system
1903 ;; …
1904 (services (cons (simple-service 'wireguard-module
1905 kernel-module-loader-service-type
1906 '("wireguard"))
1907 %desktop-services))
1908 (packages (cons wireguard-tools %base-packages))
1909 (kernel-loadable-modules (list wireguard-linux-compat)))
1910 @end lisp
1911
1912 After reconfiguring and restarting your system you can either use
1913 Wireguard tools or NetworkManager to connect to a VPN server.
1914
1915 @subsection Using Wireguard tools
1916
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}
1920 instead.
1921
1922 @quotation Note
1923 Be warned that the author described this command as a: “[…] very quick
1924 and dirty bash script […]”.
1925 @end quotation
1926
1927 @subsection Using NetworkManager
1928
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
1934 Guix system.
1935
1936 To import your VPN configuration execute nmcli import command:
1937
1938 @example shell
1939 # nmcli connection import type wireguard file wg0.conf
1940 Connection 'wg0' (edbee261-aa5a-42db-b032-6c7757c60fde) successfully added
1941 @end example
1942
1943 This will create a configuration file in
1944 @file{/etc/NetworkManager/wg0.nmconnection}. Next connect to the
1945 Wireguard server:
1946
1947 @example shell
1948 $ nmcli connection up wg0
1949 Connection successfully activated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/6)
1950 @end example
1951
1952 By default NetworkManager will connect automatically on system boot. To
1953 change that behaviour you need to edit your config:
1954
1955 @example shell
1956 # nmcli connection modify wg0 connection.autoconnect no
1957 @end example
1958
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}.
1962
1963 @node Customizing a Window Manager
1964 @section Customizing a Window Manager
1965 @cindex wm
1966
1967 @node StumpWM
1968 @subsection StumpWM
1969 @cindex stumpwm
1970
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}.
1974
1975 An example configuration can look like this:
1976
1977 @lisp
1978 (use-modules (gnu))
1979 (use-package-modules wm)
1980
1981 (operating-system
1982 ;; …
1983 (packages (append (list sbcl stumpwm `(,stumpwm "lib"))
1984 %base-packages)))
1985 @end lisp
1986
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:
1991
1992 @lisp
1993 (use-modules (gnu))
1994 (use-package-modules fonts wm)
1995
1996 (operating-system
1997 ;; …
1998 (packages (append (list sbcl stumpwm `(,stumpwm "lib"))
1999 sbcl-ttf-fonts font-dejavu %base-packages)))
2000 @end lisp
2001
2002 Then you need to add the following code to a StumpWM configuration file
2003 @file{~/.stumpwm.d/init.lisp}:
2004
2005 @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"))
2009 (xft:cache-fonts)
2010 (set-font (make-instance 'xft:font :family "DejaVu Sans Mono" :subfamily "Book" :size 11))
2011 @end lisp
2012
2013 @node Session lock
2014 @subsection Session lock
2015 @cindex sessionlock
2016
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.
2021
2022 @node Xorg
2023 @subsubsection Xorg
2024
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.
2029
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}:
2032
2033 @example
2034 xss-lock -- slock &
2035 exec stumpwm
2036 @end example
2037
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.
2040
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}:
2044
2045 @lisp
2046 (screen-locker-service slock)
2047 @end lisp
2048
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.
2053
2054 @node Running Guix on a Linode Server
2055 @section Running Guix on a Linode Server
2056 @cindex linode, Linode
2057
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.
2061
2062 @example
2063 ssh-keygen
2064 @end example
2065
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:
2070
2071 @example
2072 cat ~/.ssh/<username>_rsa.pub
2073 @end example
2074
2075 Power the Linode down.
2076
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:
2080
2081 @itemize @bullet
2082 @item
2083 Label: "Guix"
2084
2085 @item
2086 Filesystem: ext4
2087
2088 @item
2089 Set it to the remaining size
2090 @end itemize
2091
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.
2095
2096 Now "Add a Configuration", with the following:
2097 @itemize @bullet
2098 @item
2099 Label: Guix
2100
2101 @item
2102 Kernel:GRUB 2 (it's at the bottom! This step is @b{IMPORTANT!})
2103
2104 @item
2105 Block device assignment:
2106
2107 @item
2108 @file{/dev/sda}: Guix
2109
2110 @item
2111 @file{/dev/sdb}: swap
2112
2113 @item
2114 Root device: @file{/dev/sda}
2115
2116 @item
2117 Turn off all the filesystem/boot helpers
2118 @end itemize
2119
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:
2125
2126 @example
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
2131 ./guix-install.sh
2132 guix pull
2133 @end example
2134
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}.
2137
2138 @lisp
2139 (use-modules (gnu)
2140 (guix modules))
2141 (use-service-modules networking
2142 ssh)
2143 (use-package-modules admin
2144 certs
2145 package-management
2146 ssh
2147 tls)
2148
2149 (operating-system
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
2156 (bootloader
2157 (bootloader
2158 (inherit grub-bootloader)
2159 (installer #~(const #true))))))
2160 (file-systems (cons (file-system
2161 (device "/dev/sda")
2162 (mount-point "/")
2163 (type "ext4"))
2164 %base-file-systems))
2165
2166
2167 (swap-devices (list "/dev/sdb"))
2168
2169
2170 (initrd-modules (cons "virtio_scsi" ; Needed to find the disk
2171 %base-initrd-modules))
2172
2173 (users (cons (user-account
2174 (name "janedoe")
2175 (group "users")
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))
2181
2182 (packages (cons* nss-certs ;for HTTPS access
2183 openssh-sans-x
2184 %base-packages))
2185
2186 (services (cons*
2187 (service dhcp-client-service-type)
2188 (service openssh-service-type
2189 (openssh-configuration
2190 (openssh openssh-sans-x)
2191 (password-authentication? #false)
2192 (authorized-keys
2193 `(("janedoe" ,(local-file "janedoe_rsa.pub"))
2194 ("root" ,(local-file "janedoe_rsa.pub"))))))
2195 %base-services)))
2196 @end lisp
2197
2198 Replace the following fields in the above configuration:
2199 @lisp
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
2207 @end lisp
2208
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
2213 login.
2214
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
2218 these commands.
2219
2220 @example
2221 sftp root@@<remote server ip address>
2222 put /path/to/files/<username>_rsa.pub .
2223 put /path/to/files/guix-config.scm .
2224 @end example
2225
2226 In your first terminal, mount the guix drive:
2227
2228 @example
2229 mkdir /mnt/guix
2230 mount /dev/sdc /mnt/guix
2231 @end example
2232
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:
2236
2237 @example
2238 mkdir -p /mnt/guix/boot/grub
2239 cp -r /boot/grub/* /mnt/guix/boot/grub/
2240 @end example
2241
2242 Now initialize the Guix installation:
2243
2244 @example
2245 guix system init guix-config.scm /mnt/guix
2246 @end example
2247
2248 Ok, power it down!
2249 Now from the Linode console, select boot and select "Guix".
2250
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:
2253
2254 @example
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.
2269 @end example
2270
2271 Either delete @file{~/.ssh/known_hosts} file, or delete the offending line
2272 starting with your server IP address.
2273
2274 Be sure to set your password and root's password.
2275
2276 @example
2277 ssh root@@<remote ip address>
2278 passwd ; for the root password
2279 passwd <username> ; for the user password
2280 @end example
2281
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.
2287
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.
2290 Congratulations!
2291
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.
2296
2297 @node Setting up a bind mount
2298 @section Setting up a bind mount
2299
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}.
2305
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.
2308
2309 @lisp
2310 (define source-drive ;; "source-drive" can be named anything you want.
2311 (file-system
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.
2315 @end lisp
2316
2317 The source folder must also be defined, so that guix will know it's not
2318 a regular block device, but a folder.
2319 @lisp
2320 (define (%source-directory) "/path-to-spinning-disk-goes-here/tmp") ;; "source-directory" can be named any valid variable name.
2321 @end lisp
2322
2323 Finally, inside the @code{file-systems} definition, we must add the
2324 mount itself.
2325
2326 @lisp
2327 (file-systems (cons*
2328
2329 ...<other drives omitted for clarity>...
2330
2331 source-drive ;; Must match the name you gave the source drive in the earlier definition.
2332
2333 (file-system
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.
2339 )
2340
2341 ...<other drives omitted for clarity>...
2342
2343 ))
2344 @end lisp
2345
2346 @node Getting substitutes from Tor
2347 @section Getting substitutes from Tor
2348
2349 Guix daemon can use a HTTP proxy to get substitutes, here we are
2350 configuring it to get them via Tor.
2351
2352 @quotation Warning
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
2357 at your own risk.
2358
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
2363 through Tor.
2364 @end quotation
2365
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
2368 follow:
2369
2370 @lisp
2371 (use-modules (gnu))
2372 (use-service-module base networking)
2373
2374 (operating-system
2375
2376 (services
2377 (cons
2378 (service tor-service-type
2379 (tor-configuration
2380 (config-file (plain-file "tor-config"
2381 "HTTPTunnelPort 127.0.0.1:9250"))))
2382 (modify-services %base-services
2383 (guix-service-type
2384 config => (guix-configuration
2385 (inherit config)
2386 ;; ci.guix.gnu.org's Onion service
2387 (substitute-urls
2388 "@value{SUBSTITUTE-TOR-URL}")
2389 (http-proxy "http://localhost:9250")))))))
2390 @end lisp
2391
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.
2399
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:
2403
2404 @example
2405 sudo herd set-http-proxy guix-daemon http://localhost:9250
2406 guix build \
2407 --substitute-urls=@value{SUBSTITUTE-TOR-URL} @dots{}
2408 @end example
2409
2410 @node Setting up NGINX with Lua
2411 @section Setting up NGINX with Lua
2412 @cindex nginx, lua, openresty, resty
2413
2414 NGINX could be extended with Lua scripts.
2415
2416 Guix provides NGINX service with ability to load Lua module and specific
2417 Lua packages, and reply to requests by evaluating Lua scripts.
2418
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:
2422
2423 @example
2424 local shell = require "resty.shell"
2425
2426 local stdin = ""
2427 local timeout = 1000 -- ms
2428 local max_size = 4096 -- byte
2429
2430 local ok, stdout, stderr, reason, status =
2431 shell.run([[/run/current-system/profile/bin/ls /tmp]], stdin, timeout, max_size)
2432
2433 ngx.say(stdout)
2434 @end example
2435
2436 @lisp
2437 (use-modules (gnu))
2438 (use-service-modules #;… web)
2439 (use-package-modules #;… lua)
2440 (operating-system
2441 ;; …
2442 (services
2443 ;; …
2444 (service nginx-service-type
2445 (nginx-configuration
2446 (modules
2447 (list
2448 (file-append nginx-lua-module "/etc/nginx/modules/ngx_http_lua_module.so")))
2449 (lua-package-path (list lua-resty-core
2450 lua-resty-lrucache
2451 lua-resty-signal
2452 lua-tablepool
2453 lua-resty-shell))
2454 (lua-package-cpath (list lua-resty-signal))
2455 (server-blocks
2456 (list (nginx-server-configuration
2457 (server-name '("localhost"))
2458 (listen '("80"))
2459 (root "/etc")
2460 (locations (list
2461 (nginx-location-configuration
2462 (uri "/hello")
2463 (body (list #~(format #f "content_by_lua_file ~s;"
2464 #$(local-file "index.lua"))))))))))))))
2465 @end lisp
2466
2467 @node Music Server with Bluetooth Audio
2468 @section Music Server with Bluetooth Audio
2469 @cindex mpd
2470 @cindex music server, headless
2471 @cindex bluetooth, ALSA configuration
2472
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.
2478
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.
2485
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.
2491
2492 Reconfigure your system with at least the following services and
2493 packages:
2494
2495 @lisp
2496 (operating-system
2497 ;; …
2498 (packages (cons* bluez bluez-alsa
2499 %base-packages))
2500 (services
2501 ;; …
2502 (dbus-service #:services (list bluez-alsa))
2503 (bluetooth-service #:auto-enable? #t)))
2504 @end lisp
2505
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:
2511
2512 @example
2513 $ bluetoothctl
2514 [NEW] Controller 00:11:22:33:95:7F BlueZ 5.40 [default]
2515
2516 [bluetooth]# power on
2517 [bluetooth]# Changing power on succeeded
2518
2519 [bluetooth]# agent on
2520 [bluetooth]# Agent registered
2521
2522 [bluetooth]# default-agent
2523 [bluetooth]# Default agent request successful
2524
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
2530 @dots{}
2531
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
2535
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
2540 Pairing successful
2541
2542 [CHG] Device AA:BB:CC:A4:AA:CD Connected: no
2543
2544 [bluetooth]#
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
2548
2549 [bluetooth]#
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
2555
2556 [My Bluetooth Speaker]# scan off
2557 [CHG] Device AA:BB:CC:A4:AA:CD RSSI is nil
2558 Discovery stopped
2559 [CHG] Controller 00:11:22:33:95:7F Discovering: no
2560 @end example
2561
2562 Congratulations, you can now automatically connect to your Bluetooth
2563 speaker!
2564
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.
2574
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.
2581
2582 What follows is the outline of an @code{operating-system} declaration
2583 that should accomplish the above-mentioned tasks:
2584
2585 @lisp
2586 (use-modules (gnu))
2587 (use-service-modules audio dbus sound #;… etc)
2588 (use-package-modules audio linux #;… etc)
2589 (operating-system
2590 ;; …
2591 (packages (cons* bluez bluez-alsa
2592 %base-packages))
2593 (services
2594 ;; …
2595 (service mpd-service-type
2596 (mpd-configuration
2597 (user "your-username")
2598 (music-dir "/path/to/your/music")
2599 (address "192.168.178.20")
2600 (outputs (list (mpd-output
2601 (type "alsa")
2602 (name "MPD")
2603 (extra-options
2604 ;; Use the same name as in the ALSA
2605 ;; configuration below.
2606 '((device . "pcm.btspeaker"))))
2607 (mpd-output
2608 (type "httpd")
2609 (name "streaming")
2610 (enabled? #false)
2611 (always-on? #true)
2612 (tags? #true)
2613 (mixer-type 'null)
2614 (extra-options
2615 '((encoder . "vorbis")
2616 (port . "8080")
2617 (bind-to-address . "192.168.178.20")
2618 (max-clients . "0") ;no limit
2619 (quality . "5.0")
2620 (format . "44100:16:1"))))))))
2621 (dbus-service #:services (list bluez-alsa))
2622 (bluetooth-service #:auto-enable? #t)
2623 (service alsa-service-type
2624 (alsa-configuration
2625 (pulseaudio? #false) ;we don't need it
2626 (extra-options
2627 #~(string-append "\
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") "\"
2631 @}
2632
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") "\"
2636 @}
2637
2638 # Define the actual Bluetooth audio device.
2639 pcm.btspeaker @{
2640 type bluealsa
2641 device \"AA:BB:CC:A4:AA:CD\" # unique device identifier
2642 profile \"a2dp\"
2643 @}
2644
2645 # Define an associated controller.
2646 ctl.btspeaker @{
2647 type bluealsa
2648 @}
2649 "))))))
2650 @end lisp
2651
2652 Enjoy the music with the MPD client of your choice or a media player
2653 capable of streaming via HTTP!
2654
2655
2656 @c *********************************************************************
2657 @node Containers
2658 @chapter Containers
2659
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
2666 view on the system.
2667
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.
2673
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
2679 system-wide.
2680
2681 @menu
2682 * Guix Containers:: Perfectly isolated environments
2683 * Guix System Containers:: A system inside your system
2684 @end menu
2685
2686 @node Guix Containers
2687 @section Guix Containers
2688
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.
2692
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.
2699
2700 @example
2701 guix shell --container
2702 @end example
2703
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
2708 itself.
2709
2710 @example sh
2711 $ echo /gnu/store/*
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
2719 @end example
2720
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.
2725
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.
2737
2738 @example sh
2739 $ guix shell --container --share=/etc=/the/host/etc coreutils
2740 $ ls /the/host/etc
2741 @end example
2742
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
2747 directory.
2748
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.
2760
2761 Let's take a comprehensive manifest providing a comfortable development
2762 environment for use with R:
2763
2764 @lisp
2765 (specifications->manifest
2766 (list "r-minimal"
2767
2768 ;; base packages
2769 "bash-minimal"
2770 "glibc-locales"
2771 "nss-certs"
2772
2773 ;; Common command line tools lest the container is too empty.
2774 "coreutils"
2775 "grep"
2776 "which"
2777 "wget"
2778 "sed"
2779
2780 ;; R markdown tools
2781 "pandoc"
2782
2783 ;; Toolchain and common libraries for "install.packages"
2784 "gcc-toolchain@@10"
2785 "gfortran-toolchain"
2786 "gawk"
2787 "tar"
2788 "gzip"
2789 "unzip"
2790 "make"
2791 "cmake"
2792 "pkg-config"
2793 "cairo"
2794 "libxt"
2795 "openssl"
2796 "curl"
2797 "zlib"))
2798 @end lisp
2799
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.
2804
2805 @example sh
2806 $ guix shell --container --network --manifest=manifest.scm -- R
2807
2808 R version 4.2.1 (2022-06-23) -- "Funny-Looking Kid"
2809 Copyright (C) 2022 The R Foundation for Statistical Computing
2810 @dots{}
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()))
2816 @dots{}
2817 * installing *source* package 'Cairo' ...
2818 @dots{}
2819 * DONE (Cairo)
2820
2821 The downloaded source packages are in
2822 '/tmp/RtmpCuwdwM/downloaded_packages'
2823 > library("Cairo", lib=getwd())
2824 > # success!
2825 @end example
2826
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
2832 container.
2833
2834
2835 @node Guix System Containers
2836 @section Guix System Containers
2837
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
2846 declare.
2847
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}).
2858
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.
2865
2866
2867 @node A Database Container
2868 @subsection A Database Container
2869
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:
2873
2874 @lisp
2875 (service postgresql-service-type
2876 (postgresql-configuration
2877 (postgresql postgresql-14)))
2878 @end lisp
2879
2880 A complete operating system declaration for use with a Guix System
2881 container would look something like this:
2882
2883 @lisp
2884 (use-modules (gnu))
2885 (use-package-modules databases)
2886 (use-service-modules databases)
2887
2888 (operating-system
2889 (host-name "container")
2890 (timezone "Europe/Berlin")
2891 (file-systems (cons (file-system
2892 (device (file-system-label "does-not-matter"))
2893 (mount-point "/")
2894 (type "ext4"))
2895 %base-file-systems))
2896 (bootloader (bootloader-configuration
2897 (bootloader grub-bootloader)
2898 (targets '("/dev/sdX"))))
2899 (services
2900 (cons* (service postgresql-service-type
2901 (postgresql-configuration
2902 (postgresql postgresql-14)
2903 (config-file
2904 (postgresql-config-file
2905 (log-destination "stderr")
2906 (hba-file
2907 (plain-file "pg_hba.conf"
2908 "\
2909 local all all trust
2910 host all all 10.0.0.1/32 trust"))
2911 (extra-config
2912 '(("listen_addresses" "*")
2913 ("log_directory" "/var/log/postgresql")))))))
2914 (service postgresql-role-service-type
2915 (postgresql-role-configuration
2916 (roles
2917 (list (postgresql-role
2918 (name "test")
2919 (create-database? #t))))))
2920 %base-services)))
2921 @end lisp
2922
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
2928 this example.
2929
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
2934 Manual}).
2935
2936 @example
2937 $ guix system container os.scm
2938 The following derivations will be built:
2939 /gnu/store/@dots{}-run-container.drv
2940 @dots{}
2941 building /gnu/store/@dots{}-run-container.drv...
2942 /gnu/store/@dots{}-run-container
2943 @end example
2944
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}.
2949
2950 @example
2951 $ sudo /gnu/store/@dots{}-run-container
2952 system container is running as PID 5983
2953 @dots{}
2954 @end example
2955
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:
2961
2962 @example
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
2974 @end example
2975
2976 The PostgreSQL service is running in the container!
2977
2978
2979 @node Container Networking
2980 @subsection Container Networking
2981 @cindex container networking
2982
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
2986 over the network.
2987
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
2992 system.
2993
2994 @example
2995 pid=5983
2996 ns="guix-test"
2997 host="veth-test"
2998 client="ceth-test"
2999
3000 # Attach the new net namespace "guix-test" to the container PID.
3001 sudo ip netns attach $ns $pid
3002
3003 # Create the pair of devices
3004 sudo ip link add $host type veth peer name $client
3005
3006 # Move the client device into the container's net namespace
3007 sudo ip link set $client netns $ns
3008 @end example
3009
3010 Then we configure the host side:
3011
3012 @example
3013 sudo ip link set $host up
3014 sudo ip addr add 10.0.0.1/24 dev $host
3015 @end example
3016
3017 @dots{}and then we configure the client side:
3018
3019 @example
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
3023 @end example
3024
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.
3029
3030 @example
3031 $ psql -h 10.0.0.2 -U test
3032 psql (14.4)
3033 Type "help" for help.
3034
3035 test=> CREATE TABLE hello (who TEXT NOT NULL);
3036 CREATE TABLE
3037 test=> INSERT INTO hello (who) VALUES ('world');
3038 INSERT 0 1
3039 test=> SELECT * FROM hello;
3040 who
3041 -------
3042 world
3043 (1 row)
3044 @end example
3045
3046 Now that we're done with this little demonstration let's clean up:
3047
3048 @example
3049 sudo kill $pid
3050 sudo ip netns del $ns
3051 sudo ip link del $host
3052 @end example
3053
3054
3055 @c *********************************************************************
3056 @node Advanced package management
3057 @chapter Advanced package management
3058
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
3063 concepts.
3064
3065 @pxref{Package Management,,, guix, GNU Guix Reference Manual} for a complete
3066 reference.
3067
3068 @menu
3069 * Guix Profiles in Practice:: Strategies for multiple profiles and manifests.
3070 @end menu
3071
3072 @node Guix Profiles in Practice
3073 @section Guix Profiles in Practice
3074
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.
3078
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.
3083
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.
3089
3090 Multiple profiles have many benefits:
3091
3092 @itemize
3093 @item
3094 Clean semantic separation of the various packages a user needs for different contexts.
3095
3096 @item
3097 Multiple profiles can be made available into the environment either on login
3098 or within a dedicated shell.
3099
3100 @item
3101 Profiles can be loaded on demand. For instance, the user can use multiple
3102 shells, each of them running different profiles.
3103
3104 @item
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.
3108
3109 @item
3110 Deduplication: Profiles share dependencies that happens to be the exact same.
3111 This makes multiple profiles storage-efficient.
3112
3113 @item
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}.
3120
3121 @item
3122 Easier upgrades and maintenance: Multiple profiles make it easy to keep
3123 package listings at hand and make upgrades completely frictionless.
3124 @end itemize
3125
3126 Concretely, here follows some typical profiles:
3127
3128 @itemize
3129 @item
3130 The dependencies of a project you are working on.
3131
3132 @item
3133 Your favourite programming language libraries.
3134
3135 @item
3136 Laptop-specific programs (like @samp{powertop}) that you don't need on a desktop.
3137
3138 @item
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).
3141
3142 @item
3143 Games.
3144 @end itemize
3145
3146 Let's dive in the set up!
3147
3148 @node Basic setup with manifests
3149 @subsection Basic setup with manifests
3150
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:
3154
3155 @lisp
3156 (specifications->manifest
3157 '("package-1"
3158 ;; Version 1.3 of package-2.
3159 "package-2@@1.3"
3160 ;; The "lib" output of package-3.
3161 "package-3:lib"
3162 ; ...
3163 "package-N"))
3164 @end lisp
3165
3166 @xref{Writing Manifests,,, guix, GNU Guix Reference Manual}, for
3167 more information about the syntax.
3168
3169 We can create a manifest specification per profile and install them this way:
3170
3171 @example
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
3175 @end example
3176
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.
3179
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}.
3185
3186 Note that it's also possible to loop over the output of
3187
3188 @example
3189 guix package --list-profiles
3190 @end example
3191
3192 although you'll probably have to filter out @file{~/.config/guix/current}.
3193
3194 To enable all profiles on login, add this to your @file{~/.bash_profile} (or similar):
3195
3196 @example
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
3202 fi
3203 unset profile
3204 done
3205 @end example
3206
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.
3210
3211 You can obviously choose to only enable a subset of them:
3212
3213 @example
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
3219 fi
3220 unset profile
3221 done
3222 @end example
3223
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:
3226
3227 @example
3228 GUIX_PROFILE="path/to/my-project" ; . "$GUIX_PROFILE"/etc/profile
3229 @end example
3230
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:
3236
3237 @example
3238 guix package --search-paths=prefix --profile=$my_profile"
3239 @end example
3240
3241 Once again, see (@pxref{Invoking guix package,,, guix, GNU Guix Reference Manual})
3242 for the command line options.
3243
3244 To upgrade a profile, simply install the manifest again:
3245
3246 @example
3247 guix package -m /path/to/guix-my-project-manifest.scm -p "$GUIX_EXTRA_PROFILES"/my-project/my-project
3248 @end example
3249
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:
3254
3255 @example
3256 for profile in "$GUIX_EXTRA_PROFILES"/*; do
3257 guix package --profile="$profile" --manifest="$HOME/.guix-manifests/guix-$profile-manifest.scm"
3258 done
3259 @end example
3260
3261 Each profile has its own generations:
3262
3263 @example
3264 guix package -p "$GUIX_EXTRA_PROFILES"/my-project/my-project --list-generations
3265 @end example
3266
3267 You can roll-back to any generation of a given profile:
3268
3269 @example
3270 guix package -p "$GUIX_EXTRA_PROFILES"/my-project/my-project --switch-generations=17
3271 @end example
3272
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:
3275
3276 @example
3277 env -i $(which bash) --login --noprofile --norc
3278 . my-project/etc/profile
3279 @end example
3280
3281 @node Required packages
3282 @subsection Required packages
3283
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
3286 profile.
3287
3288 @emph{Note: Only the environmental variables of the packages that consume them will
3289 be set.}
3290
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:
3294
3295 @itemize
3296 @item
3297 Either export the variable manually, e.g.
3298 @example
3299 export MANPATH=/path/to/profile$@{MANPATH:+:@}$MANPATH
3300 @end example
3301
3302 @item
3303 Or include @samp{man-db} to the profile manifest.
3304 @end itemize
3305
3306 The same is true for @samp{INFOPATH} (you can install @samp{info-reader}),
3307 @samp{PKG_CONFIG_PATH} (install @samp{pkg-config}), etc.
3308
3309 @node Default profile
3310 @subsection Default profile
3311
3312 What about the default profile that Guix keeps in @file{~/.guix-profile}?
3313
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.
3316
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
3320
3321 @example
3322 guix install package-foo
3323 guix upgrade package-bar
3324 @end example
3325
3326 without having to specify the path to a profile.
3327
3328 @node The benefits of manifests
3329 @subsection The benefits of manifests
3330
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.
3333
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.
3337
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
3341 usability.
3342
3343 Manifests come with multiple benefits. In particular, they ease maintenance:
3344
3345 @itemize
3346 @item
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.
3352
3353 @item
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
3356 problem.
3357
3358 @item
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.
3363
3364 @item
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}.
3369
3370 @item
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).
3377
3378 @item
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}.
3381 @end itemize
3382
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
3388 the future.
3389
3390 Let's take an example:
3391
3392 @enumerate
3393 @item
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.
3397
3398 @item
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
3402 garbage-collected.
3403
3404 @item
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
3407 stuff!
3408 @end enumerate
3409
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.
3414
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.
3417
3418 @node Reproducible profiles
3419 @subsection Reproducible profiles
3420
3421 To reproduce a profile bit-for-bit, we need two pieces of information:
3422
3423 @itemize
3424 @item
3425 a manifest,
3426 @item
3427 a Guix channel specification.
3428 @end itemize
3429
3430 Indeed, manifests alone might not be enough: different Guix versions (or
3431 different channels) can produce different outputs for a given manifest.
3432
3433 You can output the Guix channel specification with @samp{guix describe
3434 --format=channels}.
3435 Save this to a file, say @samp{channel-specs.scm}.
3436
3437 On another computer, you can use the channel specification file and the manifest
3438 to reproduce the exact same profile:
3439
3440 @example
3441 GUIX_EXTRA_PROFILES=$HOME/.guix-extra-profiles
3442 GUIX_EXTRA=$HOME/.guix-extra
3443
3444 mkdir "$GUIX_EXTRA"/my-project
3445 guix pull --channels=channel-specs.scm --profile "$GUIX_EXTRA/my-project/guix"
3446
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
3449 @end example
3450
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.
3453
3454 @c *********************************************************************
3455 @node Environment management
3456 @chapter Environment management
3457
3458 Guix provides multiple tools to manage environment. This chapter
3459 demonstrate such utilities.
3460
3461 @menu
3462 * Guix environment via direnv:: Setup Guix environment with direnv
3463 @end menu
3464
3465 @node Guix environment via direnv
3466 @section Guix environment via direnv
3467
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
3470 environment.
3471
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
3476 Manual}.
3477
3478 Create a @file{~/.direnvrc} with a Bash code:
3479
3480 @example
3481 # Thanks <https://github.com/direnv/direnv/issues/73#issuecomment-152284914>
3482 export_function()
3483 @{
3484 local name=$1
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"
3494 chmod +x "$target"
3495 fi
3496 @}
3497
3498 use_guix()
3499 @{
3500 # Set GitHub token.
3501 export GUIX_GITHUB_TOKEN="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
3502
3503 # Unset 'GUIX_PACKAGE_PATH'.
3504 export GUIX_PACKAGE_PATH=""
3505
3506 # Recreate a garbage collector root.
3507 gcroots="$HOME/.config/guix/gcroots"
3508 mkdir -p "$gcroots"
3509 gcroot="$gcroots/guix"
3510 if [ -L "$gcroot" ]
3511 then
3512 rm -v "$gcroot"
3513 fi
3514
3515 # Miscellaneous packages.
3516 PACKAGES_MAINTENANCE=(
3517 direnv
3518 git
3519 git:send-email
3520 git-cal
3521 gnupg
3522 guile-colorized
3523 guile-readline
3524 less
3525 ncurses
3526 openssh
3527 xdot
3528 )
3529
3530 # Environment packages.
3531 PACKAGES=(help2man guile-sqlite3 guile-gcrypt)
3532
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[@@]@} "$@@")"
3535
3536 # Predefine configure flags.
3537 configure()
3538 @{
3539 ./configure --localstatedir=/var --prefix=
3540 @}
3541 export_function configure
3542
3543 # Run make and optionally build something.
3544 build()
3545 @{
3546 make -j 2
3547 if [ $# -gt 0 ]
3548 then
3549 ./pre-inst-env guix build "$@@"
3550 fi
3551 @}
3552 export_function build
3553
3554 # Predefine push Git command.
3555 push()
3556 @{
3557 git push --set-upstream origin
3558 @}
3559 export_function push
3560
3561 clear # Clean up the screen.
3562 git-cal --author='Your Name' # Show contributions calendar.
3563
3564 # Show commands help.
3565 echo "
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
3569 "
3570 @}
3571 @end example
3572
3573 Every project containing @file{.envrc} with a string @code{use guix}
3574 will have predefined environment variables and procedures.
3575
3576 Run @command{direnv allow} to setup the environment for the first time.
3577
3578 @c *********************************************************************
3579 @node Acknowledgments
3580 @chapter Acknowledgments
3581
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.
3589
3590 The Nix-based software distributions, Nixpkgs and NixOS, have also been
3591 an inspiration for Guix.
3592
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!
3598
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}.
3601
3602
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
3608
3609 @c *********************************************************************
3610 @node Concept Index
3611 @unnumbered Concept Index
3612 @printindex cp
3613
3614 @bye
3615
3616 @c Local Variables:
3617 @c ispell-local-dictionary: "american";
3618 @c End: