Gentoo Linux Handbook: Working with Gentoo

From Gentoo Wiki
Jump to:navigation Jump to:search


Portage vás vítá

Portage je jednou s nejpozoruhodnějších inovací Gentoo na poli správy softwaru. Díky své velké flexibilitě a obrovskému množstvím funkcí je často pokládána za nejlepší nástroj pro správu softwaru dostupný pro Linux.

Portage je celá napsaná v Pythonu a Bashi a je tak pro uživatele plně transparentní, jelikož se jedná o skriptovací jazyky.

Většina uživatelů bude s Portage pracovat prostřednictvím nástroje emerge. Cílem této kapitoly není duplikovat informace dostupné v manuálové stránce emerge. Pro vyčerpávající přehled voleb emerge se prosím podívejte na manuálovou stránku:

user $man emerge

Repozitář Gentoo

Ebuildy

Pokud dokumentace Gentoo hovoří o balíčcích, má tím na mysli softwarové tituly dostupné uživatelům Gentoo skrze repozitář Gentoo. Ten obsahuje sbírku ebuildů, souborů, které obsahují veškeré informace, které Portage potřebuje k nakládání s programy (instalaci, vyhledávání, dotazování atd.). Ve výchozím stavu se soubory ebuildů nacházejí v .

Kdykoli je Portage dán požadavek na provedení akce, která se týká softwaru, použije ebuildy v systému, jako výchozí bod. Proto je třeba pravidelně aktualizovat ebuildy v systému, tak, aby Portage věděl o novém softwaru, bezpečnostních aktualizacích atd.

Aktualizace repozitáře Gentoo

Repozitář Gentoo se aktualizuje příkazem rsync, utilitou pro rychlý přírůstkový přenos souborů. Aktualizace je opravdu jednoduchá, jelikož příkaz emerge poskytuje rozhraní pro rsync.

root #emerge --sync

Někdy se však vyskytnou omezení daná firewallem, která znemožní příkazu rsync navázat spojení se zrcadly. V takovém případě aktualizujte repozitář Gentoo přes každodenně generovaný snímek stromu Portage. Nástroj emerge-webrsync automaticky stáhne a nainstaluje poslední snímek do systému:

root #emerge-webrsync

Nakládání se softwarem

Vyhledání softwaru

Způsobů jak vyhledávat software ve repozitáře Gentoo je mnoho. Jednou z cest je využití samotného programu emerge. V základu příkaz emerge --search vrátí názvy balíčků, jejichž název odpovídá (buď úplně, nebo i částečně) danému vyhledávacímu dotazu.

Například k vyhledání všech balíčků, které mají v názvu "pdf":

user $emerge --search pdf

Pokud chcete prohledávat také popisy, použijte volbu --searchdesc (nebo také -S):

user $emerge --searchdesc pdf

Všimněte si, že výstup vrací mnoho informací. jednotlivá pole jsou jasně označena, tudíž nebudeme více vysvětlovat jejich význam:

CODE Příklad vyhledávání v příkazovém řádku
*  net-print/cups-pdf
      Latest version available: 1.5.2
      Latest version installed: [ Not Installed ]
      Size of downloaded files: 15 kB
      Homepage:    http://cip.physik.uni-wuerzburg.de/~vrbehr/cups-pdf/
      Description: Provides a virtual printer for CUPS to produce PDF files.
      License:     GPL-2

Instalace softwaru

Pokud jsme žádaný software našli, dělí nás od jeho instalace již jen jeden příkaz. Pro nainstalování gnumeric je to například:

root #emerge --ask app-office/gnumeric

Jelikož mnoho aplikací závisí jedna na druhé, jakýkoli pokus o instalaci určitého softwaru může vést také k instalaci několik závislostí. Nebojte, Portage si se závislostmi poradí. Abyste zjistili, co Portage nainstaluje, použijte volbu --pretend. Například:

root #emerge --pretend gnumeric

To do the same, but interactively choose whether or not to proceed with the installation, add the --ask flag:

root #emerge --ask gnumeric

Během instalování balíčku Portage stáhne z internetu nezbytný zdrojový kód (je-li to potřeba) a uloží jej (ve výchozím stavu) do /var/cache/distfiles/. Potom jej rozbalí, zkompiluje a balíček nainstaluje. Chcete-li dát Portage instrukce, aby došlo pouze ke střžení zdrojových kódů bez jejich instalace, předejte příkazu emerge volbu --fetchonly:

root #emerge --fetchonly gnumeric

Nalezení dokumentace nainstalovaných balíčků

Spousta balíčků obsahuje vlastní dokumentaci. Někdy se to, zda bude dokumentace balíčku nainstalována nebo ne, určuje pomocí přepínače USE doc. Ke zjištění, zda je přepínač USE doc balíčkem používán, použijte příkaz emerge -vp category/package:

root #emerge -vp media-libs/alsa-lib
These are the packages that would be merged, in order:
 
Calculating dependencies... done!
[ebuild   R    ] media-libs/alsa-lib-1.1.3::gentoo  USE="python -alisp -debug -doc" ABI_X86="(64) -32 (-x32)" PYTHON_TARGETS="python2_7" 0 KiB

Nejlepší je zapínat přepínač USE doc pro každý balíček zvlášť pomocí souboru /etc/portage/package.use, tak aby byla instalována dokumentace jen pro balíčky, u kterých to chceme. Více informací si můžete přečíst v sekci o přepínačích USE.

Jakmile je balíček nainstalován, lze jeho dokumentaci většinou najít v podadresáři pojmenovaném po balíčku uvnitř adresáře /usr/share/doc:

user $ls -l /usr/share/doc/alsa-lib-1.1.3
celkem 16
-rw-r--r-- 1 root root 3098 Bře  9 15:36 asoundrc.txt.bz2
-rw-r--r-- 1 root root  672 Bře  9 15:36 ChangeLog.bz2
-rw-r--r-- 1 root root 1083 Bře  9 15:36 NOTES.bz2
-rw-r--r-- 1 root root  220 Bře  9 15:36 TODO.bz2

Jistější postup jak vypsat nainstalované soubory dokumentace je použít equery s volbou --filter. Příkaz equery se používá k dotazům na databází portage a je součástí balíčku app-portage/gentoolkit:

user $equery files --filter=doc alsa-lib
 * Searching for alsa-lib in media-libs ...
 * Contents of media-libs/alsa-lib-1.1.3:
/usr/share/doc/alsa-lib-1.1.3/ChangeLog.bz2
/usr/share/doc/alsa-lib-1.1.3/NOTES.bz2
/usr/share/doc/alsa-lib-1.1.3/TODO.bz2
/usr/share/doc/alsa-lib-1.1.3/asoundrc.txt.bz2

Volba --filter může být použita s ostatními pravidly ke zobrazení míst kam se instalují různé typy souborů. Další funkce si můžete nastudovat v man stránce equery: man 1 equery.

Odstranění softwaru

K odstranění softwaru ze systému použijte příkaz emerge --unmerge. Tím dáte Portage instrukce, aby odstranila soubory nainstalované daným balíčkem ze systému. Vyjímkou jsou konfigurační soubory aplikace, "pokud" byly uživatelem změněny. Ponechání konfiguračních souborů umožňuje uživateli, aby mohl pokračovat v práci s balíčkem bez nutnosti rekonfigurace, pokud by byl později znovu nainstalován.

root #emerge --unmerge gnumeric

Pokud je balíček odstraněn ze systému, závislosti tohoto balíčku, které byly automaticky nainstalovány spolu s ním, jsou stále zachovány v systému. Aby Portage nalezl všechny závislosti, které mohou být nyní odstraněny, použijte funkci emerge --depclean, která je popsána později.

Aktualizace systému

Abyste udrželi systém ve formě (nemluvě o instalaci nejnovějších bezpečnostních aktualizací), je třeba aktualizovat pravidelně systém. Jelikož Portage kontroluje pouze ebuildy v repozitáři Gentoo, první věcí, kterou musíte udělat, je aktualizace repozitáře Gentoo. Jakmile je repozitář Gentoo aktualizován, může být systém aktualizován pomocí emerge --update @world. V následujícím příkladu používáme také volbu --ask, který říká Portage, aby zobrazil seznam balíčků, které chce aktualizovat a vyžádal potvrzení:

Portage po vyhledá novější verze instalovaných aplikací. Nicméně zkontroluje pouze verze aplikací, které byly explicitně nainstalovány (aplikace obsažené v /var/lib/portage/world) - nebude zevrubně kontrolovat jejich závislosti. Chcete-li aktualizovat zároveň i závislosti, použijte volbu --deep:

root #emerge --update --deep @world

Pokud jste v systému změnili nastavení USE, doporučuje se také přidat volbu --newuse. Portage pak ověří, zda změna vyžaduje instalaci nových balíčků nebo překompilování již existujících:

root #emerge --update --deep --with-bdeps=y --newuse @world

Metabalíčky

Některé balíčky ve repozitáři Gentoo nemají žádný reálný obsah, ale používají se k instalaci sestav balíčků. Například balíček kde-plasma/plasma-meta nainstaluje do systému kompletní desktop KDE Plasma tím, že vtáhne rozličné balíčky související s Plasmou jako závislosti.

Spuštění emerge --unmerge k odstranění takového balíku ze systému nebude mít žádný efekt, jelikož závislosti zůstanou v systému.

Portage obsahuje funkci k odstranění osiřelých závislostí, avšak jelikož je dostupnost softwaru dynamicky proměnná, je nejdříve nejdůležitější provést celkovou aktualizaci systému, včetně změn přepínačů USE. Potom lze spustit příkaz emerge --depclean k odstranění osiřelých závislostí. Jakmile je toto dokončeno, může být nutné znovu sestavit aplikace, které byly dynamicky propojené k nyní již odstraněnému softwaru, ale nadále ho již nepotřebují. Tato funkce byla do Portage nedávno přidána.

O vše se postarají následující tři příkazy:

root #emerge --update --deep --newuse @world
root #emerge --depclean
root #revdep-rebuild

Licence

Počínaje Portage verze 2.1.7 je možné schválit nebo naopak odmítnout instalaci software na základě jeho licence. Všechny balíčky ve stromu obsahují ve svém ebuildu údaj o licenci (LICENSE). Příkaz emerge --search package/category zobrazí licenci balíčku.

Important
Proměnná LICENCE v ebuildu je jen pomůckou pro vývojáře a uživatele Gentoo. Nejedná se o právní stanovisko a není žádná garance, že odpovídá skutečnému stavu. Nespoléhejte tedy na ni a zkontrolujte balíček pořádně sami, včetně všech souborů, které používáte.

If a discrepancies is found in the ebuild, please file a bug to suggest a change to the value(s) assigned to the ebuild's LICENSE variable.}}

Ve výchozím stavu Portage povoluje licence schválené Free Software Foundation, Open Source Initiative nebo ty, které se řídí definicí svobodného software.

Proměnná, která povoluje licence, se nazývá ACCEPT_LICENSE a může být nastavena v /etc/portage/make.conf. V následujícím příkladu je zobrazena její výchozí hodnota:

FILE /etc/portage/make.confVýchozí nastavení ACCEPT_LICENSE
ACCEPT_LICENSE="-* @FREE"

S tímto nastavením buden možné nainstalovat balíčky pod svobodnou softwarovou nebo dokumentační licencí. Nesvobodný software nebude možné instalovat.

Proměnnou ACCEPT_LICENSE je možné nastavit globálně v /etc/portage/make.conf, nebo zvlášť specifikovat pro každý balíček v souboru /etc/portage/packages.license.

Abyste mohli například povolili licenci google-chrome balíčku www-client/google-chrome, vložte do /etc/portage/package.license následující:

FILE /etc/portage/package.licenseAkceptace licence google-chrome balíčku google-chrome
www-client/google-chrome google-chrome

Tímto umožníte instalaci www-client/google-chrome, ale zamezíte instalaci balíčku www-plugins/chrome-binary-plugins, ačkoli mají stejnou licenci.

Or to allow the often-needed sys-kernel/linux-firmware:

FILE /etc/portage/package.licenseAccepting the licenses for the linux-firmware package
# Accepting the license for linux-firmware
sys-kernel/linux-firmware linux-fw-redistributable
</div>

<div lang="en" dir="ltr" class="mw-content-ltr">
# Accepting any license that permits redistribution
sys-kernel/linux-firmware @BINARY-REDISTRIBUTABLE
Important
Licence jsou uloženy v adresáři /usr/portage/licenses/ a skupiny licencí se nacházejí v souboru /usr/portage/profiles/license_groups. První údaj na každém řádku vyvedený ve "VELKÝCH" písmenech je názvem skupiny licencí, a všechny údaje za ním jsou názvy jednotlivých licencí

.

Skupiny licencí se v proměnné ACCEPT_LICENSE označují znakem @. Je možné provést nastavení (které bylo předchozí výchozí volbou Portage) umožňující všechny licence vyjma End User Licence Agreement (EULAs), kteřé vyžadují přečtení a podpis akceptace. Abychom toho dosáhli, udělte souhlas se všemi licencemi (pomocí -*) a pak odstraňte všechny licence ve skupině EULA následujícím způsobem:

FILE /etc/portage/make.confSouhlas se všemi licencemi kromě EULA
ACCEPT_LICENSE="* -@EULA"

Vemte na vědomí, že tímto nastavením udělíte souhlas s nesvobodným softwarem a dokumentací.

Když si Portage stěžuje

Terminologie

Jak bylo řečeno dříve, Portage je extrémně silná a podporuje mnoho funkcí, které jiné nástroje správy softwaru nemají. Abyste vše pochopili, vysvětlíme několik aspektů Portage, aniž bychom zabíhali do přílišných detailů.

Portage umožňuje koexistenci několika verzí jednoho balíčku v systému. Zatímco ostatní distribuce se přiklání k tomu pojmenovávat balíčky podle těchto verzí (například freetype a freetype2), Portage používá techniku zvanou "SLOT"y. Ebuild deklaruje určitý SLOT své verze. Ebuildy s různými SLOTy mohou koexistovat v jednom systému. Například balíček freetype používá v ebuildech SLOT="1" a SLOT="2".

Existují také balíčky, které poskytují stejnou funkcionalitu, alejinou implementaci. Například metalogd, sysklogd a syslog-ng jsou systémové loggery. Aplikace, které spoléhají na dostupnost "systémového loggeru", nemohou například záviset na metalogd, jelikož volba kteréhokoli loggeru je stejně dobrá. Portage umí virtuální balíčky: všechny systémové loggery jsou na seznamu vzájemně se vylučujících závislostí virtuálního balíčku logovací služby v kategorii virtual tak, aby aplikace mohly záviset na balíčku virtual/logger. Je-li tento balíček instalován, natáhne s sebou logovací balíček jmenovaný v něm na prvním místě, pokud už není nainstalovaný jiný logovací balíček (v takovém případě je virtual uspokojen).

Software v repozitáři Gentoo může být umístěn v rozdílných větvích. Ve výchozím stavu systém akceptuje pouze balíčky, které Gentoo považuje za stabilní. Většina nových softwarových titulů bývá při svém zahrnutí přidána do testovací větve, což znamená, že je třeba provést další testování, než budou označeny za stabilní. Ačkoli jsou ebuildy tohoto softwaru v repozitáři Gentoo, Portage je nebude aktualizovat do doby, než budou přidány do stabilní větve.

Některý software je dostupná pouzte pro pár architektur. Nebo software funguje jenom na jiných architekturách nebo potřebuje víc testování nebo vývojář, který zahrnul software do repozitáře Gentoo nemá možnost ověřit, že balíček funguje na jiných architekturách.

Každá instalace Gentoo se také drží určeného profilu, který obsahuje, mimo další informace, seznam balíčků, které jsou vyžadovány k tomu, aby systém normálně fungoval.

Blokované balíčky

CODE Varování Portage ohledně blokovaných balíčku (s volbou --pretend)
[blocks B     ] mail-mta/ssmtp (is blocking mail-mta/postfix-2.2.2-r1)
  • Error: The above package list contains packages which cannot be
* installed at the same time on the same system.

(x11-wm/i3-4.20.1:0/0::gentoo, ebuild scheduled for merge) pulled in by

   x11-wm/i3

Ebuildy obsahují specifická pole, která informují Portage o svých závislostech. Jsou dvě možné závislosti: závislost sestavení, deklarovaná v proměnné DEPEND a závislosti běhu, obdobně deklarované v proměnné RDEPEND. Pokud jdna z těchto závislostí výslovně uvede, že je balíček nebo virtual nekompatibilní, vyvolá to blokaci.

Nakolik jsou novější verze Portage dostatečně chytré, aby obešly dorbné blokace bez uživatelského zásahu, občas je třeba takové blokace vyřešit ručně.

Vyřešení blokace vyžaduje, aby se uživatel rozhodl buď neinstalovat balíček nebo odinstalovat nejdříve balíček, který zapříčiňuje konflikt. V daném příkladu lze zvolit buď neinstalovat postfix nebo nejprve odebrat ssmtp.

Občas se objeví blokující balíčky se specifickými atomy, jako je <media-video/mplayer-1.0_rc1-r2. V takovém případě může být blok odstraněn aktualizací blokujícího balíčku na novější verzi.

Je také možné, že se dva balíčky, které mají být teprve nainstalovány, navzájem blokují. V těchto vzácných případech se pokuste zjistit, pro je potřeba instalovat oba dva. Ve většině případů by měla postačovat instalace jen jednoho z nich. Pokud tomu tak není, nahlašte chybu Systému správy chybových hlášení Gentoo.

Maskované balíčky

CODE Varování Portage ohledně maskovaných balíčků
!!! all ebuilds that could satisfy "bootsplash" have been masked.
CODE Varování Portage ohledně maskovaných balíčků - důvody
!!! possible candidates are:
  
- gnome-base/gnome-2.8.0_pre1 (masked by: ~x86 keyword)
- lm-sensors/lm-sensors-2.8.7 (masked by: -sparc keyword)
- sys-libs/glibc-2.3.4.20040808 (masked by: -* keyword)
- dev-util/cvsd-1.0.2 (masked by: missing keyword)
- games-fps/unreal-tournament-451 (masked by: package.mask)
- sys-libs/glibc-2.3.2-r11 (masked by: profile)
- net-im/skype-2.1.0.81 (masked by: skype-eula license(s))

Když se pokoušíte nainstalovat balíček, který není dostupný pro daný systém, objeví se tato chyba maskování. Uživatelé by měli zkusit nainstalovat jinou, v systému dostupnou aplikaci nebo počkat, dokud nebude balíček dostupný. Zamaskování balíčku má vždy svůj důvod:

Důvody maskování Description
klíčové slovo ~arch Aplikace nebyla dostatečně otestována, aby mohla být umístěna do stabilní větve. Počkejte pár dnů nebo týdnů a zkuste to znova.
klíčová slova -arch nebo -* Aplikace nefunguje na vaší architektuře. Pokud máte za to, že na ní funguje, nahlašte chybu do naší Bugzilly.
chybějící klíčové slovo Aplikace zatím nebyla na vaší architektuře testována. Požádejte tým pro portování na architekturu, aby balíček otestoval nebo ji vyzkoušejte sami a nahlašte své poznatky do naší Bugzilly.
package.mask Bylo zjištěno, že balíček je poškozený, nestabilní nebo i něco horšího a bylo mu přiřazeno označení nepoužívat.
profile Bylo zjištěno, že balíček není vhodný pro současný profil. Pokud by byl nainstalován, může balíček rozbít systém nebo je jen nekompatibilní s právě používaným profilem.
license Licence balíčku není kompatibilní s hodnotou ACCEPT_LICENSE. Povolte jeho licenci nebo správnou skupinu licencí nastavením v /etc/portage/make.conf nebo /etc/portage/package.license

Potřebné změny přepínače USE

CODE Varování Portage ohledně potřebných změn přepínače USE
The following USE changes are necessary to proceed:
#required by app-text/happypackage-2.0, required by happypackage (argument)
>=app-text/feelings-1.0.0 test

Chybová hláška se může zobrazit i takto, pokud není použitá volba --autounmask:

CODE Chyba Portage ohledně potřebných změn přepínače USE
emerge: there are no ebuilds built with USE flags to satisfy "app-text/feelings[test]".
!!! One of the following packages is required to complete your request:
- app-text/feelings-1.0.0 (Change USE: +test)
(dependency required by "app-text/happypackage-2.0" [ebuild])
(dependency required by "happypackage" [argument])

Takové varování nebo chyba nastanou pokud je vyžadována instalace balíčku, který nejenže závisí na jiném balíčku, ale také vyžaduje, aby byl tento balíček sestaven s určitým přepínačem USE (nebo sadou přepínačů USE). V daném případě je vyžadováno, aby byl balíček app-text/feelings sestaven s USE="test", ale tento přepínač USE nebyl v systému zapnut.

Řešení spočívá buď v přidání požadovaného USE přepínače mezi globální USE přepínače v /etc/portage/make.conf, nebo jeho nastavení pro daný balíček v /etc/portage/package.use.

Chybějící závislosti

CODE Varování Portage ohledně chybějící závislosti
emerge: there are no ebuilds to satisfy ">=sys-devel/gcc-3.4.2-r4".
  
