guix-cookbook.texi 145 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099
  1. \input texinfo
  2. @c -*-texinfo-*-
  3. @c %**start of header
  4. @setfilename guix-cookbook.info
  5. @documentencoding UTF-8
  6. @settitle GNU Guix Cookbook
  7. @c %**end of header
  8. @c Onion service for ci.guix.gnu.org.
  9. @set SUBSTITUTE-TOR-URL https://4zwzi66wwdaalbhgnix55ea3ab4pvvw66ll2ow53kjub6se4q2bclcyd.onion
  10. @copying
  11. Copyright @copyright{} 2019, 2022 Ricardo Wurmus@*
  12. Copyright @copyright{} 2019 Efraim Flashner@*
  13. Copyright @copyright{} 2019 Pierre Neidhardt@*
  14. Copyright @copyright{} 2020 Oleg Pykhalov@*
  15. Copyright @copyright{} 2020 Matthew Brooks@*
  16. Copyright @copyright{} 2020 Marcin Karpezo@*
  17. Copyright @copyright{} 2020 Brice Waegeneire@*
  18. Copyright @copyright{} 2020 André Batista@*
  19. Copyright @copyright{} 2020 Christine Lemmer-Webber@*
  20. Copyright @copyright{} 2021 Joshua Branson@*
  21. Copyright @copyright{} 2022 Maxim Cournoyer@*
  22. Copyright @copyright{} 2023 Ludovic Courtès
  23. Permission is granted to copy, distribute and/or modify this document
  24. under the terms of the GNU Free Documentation License, Version 1.3 or
  25. any later version published by the Free Software Foundation; with no
  26. Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A
  27. copy of the license is included in the section entitled ``GNU Free
  28. Documentation License''.
  29. @end copying
  30. @dircategory System administration
  31. @direntry
  32. * Guix cookbook: (guix-cookbook). Tutorials and examples for GNU Guix.
  33. @end direntry
  34. @titlepage
  35. @title GNU Guix Cookbook
  36. @subtitle Tutorials and examples for using the GNU Guix Functional Package Manager
  37. @author The GNU Guix Developers
  38. @page
  39. @vskip 0pt plus 1filll
  40. @insertcopying
  41. @end titlepage
  42. @contents
  43. @c *********************************************************************
  44. @node Top
  45. @top GNU Guix Cookbook
  46. This document presents tutorials and detailed examples for GNU@tie{}Guix, a
  47. functional package management tool written for the GNU system. Please
  48. @pxref{Top,,, guix, GNU Guix reference manual} for details about the system,
  49. its API, and related concepts.
  50. @c TRANSLATORS: You can replace the following paragraph with information on
  51. @c how to join your own translation team and how to report issues with the
  52. @c translation.
  53. This manual is also available in French (@pxref{Top,,, guix-cookbook.fr,
  54. Livre de recettes de GNU Guix}), German (@pxref{Top,,,
  55. guix-cookbook.de, GNU-Guix-Kochbuch}) and Slovak (@pxref{Top,,,
  56. guix-cookbook.sk, Receptár GNU Guix}). If you would like to translate
  57. this document in your native language, consider joining
  58. @uref{https://translate.fedoraproject.org/projects/guix/documentation-cookbook,
  59. Weblate} (@pxref{Translating Guix,,, guix, GNU Guix reference
  60. manual}).
  61. @menu
  62. * Scheme tutorials:: Meet your new favorite language!
  63. * Packaging:: Packaging tutorials
  64. * System Configuration:: Customizing the GNU System
  65. * Containers:: Isolated environments and nested systems
  66. * Advanced package management:: Power to the users!
  67. * Environment management:: Control environment
  68. * Installing Guix on a Cluster:: High-performance computing.
  69. * Acknowledgments:: Thanks!
  70. * GNU Free Documentation License:: The license of this document.
  71. * Concept Index:: Concepts.
  72. @detailmenu
  73. --- The Detailed Node Listing ---
  74. Packaging
  75. * Packaging Tutorial:: A tutorial on how to add packages to Guix.
  76. System Configuration
  77. * Auto-Login to a Specific TTY:: Automatically Login a User to a Specific TTY
  78. * Customizing the Kernel:: Creating and using a custom Linux kernel on Guix System.
  79. * Guix System Image API:: Customizing images to target specific platforms.
  80. * Using security keys:: How to use security keys with Guix System.
  81. * Connecting to Wireguard VPN:: Connecting to a Wireguard VPN.
  82. * Customizing a Window Manager:: Handle customization of a Window manager on Guix System.
  83. * Running Guix on a Linode Server:: Running Guix on a Linode Server
  84. * Setting up a bind mount:: Setting up a bind mount in the file-systems definition.
  85. * Getting substitutes from Tor:: Configuring Guix daemon to get substitutes through Tor.
  86. * Setting up NGINX with Lua:: Configuring NGINX web-server to load Lua modules.
  87. * Music Server with Bluetooth Audio:: Headless music player with Bluetooth output.
  88. Containers
  89. * Guix Containers:: Perfectly isolated environments
  90. * Guix System Containers:: A system inside your system
  91. Advanced package management
  92. * Guix Profiles in Practice:: Strategies for multiple profiles and manifests.
  93. Environment management
  94. * Guix environment via direnv:: Setup Guix environment with direnv
  95. Installing Guix on a Cluster
  96. * Setting Up a Head Node:: The node that runs the daemon.
  97. * Setting Up Compute Nodes:: Client nodes.
  98. * Cluster Network Access:: Dealing with network access restrictions.
  99. * Cluster Disk Usage:: Disk usage considerations.
  100. * Cluster Security Considerations:: Keeping the cluster secure.
  101. @end detailmenu
  102. @end menu
  103. @c *********************************************************************
  104. @node Scheme tutorials
  105. @chapter Scheme tutorials
  106. GNU@tie{}Guix is written in the general purpose programming language Scheme,
  107. and many of its features can be accessed and manipulated programmatically.
  108. You can use Scheme to generate package definitions, to modify them, to build
  109. them, to deploy whole operating systems, etc.
  110. Knowing the basics of how to program in Scheme will unlock many of the
  111. advanced features Guix provides --- and you don't even need to be an
  112. experienced programmer to use them!
  113. Let's get started!
  114. @node A Scheme Crash Course
  115. @section A Scheme Crash Course
  116. @cindex Scheme, crash course
  117. Guix uses the Guile implementation of Scheme. To start playing with the
  118. language, install it with @code{guix install guile} and start a
  119. @dfn{REPL}---short for @uref{https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop,
  120. @dfn{read-eval-print loop}}---by running @code{guile} from the command line.
  121. Alternatively you can also run @code{guix shell guile -- guile}
  122. if you'd rather not have Guile installed in your user profile.
  123. In the following examples, lines show what you would type at the REPL;
  124. lines starting with ``@result{}'' show evaluation results, while lines
  125. starting with ``@print{}'' show things that get printed. @xref{Using Guile
  126. Interactively,,, guile, GNU Guile Reference Manual}, for more details on the
  127. REPL.
  128. @itemize
  129. @item
  130. Scheme syntax boils down to a tree of expressions (or @emph{s-expression} in
  131. Lisp lingo). An expression can be a literal such as numbers and strings, or a
  132. compound which is a parenthesized list of compounds and literals. @code{#true}
  133. and @code{#false} (abbreviated @code{#t} and @code{#f}) stand for the
  134. Booleans ``true'' and ``false'', respectively.
  135. Examples of valid expressions:
  136. @lisp
  137. "Hello World!"
  138. @result{} "Hello World!"
  139. 17
  140. @result{} 17
  141. (display (string-append "Hello " "Guix" "\n"))
  142. @print{} Hello Guix!
  143. @result{} #<unspecified>
  144. @end lisp
  145. @item
  146. This last example is a function call nested in another function call. When a
  147. parenthesized expression is evaluated, the first term is the function and the
  148. rest are the arguments passed to the function. Every function returns the
  149. last evaluated expression as its return value.
  150. @item
  151. Anonymous functions are declared with the @code{lambda} term:
  152. @lisp
  153. (lambda (x) (* x x))
  154. @result{} #<procedure 120e348 at <unknown port>:24:0 (x)>
  155. @end lisp
  156. The above procedure returns the square of its argument. Since everything is
  157. an expression, the @code{lambda} expression returns an anonymous procedure,
  158. which can in turn be applied to an argument:
  159. @lisp
  160. ((lambda (x) (* x x)) 3)
  161. @result{} 9
  162. @end lisp
  163. @item
  164. Anything can be assigned a global name with @code{define}:
  165. @lisp
  166. (define a 3)
  167. (define square (lambda (x) (* x x)))
  168. (square a)
  169. @result{} 9
  170. @end lisp
  171. @item
  172. Procedures can be defined more concisely with the following syntax:
  173. @lisp
  174. (define (square x) (* x x))
  175. @end lisp
  176. @item
  177. A list structure can be created with the @code{list} procedure:
  178. @lisp
  179. (list 2 a 5 7)
  180. @result{} (2 3 5 7)
  181. @end lisp
  182. @item
  183. The @dfn{quote} disables evaluation of a parenthesized expression: the
  184. first term is not called over the other terms (@pxref{Expression Syntax,
  185. quote,, guile, GNU Guile Reference Manual}). Thus it effectively
  186. returns a list of terms.
  187. @lisp
  188. '(display (string-append "Hello " "Guix" "\n"))
  189. @result{} (display (string-append "Hello " "Guix" "\n"))
  190. '(2 a 5 7)
  191. @result{} (2 a 5 7)
  192. @end lisp
  193. @item
  194. The @dfn{quasiquote} disables evaluation of a parenthesized expression
  195. until @dfn{unquote} (a comma) re-enables it. Thus it provides us with
  196. fine-grained control over what is evaluated and what is not.
  197. @lisp
  198. `(2 a 5 7 (2 ,a 5 ,(+ a 4)))
  199. @result{} (2 a 5 7 (2 3 5 7))
  200. @end lisp
  201. Note that the above result is a list of mixed elements: numbers, symbols (here
  202. @code{a}) and the last element is a list itself.
  203. @item
  204. Multiple variables can be named locally with @code{let} (@pxref{Local
  205. Bindings,,, guile, GNU Guile Reference Manual}):
  206. @lisp
  207. (define x 10)
  208. (let ((x 2)
  209. (y 3))
  210. (list x y))
  211. @result{} (2 3)
  212. x
  213. @result{} 10
  214. y
  215. @error{} In procedure module-lookup: Unbound variable: y
  216. @end lisp
  217. Use @code{let*} to allow later variable declarations to refer to earlier
  218. definitions.
  219. @lisp
  220. (let* ((x 2)
  221. (y (* x 3)))
  222. (list x y))
  223. @result{} (2 6)
  224. @end lisp
  225. @item
  226. @dfn{Keywords} are typically used to identify the named parameters of a
  227. procedure. They are prefixed by @code{#:} (hash, colon) followed by
  228. alphanumeric characters: @code{#:like-this}.
  229. @xref{Keywords,,, guile, GNU Guile Reference Manual}.
  230. @item
  231. The percentage @code{%} is typically used for read-only global variables in
  232. the build stage. Note that it is merely a convention, like @code{_} in C.
  233. Scheme treats @code{%} exactly the same as any other letter.
  234. @item
  235. Modules are created with @code{define-module} (@pxref{Creating Guile
  236. Modules,,, guile, GNU Guile Reference Manual}). For instance
  237. @lisp
  238. (define-module (guix build-system ruby)
  239. #:use-module (guix store)
  240. #:export (ruby-build
  241. ruby-build-system))
  242. @end lisp
  243. defines the module @code{guix build-system ruby} which must be located in
  244. @file{guix/build-system/ruby.scm} somewhere in the Guile load path. It
  245. depends on the @code{(guix store)} module and it exports two variables,
  246. @code{ruby-build} and @code{ruby-build-system}.
  247. @end itemize
  248. @quotation Going further
  249. Scheme is a language that has been widely used to teach programming and
  250. you'll find plenty of material using it as a vehicle. Here's a
  251. selection of documents to learn more about Scheme:
  252. @itemize
  253. @item
  254. @uref{https://spritely.institute/static/papers/scheme-primer.html, @i{A
  255. Scheme Primer}}, by Christine Lemmer-Webber and the Spritely Institute.
  256. @item
  257. @uref{http://www.troubleshooters.com/codecorn/scheme_guile/hello.htm,
  258. @i{Scheme at a Glance}}, by Steve Litt.
  259. @item
  260. @c There used to be a copy at mitpress.mit.edu but it vanished.
  261. @uref{https://sarabander.github.io/sicp/,
  262. @i{Structure and Interpretation of Computer Programs}}, by Harold
  263. Abelson and Gerald Jay Sussman, with Julie Sussman. Colloquially known
  264. as ``SICP'', this book is a reference.
  265. You can also install it and read it from your computer:
  266. @example
  267. guix install sicp info-reader
  268. info sicp
  269. @end example
  270. @end itemize
  271. You'll find more books, tutorials and other resources at
  272. @url{https://schemers.org/}.
  273. @end quotation
  274. @c *********************************************************************
  275. @node Packaging
  276. @chapter Packaging
  277. @cindex packaging
  278. This chapter is dedicated to teaching you how to add packages to the
  279. collection of packages that come with GNU Guix. This involves writing package
  280. definitions in Guile Scheme, organizing them in package modules, and building
  281. them.
  282. @menu
  283. * Packaging Tutorial:: A tutorial on how to add packages to Guix.
  284. @end menu
  285. @node Packaging Tutorial
  286. @section Packaging Tutorial
  287. GNU Guix stands out as the @emph{hackable} package manager, mostly because it
  288. uses @uref{https://www.gnu.org/software/guile/, GNU Guile}, a powerful
  289. high-level programming language, one of the
  290. @uref{https://en.wikipedia.org/wiki/Scheme_%28programming_language%29, Scheme}
  291. dialects from the
  292. @uref{https://en.wikipedia.org/wiki/Lisp_%28programming_language%29, Lisp family}.
  293. Package definitions are also written in Scheme, which empowers Guix in some
  294. very unique ways, unlike most other package managers that use shell scripts or
  295. simple languages.
  296. @itemize
  297. @item
  298. Use functions, structures, macros and all of Scheme expressiveness for your
  299. package definitions.
  300. @item
  301. Inheritance makes it easy to customize a package by inheriting from it and
  302. modifying only what is needed.
  303. @item
  304. Batch processing: the whole package collection can be parsed, filtered and
  305. processed. Building a headless server with all graphical interfaces stripped
  306. out? It's possible. Want to rebuild everything from source using specific
  307. compiler optimization flags? Pass the @code{#:make-flags "..."} argument to
  308. the list of packages. It wouldn't be a stretch to think
  309. @uref{https://wiki.gentoo.org/wiki/USE_flag, Gentoo USE flags} here, but this
  310. goes even further: the changes don't have to be thought out beforehand by the
  311. packager, they can be @emph{programmed} by the user!
  312. @end itemize
  313. The following tutorial covers all the basics around package creation with Guix.
  314. It does not assume much knowledge of the Guix system nor of the Lisp language.
  315. The reader is only expected to be familiar with the command line and to have some
  316. basic programming knowledge.
  317. @node A ``Hello World'' package
  318. @subsection A ``Hello World'' package
  319. The ``Defining Packages'' section of the manual introduces the basics of Guix
  320. packaging (@pxref{Defining Packages,,, guix, GNU Guix Reference Manual}). In
  321. the following section, we will partly go over those basics again.
  322. GNU@tie{}Hello is a dummy project that serves as an idiomatic example for
  323. packaging. It uses the GNU build system (@code{./configure && make && make
  324. install}). Guix already provides a package definition which is a perfect
  325. example to start with. You can look up its declaration with @code{guix edit
  326. hello} from the command line. Let's see how it looks:
  327. @lisp
  328. (define-public hello
  329. (package
  330. (name "hello")
  331. (version "2.10")
  332. (source (origin
  333. (method url-fetch)
  334. (uri (string-append "mirror://gnu/hello/hello-" version
  335. ".tar.gz"))
  336. (sha256
  337. (base32
  338. "0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i"))))
  339. (build-system gnu-build-system)
  340. (synopsis "Hello, GNU world: An example GNU package")
  341. (description
  342. "GNU Hello prints the message \"Hello, world!\" and then exits. It
  343. serves as an example of standard GNU coding practices. As such, it supports
  344. command-line arguments, multiple languages, and so on.")
  345. (home-page "https://www.gnu.org/software/hello/")
  346. (license gpl3+)))
  347. @end lisp
  348. As you can see, most of it is rather straightforward. But let's review the
  349. fields together:
  350. @table @samp
  351. @item name
  352. The project name. Using Scheme conventions, we prefer to keep it
  353. lower case, without underscore and using dash-separated words.
  354. @item source
  355. This field contains a description of the source code origin. The
  356. @code{origin} record contains these fields:
  357. @enumerate
  358. @item The method, here @code{url-fetch} to download via HTTP/FTP, but other methods
  359. exist, such as @code{git-fetch} for Git repositories.
  360. @item The URI, which is typically some @code{https://} location for @code{url-fetch}. Here
  361. the special `mirror://gnu` refers to a set of well known locations, all of
  362. which can be used by Guix to fetch the source, should some of them fail.
  363. @item The @code{sha256} checksum of the requested file. This is essential to ensure
  364. the source is not corrupted. Note that Guix works with base32 strings,
  365. hence the call to the @code{base32} function.
  366. @end enumerate
  367. @item build-system
  368. This is where the power of abstraction provided by the Scheme language really
  369. shines: in this case, the @code{gnu-build-system} abstracts away the famous
  370. @code{./configure && make && make install} shell invocations. Other build
  371. systems include the @code{trivial-build-system} which does not do anything and
  372. requires from the packager to program all the build steps, the
  373. @code{python-build-system}, the @code{emacs-build-system}, and many more
  374. (@pxref{Build Systems,,, guix, GNU Guix Reference Manual}).
  375. @item synopsis
  376. It should be a concise summary of what the package does. For many packages a
  377. tagline from the project's home page can be used as the synopsis.
  378. @item description
  379. Same as for the synopsis, it's fine to re-use the project description from the
  380. homepage. Note that Guix uses Texinfo syntax.
  381. @item home-page
  382. Use HTTPS if available.
  383. @item license
  384. See @code{guix/licenses.scm} in the project source for a full list of
  385. available licenses.
  386. @end table
  387. Time to build our first package! Nothing fancy here for now: we will stick to a
  388. dummy @code{my-hello}, a copy of the above declaration.
  389. As with the ritualistic ``Hello World'' taught with most programming languages,
  390. this will possibly be the most ``manual'' approach. We will work out an ideal
  391. setup later; for now we will go the simplest route.
  392. Save the following to a file @file{my-hello.scm}.
  393. @lisp
  394. (use-modules (guix packages)
  395. (guix download)
  396. (guix build-system gnu)
  397. (guix licenses))
  398. (package
  399. (name "my-hello")
  400. (version "2.10")
  401. (source (origin
  402. (method url-fetch)
  403. (uri (string-append "mirror://gnu/hello/hello-" version
  404. ".tar.gz"))
  405. (sha256
  406. (base32
  407. "0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i"))))
  408. (build-system gnu-build-system)
  409. (synopsis "Hello, Guix world: An example custom Guix package")
  410. (description
  411. "GNU Hello prints the message \"Hello, world!\" and then exits. It
  412. serves as an example of standard GNU coding practices. As such, it supports
  413. command-line arguments, multiple languages, and so on.")
  414. (home-page "https://www.gnu.org/software/hello/")
  415. (license gpl3+))
  416. @end lisp
  417. We will explain the extra code in a moment.
  418. Feel free to play with the different values of the various fields. If you
  419. change the source, you'll need to update the checksum. Indeed, Guix refuses to
  420. build anything if the given checksum does not match the computed checksum of the
  421. source code. To obtain the correct checksum of the package declaration, we
  422. need to download the source, compute the sha256 checksum and convert it to
  423. base32.
  424. Thankfully, Guix can automate this task for us; all we need is to provide the
  425. URI:
  426. @c TRANSLATORS: This is example shell output.
  427. @example sh
  428. $ guix download mirror://gnu/hello/hello-2.10.tar.gz
  429. Starting download of /tmp/guix-file.JLYgL7
  430. From https://ftpmirror.gnu.org/gnu/hello/hello-2.10.tar.gz...
  431. following redirection to `https://mirror.ibcp.fr/pub/gnu/hello/hello-2.10.tar.gz'...
  432. …10.tar.gz 709KiB 2.5MiB/s 00:00 [##################] 100.0%
  433. /gnu/store/hbdalsf5lpf01x4dcknwx6xbn6n5km6k-hello-2.10.tar.gz
  434. 0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i
  435. @end example
  436. In this specific case the output tells us which mirror was chosen.
  437. If the result of the above command is not the same as in the above snippet,
  438. update your @code{my-hello} declaration accordingly.
  439. Note that GNU package tarballs come with an OpenPGP signature, so you
  440. should definitely check the signature of this tarball with `gpg` to
  441. authenticate it before going further:
  442. @c TRANSLATORS: This is example shell output.
  443. @example sh
  444. $ guix download mirror://gnu/hello/hello-2.10.tar.gz.sig
  445. Starting download of /tmp/guix-file.03tFfb
  446. From https://ftpmirror.gnu.org/gnu/hello/hello-2.10.tar.gz.sig...
  447. following redirection to `https://ftp.igh.cnrs.fr/pub/gnu/hello/hello-2.10.tar.gz.sig'...
  448. ….tar.gz.sig 819B 1.2MiB/s 00:00 [##################] 100.0%
  449. /gnu/store/rzs8wba9ka7grrmgcpfyxvs58mly0sx6-hello-2.10.tar.gz.sig
  450. 0q0v86n3y38z17rl146gdakw9xc4mcscpk8dscs412j22glrv9jf
  451. $ gpg --verify /gnu/store/rzs8wba9ka7grrmgcpfyxvs58mly0sx6-hello-2.10.tar.gz.sig /gnu/store/hbdalsf5lpf01x4dcknwx6xbn6n5km6k-hello-2.10.tar.gz
  452. gpg: Signature made Sun 16 Nov 2014 01:08:37 PM CET
  453. gpg: using RSA key A9553245FDE9B739
  454. gpg: Good signature from "Sami Kerola <kerolasa@@iki.fi>" [unknown]
  455. gpg: aka "Sami Kerola (http://www.iki.fi/kerolasa/) <kerolasa@@iki.fi>" [unknown]
  456. gpg: WARNING: This key is not certified with a trusted signature!
  457. gpg: There is no indication that the signature belongs to the owner.
  458. Primary key fingerprint: 8ED3 96E3 7E38 D471 A005 30D3 A955 3245 FDE9 B739
  459. @end example
  460. You can then happily run
  461. @c TRANSLATORS: Do not translate this command
  462. @example sh
  463. $ guix package --install-from-file=my-hello.scm
  464. @end example
  465. You should now have @code{my-hello} in your profile!
  466. @c TRANSLATORS: Do not translate this command
  467. @example sh
  468. $ guix package --list-installed=my-hello
  469. my-hello 2.10 out
  470. /gnu/store/f1db2mfm8syb8qvc357c53slbvf1g9m9-my-hello-2.10
  471. @end example
  472. We've gone as far as we could without any knowledge of Scheme. Before moving
  473. on to more complex packages, now is the right time to brush up on your Scheme
  474. knowledge. @pxref{A Scheme Crash Course} to get up to speed.
  475. @node Setup
  476. @subsection Setup
  477. In the rest of this chapter we will rely on some basic Scheme
  478. programming knowledge. Now let's detail the different possible setups
  479. for working on Guix packages.
  480. There are several ways to set up a Guix packaging environment.
  481. We recommend you work directly on the Guix source checkout since it makes it
  482. easier for everyone to contribute to the project.
  483. But first, let's look at other possibilities.
  484. @node Local file
  485. @subsubsection Local file
  486. This is what we previously did with @samp{my-hello}. With the Scheme basics we've
  487. covered, we are now able to explain the leading chunks. As stated in @code{guix
  488. package --help}:
  489. @example
  490. -f, --install-from-file=FILE
  491. install the package that the code within FILE
  492. evaluates to
  493. @end example
  494. Thus the last expression @emph{must} return a package, which is the case in our
  495. earlier example.
  496. The @code{use-modules} expression tells which of the modules we need in the file.
  497. Modules are a collection of values and procedures. They are commonly called
  498. ``libraries'' or ``packages'' in other programming languages.
  499. @node Channels
  500. @subsubsection Channels
  501. @cindex channel
  502. Guix and its package collection can be extended through @dfn{channels}.
  503. A channel is a Git repository, public or not, containing @file{.scm}
  504. files that provide packages (@pxref{Defining Packages,,, guix, GNU Guix
  505. Reference Manual}) or services (@pxref{Defining Services,,, guix, GNU
  506. Guix Reference Manual}).
  507. How would you go about creating a channel? First, create a directory
  508. that will contain your @file{.scm} files, say @file{~/my-channel}:
  509. @example
  510. mkdir ~/my-channel
  511. @end example
  512. Suppose you want to add the @samp{my-hello} package we saw previously;
  513. it first needs some adjustments:
  514. @lisp
  515. (define-module (my-hello)
  516. #:use-module (guix licenses)
  517. #:use-module (guix packages)
  518. #:use-module (guix build-system gnu)
  519. #:use-module (guix download))
  520. (define-public my-hello
  521. (package
  522. (name "my-hello")
  523. (version "2.10")
  524. (source (origin
  525. (method url-fetch)
  526. (uri (string-append "mirror://gnu/hello/hello-" version
  527. ".tar.gz"))
  528. (sha256
  529. (base32
  530. "0ssi1wpaf7plaswqqjwigppsg5fyh99vdlb9kzl7c9lng89ndq1i"))))
  531. (build-system gnu-build-system)
  532. (synopsis "Hello, Guix world: An example custom Guix package")
  533. (description
  534. "GNU Hello prints the message \"Hello, world!\" and then exits. It
  535. serves as an example of standard GNU coding practices. As such, it supports
  536. command-line arguments, multiple languages, and so on.")
  537. (home-page "https://www.gnu.org/software/hello/")
  538. (license gpl3+)))
  539. @end lisp
  540. Note that we have assigned the package value to an exported variable name with
  541. @code{define-public}. This is effectively assigning the package to the @code{my-hello}
  542. variable so that it can be referenced, among other as dependency of other
  543. packages.
  544. If you use @code{guix package --install-from-file=my-hello.scm} on the above file, it
  545. will fail because the last expression, @code{define-public}, does not return a
  546. package. If you want to use @code{define-public} in this use-case nonetheless, make
  547. sure the file ends with an evaluation of @code{my-hello}:
  548. @lisp
  549. ;; ...
  550. (define-public my-hello
  551. ;; ...
  552. )
  553. my-hello
  554. @end lisp
  555. This last example is not very typical.
  556. Now how do you make that package visible to @command{guix} commands so
  557. you can test your packages? You need to add the directory to the search
  558. path using the @option{-L} command-line option, as in these examples:
  559. @example
  560. guix show -L ~/my-channel my-hello
  561. guix build -L ~/my-channel my-hello
  562. @end example
  563. The final step is to turn @file{~/my-channel} into an actual channel,
  564. making your package collection seamlessly available @i{via} any
  565. @command{guix} command. To do that, you first need to make it a Git
  566. repository:
  567. @example
  568. cd ~/my-channel
  569. git init
  570. git add my-hello.scm
  571. git commit -m "First commit of my channel."
  572. @end example
  573. And that's it, you have a channel! From there on, you can add this
  574. channel to your channel configuration in
  575. @file{~/.config/guix/channels.scm} (@pxref{Specifying Additional
  576. Channels,,, guix, GNU Guix Reference Manual}); assuming you keep your
  577. channel local for now, the @file{channels.scm} would look something like
  578. this:
  579. @lisp
  580. (append (list (channel
  581. (name 'my-channel)
  582. (url (string-append "file://" (getenv "HOME")
  583. "/my-channel"))))
  584. %default-channels)
  585. @end lisp
  586. Next time you run @command{guix pull}, your channel will be picked up
  587. and the packages it defines will be readily available to all the
  588. @command{guix} commands, even if you do not pass @option{-L}. The
  589. @command{guix describe} command will show that Guix is, indeed, using
  590. both the @code{my-channel} and the @code{guix} channels.
  591. @xref{Creating a Channel,,, guix, GNU Guix Reference Manual}, for
  592. details.
  593. @node Direct checkout hacking
  594. @subsubsection Direct checkout hacking
  595. Working directly on the Guix project is recommended: it reduces the friction
  596. when the time comes to submit your changes upstream to let the community benefit
  597. from your hard work!
  598. Unlike most software distributions, the Guix repository holds in one place both
  599. the tooling (including the package manager) and the package definitions. This
  600. choice was made so that it would give developers the flexibility to modify the
  601. API without breakage by updating all packages at the same time. This reduces
  602. development inertia.
  603. Check out the official @uref{https://git-scm.com/, Git} repository:
  604. @example
  605. $ git clone https://git.savannah.gnu.org/git/guix.git
  606. @end example
  607. In the rest of this article, we use @samp{$GUIX_CHECKOUT} to refer to the location of
  608. the checkout.
  609. Follow the instructions in the manual (@pxref{Contributing,,, guix, GNU Guix
  610. Reference Manual}) to set up the repository environment.
  611. Once ready, you should be able to use the package definitions from the
  612. repository environment.
  613. Feel free to edit package definitions found in @samp{$GUIX_CHECKOUT/gnu/packages}.
  614. The @samp{$GUIX_CHECKOUT/pre-inst-env} script lets you use @samp{guix} over the package
  615. collection of the repository (@pxref{Running Guix Before It Is
  616. Installed,,, guix, GNU Guix Reference Manual}).
  617. @itemize
  618. @item
  619. Search packages, such as Ruby:
  620. @example
  621. $ cd $GUIX_CHECKOUT
  622. $ ./pre-inst-env guix package --list-available=ruby
  623. ruby 1.8.7-p374 out gnu/packages/ruby.scm:119:2
  624. ruby 2.1.6 out gnu/packages/ruby.scm:91:2
  625. ruby 2.2.2 out gnu/packages/ruby.scm:39:2
  626. @end example
  627. @item
  628. Build a package, here Ruby version 2.1:
  629. @example
  630. $ ./pre-inst-env guix build --keep-failed ruby@@2.1
  631. /gnu/store/c13v73jxmj2nir2xjqaz5259zywsa9zi-ruby-2.1.6
  632. @end example
  633. @item
  634. Install it to your user profile:
  635. @example
  636. $ ./pre-inst-env guix package --install ruby@@2.1
  637. @end example
  638. @item
  639. Check for common mistakes:
  640. @example
  641. $ ./pre-inst-env guix lint ruby@@2.1
  642. @end example
  643. @end itemize
  644. Guix strives at maintaining a high packaging standard; when contributing to the
  645. Guix project, remember to
  646. @itemize
  647. @item
  648. follow the coding style (@pxref{Coding Style,,, guix, GNU Guix Reference Manual}),
  649. @item
  650. and review the check list from the manual (@pxref{Submitting Patches,,, guix, GNU Guix Reference Manual}).
  651. @end itemize
  652. Once you are happy with the result, you are welcome to send your contribution to
  653. make it part of Guix. This process is also detailed in the manual. (@pxref{Contributing,,, guix, GNU Guix Reference Manual})
  654. It's a community effort so the more join in, the better Guix becomes!
  655. @node Extended example
  656. @subsection Extended example
  657. The above ``Hello World'' example is as simple as it goes. Packages can be more
  658. complex than that and Guix can handle more advanced scenarios. Let's look at
  659. another, more sophisticated package (slightly modified from the source):
  660. @lisp
  661. (define-module (gnu packages version-control)
  662. #:use-module ((guix licenses) #:prefix license:)
  663. #:use-module (guix utils)
  664. #:use-module (guix packages)
  665. #:use-module (guix git-download)
  666. #:use-module (guix build-system cmake)
  667. #:use-module (gnu packages ssh)
  668. #:use-module (gnu packages web)
  669. #:use-module (gnu packages pkg-config)
  670. #:use-module (gnu packages python)
  671. #:use-module (gnu packages compression)
  672. #:use-module (gnu packages tls))
  673. (define-public my-libgit2
  674. (let ((commit "e98d0a37c93574d2c6107bf7f31140b548c6a7bf")
  675. (revision "1"))
  676. (package
  677. (name "my-libgit2")
  678. (version (git-version "0.26.6" revision commit))
  679. (source (origin
  680. (method git-fetch)
  681. (uri (git-reference
  682. (url "https://github.com/libgit2/libgit2/")
  683. (commit commit)))
  684. (file-name (git-file-name name version))
  685. (sha256
  686. (base32
  687. "17pjvprmdrx4h6bb1hhc98w9qi6ki7yl57f090n9kbhswxqfs7s3"))
  688. (patches (search-patches "libgit2-mtime-0.patch"))
  689. (modules '((guix build utils)))
  690. ;; Remove bundled software.
  691. (snippet '(delete-file-recursively "deps"))))
  692. (build-system cmake-build-system)
  693. (outputs '("out" "debug"))
  694. (arguments
  695. `(#:tests? #true ; Run the test suite (this is the default)
  696. #:configure-flags '("-DUSE_SHA1DC=ON") ; SHA-1 collision detection
  697. #:phases
  698. (modify-phases %standard-phases
  699. (add-after 'unpack 'fix-hardcoded-paths
  700. (lambda _
  701. (substitute* "tests/repo/init.c"
  702. (("#!/bin/sh") (string-append "#!" (which "sh"))))
  703. (substitute* "tests/clar/fs.h"
  704. (("/bin/cp") (which "cp"))
  705. (("/bin/rm") (which "rm")))))
  706. ;; Run checks more verbosely.
  707. (replace 'check
  708. (lambda _ (invoke "./libgit2_clar" "-v" "-Q")))
  709. (add-after 'unpack 'make-files-writable-for-tests
  710. (lambda _ (for-each make-file-writable (find-files "." ".*")))))))
  711. (inputs
  712. (list libssh2 http-parser python-wrapper))
  713. (native-inputs
  714. (list pkg-config))
  715. (propagated-inputs
  716. ;; These two libraries are in 'Requires.private' in libgit2.pc.
  717. (list openssl zlib))
  718. (home-page "https://libgit2.github.com/")
  719. (synopsis "Library providing Git core methods")
  720. (description
  721. "Libgit2 is a portable, pure C implementation of the Git core methods
  722. provided as a re-entrant linkable library with a solid API, allowing you to
  723. write native speed custom Git applications in any language with bindings.")
  724. ;; GPLv2 with linking exception
  725. (license license:gpl2))))
  726. @end lisp
  727. (In those cases were you only want to tweak a few fields from a package
  728. definition, you should rely on inheritance instead of copy-pasting everything.
  729. See below.)
  730. Let's discuss those fields in depth.
  731. @subsubsection @code{git-fetch} method
  732. Unlike the @code{url-fetch} method, @code{git-fetch} expects a @code{git-reference} which takes
  733. a Git repository and a commit. The commit can be any Git reference such as
  734. tags, so if the @code{version} is tagged, then it can be used directly. Sometimes
  735. the tag is prefixed with a @code{v}, in which case you'd use @code{(commit (string-append
  736. "v" version))}.
  737. To ensure that the source code from the Git repository is stored in a
  738. directory with a descriptive name, we use @code{(file-name (git-file-name name
  739. version))}.
  740. The @code{git-version} procedure can be used to derive the
  741. version when packaging programs for a specific commit, following the
  742. Guix contributor guidelines (@pxref{Version Numbers,,, guix, GNU Guix
  743. Reference Manual}).
  744. How does one obtain the @code{sha256} hash that's in there, you ask? By
  745. invoking @command{guix hash} on a checkout of the desired commit, along
  746. these lines:
  747. @example
  748. git clone https://github.com/libgit2/libgit2/
  749. cd libgit2
  750. git checkout v0.26.6
  751. guix hash -rx .
  752. @end example
  753. @command{guix hash -rx} computes a SHA256 hash over the whole directory,
  754. excluding the @file{.git} sub-directory (@pxref{Invoking guix hash,,,
  755. guix, GNU Guix Reference Manual}).
  756. In the future, @command{guix download} will hopefully be able to do
  757. these steps for you, just like it does for regular downloads.
  758. @subsubsection Snippets
  759. Snippets are quoted (i.e. non-evaluated) Scheme code that are a means of patching
  760. the source. They are a Guix-y alternative to the traditional @file{.patch} files.
  761. Because of the quote, the code in only evaluated when passed to the Guix daemon
  762. for building. There can be as many snippets as needed.
  763. Snippets might need additional Guile modules which can be imported from the
  764. @code{modules} field.
  765. @subsubsection Inputs
  766. There are 3 different input types. In short:
  767. @table @asis
  768. @item native-inputs
  769. Required for building but not runtime -- installing a package
  770. through a substitute won't install these inputs.
  771. @item inputs
  772. Installed in the store but not in the profile, as well as being
  773. present at build time.
  774. @item propagated-inputs
  775. Installed in the store and in the profile, as well as
  776. being present at build time.
  777. @end table
  778. @xref{package Reference,,, guix, GNU Guix Reference Manual} for more details.
  779. The distinction between the various inputs is important: if a dependency can be
  780. handled as an @emph{input} instead of a @emph{propagated input}, it should be done so, or
  781. else it ``pollutes'' the user profile for no good reason.
  782. For instance, a user installing a graphical program that depends on a
  783. command line tool might only be interested in the graphical part, so there is no
  784. need to force the command line tool into the user profile. The dependency is a
  785. concern to the package, not to the user. @emph{Inputs} make it possible to handle
  786. dependencies without bugging the user by adding undesired executable files (or
  787. libraries) to their profile.
  788. Same goes for @emph{native-inputs}: once the program is installed, build-time
  789. dependencies can be safely garbage-collected.
  790. It also matters when a substitute is available, in which case only the @emph{inputs}
  791. and @emph{propagated inputs} will be fetched: the @emph{native inputs} are not required to
  792. install a package from a substitute.
  793. @quotation Note
  794. You may see here and there snippets where package inputs are written
  795. quite differently, like so:
  796. @lisp
  797. ;; The "old style" for inputs.
  798. (inputs
  799. `(("libssh2" ,libssh2)
  800. ("http-parser" ,http-parser)
  801. ("python" ,python-wrapper)))
  802. @end lisp
  803. This is the ``old style'', where each input in the list is explicitly
  804. given a label (a string). It is still supported but we recommend using
  805. the style above instead. @xref{package Reference,,, guix, GNU Guix
  806. Reference Manual}, for more info.
  807. @end quotation
  808. @subsubsection Outputs
  809. Just like how a package can have multiple inputs, it can also produce multiple
  810. outputs.
  811. Each output corresponds to a separate directory in the store.
  812. The user can choose which output to install; this is useful to save space or
  813. to avoid polluting the user profile with unwanted executables or libraries.
  814. Output separation is optional. When the @code{outputs} field is left out, the
  815. default and only output (the complete package) is referred to as @code{"out"}.
  816. Typical separate output names include @code{debug} and @code{doc}.
  817. It's advised to separate outputs only when you've shown it's worth it: if the
  818. output size is significant (compare with @code{guix size}) or in case the package is
  819. modular.
  820. @subsubsection Build system arguments
  821. The @code{arguments} is a keyword-value list used to configure the build process.
  822. The simplest argument @code{#:tests?} can be used to disable the test suite when
  823. building the package. This is mostly useful when the package does not feature
  824. any test suite. It's strongly recommended to keep the test suite on if there is
  825. one.
  826. Another common argument is @code{:make-flags}, which specifies a list of flags to
  827. append when running make, as you would from the command line. For instance, the
  828. following flags
  829. @lisp
  830. #:make-flags (list (string-append "prefix=" (assoc-ref %outputs "out"))
  831. "CC=gcc")
  832. @end lisp
  833. translate into
  834. @example
  835. $ make CC=gcc prefix=/gnu/store/...-<out>
  836. @end example
  837. This sets the C compiler to @code{gcc} and the @code{prefix} variable (the installation
  838. directory in Make parlance) to @code{(assoc-ref %outputs "out")}, which is a build-stage
  839. global variable pointing to the destination directory in the store (something like
  840. @file{/gnu/store/...-my-libgit2-20180408}).
  841. Similarly, it's possible to set the configure flags:
  842. @lisp
  843. #:configure-flags '("-DUSE_SHA1DC=ON")
  844. @end lisp
  845. The @code{%build-inputs} variable is also generated in scope. It's an association
  846. table that maps the input names to their store directories.
  847. The @code{phases} keyword lists the sequential steps of the build system. Typically
  848. phases include @code{unpack}, @code{configure}, @code{build}, @code{install} and @code{check}. To know
  849. more about those phases, you need to work out the appropriate build system
  850. definition in @samp{$GUIX_CHECKOUT/guix/build/gnu-build-system.scm}:
  851. @lisp
  852. (define %standard-phases
  853. ;; Standard build phases, as a list of symbol/procedure pairs.
  854. (let-syntax ((phases (syntax-rules ()
  855. ((_ p ...) `((p . ,p) ...)))))
  856. (phases set-SOURCE-DATE-EPOCH set-paths install-locale unpack
  857. bootstrap
  858. patch-usr-bin-file
  859. patch-source-shebangs configure patch-generated-file-shebangs
  860. build check install
  861. patch-shebangs strip
  862. validate-runpath
  863. validate-documentation-location
  864. delete-info-dir-file
  865. patch-dot-desktop-files
  866. install-license-files
  867. reset-gzip-timestamps
  868. compress-documentation)))
  869. @end lisp
  870. Or from the REPL:
  871. @lisp
  872. (add-to-load-path "/path/to/guix/checkout")
  873. ,use (guix build gnu-build-system)
  874. (map first %standard-phases)
  875. @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)
  876. @end lisp
  877. If you want to know more about what happens during those phases, consult the
  878. associated procedures.
  879. For instance, as of this writing the definition of @code{unpack} for the GNU build
  880. system is:
  881. @lisp
  882. (define* (unpack #:key source #:allow-other-keys)
  883. "Unpack SOURCE in the working directory, and change directory within the
  884. source. When SOURCE is a directory, copy it in a sub-directory of the current
  885. working directory."
  886. (if (file-is-directory? source)
  887. (begin
  888. (mkdir "source")
  889. (chdir "source")
  890. ;; Preserve timestamps (set to the Epoch) on the copied tree so that
  891. ;; things work deterministically.
  892. (copy-recursively source "."
  893. #:keep-mtime? #true))
  894. (begin
  895. (if (string-suffix? ".zip" source)
  896. (invoke "unzip" source)
  897. (invoke "tar" "xvf" source))
  898. (chdir (first-subdirectory "."))))
  899. #true)
  900. @end lisp
  901. Note the @code{chdir} call: it changes the working directory to where the source was
  902. unpacked.
  903. Thus every phase following the @code{unpack} will use the source as a working
  904. directory, which is why we can directly work on the source files.
  905. That is to say, unless a later phase changes the working directory to something
  906. else.
  907. We modify the list of @code{%standard-phases} of the build system with the
  908. @code{modify-phases} macro as per the list of specified modifications, which may have
  909. the following forms:
  910. @itemize
  911. @item
  912. @code{(add-before @var{phase} @var{new-phase} @var{procedure})}: Run @var{procedure} named @var{new-phase} before @var{phase}.
  913. @item
  914. @code{(add-after @var{phase} @var{new-phase} @var{procedure})}: Same, but afterwards.
  915. @item
  916. @code{(replace @var{phase} @var{procedure})}.
  917. @item
  918. @code{(delete @var{phase})}.
  919. @end itemize
  920. The @var{procedure} supports the keyword arguments @code{inputs} and @code{outputs}. Each
  921. input (whether @emph{native}, @emph{propagated} or not) and output directory is referenced
  922. by their name in those variables. Thus @code{(assoc-ref outputs "out")} is the store
  923. directory of the main output of the package. A phase procedure may look like
  924. this:
  925. @lisp
  926. (lambda* (#:key inputs outputs #:allow-other-keys)
  927. (let ((bash-directory (assoc-ref inputs "bash"))
  928. (output-directory (assoc-ref outputs "out"))
  929. (doc-directory (assoc-ref outputs "doc")))
  930. ;; ...
  931. #true))
  932. @end lisp
  933. The procedure must return @code{#true} on success. It's brittle to rely on the return
  934. value of the last expression used to tweak the phase because there is no
  935. guarantee it would be a @code{#true}. Hence the trailing @code{#true} to ensure the right value
  936. is returned on success.
  937. @subsubsection Code staging
  938. The astute reader may have noticed the quasi-quote and comma syntax in the
  939. argument field. Indeed, the build code in the package declaration should not be
  940. evaluated on the client side, but only when passed to the Guix daemon. This
  941. mechanism of passing code around two running processes is called @uref{https://arxiv.org/abs/1709.00833, code staging}.
  942. @subsubsection Utility functions
  943. When customizing @code{phases}, we often need to write code that mimics the
  944. equivalent system invocations (@code{make}, @code{mkdir}, @code{cp}, etc.)@: commonly used during
  945. regular ``Unix-style'' installations.
  946. Some like @code{chmod} are native to Guile.
  947. @xref{,,, guile, Guile reference manual} for a complete list.
  948. Guix provides additional helper functions which prove especially handy in the
  949. context of package management.
  950. Some of those functions can be found in
  951. @samp{$GUIX_CHECKOUT/guix/guix/build/utils.scm}. Most of them mirror the behaviour
  952. of the traditional Unix system commands:
  953. @table @code
  954. @item which
  955. Like the @samp{which} system command.
  956. @item find-files
  957. Akin to the @samp{find} system command.
  958. @item mkdir-p
  959. Like @samp{mkdir -p}, which creates all parents as needed.
  960. @item install-file
  961. Similar to @samp{install} when installing a file to a (possibly
  962. non-existing) directory. Guile has @code{copy-file} which works
  963. like @samp{cp}.
  964. @item copy-recursively
  965. Like @samp{cp -r}.
  966. @item delete-file-recursively
  967. Like @samp{rm -rf}.
  968. @item invoke
  969. Run an executable. This should be used instead of @code{system*}.
  970. @item with-directory-excursion
  971. Run the body in a different working directory,
  972. then restore the previous working directory.
  973. @item substitute*
  974. A ``@command{sed}-like'' function.
  975. @end table
  976. @xref{Build Utilities,,, guix, GNU Guix Reference Manual}, for more
  977. information on these utilities.
  978. @subsubsection Module prefix
  979. The license in our last example needs a prefix: this is because of how the
  980. @code{license} module was imported in the package, as @code{#:use-module ((guix licenses)
  981. #:prefix license:)}. The Guile module import mechanism
  982. (@pxref{Using Guile Modules,,, guile, Guile reference manual})
  983. gives the user full control over namespacing: this is needed to avoid
  984. clashes between, say, the
  985. @samp{zlib} variable from @samp{licenses.scm} (a @emph{license} value) and the @samp{zlib} variable
  986. from @samp{compression.scm} (a @emph{package} value).
  987. @node Other build systems
  988. @subsection Other build systems
  989. What we've seen so far covers the majority of packages using a build system
  990. other than the @code{trivial-build-system}. The latter does not automate anything
  991. and leaves you to build everything manually. This can be more demanding and we
  992. won't cover it here for now, but thankfully it is rarely necessary to fall back
  993. on this system.
  994. For the other build systems, such as ASDF, Emacs, Perl, Ruby and many more, the
  995. process is very similar to the GNU build system except for a few specialized
  996. arguments.
  997. @xref{Build Systems,,, guix, GNU Guix Reference Manual}, for more
  998. information on build systems, or check the source code in the
  999. @samp{$GUIX_CHECKOUT/guix/build} and
  1000. @samp{$GUIX_CHECKOUT/guix/build-system} directories.
  1001. @node Programmable and automated package definition
  1002. @subsection Programmable and automated package definition
  1003. We can't repeat it enough: having a full-fledged programming language at hand
  1004. empowers us in ways that reach far beyond traditional package management.
  1005. Let's illustrate this with some awesome features of Guix!
  1006. @node Recursive importers
  1007. @subsubsection Recursive importers
  1008. You might find some build systems good enough that there is little to do at all
  1009. to write a package, to the point that it becomes repetitive and tedious after a
  1010. while. A @emph{raison d'être} of computers is to replace human beings at those
  1011. boring tasks. So let's tell Guix to do this for us and create the package
  1012. definition of an R package from CRAN (the output is trimmed for conciseness):
  1013. @example
  1014. $ guix import cran --recursive walrus
  1015. (define-public r-mc2d
  1016. ; ...
  1017. (license gpl2+)))
  1018. (define-public r-jmvcore
  1019. ; ...
  1020. (license gpl2+)))
  1021. (define-public r-wrs2
  1022. ; ...
  1023. (license gpl3)))
  1024. (define-public r-walrus
  1025. (package
  1026. (name "r-walrus")
  1027. (version "1.0.3")
  1028. (source
  1029. (origin
  1030. (method url-fetch)
  1031. (uri (cran-uri "walrus" version))
  1032. (sha256
  1033. (base32
  1034. "1nk2glcvy4hyksl5ipq2mz8jy4fss90hx6cq98m3w96kzjni6jjj"))))
  1035. (build-system r-build-system)
  1036. (propagated-inputs
  1037. (list r-ggplot2 r-jmvcore r-r6 r-wrs2))
  1038. (home-page "https://github.com/jamovi/walrus")
  1039. (synopsis "Robust Statistical Methods")
  1040. (description
  1041. "This package provides a toolbox of common robust statistical
  1042. tests, including robust descriptives, robust t-tests, and robust ANOVA.
  1043. It is also available as a module for 'jamovi' (see
  1044. <https://www.jamovi.org> for more information). Walrus is based on the
  1045. WRS2 package by Patrick Mair, which is in turn based on the scripts and
  1046. work of Rand Wilcox. These analyses are described in depth in the book
  1047. 'Introduction to Robust Estimation & Hypothesis Testing'.")
  1048. (license gpl3)))
  1049. @end example
  1050. The recursive importer won't import packages for which Guix already has package
  1051. definitions, except for the very first.
  1052. Not all applications can be packaged this way, only those relying on a select
  1053. number of supported systems. Read about the full list of importers in
  1054. the guix import section of the manual
  1055. (@pxref{Invoking guix import,,, guix, GNU Guix Reference Manual}).
  1056. @node Automatic update
  1057. @subsubsection Automatic update
  1058. Guix can be smart enough to check for updates on systems it knows. It can
  1059. report outdated package definitions with
  1060. @example
  1061. $ guix refresh hello
  1062. @end example
  1063. In most cases, updating a package to a newer version requires little more than
  1064. changing the version number and the checksum. Guix can do that automatically as
  1065. well:
  1066. @example
  1067. $ guix refresh hello --update
  1068. @end example
  1069. @node Inheritance
  1070. @subsubsection Inheritance
  1071. If you've started browsing the existing package definitions, you might have
  1072. noticed that a significant number of them have a @code{inherit} field:
  1073. @lisp
  1074. (define-public adwaita-icon-theme
  1075. (package (inherit gnome-icon-theme)
  1076. (name "adwaita-icon-theme")
  1077. (version "3.26.1")
  1078. (source (origin
  1079. (method url-fetch)
  1080. (uri (string-append "mirror://gnome/sources/" name "/"
  1081. (version-major+minor version) "/"
  1082. name "-" version ".tar.xz"))
  1083. (sha256
  1084. (base32
  1085. "17fpahgh5dyckgz7rwqvzgnhx53cx9kr2xw0szprc6bnqy977fi8"))))
  1086. (native-inputs (list `(,gtk+ "bin")))))
  1087. @end lisp
  1088. All unspecified fields are inherited from the parent package. This is very
  1089. convenient to create alternative packages, for instance with different source,
  1090. version or compilation options.
  1091. @node Getting help
  1092. @subsection Getting help
  1093. Sadly, some applications can be tough to package. Sometimes they need a patch to
  1094. work with the non-standard file system hierarchy enforced by the store.
  1095. Sometimes the tests won't run properly. (They can be skipped but this is not
  1096. recommended.) Other times the resulting package won't be reproducible.
  1097. Should you be stuck, unable to figure out how to fix any sort of packaging
  1098. issue, don't hesitate to ask the community for help.
  1099. See the @uref{https://www.gnu.org/software/guix/contact/, Guix homepage} for information on the mailing lists, IRC, etc.
  1100. @node Conclusion
  1101. @subsection Conclusion
  1102. This tutorial was a showcase of the sophisticated package management that Guix
  1103. boasts. At this point we have mostly restricted this introduction to the
  1104. @code{gnu-build-system} which is a core abstraction layer on which more advanced
  1105. abstractions are based.
  1106. Where do we go from here? Next we ought to dissect the innards of the build
  1107. system by removing all abstractions, using the @code{trivial-build-system}: this
  1108. should give us a thorough understanding of the process before investigating some
  1109. more advanced packaging techniques and edge cases.
  1110. Other features worth exploring are the interactive editing and debugging
  1111. capabilities of Guix provided by the Guile REPL@.
  1112. Those fancy features are completely optional and can wait; now is a good time
  1113. to take a well-deserved break. With what we've introduced here you should be
  1114. well armed to package lots of programs. You can get started right away and
  1115. hopefully we will see your contributions soon!
  1116. @node References
  1117. @subsection References
  1118. @itemize
  1119. @item
  1120. The @uref{https://www.gnu.org/software/guix/manual/en/html_node/Defining-Packages.html, package reference in the manual}
  1121. @item
  1122. @uref{https://gitlab.com/pjotrp/guix-notes/blob/master/HACKING.org, Pjotr’s hacking guide to GNU Guix}
  1123. @item
  1124. @uref{https://www.gnu.org/software/guix/guix-ghm-andreas-20130823.pdf, ``GNU Guix: Package without a scheme!''}, by Andreas Enge
  1125. @end itemize
  1126. @c *********************************************************************
  1127. @node System Configuration
  1128. @chapter System Configuration
  1129. Guix offers a flexible language for declaratively configuring your Guix
  1130. System. This flexibility can at times be overwhelming. The purpose of this
  1131. chapter is to demonstrate some advanced configuration concepts.
  1132. @pxref{System Configuration,,, guix, GNU Guix Reference Manual} for a complete
  1133. reference.
  1134. @menu
  1135. * Auto-Login to a Specific TTY:: Automatically Login a User to a Specific TTY
  1136. * Customizing the Kernel:: Creating and using a custom Linux kernel on Guix System.
  1137. * Guix System Image API:: Customizing images to target specific platforms.
  1138. * Using security keys:: How to use security keys with Guix System.
  1139. * Connecting to Wireguard VPN:: Connecting to a Wireguard VPN.
  1140. * Customizing a Window Manager:: Handle customization of a Window manager on Guix System.
  1141. * Running Guix on a Linode Server:: Running Guix on a Linode Server
  1142. * Setting up a bind mount:: Setting up a bind mount in the file-systems definition.
  1143. * Getting substitutes from Tor:: Configuring Guix daemon to get substitutes through Tor.
  1144. * Setting up NGINX with Lua:: Configuring NGINX web-server to load Lua modules.
  1145. * Music Server with Bluetooth Audio:: Headless music player with Bluetooth output.
  1146. @end menu
  1147. @node Auto-Login to a Specific TTY
  1148. @section Auto-Login to a Specific TTY
  1149. While the Guix manual explains auto-login one user to @emph{all} TTYs (
  1150. @pxref{auto-login to TTY,,, guix, GNU Guix Reference Manual}), some
  1151. might prefer a situation, in which one user is logged into one TTY with
  1152. the other TTYs either configured to login different users or no one at
  1153. all. Note that one can auto-login one user to any TTY, but it is
  1154. usually advisable to avoid @code{tty1}, which, by default, is used to
  1155. log warnings and errors.
  1156. Here is how one might set up auto login for one user to one tty:
  1157. @lisp
  1158. (define (auto-login-to-tty config tty user)
  1159. (if (string=? tty (mingetty-configuration-tty config))
  1160. (mingetty-configuration
  1161. (inherit config)
  1162. (auto-login user))
  1163. config))
  1164. (define %my-services
  1165. (modify-services %base-services
  1166. ;; @dots{}
  1167. (mingetty-service-type config =>
  1168. (auto-login-to-tty
  1169. config "tty3" "alice"))))
  1170. (operating-system
  1171. ;; @dots{}
  1172. (services %my-services))
  1173. @end lisp
  1174. One could also @code{compose} (@pxref{Higher-Order Functions,,, guile,
  1175. The Guile Reference Manual}) @code{auto-login-to-tty} to login multiple
  1176. users to multiple ttys.
  1177. Finally, here is a note of caution. Setting up auto login to a TTY,
  1178. means that anyone can turn on your computer and run commands as your
  1179. regular user.
  1180. However, if you have an encrypted root partition, and thus already need
  1181. to enter a passphrase when the system boots, auto-login might be a
  1182. convenient option.
  1183. @node Customizing the Kernel
  1184. @section Customizing the Kernel
  1185. Guix is, at its core, a source based distribution with substitutes
  1186. (@pxref{Substitutes,,, guix, GNU Guix Reference Manual}), and as such building
  1187. packages from their source code is an expected part of regular package
  1188. installations and upgrades. Given this starting point, it makes sense that
  1189. efforts are made to reduce the amount of time spent compiling packages, and
  1190. recent changes and upgrades to the building and distribution of substitutes
  1191. continues to be a topic of discussion within Guix.
  1192. The kernel, while not requiring an overabundance of RAM to build, does take a
  1193. rather long time on an average machine. The official kernel configuration, as
  1194. is the case with many GNU/Linux distributions, errs on the side of
  1195. inclusiveness, and this is really what causes the build to take such a long
  1196. time when the kernel is built from source.
  1197. The Linux kernel, however, can also just be described as a regular old
  1198. package, and as such can be customized just like any other package. The
  1199. procedure is a little bit different, although this is primarily due to the
  1200. nature of how the package definition is written.
  1201. The @code{linux-libre} kernel package definition is actually a procedure which
  1202. creates a package.
  1203. @lisp
  1204. (define* (make-linux-libre* version gnu-revision source supported-systems
  1205. #:key
  1206. (extra-version #f)
  1207. ;; A function that takes an arch and a variant.
  1208. ;; See kernel-config for an example.
  1209. (configuration-file #f)
  1210. (defconfig "defconfig")
  1211. (extra-options %default-extra-linux-options))
  1212. ...)
  1213. @end lisp
  1214. The current @code{linux-libre} package is for the 5.15.x series, and is
  1215. declared like this:
  1216. @lisp
  1217. (define-public linux-libre-5.15
  1218. (make-linux-libre* linux-libre-5.15-version
  1219. linux-libre-5.15-gnu-revision
  1220. linux-libre-5.15-source
  1221. '("x86_64-linux" "i686-linux" "armhf-linux" "aarch64-linux" "riscv64-linux")
  1222. #:configuration-file kernel-config))
  1223. @end lisp
  1224. Any keys which are not assigned values inherit their default value from the
  1225. @code{make-linux-libre} definition. When comparing the two snippets above,
  1226. notice the code comment that refers to @code{#:configuration-file}. Because of
  1227. this, it is not actually easy to include a custom kernel configuration from the
  1228. definition, but don't worry, there are other ways to work with what we do have.
  1229. There are two ways to create a kernel with a custom kernel configuration. The
  1230. first is to provide a standard @file{.config} file during the build process by
  1231. including an actual @file{.config} file as a native input to our custom
  1232. kernel. The following is a snippet from the custom @code{'configure} phase of
  1233. the @code{make-linux-libre} package definition:
  1234. @lisp
  1235. (let ((build (assoc-ref %standard-phases 'build))
  1236. (config (assoc-ref (or native-inputs inputs) "kconfig")))
  1237. ;; Use a custom kernel configuration file or a default
  1238. ;; configuration file.
  1239. (if config
  1240. (begin
  1241. (copy-file config ".config")
  1242. (chmod ".config" #o666))
  1243. (invoke "make" ,defconfig)))
  1244. @end lisp
  1245. Below is a sample kernel package. The @code{linux-libre} package is nothing
  1246. special and can be inherited from and have its fields overridden like any
  1247. other package:
  1248. @lisp
  1249. (define-public linux-libre/E2140
  1250. (package
  1251. (inherit linux-libre)
  1252. (native-inputs
  1253. `(("kconfig" ,(local-file "E2140.config"))
  1254. ,@@(alist-delete "kconfig"
  1255. (package-native-inputs linux-libre))))))
  1256. @end lisp
  1257. In the same directory as the file defining @code{linux-libre-E2140} is a file
  1258. named @file{E2140.config}, which is an actual kernel configuration file. The
  1259. @code{defconfig} keyword of @code{make-linux-libre} is left blank here, so the
  1260. only kernel configuration in the package is the one which was included in the
  1261. @code{native-inputs} field.
  1262. The second way to create a custom kernel is to pass a new value to the
  1263. @code{extra-options} keyword of the @code{make-linux-libre} procedure. The
  1264. @code{extra-options} keyword works with another function defined right below
  1265. it:
  1266. @lisp
  1267. (define %default-extra-linux-options
  1268. `(;; https://lists.gnu.org/archive/html/guix-devel/2014-04/msg00039.html
  1269. ("CONFIG_DEVPTS_MULTIPLE_INSTANCES" . #true)
  1270. ;; Modules required for initrd:
  1271. ("CONFIG_NET_9P" . m)
  1272. ("CONFIG_NET_9P_VIRTIO" . m)
  1273. ("CONFIG_VIRTIO_BLK" . m)
  1274. ("CONFIG_VIRTIO_NET" . m)
  1275. ("CONFIG_VIRTIO_PCI" . m)
  1276. ("CONFIG_VIRTIO_BALLOON" . m)
  1277. ("CONFIG_VIRTIO_MMIO" . m)
  1278. ("CONFIG_FUSE_FS" . m)
  1279. ("CONFIG_CIFS" . m)
  1280. ("CONFIG_9P_FS" . m)))
  1281. (define (config->string options)
  1282. (string-join (map (match-lambda
  1283. ((option . 'm)
  1284. (string-append option "=m"))
  1285. ((option . #true)
  1286. (string-append option "=y"))
  1287. ((option . #false)
  1288. (string-append option "=n")))
  1289. options)
  1290. "\n"))
  1291. @end lisp
  1292. And in the custom configure script from the `make-linux-libre` package:
  1293. @lisp
  1294. ;; Appending works even when the option wasn't in the
  1295. ;; file. The last one prevails if duplicated.
  1296. (let ((port (open-file ".config" "a"))
  1297. (extra-configuration ,(config->string extra-options)))
  1298. (display extra-configuration port)
  1299. (close-port port))
  1300. (invoke "make" "oldconfig")
  1301. @end lisp
  1302. So by not providing a configuration-file the @file{.config} starts blank, and
  1303. then we write into it the collection of flags that we want. Here's another
  1304. custom kernel:
  1305. @lisp
  1306. (define %macbook41-full-config
  1307. (append %macbook41-config-options
  1308. %file-systems
  1309. %efi-support
  1310. %emulation
  1311. (@@@@ (gnu packages linux) %default-extra-linux-options)))
  1312. (define-public linux-libre-macbook41
  1313. ;; XXX: Access the internal 'make-linux-libre*' procedure, which is
  1314. ;; private and unexported, and is liable to change in the future.
  1315. ((@@@@ (gnu packages linux) make-linux-libre*)
  1316. (@@@@ (gnu packages linux) linux-libre-version)
  1317. (@@@@ (gnu packages linux) linux-libre-gnu-revision)
  1318. (@@@@ (gnu packages linux) linux-libre-source)
  1319. '("x86_64-linux")
  1320. #:extra-version "macbook41"
  1321. #:extra-options %macbook41-config-options))
  1322. @end lisp
  1323. In the above example @code{%file-systems} is a collection of flags enabling
  1324. different file system support, @code{%efi-support} enables EFI support and
  1325. @code{%emulation} enables a x86_64-linux machine to act in 32-bit mode also.
  1326. @code{%default-extra-linux-options} are the ones quoted above, which had to be
  1327. added in since they were replaced in the @code{extra-options} keyword.
  1328. This all sounds like it should be doable, but how does one even know which
  1329. modules are required for a particular system? Two places that can be helpful
  1330. in trying to answer this question is the
  1331. @uref{https://wiki.gentoo.org/wiki/Handbook:AMD64/Installation/Kernel, Gentoo
  1332. Handbook} and the
  1333. @uref{https://www.kernel.org/doc/html/latest/admin-guide/README.html?highlight=localmodconfig,
  1334. documentation from the kernel itself}. From the kernel documentation, it
  1335. seems that @code{make localmodconfig} is the command we want.
  1336. In order to actually run @code{make localmodconfig} we first need to get and
  1337. unpack the kernel source code:
  1338. @example shell
  1339. tar xf $(guix build linux-libre --source)
  1340. @end example
  1341. Once inside the directory containing the source code run @code{touch .config}
  1342. to create an initial, empty @file{.config} to start with. @code{make
  1343. localmodconfig} works by seeing what you already have in @file{.config} and
  1344. letting you know what you're missing. If the file is blank then you're
  1345. missing everything. The next step is to run:
  1346. @example shell
  1347. guix shell -D linux-libre -- make localmodconfig
  1348. @end example
  1349. and note the output. Do note that the @file{.config} file is still empty.
  1350. The output generally contains two types of warnings. The first start with
  1351. "WARNING" and can actually be ignored in our case. The second read:
  1352. @example shell
  1353. module pcspkr did not have configs CONFIG_INPUT_PCSPKR
  1354. @end example
  1355. For each of these lines, copy the @code{CONFIG_XXXX_XXXX} portion into the
  1356. @file{.config} in the directory, and append @code{=m}, so in the end it looks
  1357. like this:
  1358. @example shell
  1359. CONFIG_INPUT_PCSPKR=m
  1360. CONFIG_VIRTIO=m
  1361. @end example
  1362. After copying all the configuration options, run @code{make localmodconfig}
  1363. again to make sure that you don't have any output starting with ``module''.
  1364. After all of these machine specific modules there are a couple more left that
  1365. are also needed. @code{CONFIG_MODULES} is necessary so that you can build and
  1366. load modules separately and not have everything built into the kernel.
  1367. @code{CONFIG_BLK_DEV_SD} is required for reading from hard drives. It is
  1368. possible that there are other modules which you will need.
  1369. This post does not aim to be a guide to configuring your own kernel however,
  1370. so if you do decide to build a custom kernel you'll have to seek out other
  1371. guides to create a kernel which is just right for your needs.
  1372. The second way to setup the kernel configuration makes more use of Guix's
  1373. features and allows you to share configuration segments between different
  1374. kernels. For example, all machines using EFI to boot have a number of EFI
  1375. configuration flags that they need. It is likely that all the kernels will
  1376. share a list of file systems to support. By using variables it is easier to
  1377. see at a glance what features are enabled and to make sure you don't have
  1378. features in one kernel but missing in another.
  1379. Left undiscussed however, is Guix's initrd and its customization. It is
  1380. likely that you'll need to modify the initrd on a machine using a custom
  1381. kernel, since certain modules which are expected to be built may not be
  1382. available for inclusion into the initrd.
  1383. @node Guix System Image API
  1384. @section Guix System Image API
  1385. Historically, Guix System is centered around an @code{operating-system}
  1386. structure. This structure contains various fields ranging from the
  1387. bootloader and kernel declaration to the services to install.
  1388. Depending on the target machine, that can go from a standard
  1389. @code{x86_64} machine to a small ARM single board computer such as the
  1390. Pine64, the image constraints can vary a lot. The hardware
  1391. manufacturers will impose different image formats with various partition
  1392. sizes and offsets.
  1393. To create images suitable for all those machines, a new abstraction is
  1394. necessary: that's the goal of the @code{image} record. This record
  1395. contains all the required information to be transformed into a
  1396. standalone image, that can be directly booted on any target machine.
  1397. @lisp
  1398. (define-record-type* <image>
  1399. image make-image
  1400. image?
  1401. (name image-name ;symbol
  1402. (default #f))
  1403. (format image-format) ;symbol
  1404. (target image-target
  1405. (default #f))
  1406. (size image-size ;size in bytes as integer
  1407. (default 'guess))
  1408. (operating-system image-operating-system ;<operating-system>
  1409. (default #f))
  1410. (partitions image-partitions ;list of <partition>
  1411. (default '()))
  1412. (compression? image-compression? ;boolean
  1413. (default #t))
  1414. (volatile-root? image-volatile-root? ;boolean
  1415. (default #t))
  1416. (substitutable? image-substitutable? ;boolean
  1417. (default #t)))
  1418. @end lisp
  1419. This record contains the operating-system to instantiate. The
  1420. @code{format} field defines the image type and can be @code{efi-raw},
  1421. @code{qcow2} or @code{iso9660} for instance. In the future, it could be
  1422. extended to @code{docker} or other image types.
  1423. A new directory in the Guix sources is dedicated to images definition. For now
  1424. there are four files:
  1425. @itemize @bullet
  1426. @item @file{gnu/system/images/hurd.scm}
  1427. @item @file{gnu/system/images/pine64.scm}
  1428. @item @file{gnu/system/images/novena.scm}
  1429. @item @file{gnu/system/images/pinebook-pro.scm}
  1430. @end itemize
  1431. Let's have a look to @file{pine64.scm}. It contains the
  1432. @code{pine64-barebones-os} variable which is a minimal definition of an
  1433. operating-system dedicated to the @b{Pine A64 LTS} board.
  1434. @lisp
  1435. (define pine64-barebones-os
  1436. (operating-system
  1437. (host-name "vignemale")
  1438. (timezone "Europe/Paris")
  1439. (locale "en_US.utf8")
  1440. (bootloader (bootloader-configuration
  1441. (bootloader u-boot-pine64-lts-bootloader)
  1442. (targets '("/dev/vda"))))
  1443. (initrd-modules '())
  1444. (kernel linux-libre-arm64-generic)
  1445. (file-systems (cons (file-system
  1446. (device (file-system-label "my-root"))
  1447. (mount-point "/")
  1448. (type "ext4"))
  1449. %base-file-systems))
  1450. (services (cons (service agetty-service-type
  1451. (agetty-configuration
  1452. (extra-options '("-L")) ; no carrier detect
  1453. (baud-rate "115200")
  1454. (term "vt100")
  1455. (tty "ttyS0")))
  1456. %base-services))))
  1457. @end lisp
  1458. The @code{kernel} and @code{bootloader} fields are pointing to packages
  1459. dedicated to this board.
  1460. Right below, the @code{pine64-image-type} variable is also defined.
  1461. @lisp
  1462. (define pine64-image-type
  1463. (image-type
  1464. (name 'pine64-raw)
  1465. (constructor (cut image-with-os arm64-disk-image <>))))
  1466. @end lisp
  1467. It's using a record we haven't talked about yet, the @code{image-type} record,
  1468. defined this way:
  1469. @lisp
  1470. (define-record-type* <image-type>
  1471. image-type make-image-type
  1472. image-type?
  1473. (name image-type-name) ;symbol
  1474. (constructor image-type-constructor)) ;<operating-system> -> <image>
  1475. @end lisp
  1476. The main purpose of this record is to associate a name to a procedure
  1477. transforming an @code{operating-system} to an image. To understand why
  1478. it is necessary, let's have a look to the command producing an image
  1479. from an @code{operating-system} configuration file:
  1480. @example
  1481. guix system image my-os.scm
  1482. @end example
  1483. This command expects an @code{operating-system} configuration but how
  1484. should we indicate that we want an image targeting a Pine64 board? We
  1485. need to provide an extra information, the @code{image-type}, by passing
  1486. the @code{--image-type} or @code{-t} flag, this way:
  1487. @example
  1488. guix system image --image-type=pine64-raw my-os.scm
  1489. @end example
  1490. This @code{image-type} parameter points to the @code{pine64-image-type}
  1491. defined above. Hence, the @code{operating-system} declared in
  1492. @code{my-os.scm} will be applied the @code{(cut image-with-os
  1493. arm64-disk-image <>)} procedure to turn it into an image.
  1494. The resulting image looks like:
  1495. @lisp
  1496. (image
  1497. (format 'disk-image)
  1498. (target "aarch64-linux-gnu")
  1499. (operating-system my-os)
  1500. (partitions
  1501. (list (partition
  1502. (inherit root-partition)
  1503. (offset root-offset)))))
  1504. @end lisp
  1505. which is the aggregation of the @code{operating-system} defined in
  1506. @code{my-os.scm} to the @code{arm64-disk-image} record.
  1507. But enough Scheme madness. What does this image API bring to the Guix user?
  1508. One can run:
  1509. @example
  1510. mathieu@@cervin:~$ guix system --list-image-types
  1511. The available image types are:
  1512. - pinebook-pro-raw
  1513. - pine64-raw
  1514. - novena-raw
  1515. - hurd-raw
  1516. - hurd-qcow2
  1517. - qcow2
  1518. - uncompressed-iso9660
  1519. - efi-raw
  1520. - arm64-raw
  1521. - arm32-raw
  1522. - iso9660
  1523. @end example
  1524. and by writing an @code{operating-system} file based on
  1525. @code{pine64-barebones-os}, you can customize your image to your
  1526. preferences in a file (@file{my-pine-os.scm}) like this:
  1527. @lisp
  1528. (use-modules (gnu services linux)
  1529. (gnu system images pine64))
  1530. (let ((base-os pine64-barebones-os))
  1531. (operating-system
  1532. (inherit base-os)
  1533. (timezone "America/Indiana/Indianapolis")
  1534. (services
  1535. (cons
  1536. (service earlyoom-service-type
  1537. (earlyoom-configuration
  1538. (prefer-regexp "icecat|chromium")))
  1539. (operating-system-user-services base-os)))))
  1540. @end lisp
  1541. run:
  1542. @example
  1543. guix system image --image-type=pine64-raw my-pine-os.scm
  1544. @end example
  1545. or,
  1546. @example
  1547. guix system image --image-type=hurd-raw my-hurd-os.scm
  1548. @end example
  1549. to get an image that can be written directly to a hard drive and booted
  1550. from.
  1551. Without changing anything to @code{my-hurd-os.scm}, calling:
  1552. @example
  1553. guix system image --image-type=hurd-qcow2 my-hurd-os.scm
  1554. @end example
  1555. will instead produce a Hurd QEMU image.
  1556. @node Using security keys
  1557. @section Using security keys
  1558. @cindex 2FA, two-factor authentication
  1559. @cindex U2F, Universal 2nd Factor
  1560. @cindex security key, configuration
  1561. The use of security keys can improve your security by providing a second
  1562. authentication source that cannot be easily stolen or copied, at least
  1563. for a remote adversary (something that you have), to the main secret (a
  1564. passphrase -- something that you know), reducing the risk of
  1565. impersonation.
  1566. The example configuration detailed below showcases what minimal
  1567. configuration needs to be made on your Guix System to allow the use of a
  1568. Yubico security key. It is hoped the configuration can be useful for
  1569. other security keys as well, with minor adjustments.
  1570. @subsection Configuration for use as a two-factor authenticator (2FA)
  1571. To be usable, the udev rules of the system should be extended with
  1572. key-specific rules. The following shows how to extend your udev rules
  1573. with the @file{lib/udev/rules.d/70-u2f.rules} udev rule file provided by
  1574. the @code{libfido2} package from the @code{(gnu packages
  1575. security-token)} module and add your user to the @samp{"plugdev"} group
  1576. it uses:
  1577. @lisp
  1578. (use-package-modules ... security-token ...)
  1579. ...
  1580. (operating-system
  1581. ...
  1582. (users (cons* (user-account
  1583. (name "your-user")
  1584. (group "users")
  1585. (supplementary-groups
  1586. '("wheel" "netdev" "audio" "video"
  1587. "plugdev")) ;<- added system group
  1588. (home-directory "/home/your-user"))
  1589. %base-user-accounts))
  1590. ...
  1591. (services
  1592. (cons*
  1593. ...
  1594. (udev-rules-service 'fido2 libfido2 #:groups '("plugdev")))))
  1595. @end lisp
  1596. After re-configuring your system and re-logging in your graphical
  1597. session so that the new group is in effect for your user, you can verify
  1598. that your key is usable by launching:
  1599. @example
  1600. guix shell ungoogled-chromium -- chromium chrome://settings/securityKeys
  1601. @end example
  1602. and validating that the security key can be reset via the ``Reset your
  1603. security key'' menu. If it works, congratulations, your security key is
  1604. ready to be used with applications supporting two-factor authentication
  1605. (2FA).
  1606. @node Connecting to Wireguard VPN
  1607. @section Connecting to Wireguard VPN
  1608. To connect to a Wireguard VPN server you need the kernel module to be
  1609. loaded in memory and a package providing networking tools that support
  1610. it (e.g. @code{wireguard-tools} or @code{network-manager}).
  1611. Here is a configuration example for Linux-Libre < 5.6, where the module
  1612. is out of tree and need to be loaded manually---following revisions of
  1613. the kernel have it built-in and so don't need such configuration:
  1614. @lisp
  1615. (use-modules (gnu))
  1616. (use-service-modules desktop)
  1617. (use-package-modules vpn)
  1618. (operating-system
  1619. ;; …
  1620. (services (cons (simple-service 'wireguard-module
  1621. kernel-module-loader-service-type
  1622. '("wireguard"))
  1623. %desktop-services))
  1624. (packages (cons wireguard-tools %base-packages))
  1625. (kernel-loadable-modules (list wireguard-linux-compat)))
  1626. @end lisp
  1627. After reconfiguring and restarting your system you can either use
  1628. Wireguard tools or NetworkManager to connect to a VPN server.
  1629. @subsection Using Wireguard tools
  1630. To test your Wireguard setup it is convenient to use @command{wg-quick}.
  1631. Just give it a configuration file @command{wg-quick up ./wg0.conf}; or
  1632. put that file in @file{/etc/wireguard} and run @command{wg-quick up wg0}
  1633. instead.
  1634. @quotation Note
  1635. Be warned that the author described this command as a: “[…] very quick
  1636. and dirty bash script […]”.
  1637. @end quotation
  1638. @subsection Using NetworkManager
  1639. Thanks to NetworkManager support for Wireguard we can connect to our VPN
  1640. using @command{nmcli} command. Up to this point this guide assumes that
  1641. you're using Network Manager service provided by
  1642. @code{%desktop-services}. Ortherwise you need to adjust your services
  1643. list to load @code{network-manager-service-type} and reconfigure your
  1644. Guix system.
  1645. To import your VPN configuration execute nmcli import command:
  1646. @example shell
  1647. # nmcli connection import type wireguard file wg0.conf
  1648. Connection 'wg0' (edbee261-aa5a-42db-b032-6c7757c60fde) successfully added
  1649. @end example
  1650. This will create a configuration file in
  1651. @file{/etc/NetworkManager/wg0.nmconnection}. Next connect to the
  1652. Wireguard server:
  1653. @example shell
  1654. $ nmcli connection up wg0
  1655. Connection successfully activated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/6)
  1656. @end example
  1657. By default NetworkManager will connect automatically on system boot. To
  1658. change that behaviour you need to edit your config:
  1659. @example shell
  1660. # nmcli connection modify wg0 connection.autoconnect no
  1661. @end example
  1662. For more specific information about NetworkManager and wireguard
  1663. @uref{https://blogs.gnome.org/thaller/2019/03/15/wireguard-in-networkmanager/,see
  1664. this post by thaller}.
  1665. @node Customizing a Window Manager
  1666. @section Customizing a Window Manager
  1667. @cindex wm
  1668. @node StumpWM
  1669. @subsection StumpWM
  1670. @cindex stumpwm
  1671. You could install StumpWM with a Guix system by adding
  1672. @code{stumpwm} and optionally @code{`(,stumpwm "lib")}
  1673. packages to a system configuration file, e.g.@: @file{/etc/config.scm}.
  1674. An example configuration can look like this:
  1675. @lisp
  1676. (use-modules (gnu))
  1677. (use-package-modules wm)
  1678. (operating-system
  1679. ;; …
  1680. (packages (append (list sbcl stumpwm `(,stumpwm "lib"))
  1681. %base-packages)))
  1682. @end lisp
  1683. @cindex stumpwm fonts
  1684. By default StumpWM uses X11 fonts, which could be small or pixelated on
  1685. your system. You could fix this by installing StumpWM contrib Lisp
  1686. module @code{sbcl-ttf-fonts}, adding it to Guix system packages:
  1687. @lisp
  1688. (use-modules (gnu))
  1689. (use-package-modules fonts wm)
  1690. (operating-system
  1691. ;; …
  1692. (packages (append (list sbcl stumpwm `(,stumpwm "lib"))
  1693. sbcl-ttf-fonts font-dejavu %base-packages)))
  1694. @end lisp
  1695. Then you need to add the following code to a StumpWM configuration file
  1696. @file{~/.stumpwm.d/init.lisp}:
  1697. @lisp
  1698. (require :ttf-fonts)
  1699. (setf xft:*font-dirs* '("/run/current-system/profile/share/fonts/"))
  1700. (setf clx-truetype:+font-cache-filename+ (concat (getenv "HOME") "/.fonts/font-cache.sexp"))
  1701. (xft:cache-fonts)
  1702. (set-font (make-instance 'xft:font :family "DejaVu Sans Mono" :subfamily "Book" :size 11))
  1703. @end lisp
  1704. @node Session lock
  1705. @subsection Session lock
  1706. @cindex sessionlock
  1707. Depending on your environment, locking the screen of your session might come built in
  1708. or it might be something you have to set up yourself. If you use a desktop environment
  1709. like GNOME or KDE, it's usually built in. If you use a plain window manager like
  1710. StumpWM or EXWM, you might have to set it up yourself.
  1711. @node Xorg
  1712. @subsubsection Xorg
  1713. If you use Xorg, you can use the utility
  1714. @uref{https://www.mankier.com/1/xss-lock, xss-lock} to lock the screen of your session.
  1715. xss-lock is triggered by DPMS which since Xorg 1.8 is auto-detected and enabled if
  1716. ACPI is also enabled at kernel runtime.
  1717. To use xss-lock, you can simple execute it and put it into the background before
  1718. you start your window manager from e.g. your @file{~/.xsession}:
  1719. @example
  1720. xss-lock -- slock &
  1721. exec stumpwm
  1722. @end example
  1723. In this example, xss-lock uses @code{slock} to do the actual locking of the screen when
  1724. it determines it's appropriate, like when you suspend your device.
  1725. For slock to be allowed to be a screen locker for the graphical session, it needs to
  1726. be made setuid-root so it can authenticate users, and it needs a PAM service. This
  1727. can be achieved by adding the following service to your @file{config.scm}:
  1728. @lisp
  1729. (screen-locker-service slock)
  1730. @end lisp
  1731. If you manually lock your screen, e.g. by directly calling slock when you want to lock
  1732. your screen but not suspend it, it's a good idea to notify xss-lock about this so no
  1733. confusion occurs. This can be done by executing @code{xset s activate} immediately
  1734. before you execute slock.
  1735. @node Running Guix on a Linode Server
  1736. @section Running Guix on a Linode Server
  1737. @cindex linode, Linode
  1738. To run Guix on a server hosted by @uref{https://www.linode.com, Linode},
  1739. start with a recommended Debian server. We recommend using the default
  1740. distro as a way to bootstrap Guix. Create your SSH keys.
  1741. @example
  1742. ssh-keygen
  1743. @end example
  1744. Be sure to add your SSH key for easy login to the remote server.
  1745. This is trivially done via Linode's graphical interface for adding
  1746. SSH keys. Go to your profile and click add SSH Key.
  1747. Copy into it the output of:
  1748. @example
  1749. cat ~/.ssh/<username>_rsa.pub
  1750. @end example
  1751. Power the Linode down.
  1752. In the Linode's Storage tab, resize the Debian disk to be smaller.
  1753. 30 GB free space is recommended. Then click "Add a disk", and fill
  1754. out the form with the following:
  1755. @itemize @bullet
  1756. @item
  1757. Label: "Guix"
  1758. @item
  1759. Filesystem: ext4
  1760. @item
  1761. Set it to the remaining size
  1762. @end itemize
  1763. In the Configurations tab, press "Edit" on the default Debian profile.
  1764. Under "Block Device Assignment" click "Add a Device". It should be
  1765. @file{/dev/sdc} and you can select the "Guix" disk. Save Changes.
  1766. Now "Add a Configuration", with the following:
  1767. @itemize @bullet
  1768. @item
  1769. Label: Guix
  1770. @item
  1771. Kernel:GRUB 2 (it's at the bottom! This step is @b{IMPORTANT!})
  1772. @item
  1773. Block device assignment:
  1774. @item
  1775. @file{/dev/sda}: Guix
  1776. @item
  1777. @file{/dev/sdb}: swap
  1778. @item
  1779. Root device: @file{/dev/sda}
  1780. @item
  1781. Turn off all the filesystem/boot helpers
  1782. @end itemize
  1783. Now power it back up, booting with the Debian configuration. Once it's
  1784. running, ssh to your server via @code{ssh
  1785. root@@@var{<your-server-IP-here>}}. (You can find your server IP address in
  1786. your Linode Summary section.) Now you can run the "install guix from
  1787. @pxref{Binary Installation,,, guix, GNU Guix}" steps:
  1788. @example
  1789. sudo apt-get install gpg
  1790. wget https://sv.gnu.org/people/viewgpg.php?user_id=15145 -qO - | gpg --import -
  1791. wget https://git.savannah.gnu.org/cgit/guix.git/plain/etc/guix-install.sh
  1792. chmod +x guix-install.sh
  1793. ./guix-install.sh
  1794. guix pull
  1795. @end example
  1796. Now it's time to write out a config for the server. The key information
  1797. is below. Save the resulting file as @file{guix-config.scm}.
  1798. @lisp
  1799. (use-modules (gnu)
  1800. (guix modules))
  1801. (use-service-modules networking
  1802. ssh)
  1803. (use-package-modules admin
  1804. certs
  1805. package-management
  1806. ssh
  1807. tls)
  1808. (operating-system
  1809. (host-name "my-server")
  1810. (timezone "America/New_York")
  1811. (locale "en_US.UTF-8")
  1812. ;; This goofy code will generate the grub.cfg
  1813. ;; without installing the grub bootloader on disk.
  1814. (bootloader (bootloader-configuration
  1815. (bootloader
  1816. (bootloader
  1817. (inherit grub-bootloader)
  1818. (installer #~(const #true))))))
  1819. (file-systems (cons (file-system
  1820. (device "/dev/sda")
  1821. (mount-point "/")
  1822. (type "ext4"))
  1823. %base-file-systems))
  1824. (swap-devices (list "/dev/sdb"))
  1825. (initrd-modules (cons "virtio_scsi" ; Needed to find the disk
  1826. %base-initrd-modules))
  1827. (users (cons (user-account
  1828. (name "janedoe")
  1829. (group "users")
  1830. ;; Adding the account to the "wheel" group
  1831. ;; makes it a sudoer.
  1832. (supplementary-groups '("wheel"))
  1833. (home-directory "/home/janedoe"))
  1834. %base-user-accounts))
  1835. (packages (cons* nss-certs ;for HTTPS access
  1836. openssh-sans-x
  1837. %base-packages))
  1838. (services (cons*
  1839. (service dhcp-client-service-type)
  1840. (service openssh-service-type
  1841. (openssh-configuration
  1842. (openssh openssh-sans-x)
  1843. (password-authentication? #false)
  1844. (authorized-keys
  1845. `(("janedoe" ,(local-file "janedoe_rsa.pub"))
  1846. ("root" ,(local-file "janedoe_rsa.pub"))))))
  1847. %base-services)))
  1848. @end lisp
  1849. Replace the following fields in the above configuration:
  1850. @lisp
  1851. (host-name "my-server") ; replace with your server name
  1852. ; if you chose a linode server outside the U.S., then
  1853. ; use tzselect to find a correct timezone string
  1854. (timezone "America/New_York") ; if needed replace timezone
  1855. (name "janedoe") ; replace with your username
  1856. ("janedoe" ,(local-file "janedoe_rsa.pub")) ; replace with your ssh key
  1857. ("root" ,(local-file "janedoe_rsa.pub")) ; replace with your ssh key
  1858. @end lisp
  1859. The last line in the above example lets you log into the server as root
  1860. and set the initial root password (see the note at the end of this
  1861. recipe about root login). After you have done this, you may
  1862. delete that line from your configuration and reconfigure to prevent root
  1863. login.
  1864. Copy your ssh public key (eg: @file{~/.ssh/id_rsa.pub}) as
  1865. @file{@var{<your-username-here>}_rsa.pub} and put
  1866. @file{guix-config.scm} in the same directory. In a new terminal run
  1867. these commands.
  1868. @example
  1869. sftp root@@<remote server ip address>
  1870. put /path/to/files/<username>_rsa.pub .
  1871. put /path/to/files/guix-config.scm .
  1872. @end example
  1873. In your first terminal, mount the guix drive:
  1874. @example
  1875. mkdir /mnt/guix
  1876. mount /dev/sdc /mnt/guix
  1877. @end example
  1878. Due to the way we set up the bootloader section of the guix-config.scm,
  1879. only the grub configuration file will be installed. So, we need to copy
  1880. over some of the other GRUB stuff already installed on the Debian system:
  1881. @example
  1882. mkdir -p /mnt/guix/boot/grub
  1883. cp -r /boot/grub/* /mnt/guix/boot/grub/
  1884. @end example
  1885. Now initialize the Guix installation:
  1886. @example
  1887. guix system init guix-config.scm /mnt/guix
  1888. @end example
  1889. Ok, power it down!
  1890. Now from the Linode console, select boot and select "Guix".
  1891. Once it boots, you should be able to log in via SSH! (The server config
  1892. will have changed though.) You may encounter an error like:
  1893. @example
  1894. $ ssh root@@<server ip address>
  1895. @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
  1896. @ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @
  1897. @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
  1898. IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
  1899. Someone could be eavesdropping on you right now (man-in-the-middle attack)!
  1900. It is also possible that a host key has just been changed.
  1901. The fingerprint for the ECDSA key sent by the remote host is
  1902. SHA256:0B+wp33w57AnKQuHCvQP0+ZdKaqYrI/kyU7CfVbS7R4.
  1903. Please contact your system administrator.
  1904. Add correct host key in /home/joshua/.ssh/known_hosts to get rid of this message.
  1905. Offending ECDSA key in /home/joshua/.ssh/known_hosts:3
  1906. ECDSA host key for 198.58.98.76 has changed and you have requested strict checking.
  1907. Host key verification failed.
  1908. @end example
  1909. Either delete @file{~/.ssh/known_hosts} file, or delete the offending line
  1910. starting with your server IP address.
  1911. Be sure to set your password and root's password.
  1912. @example
  1913. ssh root@@<remote ip address>
  1914. passwd ; for the root password
  1915. passwd <username> ; for the user password
  1916. @end example
  1917. You may not be able to run the above commands at this point. If you
  1918. have issues remotely logging into your linode box via SSH, then you may
  1919. still need to set your root and user password initially by clicking on
  1920. the ``Launch Console'' option in your linode. Choose the ``Glish''
  1921. instead of ``Weblish''. Now you should be able to ssh into the machine.
  1922. Hooray! At this point you can shut down the server, delete the
  1923. Debian disk, and resize the Guix to the rest of the size.
  1924. Congratulations!
  1925. By the way, if you save it as a disk image right at this point, you'll
  1926. have an easy time spinning up new Guix images! You may need to
  1927. down-size the Guix image to 6144MB, to save it as an image. Then you
  1928. can resize it again to the max size.
  1929. @node Setting up a bind mount
  1930. @section Setting up a bind mount
  1931. To bind mount a file system, one must first set up some definitions
  1932. before the @code{operating-system} section of the system definition. In
  1933. this example we will bind mount a folder from a spinning disk drive to
  1934. @file{/tmp}, to save wear and tear on the primary SSD, without
  1935. dedicating an entire partition to be mounted as @file{/tmp}.
  1936. First, the source drive that hosts the folder we wish to bind mount
  1937. should be defined, so that the bind mount can depend on it.
  1938. @lisp
  1939. (define source-drive ;; "source-drive" can be named anything you want.
  1940. (file-system
  1941. (device (uuid "UUID goes here"))
  1942. (mount-point "/path-to-spinning-disk-goes-here")
  1943. (type "ext4"))) ;; Make sure to set this to the appropriate type for your drive.
  1944. @end lisp
  1945. The source folder must also be defined, so that guix will know it's not
  1946. a regular block device, but a folder.
  1947. @lisp
  1948. (define (%source-directory) "/path-to-spinning-disk-goes-here/tmp") ;; "source-directory" can be named any valid variable name.
  1949. @end lisp
  1950. Finally, inside the @code{file-systems} definition, we must add the
  1951. mount itself.
  1952. @lisp
  1953. (file-systems (cons*
  1954. ...<other drives omitted for clarity>...
  1955. source-drive ;; Must match the name you gave the source drive in the earlier definition.
  1956. (file-system
  1957. (device (%source-directory)) ;; Make sure "source-directory" matches your earlier definition.
  1958. (mount-point "/tmp")
  1959. (type "none") ;; We are mounting a folder, not a partition, so this type needs to be "none"
  1960. (flags '(bind-mount))
  1961. (dependencies (list source-drive)) ;; Ensure "source-drive" matches what you've named the variable for the drive.
  1962. )
  1963. ...<other drives omitted for clarity>...
  1964. ))
  1965. @end lisp
  1966. @node Getting substitutes from Tor
  1967. @section Getting substitutes from Tor
  1968. Guix daemon can use a HTTP proxy to get substitutes, here we are
  1969. configuring it to get them via Tor.
  1970. @quotation Warning
  1971. @emph{Not all} Guix daemon's traffic will go through Tor! Only
  1972. HTTP/HTTPS will get proxied; FTP, Git protocol, SSH, etc connections
  1973. will still go through the clearnet. Again, this configuration isn't
  1974. foolproof some of your traffic won't get routed by Tor at all. Use it
  1975. at your own risk.
  1976. Also note that the procedure described here applies only to package
  1977. substitution. When you update your guix distribution with
  1978. @command{guix pull}, you still need to use @command{torsocks} if
  1979. you want to route the connection to guix's git repository servers
  1980. through Tor.
  1981. @end quotation
  1982. Guix's substitute server is available as a Onion service, if you want
  1983. to use it to get your substitutes through Tor configure your system as
  1984. follow:
  1985. @lisp
  1986. (use-modules (gnu))
  1987. (use-service-module base networking)
  1988. (operating-system
  1989. (services
  1990. (cons
  1991. (service tor-service-type
  1992. (tor-configuration
  1993. (config-file (plain-file "tor-config"
  1994. "HTTPTunnelPort 127.0.0.1:9250"))))
  1995. (modify-services %base-services
  1996. (guix-service-type
  1997. config => (guix-configuration
  1998. (inherit config)
  1999. ;; ci.guix.gnu.org's Onion service
  2000. (substitute-urls
  2001. "@value{SUBSTITUTE-TOR-URL}")
  2002. (http-proxy "http://localhost:9250")))))))
  2003. @end lisp
  2004. This will keep a tor process running that provides a HTTP CONNECT tunnel
  2005. which will be used by @command{guix-daemon}. The daemon can use other
  2006. protocols than HTTP(S) to get remote resources, request using those
  2007. protocols won't go through Tor since we are only setting a HTTP tunnel
  2008. here. Note that @code{substitutes-urls} is using HTTPS and not HTTP or
  2009. it won't work, that's a limitation of Tor's tunnel; you may want to use
  2010. @command{privoxy} instead to avoid such limitations.
  2011. If you don't want to always get substitutes through Tor but using it just
  2012. some of the times, then skip the @code{guix-configuration}. When you
  2013. want to get a substitute from the Tor tunnel run:
  2014. @example
  2015. sudo herd set-http-proxy guix-daemon http://localhost:9250
  2016. guix build \
  2017. --substitute-urls=@value{SUBSTITUTE-TOR-URL} @dots{}
  2018. @end example
  2019. @node Setting up NGINX with Lua
  2020. @section Setting up NGINX with Lua
  2021. @cindex nginx, lua, openresty, resty
  2022. NGINX could be extended with Lua scripts.
  2023. Guix provides NGINX service with ability to load Lua module and specific
  2024. Lua packages, and reply to requests by evaluating Lua scripts.
  2025. The following example demonstrates system definition with configuration
  2026. to evaluate @file{index.lua} Lua script on HTTP request to
  2027. @uref{http://localhost/hello} endpoint:
  2028. @example
  2029. local shell = require "resty.shell"
  2030. local stdin = ""
  2031. local timeout = 1000 -- ms
  2032. local max_size = 4096 -- byte
  2033. local ok, stdout, stderr, reason, status =
  2034. shell.run([[/run/current-system/profile/bin/ls /tmp]], stdin, timeout, max_size)
  2035. ngx.say(stdout)
  2036. @end example
  2037. @lisp
  2038. (use-modules (gnu))
  2039. (use-service-modules #;… web)
  2040. (use-package-modules #;… lua)
  2041. (operating-system
  2042. ;; …
  2043. (services
  2044. ;; …
  2045. (service nginx-service-type
  2046. (nginx-configuration
  2047. (modules
  2048. (list
  2049. (file-append nginx-lua-module "/etc/nginx/modules/ngx_http_lua_module.so")))
  2050. (lua-package-path (list lua-resty-core
  2051. lua-resty-lrucache
  2052. lua-resty-signal
  2053. lua-tablepool
  2054. lua-resty-shell))
  2055. (lua-package-cpath (list lua-resty-signal))
  2056. (server-blocks
  2057. (list (nginx-server-configuration
  2058. (server-name '("localhost"))
  2059. (listen '("80"))
  2060. (root "/etc")
  2061. (locations (list
  2062. (nginx-location-configuration
  2063. (uri "/hello")
  2064. (body (list #~(format #f "content_by_lua_file ~s;"
  2065. #$(local-file "index.lua"))))))))))))))
  2066. @end lisp
  2067. @node Music Server with Bluetooth Audio
  2068. @section Music Server with Bluetooth Audio
  2069. @cindex mpd
  2070. @cindex music server, headless
  2071. @cindex bluetooth, ALSA configuration
  2072. MPD, the Music Player Daemon, is a flexible server-side application for
  2073. playing music. Client programs on different machines on the network ---
  2074. a mobile phone, a laptop, a desktop workstation --- can connect to it to
  2075. control the playback of audio files from your local music collection.
  2076. MPD decodes the audio files and plays them back on one or many outputs.
  2077. By default MPD will play to the default audio device. In the example
  2078. below we make things a little more interesting by setting up a headless
  2079. music server. There will be no graphical user interface, no Pulseaudio
  2080. daemon, and no local audio output. Instead we will configure MPD with
  2081. two outputs: a bluetooth speaker and a web server to serve audio streams
  2082. to any streaming media player.
  2083. Bluetooth is often rather frustrating to set up. You will have to pair
  2084. your Bluetooth device and make sure that the device is automatically
  2085. connected as soon as it powers on. The Bluetooth system service
  2086. returned by the @code{bluetooth-service} procedure provides the
  2087. infrastructure needed to set this up.
  2088. Reconfigure your system with at least the following services and
  2089. packages:
  2090. @lisp
  2091. (operating-system
  2092. ;; …
  2093. (packages (cons* bluez bluez-alsa
  2094. %base-packages))
  2095. (services
  2096. ;; …
  2097. (dbus-service #:services (list bluez-alsa))
  2098. (bluetooth-service #:auto-enable? #t)))
  2099. @end lisp
  2100. Start the @code{bluetooth} service and then use @command{bluetoothctl}
  2101. to scan for Bluetooth devices. Try to identify your Bluetooth speaker
  2102. and pick out its device ID from the resulting list of devices that is
  2103. indubitably dominated by a baffling smorgasbord of your neighbors' home
  2104. automation gizmos. This only needs to be done once:
  2105. @example
  2106. $ bluetoothctl
  2107. [NEW] Controller 00:11:22:33:95:7F BlueZ 5.40 [default]
  2108. [bluetooth]# power on
  2109. [bluetooth]# Changing power on succeeded
  2110. [bluetooth]# agent on
  2111. [bluetooth]# Agent registered
  2112. [bluetooth]# default-agent
  2113. [bluetooth]# Default agent request successful
  2114. [bluetooth]# scan on
  2115. [bluetooth]# Discovery started
  2116. [CHG] Controller 00:11:22:33:95:7F Discovering: yes
  2117. [NEW] Device AA:BB:CC:A4:AA:CD My Bluetooth Speaker
  2118. [NEW] Device 44:44:FF:2A:20:DC My Neighbor's TV
  2119. @dots{}
  2120. [bluetooth]# pair AA:BB:CC:A4:AA:CD
  2121. Attempting to pair with AA:BB:CC:A4:AA:CD
  2122. [CHG] Device AA:BB:CC:A4:AA:CD Connected: yes
  2123. [My Bluetooth Speaker]# [CHG] Device AA:BB:CC:A4:AA:CD UUIDs: 0000110b-0000-1000-8000-00xxxxxxxxxx
  2124. [CHG] Device AA:BB:CC:A4:AA:CD UUIDs: 0000110c-0000-1000-8000-00xxxxxxxxxx
  2125. [CHG] Device AA:BB:CC:A4:AA:CD UUIDs: 0000110e-0000-1000-8000-00xxxxxxxxxx
  2126. [CHG] Device AA:BB:CC:A4:AA:CD Paired: yes
  2127. Pairing successful
  2128. [CHG] Device AA:BB:CC:A4:AA:CD Connected: no
  2129. [bluetooth]#
  2130. [bluetooth]# trust AA:BB:CC:A4:AA:CD
  2131. [bluetooth]# [CHG] Device AA:BB:CC:A4:AA:CD Trusted: yes
  2132. Changing AA:BB:CC:A4:AA:CD trust succeeded
  2133. [bluetooth]#
  2134. [bluetooth]# connect AA:BB:CC:A4:AA:CD
  2135. Attempting to connect to AA:BB:CC:A4:AA:CD
  2136. [bluetooth]# [CHG] Device AA:BB:CC:A4:AA:CD RSSI: -63
  2137. [CHG] Device AA:BB:CC:A4:AA:CD Connected: yes
  2138. Connection successful
  2139. [My Bluetooth Speaker]# scan off
  2140. [CHG] Device AA:BB:CC:A4:AA:CD RSSI is nil
  2141. Discovery stopped
  2142. [CHG] Controller 00:11:22:33:95:7F Discovering: no
  2143. @end example
  2144. Congratulations, you can now automatically connect to your Bluetooth
  2145. speaker!
  2146. It is now time to configure ALSA to use the @emph{bluealsa} Bluetooth
  2147. module, so that you can define an ALSA pcm device corresponding to your
  2148. Bluetooth speaker. For a headless server using @emph{bluealsa} with a
  2149. fixed Bluetooth device is likely simpler than configuring Pulseaudio and
  2150. its stream switching behavior. We configure ALSA by crafting a custom
  2151. @code{alsa-configuration} for the @code{alsa-service-type}. The
  2152. configuration will declare a @code{pcm} type @code{bluealsa} from the
  2153. @code{bluealsa} module provided by the @code{bluez-alsa} package, and
  2154. then define a @code{pcm} device of that type for your Bluetooth speaker.
  2155. All that is left then is to make MPD send audio data to this ALSA
  2156. device. We also add a secondary MPD output that makes the currently
  2157. played audio files available as a stream through a web server on port
  2158. 8080. When enabled a device on the network could listen to the audio
  2159. stream by connecting any capable media player to the HTTP server on port
  2160. 8080, independent of the status of the Bluetooth speaker.
  2161. What follows is the outline of an @code{operating-system} declaration
  2162. that should accomplish the above-mentioned tasks:
  2163. @lisp
  2164. (use-modules (gnu))
  2165. (use-service-modules audio dbus sound #;… etc)
  2166. (use-package-modules audio linux #;… etc)
  2167. (operating-system
  2168. ;; …
  2169. (packages (cons* bluez bluez-alsa
  2170. %base-packages))
  2171. (services
  2172. ;; …
  2173. (service mpd-service-type
  2174. (mpd-configuration
  2175. (user "your-username")
  2176. (music-dir "/path/to/your/music")
  2177. (address "192.168.178.20")
  2178. (outputs (list (mpd-output
  2179. (type "alsa")
  2180. (name "MPD")
  2181. (extra-options
  2182. ;; Use the same name as in the ALSA
  2183. ;; configuration below.
  2184. '((device . "pcm.btspeaker"))))
  2185. (mpd-output
  2186. (type "httpd")
  2187. (name "streaming")
  2188. (enabled? #false)
  2189. (always-on? #true)
  2190. (tags? #true)
  2191. (mixer-type 'null)
  2192. (extra-options
  2193. '((encoder . "vorbis")
  2194. (port . "8080")
  2195. (bind-to-address . "192.168.178.20")
  2196. (max-clients . "0") ;no limit
  2197. (quality . "5.0")
  2198. (format . "44100:16:1"))))))))
  2199. (dbus-service #:services (list bluez-alsa))
  2200. (bluetooth-service #:auto-enable? #t)
  2201. (service alsa-service-type
  2202. (alsa-configuration
  2203. (pulseaudio? #false) ;we don't need it
  2204. (extra-options
  2205. #~(string-append "\
  2206. # Declare Bluetooth audio device type \"bluealsa\" from bluealsa module
  2207. pcm_type.bluealsa @{
  2208. lib \"" #$(file-append bluez-alsa "/lib/alsa-lib/libasound_module_pcm_bluealsa.so") "\"
  2209. @}
  2210. # Declare control device type \"bluealsa\" from the same module
  2211. ctl_type.bluealsa @{
  2212. lib \"" #$(file-append bluez-alsa "/lib/alsa-lib/libasound_module_ctl_bluealsa.so") "\"
  2213. @}
  2214. # Define the actual Bluetooth audio device.
  2215. pcm.btspeaker @{
  2216. type bluealsa
  2217. device \"AA:BB:CC:A4:AA:CD\" # unique device identifier
  2218. profile \"a2dp\"
  2219. @}
  2220. # Define an associated controller.
  2221. ctl.btspeaker @{
  2222. type bluealsa
  2223. @}
  2224. "))))))
  2225. @end lisp
  2226. Enjoy the music with the MPD client of your choice or a media player
  2227. capable of streaming via HTTP!
  2228. @c *********************************************************************
  2229. @node Containers
  2230. @chapter Containers
  2231. The kernel Linux provides a number of shared facilities that are
  2232. available to processes in the system. These facilities include a shared
  2233. view on the file system, other processes, network devices, user and
  2234. group identities, and a few others. Since Linux 3.19 a user can choose
  2235. to @emph{unshare} some of these shared facilities for selected
  2236. processes, providing them (and their child processes) with a different
  2237. view on the system.
  2238. A process with an unshared @code{mount} namespace, for example, has its
  2239. own view on the file system --- it will only be able to see directories
  2240. that have been explicitly bound in its mount namespace. A process with
  2241. its own @code{proc} namespace will consider itself to be the only
  2242. process running on the system, running as PID 1.
  2243. Guix uses these kernel features to provide fully isolated environments
  2244. and even complete Guix System containers, lightweight virtual machines
  2245. that share the host system's kernel. This feature comes in especially
  2246. handy when using Guix on a foreign distribution to prevent interference
  2247. from foreign libraries or configuration files that are available
  2248. system-wide.
  2249. @menu
  2250. * Guix Containers:: Perfectly isolated environments
  2251. * Guix System Containers:: A system inside your system
  2252. @end menu
  2253. @node Guix Containers
  2254. @section Guix Containers
  2255. The easiest way to get started is to use @command{guix shell} with the
  2256. @option{--container} option. @xref{Invoking guix shell,,, guix, GNU
  2257. Guix Reference Manual} for a reference of valid options.
  2258. The following snippet spawns a minimal shell process with most
  2259. namespaces unshared from the system. The current working directory is
  2260. visible to the process, but anything else on the file system is
  2261. unavailable. This extreme isolation can be very useful when you want to
  2262. rule out any sort of interference from environment variables, globally
  2263. installed libraries, or configuration files.
  2264. @example
  2265. guix shell --container
  2266. @end example
  2267. It is a bleak environment, barren, desolate. You will find that not
  2268. even the GNU coreutils are available here, so to explore this deserted
  2269. wasteland you need to use built-in shell commands. Even the usually
  2270. gigantic @file{/gnu/store} directory is reduced to a faint shadow of
  2271. itself.
  2272. @example sh
  2273. $ echo /gnu/store/*
  2274. /gnu/store/@dots{}-gcc-10.3.0-lib
  2275. /gnu/store/@dots{}-glibc-2.33
  2276. /gnu/store/@dots{}-bash-static-5.1.8
  2277. /gnu/store/@dots{}-ncurses-6.2.20210619
  2278. /gnu/store/@dots{}-bash-5.1.8
  2279. /gnu/store/@dots{}-profile
  2280. /gnu/store/@dots{}-readline-8.1.1
  2281. @end example
  2282. @cindex exiting a container
  2283. There isn't much you can do in an environment like this other than
  2284. exiting it. You can use @key{^D} or @command{exit} to terminate this
  2285. limited shell environment.
  2286. @cindex exposing directories, container
  2287. @cindex sharing directories, container
  2288. @cindex mapping locations, container
  2289. You can make other directories available inside of the container
  2290. environment; use @option{--expose=DIRECTORY} to bind-mount the given
  2291. directory as a read-only location inside the container, or use
  2292. @option{--share=DIRECTORY} to make the location writable. With an
  2293. additional mapping argument after the directory name you can control the
  2294. name of the directory inside the container. In the following example we
  2295. map @file{/etc} on the host system to @file{/the/host/etc} inside a
  2296. container in which the GNU coreutils are installed.
  2297. @example sh
  2298. $ guix shell --container --share=/etc=/the/host/etc coreutils
  2299. $ ls /the/host/etc
  2300. @end example
  2301. Similarly, you can prevent the current working directory from being
  2302. mapped into the container with the @option{--no-cwd} option. Another
  2303. good idea is to create a dedicated directory that will serve as the
  2304. container's home directory, and spawn the container shell from that
  2305. directory.
  2306. @cindex hide system libraries, container
  2307. @cindex avoid ABI mismatch, container
  2308. On a foreign system a container environment can be used to compile
  2309. software that cannot possibly be linked with system libraries or with
  2310. the system's compiler toolchain. A common use-case in a research
  2311. context is to install packages from within an R session. Outside of a
  2312. container environment there is a good chance that the foreign compiler
  2313. toolchain and incompatible system libraries are found first, resulting
  2314. in incompatible binaries that cannot be used by R. In a container shell
  2315. this problem disappears, as system libraries and executables simply
  2316. aren't available due to the unshared @code{mount} namespace.
  2317. Let's take a comprehensive manifest providing a comfortable development
  2318. environment for use with R:
  2319. @lisp
  2320. (specifications->manifest
  2321. (list "r-minimal"
  2322. ;; base packages
  2323. "bash-minimal"
  2324. "glibc-locales"
  2325. "nss-certs"
  2326. ;; Common command line tools lest the container is too empty.
  2327. "coreutils"
  2328. "grep"
  2329. "which"
  2330. "wget"
  2331. "sed"
  2332. ;; R markdown tools
  2333. "pandoc"
  2334. ;; Toolchain and common libraries for "install.packages"
  2335. "gcc-toolchain@@10"
  2336. "gfortran-toolchain"
  2337. "gawk"
  2338. "tar"
  2339. "gzip"
  2340. "unzip"
  2341. "make"
  2342. "cmake"
  2343. "pkg-config"
  2344. "cairo"
  2345. "libxt"
  2346. "openssl"
  2347. "curl"
  2348. "zlib"))
  2349. @end lisp
  2350. Let's use this to run R inside a container environment. For convenience
  2351. we share the @code{net} namespace to use the host system's network
  2352. interfaces. Now we can build R packages from source the traditional way
  2353. without having to worry about ABI mismatch or incompatibilities.
  2354. @example sh
  2355. $ guix shell --container --network --manifest=manifest.scm -- R
  2356. R version 4.2.1 (2022-06-23) -- "Funny-Looking Kid"
  2357. Copyright (C) 2022 The R Foundation for Statistical Computing
  2358. @dots{}
  2359. > e <- Sys.getenv("GUIX_ENVIRONMENT")
  2360. > Sys.setenv(GIT_SSL_CAINFO=paste0(e, "/etc/ssl/certs/ca-certificates.crt"))
  2361. > Sys.setenv(SSL_CERT_FILE=paste0(e, "/etc/ssl/certs/ca-certificates.crt"))
  2362. > Sys.setenv(SSL_CERT_DIR=paste0(e, "/etc/ssl/certs"))
  2363. > install.packages("Cairo", lib=paste0(getwd()))
  2364. @dots{}
  2365. * installing *source* package 'Cairo' ...
  2366. @dots{}
  2367. * DONE (Cairo)
  2368. The downloaded source packages are in
  2369. '/tmp/RtmpCuwdwM/downloaded_packages'
  2370. > library("Cairo", lib=getwd())
  2371. > # success!
  2372. @end example
  2373. Using container shells is fun, but they can become a little cumbersome
  2374. when you want to go beyond just a single interactive process. Some
  2375. tasks become a lot easier when they sit on the rock solid foundation of
  2376. a proper Guix System and its rich set of system services. The next
  2377. section shows you how to launch a complete Guix System inside of a
  2378. container.
  2379. @node Guix System Containers
  2380. @section Guix System Containers
  2381. The Guix System provides a wide array of interconnected system services
  2382. that are configured declaratively to form a dependable stateless GNU
  2383. System foundation for whatever tasks you throw at it. Even when using
  2384. Guix on a foreign distribution you can benefit from the design of Guix
  2385. System by running a system instance as a container. Using the same
  2386. kernel features of unshared namespaces mentioned in the previous
  2387. section, the resulting Guix System instance is isolated from the host
  2388. system and only shares file system locations that you explicitly
  2389. declare.
  2390. A Guix System container differs from the shell process created by
  2391. @command{guix shell --container} in a number of important ways. While
  2392. in a container shell the containerized process is a Bash shell process,
  2393. a Guix System container runs the Shepherd as PID 1. In a system
  2394. container all system services (@pxref{Services,,, guix, GNU Guix
  2395. Reference Manual}) are set up just as they would be on a Guix System in
  2396. a virtual machine or on bare metal---this includes daemons managed by
  2397. the GNU@tie{}Shepherd (@pxref{Shepherd Services,,, guix, GNU Guix
  2398. Reference Manual}) as well as other kinds of extensions to the operating
  2399. system (@pxref{Service Composition,,, guix, GNU Guix Reference Manual}).
  2400. The perceived increase in complexity of running a Guix System container
  2401. is easily justified when dealing with more complex applications that
  2402. have higher or just more rigid requirements on their execution
  2403. contexts---configuration files, dedicated user accounts, directories for
  2404. caches or log files, etc. In Guix System the demands of this kind of
  2405. software are satisfied through the deployment of system services.
  2406. @node A Database Container
  2407. @subsection A Database Container
  2408. A good example might be a PostgreSQL database server. Much of the
  2409. complexity of setting up such a database server is encapsulated in this
  2410. deceptively short service declaration:
  2411. @lisp
  2412. (service postgresql-service-type
  2413. (postgresql-configuration
  2414. (postgresql postgresql-14)))
  2415. @end lisp
  2416. A complete operating system declaration for use with a Guix System
  2417. container would look something like this:
  2418. @lisp
  2419. (use-modules (gnu))
  2420. (use-package-modules databases)
  2421. (use-service-modules databases)
  2422. (operating-system
  2423. (host-name "container")
  2424. (timezone "Europe/Berlin")
  2425. (file-systems (cons (file-system
  2426. (device (file-system-label "does-not-matter"))
  2427. (mount-point "/")
  2428. (type "ext4"))
  2429. %base-file-systems))
  2430. (bootloader (bootloader-configuration
  2431. (bootloader grub-bootloader)
  2432. (targets '("/dev/sdX"))))
  2433. (services
  2434. (cons* (service postgresql-service-type
  2435. (postgresql-configuration
  2436. (postgresql postgresql-14)
  2437. (config-file
  2438. (postgresql-config-file
  2439. (log-destination "stderr")
  2440. (hba-file
  2441. (plain-file "pg_hba.conf"
  2442. "\
  2443. local all all trust
  2444. host all all 10.0.0.1/32 trust"))
  2445. (extra-config
  2446. '(("listen_addresses" "*")
  2447. ("log_directory" "/var/log/postgresql")))))))
  2448. (service postgresql-role-service-type
  2449. (postgresql-role-configuration
  2450. (roles
  2451. (list (postgresql-role
  2452. (name "test")
  2453. (create-database? #t))))))
  2454. %base-services)))
  2455. @end lisp
  2456. With @code{postgresql-role-service-type} we define a role ``test'' and
  2457. create a matching database, so that we can test right away without any
  2458. further manual setup. The @code{postgresql-config-file} settings allow
  2459. a client from IP address 10.0.0.1 to connect without requiring
  2460. authentication---a bad idea in production systems, but convenient for
  2461. this example.
  2462. Let's build a script that will launch an instance of this Guix System as
  2463. a container. Write the @code{operating-system} declaration above to a
  2464. file @file{os.scm} and then use @command{guix system container} to build
  2465. the launcher. (@pxref{Invoking guix system,,, guix, GNU Guix Reference
  2466. Manual}).
  2467. @example
  2468. $ guix system container os.scm
  2469. The following derivations will be built:
  2470. /gnu/store/@dots{}-run-container.drv
  2471. @dots{}
  2472. building /gnu/store/@dots{}-run-container.drv...
  2473. /gnu/store/@dots{}-run-container
  2474. @end example
  2475. Now that we have a launcher script we can run it to spawn the new system
  2476. with a running PostgreSQL service. Note that due to some as yet
  2477. unresolved limitations we need to run the launcher as the root user, for
  2478. example with @command{sudo}.
  2479. @example
  2480. $ sudo /gnu/store/@dots{}-run-container
  2481. system container is running as PID 5983
  2482. @dots{}
  2483. @end example
  2484. Background the process with @key{Ctrl-z} followed by @command{bg}. Note
  2485. the process ID in the output; we will need it to connect to the
  2486. container later. You know what? Let's try attaching to the container
  2487. right now. We will use @command{nsenter}, a tool provided by the
  2488. @code{util-linux} package:
  2489. @example
  2490. $ guix shell util-linux
  2491. $ sudo nsenter -a -t 5983
  2492. root@@container /# pgrep -a postgres
  2493. 49 /gnu/store/@dots{}-postgresql-14.4/bin/postgres -D /var/lib/postgresql/data --config-file=/gnu/store/@dots{}-postgresql.conf -p 5432
  2494. 51 postgres: checkpointer
  2495. 52 postgres: background writer
  2496. 53 postgres: walwriter
  2497. 54 postgres: autovacuum launcher
  2498. 55 postgres: stats collector
  2499. 56 postgres: logical replication launcher
  2500. root@@container /# exit
  2501. @end example
  2502. The PostgreSQL service is running in the container!
  2503. @node Container Networking
  2504. @subsection Container Networking
  2505. @cindex container networking
  2506. What good is a Guix System running a PostgreSQL database service as a
  2507. container when we can only talk to it with processes originating in the
  2508. container? It would be much better if we could talk to the database
  2509. over the network.
  2510. The easiest way to do this is to create a pair of connected virtual
  2511. Ethernet devices (known as @code{veth}). We move one of the devices
  2512. (@code{ceth-test}) into the @code{net} namespace of the container and
  2513. leave the other end (@code{veth-test}) of the connection on the host
  2514. system.
  2515. @example
  2516. pid=5983
  2517. ns="guix-test"
  2518. host="veth-test"
  2519. client="ceth-test"
  2520. # Attach the new net namespace "guix-test" to the container PID.
  2521. sudo ip netns attach $ns $pid
  2522. # Create the pair of devices
  2523. sudo ip link add $host type veth peer name $client
  2524. # Move the client device into the container's net namespace
  2525. sudo ip link set $client netns $ns
  2526. @end example
  2527. Then we configure the host side:
  2528. @example
  2529. sudo ip link set $host up
  2530. sudo ip addr add 10.0.0.1/24 dev $host
  2531. @end example
  2532. @dots{}and then we configure the client side:
  2533. @example
  2534. sudo ip netns exec $ns ip link set lo up
  2535. sudo ip netns exec $ns ip link set $client up
  2536. sudo ip netns exec $ns ip addr add 10.0.0.2/24 dev $client
  2537. @end example
  2538. At this point the host can reach the container at IP address 10.0.0.2,
  2539. and the container can reach the host at IP 10.0.0.1. This is all we
  2540. need to talk to the database server inside the container from the host
  2541. system on the outside.
  2542. @example
  2543. $ psql -h 10.0.0.2 -U test
  2544. psql (14.4)
  2545. Type "help" for help.
  2546. test=> CREATE TABLE hello (who TEXT NOT NULL);
  2547. CREATE TABLE
  2548. test=> INSERT INTO hello (who) VALUES ('world');
  2549. INSERT 0 1
  2550. test=> SELECT * FROM hello;
  2551. who
  2552. -------
  2553. world
  2554. (1 row)
  2555. @end example
  2556. Now that we're done with this little demonstration let's clean up:
  2557. @example
  2558. sudo kill $pid
  2559. sudo ip netns del $ns
  2560. sudo ip link del $host
  2561. @end example
  2562. @c *********************************************************************
  2563. @node Advanced package management
  2564. @chapter Advanced package management
  2565. Guix is a functional package manager that offers many features beyond
  2566. what more traditional package managers can do. To the uninitiated,
  2567. those features might not have obvious use cases at first. The purpose
  2568. of this chapter is to demonstrate some advanced package management
  2569. concepts.
  2570. @pxref{Package Management,,, guix, GNU Guix Reference Manual} for a complete
  2571. reference.
  2572. @menu
  2573. * Guix Profiles in Practice:: Strategies for multiple profiles and manifests.
  2574. @end menu
  2575. @node Guix Profiles in Practice
  2576. @section Guix Profiles in Practice
  2577. Guix provides a very useful feature that may be quite foreign to newcomers:
  2578. @emph{profiles}. They are a way to group package installations together and all users
  2579. on the same system are free to use as many profiles as they want.
  2580. Whether you're a developer or not, you may find that multiple profiles bring you
  2581. great power and flexibility. While they shift the paradigm somewhat compared to
  2582. @emph{traditional package managers}, they are very convenient to use once you've
  2583. understood how to set them up.
  2584. If you are familiar with Python's @samp{virtualenv}, you can think of a profile as a
  2585. kind of universal @samp{virtualenv} that can hold any kind of software whatsoever, not
  2586. just Python software. Furthermore, profiles are self-sufficient: they capture
  2587. all the runtime dependencies which guarantees that all programs within a profile
  2588. will always work at any point in time.
  2589. Multiple profiles have many benefits:
  2590. @itemize
  2591. @item
  2592. Clean semantic separation of the various packages a user needs for different contexts.
  2593. @item
  2594. Multiple profiles can be made available into the environment either on login
  2595. or within a dedicated shell.
  2596. @item
  2597. Profiles can be loaded on demand. For instance, the user can use multiple
  2598. shells, each of them running different profiles.
  2599. @item
  2600. Isolation: Programs from one profile will not use programs from the other, and
  2601. the user can even install different versions of the same programs to the two
  2602. profiles without conflict.
  2603. @item
  2604. Deduplication: Profiles share dependencies that happens to be the exact same.
  2605. This makes multiple profiles storage-efficient.
  2606. @item
  2607. Reproducible: when used with declarative manifests, a profile can be fully
  2608. specified by the Guix commit that was active when it was set up. This means
  2609. that the exact same profile can be
  2610. @uref{https://guix.gnu.org/blog/2018/multi-dimensional-transactions-and-rollbacks-oh-my/,
  2611. set up anywhere and anytime}, with just the commit information. See the
  2612. section on @ref{Reproducible profiles}.
  2613. @item
  2614. Easier upgrades and maintenance: Multiple profiles make it easy to keep
  2615. package listings at hand and make upgrades completely frictionless.
  2616. @end itemize
  2617. Concretely, here follows some typical profiles:
  2618. @itemize
  2619. @item
  2620. The dependencies of a project you are working on.
  2621. @item
  2622. Your favourite programming language libraries.
  2623. @item
  2624. Laptop-specific programs (like @samp{powertop}) that you don't need on a desktop.
  2625. @item
  2626. @TeX{}live (this one can be really useful when you need to install just one
  2627. package for this one document you've just received over email).
  2628. @item
  2629. Games.
  2630. @end itemize
  2631. Let's dive in the set up!
  2632. @node Basic setup with manifests
  2633. @subsection Basic setup with manifests
  2634. A Guix profile can be set up @i{via} a @dfn{manifest}. A manifest is a
  2635. snippet of Scheme code that specifies the set of packages you want to
  2636. have in your profile; it looks like this:
  2637. @lisp
  2638. (specifications->manifest
  2639. '("package-1"
  2640. ;; Version 1.3 of package-2.
  2641. "package-2@@1.3"
  2642. ;; The "lib" output of package-3.
  2643. "package-3:lib"
  2644. ; ...
  2645. "package-N"))
  2646. @end lisp
  2647. @xref{Writing Manifests,,, guix, GNU Guix Reference Manual}, for
  2648. more information about the syntax.
  2649. We can create a manifest specification per profile and install them this way:
  2650. @example
  2651. GUIX_EXTRA_PROFILES=$HOME/.guix-extra-profiles
  2652. mkdir -p "$GUIX_EXTRA_PROFILES"/my-project # if it does not exist yet
  2653. guix package --manifest=/path/to/guix-my-project-manifest.scm --profile="$GUIX_EXTRA_PROFILES"/my-project/my-project
  2654. @end example
  2655. Here we set an arbitrary variable @samp{GUIX_EXTRA_PROFILES} to point to the directory
  2656. where we will store our profiles in the rest of this article.
  2657. Placing all your profiles in a single directory, with each profile getting its
  2658. own sub-directory, is somewhat cleaner. This way, each sub-directory will
  2659. contain all the symlinks for precisely one profile. Besides, ``looping over
  2660. profiles'' becomes obvious from any programming language (e.g.@: a shell script) by
  2661. simply looping over the sub-directories of @samp{$GUIX_EXTRA_PROFILES}.
  2662. Note that it's also possible to loop over the output of
  2663. @example
  2664. guix package --list-profiles
  2665. @end example
  2666. although you'll probably have to filter out @file{~/.config/guix/current}.
  2667. To enable all profiles on login, add this to your @file{~/.bash_profile} (or similar):
  2668. @example
  2669. for i in $GUIX_EXTRA_PROFILES/*; do
  2670. profile=$i/$(basename "$i")
  2671. if [ -f "$profile"/etc/profile ]; then
  2672. GUIX_PROFILE="$profile"
  2673. . "$GUIX_PROFILE"/etc/profile
  2674. fi
  2675. unset profile
  2676. done
  2677. @end example
  2678. Note to Guix System users: the above reflects how your default profile
  2679. @file{~/.guix-profile} is activated from @file{/etc/profile}, that latter being loaded by
  2680. @file{~/.bashrc} by default.
  2681. You can obviously choose to only enable a subset of them:
  2682. @example
  2683. for i in "$GUIX_EXTRA_PROFILES"/my-project-1 "$GUIX_EXTRA_PROFILES"/my-project-2; do
  2684. profile=$i/$(basename "$i")
  2685. if [ -f "$profile"/etc/profile ]; then
  2686. GUIX_PROFILE="$profile"
  2687. . "$GUIX_PROFILE"/etc/profile
  2688. fi
  2689. unset profile
  2690. done
  2691. @end example
  2692. When a profile is off, it's straightforward to enable it for an individual shell
  2693. without "polluting" the rest of the user session:
  2694. @example
  2695. GUIX_PROFILE="path/to/my-project" ; . "$GUIX_PROFILE"/etc/profile
  2696. @end example
  2697. The key to enabling a profile is to @emph{source} its @samp{etc/profile} file. This file
  2698. contains shell code that exports the right environment variables necessary to
  2699. activate the software contained in the profile. It is built automatically by
  2700. Guix and meant to be sourced.
  2701. It contains the same variables you would get if you ran:
  2702. @example
  2703. guix package --search-paths=prefix --profile=$my_profile"
  2704. @end example
  2705. Once again, see (@pxref{Invoking guix package,,, guix, GNU Guix Reference Manual})
  2706. for the command line options.
  2707. To upgrade a profile, simply install the manifest again:
  2708. @example
  2709. guix package -m /path/to/guix-my-project-manifest.scm -p "$GUIX_EXTRA_PROFILES"/my-project/my-project
  2710. @end example
  2711. To upgrade all profiles, it's easy enough to loop over them. For instance,
  2712. assuming your manifest specifications are stored in
  2713. @file{~/.guix-manifests/guix-$profile-manifest.scm}, with @samp{$profile} being the name
  2714. of the profile (e.g.@: "project1"), you could do the following in Bourne shell:
  2715. @example
  2716. for profile in "$GUIX_EXTRA_PROFILES"/*; do
  2717. guix package --profile="$profile" --manifest="$HOME/.guix-manifests/guix-$profile-manifest.scm"
  2718. done
  2719. @end example
  2720. Each profile has its own generations:
  2721. @example
  2722. guix package -p "$GUIX_EXTRA_PROFILES"/my-project/my-project --list-generations
  2723. @end example
  2724. You can roll-back to any generation of a given profile:
  2725. @example
  2726. guix package -p "$GUIX_EXTRA_PROFILES"/my-project/my-project --switch-generations=17
  2727. @end example
  2728. Finally, if you want to switch to a profile without inheriting from the
  2729. current environment, you can activate it from an empty shell:
  2730. @example
  2731. env -i $(which bash) --login --noprofile --norc
  2732. . my-project/etc/profile
  2733. @end example
  2734. @node Required packages
  2735. @subsection Required packages
  2736. Activating a profile essentially boils down to exporting a bunch of
  2737. environmental variables. This is the role of the @samp{etc/profile} within the
  2738. profile.
  2739. @emph{Note: Only the environmental variables of the packages that consume them will
  2740. be set.}
  2741. For instance, @samp{MANPATH} won't be set if there is no consumer application for man
  2742. pages within the profile. So if you need to transparently access man pages once
  2743. the profile is loaded, you've got two options:
  2744. @itemize
  2745. @item
  2746. Either export the variable manually, e.g.
  2747. @example
  2748. export MANPATH=/path/to/profile$@{MANPATH:+:@}$MANPATH
  2749. @end example
  2750. @item
  2751. Or include @samp{man-db} to the profile manifest.
  2752. @end itemize
  2753. The same is true for @samp{INFOPATH} (you can install @samp{info-reader}),
  2754. @samp{PKG_CONFIG_PATH} (install @samp{pkg-config}), etc.
  2755. @node Default profile
  2756. @subsection Default profile
  2757. What about the default profile that Guix keeps in @file{~/.guix-profile}?
  2758. You can assign it the role you want. Typically you would install the manifest
  2759. of the packages you want to use all the time.
  2760. Alternatively, you could keep it ``manifest-less'' for throw-away packages
  2761. that you would just use for a couple of days.
  2762. This way makes it convenient to run
  2763. @example
  2764. guix install package-foo
  2765. guix upgrade package-bar
  2766. @end example
  2767. without having to specify the path to a profile.
  2768. @node The benefits of manifests
  2769. @subsection The benefits of manifests
  2770. Manifests are a convenient way to keep your package lists around and, say,
  2771. to synchronize them across multiple machines using a version control system.
  2772. A common complaint about manifests is that they can be slow to install when they
  2773. contain large number of packages. This is especially cumbersome when you just
  2774. want get an upgrade for one package within a big manifest.
  2775. This is one more reason to use multiple profiles, which happen to be just
  2776. perfect to break down manifests into multiple sets of semantically connected
  2777. packages. Using multiple, small profiles provides more flexibility and
  2778. usability.
  2779. Manifests come with multiple benefits. In particular, they ease maintenance:
  2780. @itemize
  2781. @item
  2782. When a profile is set up from a manifest, the manifest itself is
  2783. self-sufficient to keep a ``package listing'' around and reinstall the profile
  2784. later or on a different system. For ad-hoc profiles, we would need to
  2785. generate a manifest specification manually and maintain the package versions
  2786. for the packages that don't use the default version.
  2787. @item
  2788. @code{guix package --upgrade} always tries to update the packages that have
  2789. propagated inputs, even if there is nothing to do. Guix manifests remove this
  2790. problem.
  2791. @item
  2792. When partially upgrading a profile, conflicts may arise (due to diverging
  2793. dependencies between the updated and the non-updated packages) and they can be
  2794. annoying to resolve manually. Manifests remove this problem altogether since
  2795. all packages are always upgraded at once.
  2796. @item
  2797. As mentioned above, manifests allow for reproducible profiles, while the
  2798. imperative @code{guix install}, @code{guix upgrade}, etc. do not, since they produce
  2799. different profiles every time even when they hold the same packages. See
  2800. @uref{https://issues.guix.gnu.org/issue/33285, the related discussion on the matter}.
  2801. @item
  2802. Manifest specifications are usable by other @samp{guix} commands. For example, you
  2803. can run @code{guix weather -m manifest.scm} to see how many substitutes are
  2804. available, which can help you decide whether you want to try upgrading today
  2805. or wait a while. Another example: you can run @code{guix pack -m manifest.scm} to
  2806. create a pack containing all the packages in the manifest (and their
  2807. transitive references).
  2808. @item
  2809. Finally, manifests have a Scheme representation, the @samp{<manifest>} record type.
  2810. They can be manipulated in Scheme and passed to the various Guix @uref{https://en.wikipedia.org/wiki/Api, APIs}.
  2811. @end itemize
  2812. It's important to understand that while manifests can be used to declare
  2813. profiles, they are not strictly equivalent: profiles have the side effect that
  2814. they ``pin'' packages in the store, which prevents them from being
  2815. garbage-collected (@pxref{Invoking guix gc,,, guix, GNU Guix Reference Manual})
  2816. and ensures that they will still be available at any point in
  2817. the future.
  2818. Let's take an example:
  2819. @enumerate
  2820. @item
  2821. We have an environment for hacking on a project for which there isn't a Guix
  2822. package yet. We build the environment using a manifest, and then run @code{guix
  2823. environment -m manifest.scm}. So far so good.
  2824. @item
  2825. Many weeks pass and we have run a couple of @code{guix pull} in the mean time.
  2826. Maybe a dependency from our manifest has been updated; or we may have run
  2827. @code{guix gc} and some packages needed by our manifest have been
  2828. garbage-collected.
  2829. @item
  2830. Eventually, we set to work on that project again, so we run @code{guix shell
  2831. -m manifest.scm}. But now we have to wait for Guix to build and install
  2832. stuff!
  2833. @end enumerate
  2834. Ideally, we could spare the rebuild time. And indeed we can, all we need is to
  2835. install the manifest to a profile and use @code{GUIX_PROFILE=/the/profile;
  2836. . "$GUIX_PROFILE"/etc/profile} as explained above: this guarantees that our
  2837. hacking environment will be available at all times.
  2838. @emph{Security warning:} While keeping old profiles around can be convenient, keep in
  2839. mind that outdated packages may not have received the latest security fixes.
  2840. @node Reproducible profiles
  2841. @subsection Reproducible profiles
  2842. To reproduce a profile bit-for-bit, we need two pieces of information:
  2843. @itemize
  2844. @item
  2845. a manifest,
  2846. @item
  2847. a Guix channel specification.
  2848. @end itemize
  2849. Indeed, manifests alone might not be enough: different Guix versions (or
  2850. different channels) can produce different outputs for a given manifest.
  2851. You can output the Guix channel specification with @samp{guix describe
  2852. --format=channels}.
  2853. Save this to a file, say @samp{channel-specs.scm}.
  2854. On another computer, you can use the channel specification file and the manifest
  2855. to reproduce the exact same profile:
  2856. @example
  2857. GUIX_EXTRA_PROFILES=$HOME/.guix-extra-profiles
  2858. GUIX_EXTRA=$HOME/.guix-extra
  2859. mkdir -p "$GUIX_EXTRA"/my-project
  2860. guix pull --channels=channel-specs.scm --profile="$GUIX_EXTRA/my-project/guix"
  2861. mkdir -p "$GUIX_EXTRA_PROFILES/my-project"
  2862. "$GUIX_EXTRA"/my-project/guix/bin/guix package --manifest=/path/to/guix-my-project-manifest.scm --profile="$GUIX_EXTRA_PROFILES"/my-project/my-project
  2863. @end example
  2864. It's safe to delete the Guix channel profile you've just installed with the
  2865. channel specification, the project profile does not depend on it.
  2866. @c *********************************************************************
  2867. @node Environment management
  2868. @chapter Environment management
  2869. Guix provides multiple tools to manage environment. This chapter
  2870. demonstrate such utilities.
  2871. @menu
  2872. * Guix environment via direnv:: Setup Guix environment with direnv
  2873. @end menu
  2874. @node Guix environment via direnv
  2875. @section Guix environment via direnv
  2876. Guix provides a @samp{direnv} package, which could extend shell after
  2877. directory change. This tool could be used to prepare a pure Guix
  2878. environment.
  2879. The following example provides a shell function for @file{~/.direnvrc}
  2880. file, which could be used from Guix Git repository in
  2881. @file{~/src/guix/.envrc} file to setup a build environment similar to
  2882. described in @pxref{Building from Git,,, guix, GNU Guix Reference
  2883. Manual}.
  2884. Create a @file{~/.direnvrc} with a Bash code:
  2885. @example
  2886. # Thanks <https://github.com/direnv/direnv/issues/73#issuecomment-152284914>
  2887. export_function()
  2888. @{
  2889. local name=$1
  2890. local alias_dir=$PWD/.direnv/aliases
  2891. mkdir -p "$alias_dir"
  2892. PATH_add "$alias_dir"
  2893. local target="$alias_dir/$name"
  2894. if declare -f "$name" >/dev/null; then
  2895. echo "#!$SHELL" > "$target"
  2896. declare -f "$name" >> "$target" 2>/dev/null
  2897. # Notice that we add shell variables to the function trigger.
  2898. echo "$name \$*" >> "$target"
  2899. chmod +x "$target"
  2900. fi
  2901. @}
  2902. use_guix()
  2903. @{
  2904. # Set GitHub token.
  2905. export GUIX_GITHUB_TOKEN="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
  2906. # Unset 'GUIX_PACKAGE_PATH'.
  2907. export GUIX_PACKAGE_PATH=""
  2908. # Recreate a garbage collector root.
  2909. gcroots="$HOME/.config/guix/gcroots"
  2910. mkdir -p "$gcroots"
  2911. gcroot="$gcroots/guix"
  2912. if [ -L "$gcroot" ]
  2913. then
  2914. rm -v "$gcroot"
  2915. fi
  2916. # Miscellaneous packages.
  2917. PACKAGES_MAINTENANCE=(
  2918. direnv
  2919. git
  2920. git:send-email
  2921. git-cal
  2922. gnupg
  2923. guile-colorized
  2924. guile-readline
  2925. less
  2926. ncurses
  2927. openssh
  2928. xdot
  2929. )
  2930. # Environment packages.
  2931. PACKAGES=(help2man guile-sqlite3 guile-gcrypt)
  2932. # Thanks <https://lists.gnu.org/archive/html/guix-devel/2016-09/msg00859.html>
  2933. eval "$(guix environment --search-paths --root="$gcroot" --pure guix --ad-hoc $@{PACKAGES[@@]@} $@{PACKAGES_MAINTENANCE[@@]@} "$@@")"
  2934. # Predefine configure flags.
  2935. configure()
  2936. @{
  2937. ./configure --localstatedir=/var --prefix=
  2938. @}
  2939. export_function configure
  2940. # Run make and optionally build something.
  2941. build()
  2942. @{
  2943. make -j 2
  2944. if [ $# -gt 0 ]
  2945. then
  2946. ./pre-inst-env guix build "$@@"
  2947. fi
  2948. @}
  2949. export_function build
  2950. # Predefine push Git command.
  2951. push()
  2952. @{
  2953. git push --set-upstream origin
  2954. @}
  2955. export_function push
  2956. clear # Clean up the screen.
  2957. git-cal --author='Your Name' # Show contributions calendar.
  2958. # Show commands help.
  2959. echo "
  2960. build build a package or just a project if no argument provided
  2961. configure run ./configure with predefined parameters
  2962. push push to upstream Git repository
  2963. "
  2964. @}
  2965. @end example
  2966. Every project containing @file{.envrc} with a string @code{use guix}
  2967. will have predefined environment variables and procedures.
  2968. Run @command{direnv allow} to setup the environment for the first time.
  2969. @c *********************************************************************
  2970. @node Installing Guix on a Cluster
  2971. @chapter Installing Guix on a Cluster
  2972. @cindex cluster installation
  2973. @cindex high-performance computing, HPC
  2974. @cindex HPC, high-performance computing
  2975. Guix is appealing to scientists and @acronym{HPC, high-performance
  2976. computing} practitioners: it makes it easy to deploy potentially complex
  2977. software stacks, and it lets you do so in a reproducible fashion---you
  2978. can redeploy the exact same software on different machines and at
  2979. different points in time.
  2980. In this chapter we look at how a cluster sysadmin can install Guix for
  2981. system-wide use, such that it can be used on all the cluster nodes, and
  2982. discuss the various tradeoffs@footnote{This chapter is adapted from a
  2983. @uref{https://hpc.guix.info/blog/2017/11/installing-guix-on-a-cluster/,
  2984. blog post published on the Guix-HPC web site in 2017}.}.
  2985. @quotation Note
  2986. Here we assume that the cluster is running a GNU/Linux distro other than
  2987. Guix System and that we are going to install Guix on top of it.
  2988. @end quotation
  2989. @menu
  2990. * Setting Up a Head Node:: The node that runs the daemon.
  2991. * Setting Up Compute Nodes:: Client nodes.
  2992. * Cluster Network Access:: Dealing with network access restrictions.
  2993. * Cluster Disk Usage:: Disk usage considerations.
  2994. * Cluster Security Considerations:: Keeping the cluster secure.
  2995. @end menu
  2996. @node Setting Up a Head Node
  2997. @section Setting Up a Head Node
  2998. The recommended approach is to set up one @emph{head node} running
  2999. @command{guix-daemon} and exporting @file{/gnu/store} over NFS to
  3000. compute nodes.
  3001. Remember that @command{guix-daemon} is responsible for spawning build
  3002. processes and downloads on behalf of clients (@pxref{Invoking
  3003. guix-daemon,,, guix, GNU Guix Reference Manual}), and more generally
  3004. accessing @file{/gnu/store}, which contains all the package binaries
  3005. built by all the users (@pxref{The Store,,, guix, GNU Guix Reference
  3006. Manual}). ``Client'' here refers to all the Guix commands that users
  3007. see, such as @code{guix install}. On a cluster, these commands may be
  3008. running on the compute nodes and we'll want them to talk to the head
  3009. node's @code{guix-daemon} instance.
  3010. To begin with, the head node can be installed following the usual binary
  3011. installation instructions (@pxref{Binary Installation,,, guix, GNU Guix
  3012. Reference Manual}). Thanks to the installation script, this should be
  3013. quick. Once installation is complete, we need to make some adjustments.
  3014. Since we want @code{guix-daemon} to be reachable not just from the head
  3015. node but also from the compute nodes, we need to arrange so that it
  3016. listens for connections over TCP/IP. To do that, we'll edit the systemd
  3017. startup file for @command{guix-daemon},
  3018. @file{/etc/systemd/system/guix-daemon.service}, and add a
  3019. @code{--listen} argument to the @code{ExecStart} line so that it looks
  3020. something like this:
  3021. @example
  3022. ExecStart=/var/guix/profiles/per-user/root/current-guix/bin/guix-daemon --build-users-group=guixbuild --listen=/var/guix/daemon-socket/socket --listen=0.0.0.0
  3023. @end example
  3024. For these changes to take effect, the service needs to be restarted:
  3025. @example
  3026. systemctl daemon-reload
  3027. systemctl restart guix-daemon
  3028. @end example
  3029. @quotation Note
  3030. The @code{--listen=0.0.0.0} bit means that @code{guix-daemon} will
  3031. process @emph{all} incoming TCP connections on port 44146
  3032. (@pxref{Invoking guix-daemon,,, guix, GNU Guix Reference Manual}). This
  3033. is usually fine in a cluster setup where the head node is reachable
  3034. exclusively from the cluster's local area network---you don't want that
  3035. to be exposed to the Internet!
  3036. @end quotation
  3037. The next step is to define our NFS exports in
  3038. @uref{https://linux.die.net/man/5/exports,@file{/etc/exports}} by adding
  3039. something along these lines:
  3040. @example
  3041. /gnu/store *(ro)
  3042. /var/guix *(rw, async)
  3043. /var/log/guix *(ro)
  3044. @end example
  3045. The @file{/gnu/store} directory can be exported read-only since only
  3046. @command{guix-daemon} on the master node will ever modify it.
  3047. @file{/var/guix} contains @emph{user profiles} as managed by @code{guix
  3048. package}; thus, to allow users to install packages with @code{guix
  3049. package}, this must be read-write.
  3050. Users can create as many profiles as they like in addition to the
  3051. default profile, @file{~/.guix-profile}. For instance, @code{guix
  3052. package -p ~/dev/python-dev -i python} installs Python in a profile
  3053. reachable from the @code{~/dev/python-dev} symlink. To make sure that
  3054. this profile is protected from garbage collection---i.e., that Python
  3055. will not be removed from @file{/gnu/store} while this profile exists---,
  3056. @emph{home directories should be mounted on the head node} as well so
  3057. that @code{guix-daemon} knows about these non-standard profiles and
  3058. avoids collecting software they refer to.
  3059. It may be a good idea to periodically remove unused bits from
  3060. @file{/gnu/store} by running @command{guix gc} (@pxref{Invoking guix
  3061. gc,,, guix, GNU Guix Reference Manual}). This can be done by adding a
  3062. crontab entry on the head node:
  3063. @example
  3064. root@@master# crontab -e
  3065. @end example
  3066. @noindent
  3067. ... with something like this:
  3068. @example
  3069. # Every day at 5AM, run the garbage collector to make sure
  3070. # at least 10 GB are free on /gnu/store.
  3071. 0 5 * * 1 /usr/local/bin/guix gc -F10G
  3072. @end example
  3073. We're done with the head node! Let's look at compute nodes now.
  3074. @node Setting Up Compute Nodes
  3075. @section Setting Up Compute Nodes
  3076. First of all, we need compute nodes to mount those NFS directories that
  3077. the head node exports. This can be done by adding the following lines
  3078. to @uref{https://linux.die.net/man/5/fstab,@file{/etc/fstab}}:
  3079. @example
  3080. @var{head-node}:/gnu/store /gnu/store nfs defaults,_netdev,vers=3 0 0
  3081. @var{head-node}:/var/guix /var/guix nfs defaults,_netdev,vers=3 0 0
  3082. @var{head-node}:/var/log/guix /var/log/guix nfs defaults,_netdev,vers=3 0 0
  3083. @end example
  3084. @noindent
  3085. ... where @var{head-node} is the name or IP address of your head node.
  3086. From there on, assuming the mount points exist, you should be able to
  3087. mount each of these on the compute nodes.
  3088. Next, we need to provide a default @command{guix} command that users can
  3089. run when they first connect to the cluster (eventually they will invoke
  3090. @command{guix pull}, which will provide them with their ``own''
  3091. @command{guix} command). Similar to what the binary installation script
  3092. did on the head node, we'll store that in @file{/usr/local/bin}:
  3093. @example
  3094. mkdir -p /usr/local/bin
  3095. ln -s /var/guix/profiles/per-user/root/current-guix/bin/guix \
  3096. /usr/local/bin/guix
  3097. @end example
  3098. We then need to tell @code{guix} to talk to the daemon running on our
  3099. master node, by adding these lines to @code{/etc/profile}:
  3100. @example
  3101. GUIX_DAEMON_SOCKET="guix://@var{head-node}"
  3102. export GUIX_DAEMON_SOCKET
  3103. @end example
  3104. To avoid warnings and make sure @code{guix} uses the right locale, we
  3105. need to tell it to use locale data provided by Guix (@pxref{Application
  3106. Setup,,, guix, GNU Guix Reference Manual}):
  3107. @example
  3108. GUIX_LOCPATH=/var/guix/profiles/per-user/root/guix-profile/lib/locale
  3109. export GUIX_LOCPATH
  3110. # Here we must use a valid locale name. Try "ls $GUIX_LOCPATH/*"
  3111. # to see what names can be used.
  3112. LC_ALL=fr_FR.utf8
  3113. export LC_ALL
  3114. @end example
  3115. For convenience, @code{guix package} automatically generates
  3116. @file{~/.guix-profile/etc/profile}, which defines all the environment
  3117. variables necessary to use the packages---@code{PATH},
  3118. @code{C_INCLUDE_PATH}, @code{PYTHONPATH}, etc. Thus it's a good idea to
  3119. source it from @code{/etc/profile}:
  3120. @example
  3121. GUIX_PROFILE="$HOME/.guix-profile"
  3122. if [ -f "$GUIX_PROFILE/etc/profile" ]; then
  3123. . "$GUIX_PROFILE/etc/profile"
  3124. fi
  3125. @end example
  3126. Last but not least, Guix provides command-line completion notably for
  3127. Bash and zsh. In @code{/etc/bashrc}, consider adding this line:
  3128. @verbatim
  3129. . /var/guix/profiles/per-user/root/current-guix/etc/bash_completion.d/guix
  3130. @end verbatim
  3131. Voilà!
  3132. You can check that everything's in place by logging in on a compute node
  3133. and running:
  3134. @example
  3135. guix install hello
  3136. @end example
  3137. The daemon on the head node should download pre-built binaries on your
  3138. behalf and unpack them in @file{/gnu/store}, and @command{guix install}
  3139. should create @file{~/.guix-profile} containing the
  3140. @file{~/.guix-profile/bin/hello} command.
  3141. @node Cluster Network Access
  3142. @section Network Access
  3143. Guix requires network access to download source code and pre-built
  3144. binaries. The good news is that only the head node needs that since
  3145. compute nodes simply delegate to it.
  3146. It is customary for cluster nodes to have access at best to a
  3147. @emph{white list} of hosts. Our head node needs at least
  3148. @code{ci.guix.gnu.org} in this white list since this is where it gets
  3149. pre-built binaries from by default, for all the packages that are in
  3150. Guix proper.
  3151. Incidentally, @code{ci.guix.gnu.org} also serves as a
  3152. @emph{content-addressed mirror} of the source code of those packages.
  3153. Consequently, it is sufficient to have @emph{only}
  3154. @code{ci.guix.gnu.org} in that white list.
  3155. Software packages maintained in a separate repository such as one of the
  3156. various @uref{https://hpc.guix.info/channels, HPC channels} are of
  3157. course unavailable from @code{ci.guix.gnu.org}. For these packages, you
  3158. may want to extend the white list such that source and pre-built
  3159. binaries (assuming this-party servers provide binaries for these
  3160. packages) can be downloaded. As a last resort, users can always
  3161. download source on their workstation and add it to the cluster's
  3162. @file{/gnu/store}, like this:
  3163. @verbatim
  3164. GUIX_DAEMON_SOCKET=ssh://compute-node.example.org \
  3165. guix download http://starpu.gforge.inria.fr/files/starpu-1.2.3/starpu-1.2.3.tar.gz
  3166. @end verbatim
  3167. The above command downloads @code{starpu-1.2.3.tar.gz} @emph{and} sends
  3168. it to the cluster's @code{guix-daemon} instance over SSH.
  3169. Air-gapped clusters require more work. At the moment, our suggestion
  3170. would be to download all the necessary source code on a workstation
  3171. running Guix. For instance, using the @option{--sources} option of
  3172. @command{guix build} (@pxref{Invoking guix build,,, guix, GNU Guix
  3173. Reference Manual}), the example below downloads all the source code the
  3174. @code{openmpi} package depends on:
  3175. @example
  3176. $ guix build --sources=transitive openmpi
  3177. @dots{}
  3178. /gnu/store/xc17sm60fb8nxadc4qy0c7rqph499z8s-openmpi-1.10.7.tar.bz2
  3179. /gnu/store/s67jx92lpipy2nfj5cz818xv430n4b7w-gcc-5.4.0.tar.xz
  3180. /gnu/store/npw9qh8a46lrxiwh9xwk0wpi3jlzmjnh-gmp-6.0.0a.tar.xz
  3181. /gnu/store/hcz0f4wkdbsvsdky3c0vdvcawhdkyldb-mpfr-3.1.5.tar.xz
  3182. /gnu/store/y9akh452n3p4w2v631nj0injx7y0d68x-mpc-1.0.3.tar.gz
  3183. /gnu/store/6g5c35q8avfnzs3v14dzl54cmrvddjm2-glibc-2.25.tar.xz
  3184. /gnu/store/p9k48dk3dvvk7gads7fk30xc2pxsd66z-hwloc-1.11.8.tar.bz2
  3185. /gnu/store/cry9lqidwfrfmgl0x389cs3syr15p13q-gcc-5.4.0.tar.xz
  3186. /gnu/store/7ak0v3rzpqm2c5q1mp3v7cj0rxz0qakf-libfabric-1.4.1.tar.bz2
  3187. /gnu/store/vh8syjrsilnbfcf582qhmvpg1v3rampf-rdma-core-14.tar.gz
  3188. @end example
  3189. (In case you're wondering, that's more than 320@ MiB of
  3190. @emph{compressed} source code.)
  3191. We can then make a big archive containing all of this (@pxref{Invoking
  3192. guix archive,,, guix, GNU Guix Reference Manual}):
  3193. @verbatim
  3194. $ guix archive --export \
  3195. `guix build --sources=transitive openmpi` \
  3196. > openmpi-source-code.nar
  3197. @end verbatim
  3198. @dots{} and we can eventually transfer that archive to the cluster on
  3199. removable storage and unpack it there:
  3200. @verbatim
  3201. $ guix archive --import < openmpi-source-code.nar
  3202. @end verbatim
  3203. This process has to be repeated every time new source code needs to be
  3204. brought to the cluster.
  3205. As we write this, the research institutes involved in Guix-HPC do not
  3206. have air-gapped clusters though. If you have experience with such
  3207. setups, we would like to hear feedback and suggestions.
  3208. @node Cluster Disk Usage
  3209. @section Disk Usage
  3210. @cindex disk usage, on a cluster
  3211. A common concern of sysadmins' is whether this is all going to eat a lot
  3212. of disk space. If anything, if something is going to exhaust disk
  3213. space, it's going to be scientific data sets rather than compiled
  3214. software---that's our experience with almost ten years of Guix usage on
  3215. HPC clusters. Nevertheless, it's worth taking a look at how Guix
  3216. contributes to disk usage.
  3217. First, having several versions or variants of a given package in
  3218. @file{/gnu/store} does not necessarily cost much, because
  3219. @command{guix-daemon} implements deduplication of identical files, and
  3220. package variants are likely to have a number of common files.
  3221. As mentioned above, we recommend having a cron job to run @code{guix gc}
  3222. periodically, which removes @emph{unused} software from
  3223. @file{/gnu/store}. However, there's always a possibility that users will
  3224. keep lots of software in their profiles, or lots of old generations of
  3225. their profiles, which is ``live'' and cannot be deleted from the
  3226. viewpoint of @command{guix gc}.
  3227. The solution to this is for users to regularly remove old generations of
  3228. their profile. For instance, the following command removes generations
  3229. that are more than two-month old:
  3230. @example
  3231. guix package --delete-generations=2m
  3232. @end example
  3233. Likewise, it's a good idea to invite users to regularly upgrade their
  3234. profile, which can reduce the number of variants of a given piece of
  3235. software stored in @file{/gnu/store}:
  3236. @example
  3237. guix pull
  3238. guix upgrade
  3239. @end example
  3240. As a last resort, it is always possible for sysadmins to do some of this
  3241. on behalf of their users. Nevertheless, one of the strengths of Guix is
  3242. the freedom and control users get on their software environment, so we
  3243. strongly recommend leaving users in control.
  3244. @node Cluster Security Considerations
  3245. @section Security Considerations
  3246. @cindex security, on a cluster
  3247. On an HPC cluster, Guix is typically used to manage scientific software.
  3248. Security-critical software such as the operating system kernel and
  3249. system services such as @code{sshd} and the batch scheduler remain under
  3250. control of sysadmins.
  3251. The Guix project has a good track record delivering security updates in
  3252. a timely fashion (@pxref{Security Updates,,, guix, GNU Guix Reference
  3253. Manual}). To get security updates, users have to run @code{guix pull &&
  3254. guix upgrade}.
  3255. Because Guix uniquely identifies software variants, it is easy to see if
  3256. a vulnerable piece of software is in use. For instance, to check whether
  3257. the glibc@ 2.25 variant without the mitigation patch against
  3258. ``@uref{https://www.qualys.com/2017/06/19/stack-clash/stack-clash.txt,Stack
  3259. Clash}'', one can check whether user profiles refer to it at all:
  3260. @example
  3261. guix gc --referrers /gnu/store/…-glibc-2.25
  3262. @end example
  3263. This will report whether profiles exist that refer to this specific
  3264. glibc variant.
  3265. @c *********************************************************************
  3266. @node Acknowledgments
  3267. @chapter Acknowledgments
  3268. Guix is based on the @uref{https://nixos.org/nix/, Nix package manager},
  3269. which was designed and
  3270. implemented by Eelco Dolstra, with contributions from other people (see
  3271. the @file{nix/AUTHORS} file in Guix.) Nix pioneered functional package
  3272. management, and promoted unprecedented features, such as transactional
  3273. package upgrades and rollbacks, per-user profiles, and referentially
  3274. transparent build processes. Without this work, Guix would not exist.
  3275. The Nix-based software distributions, Nixpkgs and NixOS, have also been
  3276. an inspiration for Guix.
  3277. GNU@tie{}Guix itself is a collective work with contributions from a
  3278. number of people. See the @file{AUTHORS} file in Guix for more
  3279. information on these fine people. The @file{THANKS} file lists people
  3280. who have helped by reporting bugs, taking care of the infrastructure,
  3281. providing artwork and themes, making suggestions, and more---thank you!
  3282. This document includes adapted sections from articles that have
  3283. previously been published on the Guix blog at
  3284. @uref{https://guix.gnu.org/blog} and on the Guix-HPC blog at
  3285. @uref{https://hpc.guix.info/blog}.
  3286. @c *********************************************************************
  3287. @node GNU Free Documentation License
  3288. @appendix GNU Free Documentation License
  3289. @cindex license, GNU Free Documentation License
  3290. @include fdl-1.3.texi
  3291. @c *********************************************************************
  3292. @node Concept Index
  3293. @unnumbered Concept Index
  3294. @printindex cp
  3295. @bye
  3296. @c Local Variables:
  3297. @c ispell-local-dictionary: "american";
  3298. @c End: