Gentoo Linux alpha Manual: Trabalhando com o Gentoo

From Gentoo Wiki
Jump to: navigation, search
This page is a translated version of the page Handbook:Alpha/Full/Working and the translation is 100% complete.

Contents

Other languages:
Deutsch • ‎English • ‎español • ‎français • ‎polski • ‎português do Brasil • ‎русский • ‎українська • ‎中文(中国大陆)‎ • ‎日本語 • ‎한국어
Alpha Handbook
Installation
About the installation
Choosing the media
Configuring the network
Preparing the disks
Installing stage3
Installing base system
Configuring the kernel
Configuring the system
Installing tools
Configuring the bootloader
Finalizing
Working with Gentoo
Portage introduction
USE flags
Portage features
Initscript system
Environment variables
Working with Portage
Files and directories
Variables
Mixing software branches
Additional tools
Custom package repository
Advanced features
Network configuration
Getting started
Advanced configuration
Modular networking
Wireless
Adding functionality
Dynamic management


Bem Vindo ao Portage

O Portage é uma das mais notáveis inovações do Gentoo em gerenciamento de software. Com sua grande flexibilidade e enorme quantidade de recursos ele é visto frequentemente como a melhor ferramenta de gerenciamento de software disponível para Linux.

O Portage é inteiramente escrito em Python e Bash e assim é totalmente transparente aos usuários uma vez que ambas são linguagens de scripts.

A maioria dos usuários irá trabalhar com o Portage através da ferramenta emerge. Este capítulo não foi feito para duplicar as informações disponíveis na página de manual do emerge. Para uma lista completa das opções do emerge, por favor consulte a página do manual:

user $man emerge

Repositório Gentoo

Ebuilds

Quando a documentação do Gentoo falar sobre pacotes, isso significa títulos de software disponíveis aos usuários Gentoo através do repositório Gentoo. Esse repositório é uma coleção de ebuilds, arquivos que contém toda a informação que o Portage necessita para manter o software (instalar, procurar etc). Essas ebuilds residem em /var/db/repos/gentoo como padrão.

Quando alguém solicita ao Portage executar alguma ação em relação ao títulos de software, ele irá usar as ebuilds no sistema como base. É muito importante atualizar regularmente as ebuilds no sistema para que o Portage saiba sobre novo software, atualizações de segurança etc.

Atualizando o repositório Gentoo

O repositório Gentoo é normalmente atualizado com o rsync, um utilitário rápido de transferência incremental de arquivos. Atualizar é bastante simples já que o comando emerge provê um front-end para o rsync:

root #emerge --sync

Algumas vezes restrições de firewall impedem o rsync de contatar os espelhos. Neste caso, atualize o repositório Gentoo através de snapshots gerados diariamente. A ferramenta emerge-webrsync automaticamente baixa e instala o último snapshot no sistema:

root #emerge-webrsync

Uma vantagem adicional de usar emerge-webrsync é que ele permite ao administrador subir no repósitório Gentoo somente snapshots assinados com a chave GPG da engenharia de lançamentos do Gentoo. Mais informações sobre isso podem se encontradas na seção de recursos do Portage em baixando snapshots validados do repositório Gentoo.

Mantendo software

Procurando por software

Há varias maneiras de se procurar software no repositório Gentoo. Uma delas e através do próprio emerge. Como padrão, emerge --search retorna os nomes do pacotes que os títulos correspondem (completa ou parcialmente) ao termo procurado.

Por exemplo, para procurar por todos os pacotes que têm "pdf" em seus nomes:

user $emerge --search pdf

Para pesquisar através das descrições também, use a opção --searchdesc (ou -S):

user $emerge --searchdesc pdf

Note que a saída retorna muita informação. Os campos são claramente descritos de modo que não iremos detalhar seus significados:

CODE Exemplo de saída para o comando search
*  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

Instalando software

Quando um título de software é encontrado, então a instalação necessita de apenas um comando emerge. Por exemplo, para instalar o gnumeric:

root #emerge --ask app-office/gnumeric

Uma vez que muitas aplicações dependem umas das outras, uma tentativa de instalar um certo pacote pode resultar na instalação de varias dependências também. Não se preocupe, o Portage cuida das dependências também. Para saber o que o Portage irá instalar, adicione a opção --pretend. Por exemplo:

root #emerge --pretend gnumeric

Durante a instalação do pacote, o Portage irá baixar o código-fonte necessário da Internet (se necessário) e armazená-lo por default em /var/cache/distfiles/. Em seguida ele irá descompactar, compilar e instalar o pacote. Para dizer ao Portage para somente baixar os fontes sem instalá-los, adicione a opção --fetchonly ao comando emerge:

root #emerge --fetchonly gnumeric

Achando a documentação de um pacote instalado

Muitos pacotes vem com sua própria documentação. Algumas vezes, a USE flag doc determina se a documentação do pacote deve ser instalada ou não. Para ver se a USE flag doc é usada por um pacote, use emerge -vp category/package:

root #emerge -vp media-libs/alsa-lib
These are the packages that would be merged, in order:
[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

A melhor maneira de habilitar a USE flag doc é fazendo para cada pacotes via /etc/portage/package.use, de modo que somente a documentação dos pacotes desejados é instalada. Para mais informação, por favor leia o seção USE flags.

Uma vez que o pacote esteja instalado, sua documentação é geralmente encontrada no subdiretório com o nome do pacote no diretório /usr/share/doc/:

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

Uma forma mais confiável de listar os arquivos de documentação instalados é usar a opção --filter do equery. O equery é usado para consultar o banco de dados do Portage e faz parte do pacote 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

A opção --filter pode ser usada com outras regras para ver o local de instalação de muitos outros tipos de arquivos. Funcionalidades adicionais podem consultadas na página de manual do equery: man 1 equery.

Removendo software

Para remover software de um sistema, use emerge --unmerge. Isto irá dizer ao Portage para remover todos os arquivos instalados por este pacote do sistema. Uma exceção são os arquivos de configuração desta aplicação se eles foram alterados pelo usuário. Deixar os arquivos de configuração permite aos usuários continuar trabalhando com o pacote sem a necessidade de reconfiguração se os pacotes forem reinstalados mais tarde.

Aviso
O Portage não irá checar se o pacote a ser removido e requerido por outro pacote. Ele irá contudo avisar quando um pacote importante se removido pode quebrar o sistema.
root #emerge --unmerge gnumeric

Quando um pacote é removido do sistema, as dependências deste pacote que foram instaladas automaticamente são deixadas no sistemas. Para que o Portage localize todas as dependências que podem agora ser removidas, use a funcionalidade do emerge code>--depclean</code>, que será explicada mais tarde.

Atualizando o sistema

Para manter o sistema em perfeito estado (e sem mencionar com as últimas atualizações de segurança) é necessário atualizar o sistema regularmente. Uma vez que o Portage somente checa as ebuilds no repositório Gentoo, a primeira coisa a fazer é atualizar esse repositório. Quando o repositório Gentoo é atualizado, o sistema pode ser atualizado usando emerge --update @world. No próximo exemplo, a opção --ask é usada também para que o Portage mostre a lista de pacotes que serão atualizados e espere uma confirmação:

root #emerge --update --ask @world

O Portage irá então procurar por novas versões dos aplicativos que estão instalados. Contudo, ele irá somente verificar as versões dos aplicativos que estão explicitamente instaladas (as aplicações listadas em /var/lib/portage/world) - ele não irá checar suas dependências. Para atualizar as dependências destes pacotes também, adicione a opção --deep:

root #emerge --update --deep @world

Ainda assim, isto não inclui todos os pacotes: alguns pacotes no sistema são necessários apenas durante o processo de compilação. O Portage chama este pacotes build dependencies. Para incluir estes pacotes em um ciclo de atualização adicione --with-bdeps=y:

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

Uma vez que atualizações de segurança acontecem em pacotes que não estão explicitamente instalados no sistema (mas que são dependências de outros programas), é recomendado executar este comando de vez em quando.

Se as configurações USE do sistemas foram alteradas, é recomendado adicionar --newuse também. O Portage irá verificar se a alteração requer a instalação de novos pacotes ou a recompilação dos existentes:

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

Metapacotes

Alguns pacotes no repositório do Gentoo não tem nenhum conteúdo real mas são usados para instalar uma coleção de pacotes. Por exemplo, o pacote kde-plasma/plasma-meta irá instalar o desktop KDE Plasma completo no sistema baixando os vários pacotes relacionados ao Plasma e sua dependências.

Para remover esse pacote de seu sistema, executar emerge --unmerge no pacote não tem muito efeito já que suas dependências ficarão no sistema.

O Portage tem a funcionalidade de remover também dependências órfãs, mas uma vez a disponibilidade de software é dinamicamente dependente, é importante primeiro atualizar completamente o sistema, incluindo as novas alterações nas USE flags. Feito isso pode-se executar emerge --depclean para remover as dependências órfãs. Quando concluído, pode ser necessário recompilar as aplicações que foram linkadas dinamicamente aos agora removidos softwares mas não os requerem mais, suporte recente para isto foi adicionado ao Portage.

Tudo isso é feito com os três seguintes comandos:

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

revdep-rebuild é fornecido pelo pacote app-portage/gentoolkit; não esqueça de emerge:

root #emerge --ask app-portage/gentoolkit

Licenças

A partir do Portage versão 2.1.7, é possível aceitar ou rejeitar a instalação de software baseado em sua licença. Todos os pacotes na árvore contém uma LICENSE em suas ebuilds. Executando emerge --search package/category irá mostrar a licença do pacote.

Importante
A variável LICENSE em uma ebuild é apenas uma indicação para os desenvolvedores e usuários do Gentoo. Ela não tem valor legal e não há garantias de que reflita a realidade. Desse modo, não confie cegamente nela, mas cheque o pacote em si cuidadosamente, incluindo todos os arquivos que usar.

Como padrão, o Portage permite as licenças que são explicitamente aprovadas pela Free Software Foundation, pela Open Source Initiative, ou que seguem a Free Software Definition.

A variável que controla as licenças permitidas é chamada ACCEPT_LICENSE, que pode ser configurada no arquivo /etc/portage/make.conf. No próximo exemplo, seu valor padrão é mostrado:

FILE /etc/portage/make.confA configuração ACCEPT_LICENSE padrão
ACCEPT_LICENSE="-* @FREE"

Com esta configuração, os pacotes de software ou documentação com uma licença livre serão instaláveis. Softwares não livres não serão instaláveis.

É possível configurar ACCEPT_LICENSE globalmente no /etc/portage/make.conf, ou especificá-la por pacote no arquivo /etc/portage/package.license.

Por exemplo, para permitir a licença google-chrome para o pacote www-client/google-chrome, adicione o seguinte em /etc/portage/package.license:

FILE /etc/portage/package.licenseAceitando a licença google-chrome para o pacote google-chrome
www-client/google-chrome google-chrome

Isto permite a instalação do pacote www-client/google-chrome, mas proíbe a instalação do pacote www-plugins/chrome-binary-plugins, mesmo que eles tenham a mesma licença.

Importante
Licenças são guardadas no diretório /var/db/repos/gentoo/licenses/, e grupos de licenças são mantidas no arquivo /var/db/repos/gentoo/profiles/license_groups. A primeira entrada de cada linha em MAIÚSCULAS é o nome do grupo de licenças, e cada entrada depois dessa é uma licença individual.

Grupos de licença definidos na variável ACCEPT_LICENSE são prefixadas com um sinal @. Uma configuração possível (que era o default antigo do Portage) é permitir todas as licenças, exceto End User License Agreements (EULAs) que requerem a leitura e aceitação de um termo de aceitação. Para conseguir isso, aceite todas as licenças (usando *) e então remova as licenças do grupo EULA, como abaixo:

FILE /etc/portage/make.confAceite todas as licenças exceto EULAs
ACCEPT_LICENSE="* -@EULA"

Note que essa configuração irá aceitar também software e documentação não livres.

Quando o Portage reclamar

Terminologia

Como dito antes, o Portage é extremamente poderoso e suporta muitas funções que outros gerenciadores de software não tem. Para entender isto, explicaremos uns poucos aspectos do Portage sem entrar em muitos detalhes.

Com o Portage diferentes versões de um mesmo pacote podem coexistir em um sistema. Enquanto outras distribuições tendem a dar nomes em seus pacotes para essas versões (como freetype e freetype2) o Portage usa uma terminologia chamada "SLOT". Um ebuild declara um certo SLOT para sua versão. Ebuilds com diferentes SLOTs podem coexistir em um mesmo sistema. Por exemplo, o pacote freetype tem ebuilds com SLOT="1" e SLOT="2".

Há também pacotes que proveem a mesma funcionalidade mas são implementados de forma diferente. Por exemplo, metalogd, sysklogd, e syslog-ng são todos sistemas de log. Aplicações que para sua disponibilidade precisam de um "sistema de log" não podem depender, por exemplo, do metalogd, se há outras opções de sistemas de log. O Portage permite virtuais: cada sistema de log é listado com uma "exclusiva" dependência de um serviço de log em um pacote virtual de uma categoria virtual, então estas aplicação pode depender do pacote virtual/logger. Quando instalado, o pacote irá baixar o primeiro pacote de log mencionado neste pacote, a não ser que um pacote de log já esteja instalado (neste caso a virtual já foi satisfeita).

Software no repositório Gentoo pode residir em diferentes ramos. Como padrão o sistema somente aceita pacotes que o Gentoo considera estáveis. Muitos títulos de software novos, quando enviados, são adicionados ao ramo de teste, significando que mais testes são necessários antes que ele seja marcado como estável. Mesmo que os ebuilds deste software esteja no repositório Gentoo, o Portage não irá atualizá-los se eles não forem colocados no ramo estável.

Alguns softwares estão disponíveis somente para umas poucas arquiteturas, ou precisam de mais testes, ou o desenvolvedor que enviou o software para o repositório Gentoo não conseguiu verificar se o pacote trabalha em uma arquitetura diferente.

Cada instalação do Gentoo adere a um certo perfil que contém, além de outras informações, a lista de pacotes que são requeridos para o sistema funcionar normalmente.

Pacotes bloqueados

CODE Portage avisando sobre pacotes bloqueados (com --pretend)
[blocks B     ] mail-mta/ssmtp (is blocking mail-mta/postfix-2.2.2-r1)
CODE Portage avisando sobre pacotes bloqueados (sem --pretend)
!!! Error: the mail-mta/postfix package conflicts with another package.
!!!        both can't be installed on the same system together.
!!!        Please use 'emerge --pretend' to determine blockers.

Ebuilds contem campos específicos que informam ao Portage sobre suas dependências. Há duas dependências possíveis: dependências de build, declaradas na variável DEPEND e dependências de execução, declaradas em RDEPEND. Quando uma dessas dependências indica explicitamente que um pacotes ou virtual não e compatível, um bloqueio é disparado.

Enquanto versões recentes do Portage são inteligentes o bastante para resolver bloqueios menores sem intervenção do usuário, ocasionalmente alguns bloqueios precisam ser resolvidos manualmente.

Para corrigir um bloqueio, usuários podem escolher não instalar o pacote ou fazer unmerge do pacore conflitante primeiro. Neste exemplo, podemos optar por não instalar o postfix ou remover o ssmtp primeiro.

Algumas vezes há também pacotes bloqueados com versões específicas, como <media-video/mplayer-1.0_rc1-r2. Neste caso, atualizar para uma versão mais recente do pacote pode remover o bloqueio.

É possível também que dois pacotes que estão para ser instalados bloqueiem um ao outro. Nesses casos raros, tente achar porque ambos precisam ser instalados. Na maioria dos casos apenas um deles é suficiente. Se não, por favor crie um bug no sistema de acompanhamento de bugs do Gentoo.

Pacotes mascarados

CODE Portage avisando sobre pacotes mascarados
!!! all ebuilds that could satisfy "bootsplash" have been masked.
CODE Portage avisando sobre pacotes mascarados - razão
!!! 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))