!!! Problem with ebuild sys-devel/gcc-3.4.2-r2
!!! Possibly a DEPEND/*DEPEND problem.

Instalovaná aplikace závisí na jiném balíčku, který není v systému dostupný. Zkontrolujte prosím Bugzillu, zda je problém nahlášen a pokud ne, nahlašte jej prosím. Pokud není v systému nastaveno mísení větví, nemělo by toto nastat a jde tedy o chybu.

Nejednoznačený název ebuildu

CODE Varování Portage ohledně nejednoznačných názvů ebuildů
[ Results for search key : listen ]
[ Applications found : 2 ]
  
*  dev-tinyos/listen [ Masked ]
      Latest version available: 1.1.15
      Latest version installed: [ Not Installed ]
      Size of files: 10,032 kB
      Homepage:      http://www.tinyos.net/
      Description:   Raw listen for TinyOS
      License:       BSD
  
*  media-sound/listen [ Masked ]
      Latest version available: 0.6.3
      Latest version installed: [ Not Installed ]
      Size of files: 859 kB
      Homepage:      http://www.listen-project.org
      Description:   A Music player and management for GNOME
      License:       GPL-2
  
!!! The short ebuild name "listen" is ambiguous. Please specify
!!! one of the above fully-qualified ebuild names instead.

Zvolená instalovaná aplikace má název, který odpovídá více než jednomu balíčku. Řešením je zadat také název kategorie. Portage informuje uživatele o možných shodách, z nichž lze vybrat.

Kruhové závislosti

CODE Varování Portage ohledně kruhových závislostí
!!! Error: circular dependencies: 
  
ebuild / net-print/cups-1.1.15-r2 depends on ebuild / app-text/ghostscript-7.05.3-r1
ebuild / app-text/ghostscript-7.05.3-r1 depends on ebuild / net-print/cups-1.1.15-r2

Dva (nebo více) instalovaných balíčků na sobě vzájemně závisí a tudíž nemohou být nainstalovány. Jedná se nejspíše o chybu v jednom z balíčků v repozitáři Gentoo. Po nějakém čase resynchronizujte a zkuste to znovu. Přínosem může být také kontrola Bugzilly, abyste zjistili, zda je problém znám a pokud ne, nahlašte ho.

Stažení selhalo

CODE Varování Portage ohledně selhání stažení
!!! Fetch failed for sys-libs/ncurses-5.4-r5, continuing...
(...)
!!! Some fetch errors were encountered.  Please see above for details.

Portage nemohla stáhnout zdrojové kódy dané aplikace a bude se snažit nainstalovat další aplikace (je-li to možné). Tato chyba může být způsobena zrcadlem, které není správně synchronizováno, nebo tím, že ebuild odkazuje na chybné umístění. Server, kde se zdrojové kódy nachází může být také z nějakých důvodů mimo provoz.

Za hodinu zkuste znova, zda problém přetrvává.

Ochrana profilu systému

CODE Varování Portage ohledně balíčku chráněného profilem
!!! Trying to unmerge package(s) in system profile. 'sys-apps/portage'
!!! This could be damaging to your system.

Uživatel požaduje odebrání balíčku, který je součástí základních systémových balíčků. Profil ho uvádí jako vyžadovaný a neměl by tedy být odstraněn ze systému.

Chyba ověření přehledu

CODE Chyba ověření přehledu
>>> checking ebuild checksums
!!! Digest verification failed:

Jedná se o známku toho, že je něco špatně s repozitářem Gentoo - často se jedná o chybu při zavádění ebuildu do repozitáře ebuildů Gentoo.

Pokud ověření přehledu selže, nepokoušejte se znovu zpracovat ebuild ručně. Spuštění ebuild foo manifest problém neodstraní, naopak ho může zhoršit.

Namísto toho počkejte hodinu nebo dvě, než se repozitář usadí. Je pravděpodobné, že byl problém ihned zaznamenán, ale může chvilku trvat, než se oprava objeví na zrcadlech rsync. Zkontrolujte Bugzillu a zjistěte, zda už někdo problém nahlásil nebo napište na #gentoo (webchat) (IRC). Pokud tomu tak není, nahlašte, že je v ebuildu chyba.

Jakmile bude chyba opravena, resnychronizujte repozitář ebuildů Gentoo, čímž stáhnete opravený přehled.

Important
Dbejte na to, abyste nesynchronizovali repozitář ebuildů Gentoo více než jednou denně. Jak uvádíme v oficiální netiketě Gentoo (stejně jako u spouštění emerge --sync), uživatelům, kteří synchronizují příliš často, může být načas další synchronizování zablokováno. Pokud to není naprosto nezbytné, je nejlepší vyčkat se synchronizací po dobu 24 hodin, aby resynchronizace nepřetížila rsync zrcadla Gentoo.





Co jsou to volby USE

Co stojí za myšlenkou voleb USE

Při instalaci Gentoo (nebo jinou distribuci, nebo dokonce jiný operační systém, když jsme u toho), činí uživatelé určité volby v závislosti na prostředí, v němž budou pracovat. Nastavení serveru se liší od nastavení pracovní stanice. Herní stanice se liší od 3D renderovací stanice.

To se týká nejen výběru instalovaných balíčků, ale také funkcí, které by tyto balíčky měly podporovat. Pokud nebudete potřebovat OpenGL, proč by jste se měli obtěžovat s instalací a údržbou OpenGL a sestavovat jeho podporu ve většině balíčků. Pokud nechcete používat KDE, proč by jste se měli obtěžovat kompilováním podpory KDE v balíčcích, když mohou bezchybně fungovat bez ní?

Abychom uživatelům pomohli při rozhodování co nainstalovat/aktivovat, chceme v Gentoo, aby mohli uživatelé své prostředí snadno popsat. Tím nutíme uživatele aby se rozhodli, co opravdu potřebují a usnadňujeme Portage, aby činila potřebná rozhodnutí.

Definice voleb USE

Vítejte ve světě voleb USE. Tyto volby jsou vlastně hesly, které obsahují informaci o funkcích a závislostech do jednotného konceptu. Pokud je nastavena určitá volba USE, Portage zjistí, že je vyždována podpora vybraného hesla. Tím se samozřejmě změní i závislosti balíčku.

Podívejme se na konkrétní případ: heslo kde. Pokud není toto heslo v proměnné USE, všechny balíčky, které obsahují volitelnou podporu KDE budou sestaveny "bez" podpory KDE. Všechny balíčky, které mají volitelnou závislost na KDE budou instalovány bez instalace knihoven KDE (jako závislostí). Pokud je heslo kde zapnuto, pak budou tyto balíčky sestaveny "s" podporou KDE a knihovny KDE "budou" nainstalovány jako závislosti.

When the kde flag is set to enabled, then those packages will be compiled with KDE support, and the KDE libraries will be installed as dependency.

Správným definováním hesel bude systém přizůpsoben přesně podle potřeb uživatele.

Používánéí voleb USE

Trvalé nastavení voleb USE

Jak bylo dříve uvedeno, volby USE se nastavují v proměnné USE. Abychom uživatelům usnadnili vyhledávání a výběr voleb USE poskytujeme výchozí nastavení USE. Toto nastavení je sadou voleb USE, o nichž si myslíme, že jsou uživateli Gentoo běžně používané. Toto výchozí nastavení je uvedeno v souborech make.defaults, které jsou součástí zvoleného profilu.

Profil, který systém používá, je označen prostřednictvím odkazu /etc/portage/make.profile. Každý profil funguje nad jinými profily a výsledek je tedy součtem všech profilů. Nejvyšší profil, je základní profil (/profiles/base).

Ke zobrazení momentálně aktivních voleb USE (úplný seznam), použijte emerge --info:

root #emerge --info | grep ^USE
USE="a52 aac acpi alsa branding cairo cdr dbus dts ..."

Jak můžete vidět, už nyní tato proměnná obsahuje mnoho hesel. Neměňte však žádný ze souborů make.defults, abyste přizpůsobili proměnnou USE svým osobním požadavkům: změny v těchto souborech budou vráceny jakmile aktualizujete repozitář Gentoo!

Změnu výchozího nastavení lze provést přidáním nebo odebráním hesel do/z proměnné USE. Na globální úrovni to provedete definováním proměnné USE v /etc/portage/make.conf. V této proměnné lze přidat další požadované volby USE nebo odebrat ty z nich, které už nejsou potřeba. Druhou možnost provedete přidáním znaku minus před dané heslo (-).

Například k odebrání podpory KDE a Qt a naopak pro přidání podpory LDAP lze definovat následující USE v /etc/portage/make.conf:

FILE /etc/portage/make.confAktualizace USE v make.conf
USE="-kde -qt4 -qt5 ldap"

Nastavení voleb USE pro jednotlivé balíčky

Uživatelé někdy chtějí deklarovat určitou volbu USE pro jednu (nebo několik) aplikací, ale ne na úrovni celého systému. Abychom toho dosáhli, upravíme /etc/portage/package.use. Soubor package.use většinou bývá jediným souborem, nicméně může jít i o adresář obsahující soubory; podívejte se na níže uvedený tip a pak na man 5 portage pro více informací o tom, jak využít tento způsob. Následující příklad předpokládá, že je package.use jediný soubor.

Například pro podporu Blu-ray pouze v mediálním přehravači VLC:

FILE /etc/portage/package.useZapnutí podpory blu-ray ve VLC
media-video/vlc bluray
Tip
Pokud už package.use existuje jako adresář (namísto jednoho souboru), lokální volby USE balíčků mohou být jednoduše měněny vytvářením souborů v adresáři package.use/. Použít lze jakékoli názvy souborů, nicméně hodí se používat jednotné schéma pojmenování. Jednou z možností je jednoduše používat název balíčku pro jméno souboru. Například nastavení volby USE bluray lokálně pro balíček media-video/vlc může být provedeno následujícím způsobem:

root #echo "media-video/vlc bluray" >> /etc/portage/package.use/vlc

Podobně je možné výslovně vypnout volbu USE pro určitou aplikaci. Například vypnutí podpory bzip2 v PHP (ale její ponechání v ostatních balíčcích prostřednictvím deklarace v make.conf):

FILE /etc/portage/package.useVypnutí podpory bzip2 v PHP
dev-lang/php -bzip2

Nastavení dočasných voleb USE

Někdy potřebují uživatelé nastavit volby USE pouze na chvíli. Namísto dvojí změny /etc/portage/make.conf (vložení a vymazání změny USE) pouze nastavte USE jako proměnnou prostředí. Pamatujte, že toto nastavení platí pouze pro zadávaný příkaz; znovu nainstalování nebo aktualizace této aplikace (ať už přímo nebo v rámci aktualizace systému) zruší změny vyvolané prostřednictvím (dočasné) definice volby USE.

V následujícím příkladu dočasně odebreme z proměnné USE hodnotu pulseaudio během instalace SeaMonkey:

root #USE="-pulseaudio" emerge www-client/seamonkey

Pořadí

Přirozeně je dané určité pořadí priorit jednotlivých voleb pro vyhodnocení nastavení USE. Řazeno podle priorit (první má nejnižší prioritu), se nastavení USE vyhodnotí takto:

  1. Výchozí nastavení USE uvedené v souborech make.defaults vašeho profilu
  2. Uživatelem definované nastavení USE v /etc/portage/make.conf
  3. Uživatelem definované nastavení USE v /etc/portage/package.use
  4. Uživatelem definované nastavení USE v proměné prostředí

Pro zobrazení konečného nastavení USE, tak jako ho vidí Portage, spusťte emerge --info. Tím se zobrazí seznam všech relevantních proměnných (včetně proměnné USE) a jejich obsah tak, jak je znám Portage.

root #emerge --info

Adaptace celého systému na nové volby USE

Po té, co jste provedli změny voleb USE, by měl být celý systém aktualizován, aby se potřebné změny projevily. To provedete použitím volby --newuse s emerge:

root #emerge --update --deep --newuse @world

Následně spusťte funkci depclean v Portage, která odebere všechny podmíněné závislosti, které byly nainstalovány na "starý" systém, ale díky novým volbám USE už nejsou potřeba.

Warning
Spuštění emerge --depclean je nebezpečná operace a měla by být prováděna s pečlivostí. Zkontrolujte dobře nabídnutý seznam "zastaralých" balíčků a ujistěte se, že neodstraníte balíček, který potřebujete. V následujícím příkladu jsme přidali přepínač -p, aby funkce depclean pouze vypsala balíčky bez jejich odstranění:
root #emerge -p --depclean

Jakmile funkce depclean skončila, může emerge vyžadovat opětovné sestavení aplikací, kterou jsou dynamicky linkovány proti sdíleným objektům poskytovaným odstraněnými balíčky. Portage tyto nezbytné knihovny zachová dokud neprovedete uvedenou akci, aby zabránil znefunkčnění aplikací. Seznam toho, co je třeba znovu sestavit, je uložen v setu preserved-rebuild. K opětovnému sestavení požadovaných balíčků spusťte:

root #emerge @preserved-rebuild

Pokud se vám tohle všechno povedlo, systém používá nové nastavení voleb USE.

Zvláštní volby USE balíčků

Zobrazení dostupných voleb USE

Vezměmě si jako příklad seamonkey: jaké volby USE lze použít? Zjistit to můžeme použitím emerge s volbami --pretend a --verbose:

root #emerge --pretend --verbose www-client/seamonkey
These are the packages that would be merged, in order:
 
Calculating dependencies... done!
[ebuild  N     ] www-client/seamonkey-2.48_beta1::gentoo  USE="calendar chatzilla crypt dbus gmp-autoupdate ipc jemalloc pulseaudio roaming skia startup-notification -custom-cflags -custom-optimization -debug -gtk3 -jack -minimal (-neon) (-selinux) (-system-cairo) -system-harfbuzz -system-icu -system-jpeg -system-libevent -system-libvpx -system-sqlite {-test} -wifi" L10N="-ca -cs -de -en-GB -es-AR -es-ES -fi -fr -gl -hu -it -ja -lt -nb -nl -pl -pt-PT -ru -sk -sv -tr -uk -zh-CN -zh-TW" 216,860 KiB
 
Total: 1 package (1 new), Size of downloads: 216,860 KiB

emerge není jediným nástrojem, který lze použít. Ve skutečnosti existuje nástroj určený právě k prohledávání informací o balíčcích zvaný equery, který se nachází v balíčku app-portage/gentoolkit.

root #emerge --ask app-portage/gentoolkit

Nyní spusťte equery s argumentem "uses", čímž zobrazíte volby USE daného balíčku. Například u balíčku gnumeric:

user $equery --nocolor uses =gnumeric-1.12.31
[ Legend : U - final flag setting for installation]
[        : I - package is installed with flag     ]
[ Colors : set, unset                             ]
 * Found these USE flags for app-office/gnumeric-1.12.31:
 U I
 + + introspection            : Add support for GObject based introspection
 - - libgda                   : Enable database support through gnome-extra/libgda.
 - - perl                     : Enable perl plugin loader.
 + + python                   : Enable python plugin loader.
 + + python_targets_python2_7 : Build with Python 2.7

Splnění podmínek REQUIRED_USE

Některé ebuildy požadují nebo zakazují určité kombinace voleb USE, aby mohly správně fungovat. To bývá vyjádřeno sadou podmínek umístěných ve výrazech REQUIRED_USE. Tyto podmínky zajišťují že budou všechny funkce a závislosti kompletní a sestavení proběhne úspěšně a podle očekávání. Pokud kterákoli není splněna, emerge vás upozorní a požádá vás o nápravu problému.

Příklad Popis
REQUIRED_USE="foo? ( bar )" Pokud je zapnuta foo, musí být zapnuta bar.
REQUIRED_USE="foo? ( !bar )" Pokud je zapnuta foo, musí být vypnuta bar.
REQUIRED_USE="foo? ( || ( bar baz ) )" Pokud je zapnuta foo, musí být zapnuta bar nebo baz.
REQUIRED_USE="^^ ( foo bar baz )" Musí být zapnuta právě jedna z foo bar nebo baz.
REQUIRED_USE="|| ( foo bar baz )" Musí být zapnuta alespoň jedna z foo bar nebo baz.
REQUIRED_USE="?? ( foo bar baz )" Nesmí být zapnuta více než jedna z foo bar nebo baz.




Funkce Portage

Portage má také několik dalších funkcí, které činí práci s Gentoo ještě lepší. Některé z těchto funkcí závisí na určitých softwarových nastrojích, které zlepšují výkon, spolehlivost, zabezpěčení...

Funkce portage zapnete a vypnete úpravou /etc/portage/make.conf nebo změnou proměnné FEATURES, která obsahuje hesla daných funkcí, oddělené mezerou. V určitých případech bude třeba také nainstalovat nástroje, které daná funkce využívá.

Neuvádíme zde všechny funkce, které Portage podporuje. Úplný přehled najdete v manuálové stránce make.conf:

user $man make.conf

Chcete-li zjistit, které funkce jsou v základu zapnuty, spusťte emerge --info a hledejte proměnnou FEATURES nebo ji zobrazte pomocí grep:

user $emerge --info | grep ^FEATURES=

Distribuovaná kompilace

Použití distcc

distcc je program, který umožňuje kompilaci pomocí několika, ne nutně stejných, zařízení v síti. Klient distcc posílá všechny potřebné informace dostupným serverům distcc (na kterých běží distccd), aby zkompilovali kousky zdrojového kódu pro klienta. Výsledkem je rychlejší kompilace.

Více informací o distcc (a o tom jak jej na Gentoo zprovoznit), můžete najít v článku o Distcc.

Instalace distcc

Distcc obsahuje grafický monitor ke sledování úloh, které systém odesílá pro kompilaci. Tento nástroj je automaticky nainstalován pokud je nastavena volba USE=gnome nebo USE=gtk.

root #emerge --ask sys-devel/distcc

Aktivace podpory distcc v Portage

Vložte heslo distcc do proměnné FEATURES v /etc/portage/make.conf. Následně upravte proměnnou MAKEOPTS a navyšte počet paralelních úloh sestavení, tak jak to systém umožňuje. Běžným doporučením je použít -jN, kde N je počet procesorů, na kterých běží distccd (včetně vašeho stroje) plus jeden, ale je to jen doporučení.

Nyní spusťte distcc-config a vložte seznam dostupných distcc serverů. Pro jendoduchost předpokládejme, že máme k dispozici DistCC servery 192.168.1.102 (náš počítač), 192.168.1.103 a 192.168.1.104 (dva "vzdálené" počítače).

root #distcc-config --set-hosts "192.168.1.102 192.168.1.103 192.168.1.104"

Nezapomeňte také spustit démona distccd:

root #rc-update add distccd default
root #/etc/init.d/distccd start

Kešování kompilovaných objektů

O ccache

ccache je rychlá keš kompilátoru. Kdykoli dochází ke kompilaci aplikace, kešuje výsledky, tak aby v případě, že dojde znovu ke kompilaci stejného programu, došlo k velké úspoře času při kompilaci. Při prvním spuštění však bude kompilace s ccache pomalejší než normálně. Další rekompilace by ale měla být značně rychlejší. ccache pomáhá jen tehdy, pokud se stejná aplikace kompiluje mnohokrát (nebo pokud je stejná aplikace často aktualizována); proto je většinou užitečná pouze pro vývojáře softwaru.

Pro více informací o ccache prosím navštivte její domovskou stránku.

Warning
Ví se, že ccache způsobuje při kompilaci mnoho chyb. Občas může ccache uchovávat zastaralé objekty kódu nebo porušené soubory, což může vést k selhání instalace balíčků. Pokud se to stane (v build logu se ukazují chyby jako "File not recognized: File truncated"), zkuste aplikaci sestavit znovu s vypnutou ccache (FEATURES="-ccache" v /etc/portage/make.conf) před nahlášením chyby.

Instalace ccache

Ccache nainstalujete následujícím příkazem:

root #emerge --ask dev-util/ccache

Aktivace podpory ccache v Portage

Otevřete /etc/portage/make.conf a vložte ccache mezi ostatní hodnoty definované v proměnné FEATURES. Pokud FEATURES neexistuje, vytvořte ji. Následně přidejte novou proměnnou jménem CCACHE_SIZE a nastavte její hodnotu na 2G:

FILE /etc/portage/make.confZapnutí podpory ccache v Portage
FEATURES="ccache"
CCACHE_SIZE="2G"

Kontrolu funkčnosti ccache provedete dotazem na její statistiky. Jelikož Portage používá pro ccache odlišný domovský adresář, je potřeba dočasně nastavit proměnnou CCACHE_DIR:

root #CCACHE_DIR="/var/tmp/ccache" ccache -s

Umístění /var/tmp/ccache/ je výchozí domovský adresář ccache v Portage; může být změněn nastavením proměnné CCACHE_DIR v /etc/portage/make.conf.

Pokud je ccache spuštěna samostatně, použije výchozí umístění ${HOME}/.ccache/, proto je třeba nastavit proměnnou CCACHE_DIR, když chceme zjistit statistiky ccache pro Portage.

Použití ccache mimo Portage

To use ccache for non-Portage compilations, add /usr/lib/ccache/bin/ to the beginning of the PATH variable (before /usr/bin). This can be accomplished by editing ~/.bash_profile in the user's home directory. Using ~/.bash_profile is one way to define PATH variables.

FILE ~/.bash_profileSetting the ccache location before any other PATH
PATH="/usr/lib/ccache/bin:${PATH}"

Binary package support

Creating prebuilt packages

Portage supports the installation of prebuilt packages. Even though Gentoo does not provide prebuilt packages by itself Portage can be made fully aware of prebuilt packages.

To create a prebuilt package use the quickpkg command if the package is already installed on the system, or emerge with the --buildpkg or --buildpkgonly options.

To have Portage create prebuilt packages of every single package that gets installed, add buildpkg to the FEATURES variable.

More extended support for creating prebuilt package sets can be obtained with catalyst. For more information on catalyst please read the Catalyst FAQ.

Installing prebuilt packages

Although Gentoo doesn't provide one, it is possible to create a central repository where prebuilt packages are stored. In order to use this repository, it is necessary to make Portage aware of it by having the PORTAGE_BINHOST variable point to it. For instance, if the prebuilt packages are on ftp://buildhost/gentoo:

FILE /etc/portage/make.confAdd PORTAGE_BINHOST location
PORTAGE_BINHOST="ftp://buildhost/gentoo"

To install a prebuilt package, add the --getbinpkg option to the emerge command alongside of the --usepkg option. The former tells emerge to download the prebuilt package from the previously defined server while the latter asks emerge to try to install the prebuilt package first before fetching the sources and compiling it.

For instance, to install gnumeric with prebuilt packages:

root #emerge --usepkg --getbinpkg gnumeric

More information about emerge's prebuilt package options can be found in the emerge man page:

user $man emerge

Distributing prebuilt packages to others

If prebuilt packages are to be distributed to others, then make sure that this is permitted. Check the distribution terms of the upstream package for this. For example, for a package released under the GNU GPL, sources must be made available along with the binaries.

Ebuilds may define a bindist restriction in their RESTRICT variable if built binaries are not distributable. Sometimes this restriction is conditional on one or more USE flags.

By default, Portage will not mask any packages because of restrictions. This can be changed globally by setting the ACCEPT_RESTRICT variable in /etc/portage/make.conf. For example, to mask packages that have a bindist restriction, add the following line to make.conf:

FILE /etc/portage/make.confOnly accept binary distributable packages
ACCEPT_RESTRICT="* -bindist"

It is also possible to override the ACCEPT_RESTRICT variable by passing the --accept-restrict option to the emerge command. For example, --accept-restrict=-bindist will temporarily mask packages with a bindist restriction.

Also consider setting the ACCEPT_LICENSE variable when distributing packages. See the Licenses section for this.

Important
It is entirely the responsibility of each user to comply with packages' license terms and with laws of each user's country. The metadata variables defined by ebuilds (RESTRICT or LICENSE) can provide guidance when distribution of binaries is not permitted, however output from Portage or questions answered by the Gentoo developers are not legal statements and should not be relied upon as such. Be cautious to abide by the law of your physical location.

Fetching files

Userfetch

Portage is normally run as the root user. Setting FEATURES="userfetch" will allow Portage to drop root privileges while fetching package sources and run with user/group permissions of portage:portage. This is a small security improvement.

If userfetch is set in FEATURES be sure to change the owner of all the files beneath using the chown command with root privileges:

root #chown --recursive --verbose portage:portage

Verify distfiles

To re-verify the integrity and (potentially) re-download previously removed/corrupted distfiles for all currently installed packages, run:

root #emerge --ask --fetchonly --emptytree @world




Runlevels

Booting the system

When the system is booted, lots of text floats by. When paying close attention, one will notice this text is (usually) the same every time the system is rebooted. The sequence of all these actions is called the boot sequence and is (more or less) statically defined.

First, the boot loader will load the kernel image that is defined in the boot loader configuration. Then, the boot loader instructs the CPU to execute kernel. When the kernel is loaded and run, it initializes all kernel-specific structures and tasks and starts the init process.

This process then makes sure that all filesystems (defined in /etc/fstab) are mounted and ready to be used. Then it executes several scripts located in /etc/init.d/, which will start the services needed in order to have a successfully booted system.

Finally, when all scripts are executed, init activates the terminals (in most cases just the virtual consoles which are hidden beneath Alt+F1, Alt+F2, etc.) attaching a special process called agetty to it. This process will then make sure users are able to log on through these terminals by running login.

Initscripts

Now init doesn't just execute the scripts in /etc/init.d/ randomly. Even more, it doesn't run all scripts in /etc/init.d/, only the scripts it is told to execute. It decides which scripts to execute by looking into /etc/runlevels/.

First, init runs all scripts from /etc/init.d/ that have symbolic links inside /etc/runlevels/boot/. Usually, it will start the scripts in alphabetical order, but some scripts have dependency information in them, telling the system that another script must be run before they can be started.

When all /etc/runlevels/boot/ referenced scripts are executed, init continues with running the scripts that have a symbolic link to them in /etc/runlevels/default/. Again, it will use the alphabetical order to decide what script to run first, unless a script has dependency information in it, in which case the order is changed to provide a valid start-up sequence. The latter is also the reason why commands used during the installation of Gentoo Linux used default, as in rc-update add sshd default.

How init works

Of course init doesn't decide all that by itself. It needs a configuration file that specifies what actions need to be taken. This configuration file is /etc/inittab.

Remember the boot sequence that was just described - init's first action is to mount all file systems. This is defined in the following line from /etc/inittab:

FILE /etc/inittabInitialization command
si::sysinit:/sbin/openrc sysinit

This line tells init that it must run /sbin/openrc sysinit to initialize the system. The /sbin/openrc script takes care of the initialization, so one might say that init doesn't do much - it delegates the task of initializing the system to another process.

Second, init executed all scripts that had symbolic links in /etc/runlevels/boot/. This is defined in the following line:

FILE /etc/inittabBoot command invocation
rc::bootwait:/sbin/openrc boot

Again the OpenRC script performs the necessary tasks. Note that the option given to OpenRC (boot) is the same as the sub-directory of /etc/runlevels/ that is used.

Now init checks its configuration file to see what runlevel it should run. To decide this, it reads the following line from /etc/inittab:

FILE /etc/inittabDefault runlevel selection
id:3:initdefault:

In this case (which the majority of Gentoo users will use), the runlevel id is 3. Using this information, init checks what it must run to start runlevel 3:

FILE /etc/inittabRunlevel definitions
l0:0:wait:/sbin/openrc shutdown
l1:S1:wait:/sbin/openrc single
l2:2:wait:/sbin/openrc nonetwork
l3:3:wait:/sbin/openrc default
l4:4:wait:/sbin/openrc default
l5:5:wait:/sbin/openrc default
l6:6:wait:/sbin/openrc reboot

The line that defines level 3, again, uses the openrc script to start the services (now with argument default). Again note that the argument of openrc is the same as the subdirectory from /etc/runlevels/.

When OpenRC has finished, init decides what virtual consoles it should activate and what commands need to be run at each console:

FILE /etc/inittabTerminal definitions
c1:12345:respawn:/sbin/agetty 38400 tty1 linux
c2:12345:respawn:/sbin/agetty 38400 tty2 linux
c3:12345:respawn:/sbin/agetty 38400 tty3 linux
c4:12345:respawn:/sbin/agetty 38400 tty4 linux
c5:12345:respawn:/sbin/agetty 38400 tty5 linux
c6:12345:respawn:/sbin/agetty 38400 tty6 linux

Available runlevels

In a previous section, we saw that init uses a numbering scheme to decide what runlevel it should activate. A runlevel is a state in which the system is running and contains a collection of scripts (runlevel scripts or initscripts) that must be executed when entering or leaving a runlevel.

In Gentoo, there are seven runlevels defined: three internal runlevels, and four user-defined runlevels. The internal runlevels are called sysinit, shutdown and reboot and do exactly what their names imply: initialize the system, powering off the system, and rebooting the system.

The user-defined runlevels are those with an accompanying /etc/runlevels/ subdirectory: boot, default, nonetwork and single. The boot runlevel starts all system-necessary services which all other runlevels use. The remaining three runlevels differ in what services they start: default is used for day-to-day operations, nonetwork is used in case no network connectivity is required, and single is used when the system needs to be fixed.

Working with initscripts

The scripts that the openrc process starts are called init scripts. Each script in /etc/init.d/ can be executed with the arguments start, stop, restart, zap, status, ineed, iuse, iwant, needsme, usesme, or wantsme.

To start, stop, or restart a service (and all depending services), the start, stop, and restart arguments should be used:

root #rc-service postfix start
Note
Only the services that need the given service are stopped or restarted. The other depending services (those that use the service but don't need it) are left untouched.

To stop a service, but not the services that depend on it, use the --nodeps option together with the stop argument:

root #rc-service --nodeps postfix stop

To see what status a service has (started, stopped, ...) use the status argument:

root #rc-service postfix status

If the status information shows that the service is running, but in reality it is not, then reset the status information to "stopped" with the zap argument:

root #rc-service postfix zap

To also ask what dependencies the service has, use iwant, iuse or ineed. With ineed it is possible to see the services that are really necessary for the correct functioning of the service. iwant or iuse, on the other hand, shows the services that can be used by the service, but are not necessary for the correct functioning.

root #rc-service postfix ineed

Similarly, it is possible to ask what services require the service (needsme) or can use it (usesme or wantsme):

root #rc-service postfix needsme

Updating runlevels

rc-update

Gentoo's init system uses a dependency-tree to decide what service needs to be started first. As this is a tedious task that we wouldn't want our users to have to do manually, we have created tools that ease the administration of the runlevels and init scripts.

With rc-update it is possible to add and remove init scripts to a runlevel. The rc-update tool will then automatically ask the depscan.sh script to rebuild the dependency tree.

Adding and removing services

In earlier instructions, init scripts have already been added to the "default" runlevel. What "default" means has been explained earlier in this document. Next to the runlevel, the rc-update script requires a second argument that defines the action: add, del, or show.

To add or remove an init script, just give rc-update the add or del argument, followed by the init script and the runlevel. For instance:

root #rc-update del postfix default

The rc-update -v show command will show all the available init scripts and list at which runlevels they will execute:

root #rc-update -v show

It is also possible to run rc-update show (without -v) to just view enabled init scripts and their runlevels.

Configuring services

Why additional configuration is needed

Init scripts can be quite complex. It is therefore not really desirable to have the users edit the init script directly, as it would make it more error-prone. It is however important to be able to configure such a service. For instance, users might want to give more options to the service itself.

A second reason to have this configuration outside the init script is to be able to update the init scripts without the fear that the user's configuration changes will be undone.

conf.d directory

Gentoo provides an easy way to configure such a service: every init script that can be configured has a file in /etc/conf.d/. For instance, the apache2 initscript (called /etc/init.d/apache2) has a configuration file called /etc/conf.d/apache2, which can contain the options to give to the Apache 2 server when it is started:

FILE /etc/conf.d/apache2Example options for apache2 init script
APACHE2_OPTS="-D PHP5"

Such a configuration file contains only variables (just like /etc/portage/make.conf does), making it very easy to configure services. It also allows us to provide more information about the variables (as comments).

Writing initscripts

Another useful resource is OpenRC's service script guide.

Is it necessary?

No, writing an init script is usually not necessary as Gentoo provides ready-to-use init scripts for all provided services. However, some users might have installed a service without using Portage, in which case they will most likely have to create an init script.

Do not use the init script provided by the service if it isn't explicitly written for Gentoo: Gentoo's init scripts are not compatible with the init scripts used by other distributions! That is, unless the other distribution is using OpenRC!

Layout

The basic layout of an init script is shown below.

CODE Example initscript layout (traditional)
#!/sbin/openrc-run
  
depend() {
#  (Dependency information)
}
  
start() {
#  (Commands necessary to start the service)
}
  
stop() {
#  (Commands necessary to stop the service)
}
CODE Example initscript layout (updated)
#!/sbin/openrc-run
command=/usr/bin/foo
command_args="${foo_args} --bar"
pidfile=/var/run/foo.pid
name="FooBar Daemon"
 
description="FooBar is a daemon that drinks"
extra_started_commands="drink"
description_drink="Opens mouth and reflexively swallows"
 
depend() {
#  (Dependency information)
}
 
start_pre() {
#  (Commands necessary to prepare to start the service)
    # Ensure that our dirs are correct
    checkpath --directory --owner foo:foo --mode 0775 \
        /var/run/foo /var/cache/foo
}
  
stop_post() {
#  (Commands necessary to clean up after the service)
    # Clean any spills
    rm -rf /var/cache/foo/*
}
 
drink() {
    ebegin "Starting to drink"
    ${command} --drink beer
    eend $? "Failed to drink any beer :("
}

Every init script requires the start() function or command variable to be defined. All other sections are optional.

Dependencies

There are three dependency-alike settings that can be defined which influence the start-up or sequencing of init scripts: want, use and need. Next to these, there are also two order-influencing methods called before and after. These last two are no dependencies per se - they do not make the original init script fail if the selected one isn't scheduled to start (or fails to start).

  • The use settings informs the init system that this script uses functionality offered by the selected script, but does not directly depend on it. A good example would be use logger or use dns. If those services are available, they will be put in good use, but if the system does not have a logger or DNS server the services will still work. If the services exist, then they are started before the script that uses them.
  • The want setting is similar to use with one exception. use only considers services which were added to an init level. want will try to start any available service even if not added to an init level.
  • The need setting is a hard dependency. It means that the script that is needing another script will not start before the other script is launched successfully. Also, if that other script is restarted, then this one will be restarted as well.
  • When using before, then the given script is launched before the selected one if the selected one is part of the init level. So an init script xdm that defines before alsasound will start before the alsasound script, but only if alsasound is scheduled to start as well in the same init level. If alsasound is not scheduled to start too, then this particular setting has no effect and xdm will be started when the init system deems it most appropriate.
  • Similarly, after informs the init system that the given script should be launched after the selected one if the selected one is part of the init level. If not, then the setting has no effect and the script will be launched by the init system when it deems it most appropriate.

It should be clear from the above that need is the only "true" dependency setting as it affects if the script will be started or not. All the others are merely pointers towards the init system to clarify in which order scripts can be (or should be) launched.

Now, look at many of Gentoo's available init scripts and notice that some have dependencies on things that are no init scripts. These "things" we call virtuals.

A virtual dependency is a dependency that a service provides, but that is not provided solely by that service. An init script can depend on a system logger, but there are many system loggers available (metalogd, syslog-ng, sysklogd, ...). As the script cannot need every single one of them (no sensible system has all these system loggers installed and running) we made sure that all these services provide a virtual dependency.

For instance, take a look at the postfix dependency information:

FILE /etc/init.d/postfixDependency information of the postfix service
depend() {
  need net
  use logger dns
  provide mta
}

As can be seen, the postfix service:

  • Requires the (virtual) net dependency (which is provided by, for instance, /etc/init.d/net.eth0).
  • Uses the (virtual) logger dependency (which is provided by, for instance, /etc/init.d/syslog-ng).
  • Uses the (virtual) dns dependency (which is provided by, for instance, /etc/init.d/named).
  • Provides the (virtual) mta dependency (which is common for all mail servers).

Controlling the order

As described in the previous section, it is possible to tell the init system what order it should use for starting (or stopping) scripts. This ordering is handled both through the dependency settings use and need, but also through the order settings before and after. As we have described these earlier already, let's take a look at the portmap service as an example of such init script.

FILE /etc/init.d/portmapDependency information of the portmap service
depend() {
  need net
  before inetd
  before xinetd
}

It is possible to use the "*" glob to catch all services in the same runlevel, although this isn't advisable.

CODE Using the * glob
depend() {
  before *
}

If the service must write to local disks, it should need localmount. If it places anything in /var/run/ such as a PID file, then it should start after bootmisc:

CODE Dependency setting with needing localmount and after bootmisc
depend() {
  need localmount
  after bootmisc
}

Standard functions

Next to the depend() functionality, it is also necessary to define the start() function. This one contains all the commands necessary to initialize the service. It is advisable to use the ebegin and eend functions to inform the user about what is happening:

CODE Example start() function
start() {
  if [ "${RC_CMD}" = "restart" ];
  then
    # Do something in case a restart requires more than stop, start
  fi
  
  ebegin "Starting my_service"
  start-stop-daemon --start --exec /path/to/my_service \
    --pidfile /path/to/my_pidfile
  eend $?
}

Both --exec and --pidfile should be used in start and stop functions. If the service does not create a pidfile, then use --make-pidfile if possible, though it is recommended to test this to be sure. Otherwise, don't use pidfiles. It is also possible to add --quiet to the start-stop-daemon options, but this is not recommended unless the service is extremely verbose. Using --quiet may hinder debugging if the service fails to start.

Another notable setting used in the above example is to check the contents of the RC_CMD variable. Unlike the previous init script system, the newer OpenRC system does not support script-specific restart functionality. Instead, the script needs to check the contents of the RC_CMD variable to see if a function (be it start() or stop()) is called as part of a restart or not.

Note
Make sure that --exec actually calls a service and not just a shell script that launches services and exits - that's what the init script is supposed to do.

For more examples of the start() function, please read the source code of the available init scripts in the /etc/init.d/ directory.

Another function that can (but does not have to) be defined is stop(). The init system is intelligent enough to fill in this function by itself if start-stop-daemon is used.

CODE Example stop() function
stop() {
  ebegin "Stopping my_service"
  start-stop-daemon --stop --exec /path/to/my_service \
    --pidfile /path/to/my_pidfile
  eend $?
}

If the service runs some other script (for example, Bash, Python, or Perl), and this script later changes names (for example, foo.py to foo), then it is necessary to add --name to start-stop-daemon. This must specify the name that the script will be changed to. In this example, a service starts foo.py, which changes names to foo:

CODE Example definition for a service that starts the foo script
start() {
  ebegin "Starting my_script"
  start-stop-daemon --start --exec /path/to/my_script \
    --pidfile /path/to/my_pidfile --name foo
  eend $?
}

start-stop-daemon has an excellent man page available if more information is needed:

user $man start-stop-daemon

Gentoo's init script syntax is based on the POSIX Shell so people are free to use sh-compatible constructs inside their init scripts. Keep other constructs, like bash-specific ones, out of the init scripts to ensure that the scripts remain functional regardless of the change Gentoo might do on its init system.

Adding custom options

If the initscript needs to support more options than the ones we have already encountered, then add the option to one of the following variables, and create a function with the same name as the option. For instance, to support an option called restartdelay:

  • extra_commands - Command is available with the service in any state
  • extra_started_commands - Command is available when the service is started
  • extra_stopped_commands - Command is available when the service is stopped


CODE Example definition of restartdelay method
extra_started_commands="restartdelay"
  
restartdelay() {
  stop
  sleep 3    # Wait 3 seconds before starting again
  start
}
Important
The restart() function cannot be overridden in OpenRC!

Service configuration variables

In order to support configuration files in /etc/conf.d/, no specifics need to be implemented: when the init script is executed, the following files are automatically sourced (i.e. the variables are available to use):

  • /etc/conf.d/YOUR_INIT_SCRIPT
  • /etc/conf.d/basic
  • /etc/rc.conf

Also, if the init script provides a virtual dependency (such as net), the file associated with that dependency (such as /etc/conf.d/net) will be sourced too.

Changing runlevel behavior

Who might benefit

Many laptop users know the situation: at home they need to start net.eth0, but they don't want to start net.eth0 while on the road (as there is no network available). With Gentoo the runlevel behavior can be altered at will.

For instance, a second "default" runlevel can be created which can be booted that has other init scripts assigned to it. At boot time, the user can then select what default runlevel to use.

Using softlevel

First of all, create the runlevel directory for the second "default" runlevel. As an example we create the offline runlevel:

root #mkdir /etc/runlevels/offline

Add the necessary init scripts to the newly created runlevel. For instance, to have an exact copy of the current default runlevel but without net.eth0:

root #cd /etc/runlevels/default
root #for service in *; do rc-update add $service offline; done
root #rc-update del net.eth0 offline
root #rc-update show offline
(Partial sample Output)
               acpid | offline
          domainname | offline
               local | offline
            net.eth0 |

Even though net.eth0 has been removed from the offline runlevel, udev might want to attempt to start any devices it detects and launch the appropriate services, a functionality that is called hotplugging. By default, Gentoo does not enable hotplugging.

To enable hotplugging, but only for a selected set of scripts, use the rc_hotplug variable in /etc/rc.conf:

FILE /etc/rc.confEnable hotplugging of the WLAN interface
rc_hotplug="net.wlan !net.*"
Note
For more information on device initiated services, please see the comments inside /etc/rc.conf.

Edit the bootloader configuration and add a new entry for the offline runlevel. In that entry, add softlevel=offline as a boot parameter.

Using bootlevel

Using bootlevel is completely analogous to softlevel. The only difference here is that a second "boot" runlevel is defined instead of a second "default" runlevel.




Environment variables

Introduction

An environment variable is a named object that contains information used by one or more applications. By using environment variables one can easily change a configuration setting for one or more applications.

Important examples

The following table lists a number of variables used by a Linux system and describes their use. Example values are presented after the table.

Variable Description
PATH This variable contains a colon-separated list of directories in which the system looks for executable files. If a name is entered of an executable (such as ls, rc-update, or emerge) but this executable is not located in a listed directory, then the system will not execute it (unless the full path is entered as the command, such as /bin/ls).
ROOTPATH This variable has the same function as PATH, but this one only lists the directories that should be checked when the root-user enters a command.
LDPATH This variable contains a colon-separated list of directories in which the dynamical linker searches through to find a library.
MANPATH This variable contains a colon-separated list of directories in which the man command searches for the man pages.
INFODIR This variable contains a colon-separated list of directories in which the info command searches for the info pages.
PAGER This variable contains the path to the program used to list the contents of files through (such as less or more).
EDITOR This variable contains the path to the program used to change the contents of files with (such as nano or vi).
KDEDIRS This variable contains a colon-separated list of directories which contain KDE-specific material.
CONFIG_PROTECT This variable contains a space-delimited list of directories which should be protected by Portage during package updates.
CONFIG_PROTECT_MASK This variable contains a space-delimited list of directories which should not be protected by Portage during package updates.

Below is an example definition of all these variables:

CODE Example settings for the mentioned variables
PATH="/bin:/usr/bin:/usr/local/bin:/opt/bin:/usr/games/bin"
ROOTPATH="/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin"
LDPATH="/lib:/usr/lib:/usr/local/lib:/usr/lib/gcc-lib/i686-pc-linux-gnu/3.2.3"
MANPATH="/usr/share/man:/usr/local/share/man"
INFODIR="/usr/share/info:/usr/local/share/info"
PAGER="/usr/bin/less"
EDITOR="/usr/bin/vim"
KDEDIRS="/usr"
# Directories that are protected during package updates.
# Note the use of the \ (backslashes) on the end of the following lines which interprets to a single space-delimited line.
CONFIG_PROTECT="/usr/X11R6/lib/X11/xkb /opt/tomcat/conf \
                /usr/kde/3.1/share/config /usr/share/texmf/tex/generic/config/ \
                /usr/share/texmf/tex/platex/config/ /usr/share/config"
# Directories that are _not_ protected during package updates.
CONFIG_PROTECT_MASK="/etc/gconf"

Defining variables globally

The env.d directory

To centralize the definitions of these variables, Gentoo introduced the /etc/env.d/ directory. Inside this directory a number of files are available, such as 50baselayout, gcc/config-x86_64-pc-linux-gnu, etc. which contain the variables needed by the application mentioned in their name.

For instance, when gcc is installed, a file called gcc/config-x86_64-pc-linux-gnu was created by the ebuild which contains the definitions of the following variables:

FILE /etc/env.d/gcc/config-x86_64-pc-linux-gnuDefault gcc enabled environment variables for GCC 13
GCC_PATH="/usr/x86_64-pc-linux-gnu/gcc-bin/13"
LDPATH="/usr/lib/gcc/x86_64-pc-linux-gnu/13:/usr/lib/gcc/x86_64-pc-linux-gnu/13/32"
MANPATH="/usr/share/gcc-data/x86_64-pc-linux-gnu/13/man"
INFOPATH="/usr/share/gcc-data/x86_64-pc-linux-gnu/13/info"
STDCXX_INCDIR="g++-v13"
CTARGET="x86_64-pc-linux-gnu"
GCC_SPECS=""
MULTIOSDIRS="../lib64:../lib"

Other distributions might tell the system administrator to change or add such environment variable definitions in /etc/profile or other locations. Gentoo on the other hand makes it easy for the sysadmins (and for Portage) to maintain and manage the environment variables without having to pay attention to the numerous files that can contain environment variables.

For instance, when gcc is updated, the associated file(s) under /etc/env.d/gcc are updated too without requesting any administrative interaction.

There is still the occasionally where a system administrator is asked to set a certain environment variable system-wide. As an example, take the http_proxy variable. Instead of editing a file under the /etc/profile directory, create a file named /etc/env.d/99local and enter the definition in it:

FILE /etc/env.d/99localSetting a global environment variable
http_proxy="proxy.server.com:8080"

By using the same file for all customized environment variables, system administrators have a quick overview on the variables they have defined themselves.

env-update

Several files within the /etc/env.d directory add definitions to the PATH variable. This is not a mistake: when the env-update command is executed, it will append the several definitions before it atomically updates each environment variable, thereby making it easy for packages (or system administrators) to add their own environment variable settings without interfering with the already existing values.

The env-update script will append the values in the alphabetical order of the /etc/env.d/ files. The file names must begin with two decimal digits.

CODE Update order used by env-update
09sandbox    50baselayout     51dconf
     +------------+----------------+-----------+
CONFIG_PROTECT_MASK="/etc/sandbox.d /etc/gentoo-release /etc/dconf ..."

The concatenation of variables does not always happen, only with the following variables: ADA_INCLUDE_PATH, ADA_OBJECTS_PATH, CLASSPATH, KDEDIRS, PATH, LDPATH, MANPATH, INFODIR, INFOPATH, ROOTPATH, CONFIG_PROTECT, CONFIG_PROTECT_MASK, PRELINK_PATH, PRELINK_PATH_MASK, PKG_CONFIG_PATH, and PYTHONPATH. For all other variables the latest defined value (in alphabetical order of the files in /etc/env.d/) is used.

It is possible to add more variables into this list of concatenate-variables by adding the variable name to either COLON_SEPARATED or SPACE_SEPARATED variables (also inside an /etc/env.d/ file).

When executing env-update, the script will create all environment variables and place them in /etc/profile.env (which is used by /etc/profile). It will also extract the information from the LDPATH variable and use that to create /etc/ld.so.conf. After this, it will run ldconfig to recreate the /etc/ld.so.cache file used by the dynamical linker.

To notice the effect of env-update immediately after running it, execute the following command to update the environment. Users who have installed Gentoo themselves will probably remember this from the installation instructions:

root #env-update && source /etc/profile
Note
The above command only updates the variables in the current terminal, new consoles, and their children. Thus, if the user is working in X11, he needs to either type source /etc/profile in every new terminal opened or restart X so that all new terminals source the new variables. If a login manager is used, it is necessary to become root and restart the /etc/init.d/xdm service.
Important
It is not possible to use shell variables when defining other variables. This means things like FOO="$BAR" (where $BAR is another variable) are forbidden.

Defining variables locally

User specific

It might not be necessary to define an environment variable globally. For instance, one might want to add /home/my_user/bin and the current working directory (the directory the user is in) to the PATH variable but do not want all other users on the system to have that in their PATH too. To define an environment variable locally, use ~/.bashrc or ~/.bash_profile:

FILE ~/.bashrcExtending PATH for local usage
# A colon followed by no directory is treated as the current working directory
PATH="${PATH}:/home/my_user/bin:"

After logout/login, the PATH variable will be updated.

Session specific

Sometimes even stricter definitions are requested. For instance, a user might want to be able to use binaries from a temporary directory created without using the path to the binaries themselves or editing ~/.bashrc for the short time necessary.

In this case, just define the PATH variable in the current session by using the export command. As long as the user does not log out, the PATH variable will be using the temporary settings.

root #export PATH="${PATH}:/home/my_user/tmp/usr/bin"