Handbook:Parts/Working/Initscripts/pt-br

Inicializando o sistema
Quando o sistema é inicializado, um monte de texto passa "voando". Prestando bastante atenção, irá-se notar que o texto é (normalmente) o mesmo sempre que o sistema é inicializado. A sequência de todas as ações é chamada de sequência de boot e é (mais ou menos) definida estaticamente.

Primeiro, o carregador de boot carrega a imagem do kernel que está definida na configuração do carregador de boot. Depois, o carregador de boot instrui a CPU para executar o kernel. Quando o kernel é carregado e executado, ele inicializa todas as estruturas e tarefas específicas do kernel e inicia o processo init.

O processo então se certifica que todos os sistemas de arquivos (definidos em ) são montados e prontos para uso. Então ele executa diversos scripts localizados em, que irá inicializar os serviços necessários de modo a se ter um sistema corretamente inicializado.

Por fim, quando todos os scripts terminaram de executar, o init ativa os terminais (normalmente são apenas os consoles virtuais ativados pelas teclas +, +, etc.), anexando um processo especial chamado  a eles. Esse processo então certifica-se os usuários são capazes de logar por esses terminais executando o login.

Scripts de inicialização
O init não executa os scripts em aleatoriamente. Nem mesmo ele executa todos os scripts em, apenas os scripts que devem ser executados. Ele decide quais scripts executar consultando em.

First, init runs all scripts from that have symbolic links inside. 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 referenced scripts are executed, init continues with running the scripts that have a symbolic link to them in. 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, as in.

Com funciona o init
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.

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 :

This line tells init that it must run to initialize the system. The 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. This is defined in the following line:

Again the openrc script performs the necessary tasks. Note that the option given to openrc (boot) is the same as the subdirectory of 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 :

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:

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

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

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 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.

Trabalhando com initscripts
The scripts that the openrc process starts are called init scripts. Each script in can be executed with the arguments ,  ,  ,  ,  ,  ,  ,  ,  ,  , or.

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

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

Para ver o status de um serviço (executando, parado, ...), use o argumento :

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  argument:

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

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

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 it is possible to add and remove init scripts to a runlevel. The tool will then automatically ask the  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 script requires a second argument that defines the action: ,  , or.

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

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

It is also possible to run (without  ) to just view enabled init scripts and their runlevels.

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. For instance, the initscript (called ) has a configuration file called, which can contain the options to give to the Apache 2 server when it is started:

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

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.

Every init script requires the  function or   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:,   and. Next to these, there are also two order-influencing methods called  and. 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  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   or  . 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  setting is similar to   with one exception.    only considers services which were added to an init level.   will try to start any available service even if not added to an init level.
 * The  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, 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   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,  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  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:

As can be seen, the postfix service:


 * Requires the (virtual) net dependency (which is provided by, for instance, ).
 * Uses the (virtual) logger dependency (which is provided by, for instance, ).
 * Uses the (virtual) dns dependency (which is provided by, for instance, ).
 * 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.

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

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

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

Both  and   should be used in start and stop functions. If the service does not create a pidfile, then use  if possible, though it is recommended to test this to be sure. Otherwise, don't use pidfiles. It is also possible to add  to the start-stop-daemon options, but this is not recommended unless the service is extremely verbose. Using  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  or  ) is called as part of a restart or not.

For more examples of the  function, please read the source code of the available init scripts in the  directory.

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

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

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

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 :


 * 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

Service configuration variables
In order to support configuration files in, 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):



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

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:

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:

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 :

Edit the bootloader configuration and add a new entry for the offline runlevel. In that entry, add  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.