Quando tentar instalar um pacote que não está disponível para o sistema, este erro de mascaramento ocorre. Usuários devem tentar instalar uma aplicação diferente que esteja disponível para o sistema ou esperar até o pacote ser marcado como disponível. Há sempre uma razão porque o pacote é mascarado:

Razões para mascaramento Descrição
palavra chave ~arch A aplicação não foi testada o suficiente para ser colocada no ramo estável. Espere uns dias ou semanas e tente novamente.
palavra chave -arch ou -* A aplicação não funciona em sua arquitetura. Se você acredita que o pacote funciona coloque um bug em nosso site Bugzilla.
palavra chave missing A aplicação não foi testada em sua arquitetura ainda. Pergunte ao time de arquitetura se eles podem testar o pacote ou teste para eles e faça um relatório em nosso site Bugzilla.
package.mask O pacote está corrompido, instável ou pior, foi deliberadamente marcado como inútil.
profile O pacote encontrado não é adequado ao perfil atual. A aplicação pode quebrar o sistema se instalada ou não é compatível com o perfil atualmente usado.
license A licença do pacote não é compatível com o valor ACCEPT_LICENSE. Habilite esta licença ou seu grupo configurando em /etc/portage/make.conf ou em /etc/portage/package.license

Mudanças necessárias nas USE flags

