Handbook:Parts/Working/Initscripts/ru

Процесс загрузки системы
При загрузке вашей системы по экрану пробегает много текста. Если присмотреться, заметно, что обычно этот текст не меняется от загрузки к загрузке. Последовательность всех этих действий называется последовательностью загрузки и в той или иной степени постоянна.

Во-первых, загрузчик размещает в памяти образ ядра, который вы указали в файле его конфигурации. После этого начальный загрузчик просит процессор запустить ядро. Когда ядро загружено и запущено, оно инициализирует относящиеся к ядру структуры и задания, и запускает процесс init.

Этот процесс удостоверяется, что все файловые системы (определенные в ) смонтированы и готовы к использованию. Затем он выполняет несколько сценариев, находящихся в каталоге, которые запускают службы, необходимые для нормального запуска системы.

И, наконец, когда все сценарии выполнены, init подключает терминалы (чаще всего просто виртуальные консоли, которые видны при нажатии, и т.д.), прикрепляя к каждой консоли специальный процесс под названием. Этот процесс впоследствии обеспечивает возможность входа в систему через эти терминалы с помощью login.

Сценарии инициализации
Сейчас процесс init запускает сценарии из каталога не просто в случайном порядке. Более того, запускаются не все сценарии из, а только те, которые предписано исполнять. Решение о запуске сценария принимается в результате просмотра каталога.

Во-первых, init запускает все сценарии из, на которые есть символьные ссылки из. Обычно сценарии запускаются в алфавитном порядке, но в некоторых сценариях имеется информация о зависимостях от других сценариев, указывающая системе на необходимость их предварительного запуска.

Когда все сценарии, указанные в, будут выполнены, init переходит к запуску сценариев, на которые есть символьные ссылки из. И снова запуск происходит в алфавитном порядке, пока в сценарии не встретится информация о	зависимостях; тогда порядок изменяется для обеспечения правильного порядка запуска. Именно по данной причине команды, используемые во время установки Gentoo Linux, используют default, как в команде.

Как работает init
Конечно, init не принимает решений сам по себе. Ему необходим конфигурационный файл, где описаны необходимые действия. Этот файл -.

Если вы запомнили последовательность загрузки, описанную чуть ранее, вы вспомните, что первое действие init - это монтирование всех файловых систем. Это определяется в следующей строке файла :

Этой строкой процессу init предписывается выполнить  для инициализации системы. Самой инициализацией занимается	сценарий, так что можно сказать, что init делает не слишком много - он просто делегирует задачу по инициализации системы другому процессу.

Во-вторых, init выполняет все сценарии, на которые есть символьные ссылки из. Это определяется следующей строкой:

И снова все необходимые действия выполняются сценарием rc. Заметьте, что параметр, переданный rc (boot), совпадает с названием используемого подкаталога в.

Теперь init проверяет свой конфигурационный файл, чтобы определить, какой уровень запуска нужно запустить. Для этого из считывается строка:

В приведенном примере (который подходит для подавляющего большинства пользователей Gentoo) номер уровня запуска - 3. Пользуясь этой информацей, init проверяет, что нужно выполнить для запуска уровня запуска 3:

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

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

Working with initscripts
The scripts that the rc process starts are called init scripts. Each script in can be executed with the arguments start, stop, restart, zap, status, ineed, iuse, needsme, usesme or 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.

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.

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

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.

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:

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:

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.