Handbook:Parts/Working/Initscripts/es

Iniciando su sistema
Al iniciar, notará que pasará al frente suyo una gran cantidad de texto. Si pone atención, notará que estos textos son (normalmente) iguales cada vez que reinicie su sistema. La secuencia de todas estas acciones se llama la secuencia de inicio y es (más o menos) definido estáticamente.

En primer lugar, su gestor de arranque cargará en memoria la imagen del núcleo que definió en la configuración del gestor de arranque, después de lo cual, se indica a la CPU que debe ejecutar el núcleo. Al ser cargado y luego ejecutado inicializa todas las estructuras y tareas específicas del núcleo e inicia el proceso init.

Este proceso asegura que todos los sistemas de archivo (definidos en ) estén montados y listos para usar. Luego ejecuta varios guiones en, correspondientes a los servicios requeridos para tener un sistema correctamente iniciado.

Finalmente, al concluir la ejecución de los guiones, init activa los terminales (generalmente solo las consolas virtuales accesibles con, , etc.) fijándoles un proceso especial denominado. Este proceso hará posible que pueda ingresar al sistema a través de uno de estos terminales ejecutando login.

Guiones de inicio (init scripts)
Ahora bien, init no solamente ejecuta los guiones contenidos en de manera aleatoria. Aún más, no ejecuta todos los guiones del, solamente los que han sido seleccionados para ejecutar. Los guiones seleccionados para ejecutar se encuentran dentro del directorio.

Primero, init ejecuta todos los guiones de cuyos enlaces simbólicos se encuentran dentro de. Usualmente los iniciará en orden alfabético, pero algunos guiones tienen información relativa a dependencias, para lo cual otros guiones deben ser iniciados anteriormente.

Cuando se ejecuten todos los guiones referenciados en, init continua su trabajo con los guiones en. Una vez más, usará el orden alfabético, salvo cuando hay dependencias, en cuyo caso es alterado el orden de inicio para realizar una secuencia válida de arranque. Esto último es también la razón por la que durante la instalación de Gentoo Linux se utiliza la opción "default" (por defecto), como en.

¿Cómo funciona Init?
Por supuesto que init no decide todo eso por su cuenta. Requiere un archivo de configuración que especifica las acciones a tomar. Este archivo es.

Si recuerda la secuencia de inicio que se ha explicado, recordará que la primera acción de init es montar todos los sistemas de archivo. Esto está definido en la siguiente línea de :

Esa línea dice a init que debe ejecutar  se encargan de la inicialización, con lo que podríamos decir que init no hace mucho, delega la tarea de inicialización del sistema a otro proceso.

En segundo lugar, init ejecutó los guiones con enlaces simbólicos en. Esto se define en la siguiente línea:

Una vez más, el guión rc lleva a cabo las tareas necesarias. Note que la opción de rc (boot) corresponde al subdirectorio usado bajo.

Ahora init revisa su archivo de configuración para ver que nivel de ejecución debe ejecutar. Para decidirlo, lee la siguiente línea de :

En este caso (para la mayoría de usuarios Gentoo), el identificador del nivel de ejecución será el 3. Con esta información init revisa qué debe ejecutar para iniciar el nivel de ejecución 3:

La línea que define el nivel 3, de nuevo usa el guión rc para iniciar los servicios (ahora con el parámetro por defecto default). Note una vez más que el parámetro pasado al guión rc corresponde al subdirectorio de.

Al terminar rc, init decide cuáles consolas virtuales debe activar y qué órdenes se deben ejecutar para cada una:

Niveles de ejecución existentes
Ha visto que init utiliza un esquema de numeración para decidir cual nivel de ejecución debe activar. Un nivel de ejecución es un estado en el cual su sistema está corriendo y contiene guiones (del nivel de ejecución o initscripts) que serán ejecutados al ingresar o salir del nivel de ejecución.

En Gentoo, hay siete niveles de ejecución definidos: tres internos y cuatro definidos por el usuario. Los internos se llaman sysinit, shutdown y reboot y hacen exactamente lo que implican sus nombres: inicialización, apagado y reinicio del sistema.

Los niveles de ejecución definidos por el usuario están acompañados de un subdirectorio bajo : boot, default, nonetwork y single. El nivel de ejecución boot inicia los servicios necesarios que requieren los demás niveles de ejecución. Los tres niveles de ejecución restantes difieren respecto a los servicios que inician: default es para uso diario, nonetwork en caso de no requerirse la red y single es utilizado en caso de necesitar arreglar el sistema.

Trabajando con los guiones de inicio
Los guiones iniciados por el proceso rc son llamados guiones de inicio o init scripts. Cada guión en puede ser ejecutado con los parámetros start, stop, restart, zap, status, ineed, iuse, needsme, usesme o broken.

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

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

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

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:

To also ask what dependencies the service has, use iuse or ineed. With ineed it is possible to see the services that are really necessary for the correct functioning of the service. iuse 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 (needsme) or can use it (usesme):

Finally, to ask what dependencies the service requires that are missing:

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 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  the add or del 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 apache2 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!

Layout
The basic layout of an init script is shown below.

Example initscript layout

Every init script requires the start function to be defined. All other sections are optional.

Dependencies
There are two dependency-alike settings that can be defined which influence the start-up or sequencing of init scripts: use and need. Next to these two, 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 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:

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.

Using the * glob

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:

Dependency setting with needing localmount and 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:

Example start function

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.

For more examples of the start 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 stop. The init system is intelligent enough to fill in this function by itself if start-stop-daemon is used.

Example stop function

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:

Example definition for a service that starts the foo script

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 the extra_commands variable, and create a function with the same name as the option. For instance, to support an option called restartdelay:

Example definition of restartdelay method

Service configuration variables
In order to support configuration files in, no specifics need to be impleneted: 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 from this
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 ythe 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  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.