CODE Portage avisando sobre a necessidade de alteração na USE flag
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

A mensagem de erro pode também ser mostrada como segue, se --autounmask não estiver habilitado:

CODE Erro do Portage sobre a necessidade de alteração na USE flag
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])

Este aviso ou erro ocorre quando um pacote é requerido para instalação ao qual não depende de outro pacote, mas este pacote requer um USE flag em particular para compilação (o conjunto de USE flags). No exemplo dado, o pacote app-text/feelings precisa ser compilado com USE="test", mas esta USE flags não está habilitada no sistema.

Para resolver isso, adicione a USE flag requerida para as USE flags globais em /etc/portage/make.conf, ou habilite para um pacote específico em /etc/portage/package.use.

Dependências faltantes

CODE Portage avisando sobre dependências faltantes
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.

A aplicação a ser instalada depende de outro pacote que não está disponível para o sistema. Por favor cheque no Bugzilla se o problema é conhecido e se não, por favor faça um relatório. A não se que o sistema esteja configurado para mais de um ramo isto não deve ocorrer e provavelmente é um bug.

Nome do ebuild ambíguo

CODE O Portage avisando sobre nomes de ebuild ambíguos
[ 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.

A aplicação selecionada para instalação tem seu nome que corresponde a mais de um pacote. Forneça também a nome da categoria para resolver isso. O Portage irá informar o usuário sobre as possíveis opções a escolher.

Dependências circulares

CODE Portage avisando sobre dependência circular
!!! 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

Dois (ou mais) pacotes a instalar dependem um do outro e não podem ser instalados. Isso é na maioria da vezes um bug em um dos pacotes do repositório Gentoo. Por favor sincronize novamente e tente mais tarde. Pode ser bom checar o Bugzilla para ver se o problema é conhecido e, se não, fazer um relatório dele.

Falha ao baixar

CODE Portage avisando sobre falha ao baixar
!!! Fetch failed for sys-libs/ncurses-5.4-r5, continuing...
(...)
!!! Some fetch errors were encountered.  Please see above for details.

O Portage não conseguiu fazer o download dos fontes da aplicação e irá tentar continuar instalando outras aplicações (se aplicável). Esta falha pode acontecer devido um espelho não estar sincronizado corretamente ou por causa de um ebuild apontar para um local incorreto. O servidor onde os fontes residem podem também estar fora do ar por alguma razão.

Tente novamente em uma hora para ver se o problema ainda persiste.

Proteção do perfil do sistema

CODE Portage avisando sobre um pacote protegido pelo perfil
!!! Trying to unmerge package(s) in system profile. 'sys-apps/portage'
!!! This could be damaging to your system.

O usuário tentou remover um pacote que é parte do núcleo de pacotes do sistema. Ele é listado como requerido pelo perfil e não deve ser removido do sistema.

Falha na verificação do resumo

CODE Falha na verificação do resumo
>>> checking ebuild checksums
!!! Digest verification failed:

Isto é um sinal que algo está errado com repositório Gentoo - frequentemente por causa de um desenvolvedor ter cometido algum erro quando no envio de um ebuild para o repositório de ebuilds do Gentoo.

Quando uma verificação de resumo falhar, não tente refazer o resumo novamente do pacote pessoalmente. Executar ebuild foo manifest não irá corrigir o problema; irá muito provavelmente fazê-lo pior!

Em vez disso, espere um hora ou duas até o repositório se estabilizar. É provável que o erro foi notado de imediato, mas pode levar um tempo para a correção chegar até os espelhos rsync. Cheque o Bugzilla e veja se alguém já reportou o problema ou pergunte no #gentoo (IRC). Se não, vá em frente e abra um bug para o ebuild com problema.

Uma vez que o bug foi corrigido, sincronize novamente o repositório de ebuild do Gentoo para obter o resumo corrigido.

Importante
Tenha cuidado para não sincronizar o repositório de ebuild do Gentoo mais de uma vez ao dia. Como declarado na política de etiqueta oficial do Gentoo (assim como quando executamos o emerge --sync), usuários que sincronizarem muito frequentemente serão barrados de sincronizar por um tempo. Usuários que repetidamente violarem essa política podem ser banidos. A menos que absolutamente necessário, é melhor esperar um período de 24 horas para sincronizar de modo que a ressincronização não sobrecarregue os espelhos rsync do Gentoo.




Other languages:
Deutsch • ‎English • ‎español • ‎français • ‎polski • ‎português do Brasil • ‎русский • ‎українська • ‎中文(中国大陆)‎ • ‎日本語 • ‎한국어
Alpha Handbook
Installation
About the installation
Choosing the media
Configuring the network
Preparing the disks
Installing stage3
Installing base system
Configuring the kernel
Configuring the system
Installing tools
Configuring the bootloader
Finalizing
Working with Gentoo
Portage introduction
USE flags
Portage features
Initscript system
Environment variables
Working with Portage
Files and directories
Variables
Mixing software branches
Additional tools
Custom package repository
Advanced features
Network configuration
Getting started
Advanced configuration
Modular networking
Wireless
Adding functionality
Dynamic management


O que são as flags USE

A ideia por trás das flags USE

When installing Gentoo (or any other distribution, or even operating system for that matter) users make choices depending on the environment they are working with. A setup for a server differs from a setup for a workstation. A gaming workstation differs from a 3D rendering workstation.

This is not only true for choosing what packages to install, but also what features a certain package should support. If there is no need for OpenGL, why would someone bother to install and maintain OpenGL and build OpenGL support in most of the packages? If someone doesn't want to use KDE, why would they bother compiling packages with KDE support if those packages work flawlessly without?

To help users in deciding what to install/activate and what not, Gentoo wanted the user to specify his/her environment in an easy way. This forces the user into deciding what they really want and eases the process for Portage to make useful decisions.

Definition of a USE flag

Enter the USE flags. Such a flag is a keyword that embodies support and dependency-information for a certain concept. If someone defines a certain USE flag, Portage will know that they want support for the chosen keyword. Of course this also alters the dependency information for a package.

Take a look at a specific example: the kde keyword. If this keyword is not in the USE variable, all packages that have optional KDE support will be compiled without KDE support. All packages that have an optional KDE dependency will be installed without installing the KDE libraries (as dependency). When the kde keyword is defined, then those packages will be compiled with KDE support, and the KDE libraries will be installed as dependency.

By correctly defining the keywords the system will be tailored specifically to the user's needs.

What USE flags exist

There are two types of USE flags: global and local USE flags.

  • A global USE flag is used by several packages, system-wide. This is what most people see as USE flags. A list of available global USE flags can be found on the main site or locally in the /var/db/repos/gentoo/profiles/use.desc file.
  • A local USE flag is used by a single package to make package-specific decisions. A list of available local USE flags can be found on the main site or locally in the /var/db/repos/gentoo/profiles/use.local.desc file.

Using USE flags

Declare permanent USE flags

As previously mentioned, all USE flags are declared inside the USE variable. To make it easy for users to search and pick USE flags, we already provide a default USE setting. This setting is a collection of USE flags we think are commonly used by the Gentoo users. This default setting is declared in the make.defaults files that are part of the selected profile.

The profile the system listens to is pointed to by the /etc/portage/make.profile symlink. Each profile works on top of other profiles, and the end result is therefore the sum of all profiles. The top profile is the base profile (/var/db/repos/gentoo/profiles/base).

To view the currently active USE flags (completely), use emerge --info:

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

As can be seen, this variable already contains quite a lot of keywords. Do not alter any make.defaults file to tailor the USE variable to personal needs though: changes in these files will be undone when the Gentoo repository is updated!

To change this default setting, add or remove keywords to/from the USE variable. This is done globally by defining the USE variable in /etc/portage/make.conf. In this variable one can add the extra USE flags required, or remove the USE flags that are no longer needed. This latter is done by prefixing the keyword with the minus-sign (-).

For instance, to remove support for KDE and Qt but add support for LDAP, the following USE can be defined in /etc/portage/make.conf:

FILE /etc/portage/make.confUpdating USE in make.conf
USE="-kde -qt4 -qt5 ldap"

Declaring USE flags for individual packages

Sometimes users want to declare a certain USE flag for one (or a couple) of applications but not system-wide. To accomplish this, edit /etc/portage/package.use. package.use is typically a single file, however it can also be a directory filled with children files; see the tip below and then man 5 portage for more information on how to use this convention. The following examples assume package.use is a single file.

For instance, to only have Blu-ray support for the VLC media player package:

FILE /etc/portage/package.useEnabling Blu-ray support for VLC
media-video/vlc bluray
Tip
If package.use is pre-existing as a directory (opposed to a single file), packages can have their local USE flags modified by simply creating files under the package.use/ directory. Any file naming convention can work, however it is wise to implement a coherent naming scheme. One convention is to simply use the package name as the title for the child file. For example, setting the bluray USE flag locally for the media-video/vlc package can be performed as follows:

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

Similarly it is possible to explicitly disable USE flags for a certain application. For instance, to disable bzip2 support in PHP (but have it for all other packages through the USE flag declaration in make.conf):

FILE /etc/portage/package.useDisable bzip2 support for PHP
dev-lang/php -bzip2

Declaring temporary USE flags

Sometimes users need to set a USE flag for a brief moment. Instead of editing /etc/portage/make.conf twice (to do and undo the USE changes) just declare the USE variable as an environment variable. Remember that this setting only applies for the command entered; re-emerging or updating this application (either explicitly or as part of a system update) will undo the changes that were triggered through the (temporary) USE flag definition.

The following example temporarily removes the pulseaudio value from the USE variable during the installation of SeaMonkey:

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

Precedence

Of course there is a certain precedence on what setting has priority over the USE setting. The precedence for the USE setting is, ordered by priority (first has lowest priority):

  1. Default USE setting declared in the make.defaults files part of your profile
  2. User-defined USE setting in /etc/portage/make.conf
  3. User-defined USE setting in /etc/portage/package.use
  4. User-defined USE setting as environment variable

To view the final USE setting as seen by Portage, run emerge --info. This will list all relevant variables (including the USE variable) with their current definition as known to Portage.

root #emerge --info

Adapting the entire system to the new USE flags

After having altered USE flags, the system should be updated to reflect the necessary changes. To do so, use the --newuse option with emerge:

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

Next, run Portage's depclean to remove the conditional dependencies that were emerged on the "old" system but that have been obsoleted by the new USE flags.

Warning
Running emerge --depclean is a dangerous operation and should be handled with care. Double-check the provided list of "obsoleted" packages to make sure it doesn't remove packages that are needed. In the following example we add the -p switch to have depclean only list the packages without removing them:
root #emerge -p --depclean

When depclean has finished, emerge may prompt to rebuild the applications that are dynamically linked against shared objects provided by possibly removed packages. Portage will preserve necessary libraries until this action is done to prevent breaking applications. It stores what needs to be rebuilt in the preserved-rebuild set. To rebuild the necessary packages, run:

root #emerge @preserved-rebuild

When all this is accomplished, the system is using the new USE flag settings.

Package specific USE flags

Viewing available USE flags

Let's take the example of seamonkey: what USE flags does it listen to? To find out, we use emerge with the --pretend and --verbose options:

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 isn't the only tool for this job. In fact, there is a tool dedicated to package information called equery which resides in the app-portage/gentoolkit package

root #emerge --ask app-portage/gentoolkit

Now run equery with the uses argument to view the USE flags of a certain package. For instance, for the gnumeric package:

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

Satisfying REQUIRED_USE conditions

Some ebuilds require or forbid certain combinations of USE flags in order to work properly. This is expressed via a set of conditions placed in a REQUIRED_USE expression. This conditions ensure that all features and dependencies are complete and that the build will succeed and perform as expected. If any of these are not met, emerge will alert you and ask you to fix the issue.

Some examples of this REQUIRED_USE expression are given below:

Example Description
REQUIRED_USE="foo? ( bar )" If foo is set, bar must be set.
REQUIRED_USE="foo? ( !bar )" If foo is set, bar must not be set.
REQUIRED_USE="foo? ( || ( bar baz ) )" If foo is set, bar or baz must be set.
REQUIRED_USE="^^ ( foo bar baz )" Exactly one of foo bar or baz must be set.
REQUIRED_USE="|| ( foo bar baz )" At least one of foo bar or baz must be set.
REQUIRED_USE="?? ( foo bar baz )" No more than one of foo bar or baz may be set.



Handbook:Alpha/Working/Features/pt-br

Other languages:
Deutsch • ‎English • ‎español • ‎français • ‎polski • ‎português do Brasil • ‎русский • ‎українська • ‎中文(中国大陆)‎ • ‎日本語 • ‎한국어
Alpha Handbook
Installation
About the installation
Choosing the media
Configuring the network
Preparing the disks
Installing stage3
Installing base system
Configuring the kernel
Configuring the system
Installing tools
Configuring the bootloader
Finalizing
Working with Gentoo
Portage introduction
USE flags
Portage features
Initscript system
Environment variables
Working with Portage
Files and directories
Variables
Mixing software branches
Additional tools
Custom package repository
Advanced features
Network configuration
Getting started
Advanced configuration
Modular networking
Wireless
Adding functionality
Dynamic management


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 subdirectory 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 #/etc/init.d/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 #/etc/init.d/postfix --nodeps stop

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

root #/etc/init.d/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 #/etc/init.d/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 #/etc/init.d/postfix ineed

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

root #/etc/init.d/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

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 pidfile, 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 behaviour 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 boottime, 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.




Other languages:
Deutsch • ‎English • ‎español • ‎français • ‎polski • ‎português do Brasil • ‎русский • ‎українська • ‎中文(中国大陆)‎ • ‎日本語 • ‎한국어
Alpha Handbook
Installation
About the installation
Choosing the media
Configuring the network
Preparing the disks
Installing stage3
Installing base system
Configuring the kernel
Configuring the system
Installing tools
Configuring the bootloader
Finalizing
Working with Gentoo
Portage introduction
USE flags
Portage features
Initscript system
Environment variables
Working with Portage
Files and directories
Variables
Mixing software branches
Additional tools
Custom package repository
Advanced features
Network configuration
Getting started
Advanced configuration
Modular networking
Wireless
Adding functionality
Dynamic management


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 updates.
CONFIG_PROTECT_MASK This variable contains a space-delimited list of directories which should not be protected by Portage during 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"
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"
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 00basic, 05gcc, etc. which contain the variables needed by the application mentioned in their name.

For instance, when gcc is installed, a file called 05gcc was created by the ebuild which contains the definitions of the following variables:

FILE /etc/env.d/05gccDefault gcc enabled environment variables
PATH="/usr/i686-pc-linux-gnu/gcc-bin/3.2"
ROOTPATH="/usr/i686-pc-linux-gnu/gcc-bin/3.2"
MANPATH="/usr/share/gcc-data/i686-pc-linux-gnu/3.2/man"
INFOPATH="/usr/share/gcc-data/i686-pc-linux-gnu/3.2/info"
CC="gcc"
CXX="g++"
LDPATH="/usr/lib/gcc-lib/i686-pc-linux-gnu/3.2.3"

Other distributions might tell their users to change or add such environment variable definitions in /etc/profile or other locations. Gentoo on the other hand makes it easy for the user (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 /etc/env.d/05gcc file is updated too without requesting any user-interaction.

This not only benefits Portage, but also the user. Occasionally users might be asked to set a certain environment variable system-wide. As an example we take the http_proxy variable. Instead of messing about with /etc/profile, users can now just create a file (say /etc/env.d/99local) and enter the definition(s) in it:

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

By using the same file for all self-managed variables, users have a quick overview on the variables they have defined themselves.

env-update

Several files in /etc/env.d/ define the PATH variable. This is not a mistake: when the env-update command is executed, it will append the several definitions before it updates the environment variables, thereby making it easy for packages (or users) 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
00basic        99kde-env       99local
     +-------------+----------------+-------------+
PATH="/bin:/usr/bin:/usr/kde/3.2/bin:/usr/local/bin"

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"




Warning: Display title "Gentoo Linux alpha Manual: Trabalhando com o Gentoo" overrides earlier display title "Manual:Alpha/Completo/Trabalhando".