OpenRC
- Review for accuracy & test.
- Complete to cover most basic usage under Gentoo.
- Rework for precision, readability, concision...
- Section BusyBox Integration needs testing and documenting (or removing).
OpenRC es un sistema init basado en dependencias para sistemas Unix-like que mantiene la compatibilidad con el init system ya provisto por el sistema, que normalmente se encuentra en /sbin/init. OpenRC es el sistema init nativo de Gentoo, si bien otros sistemas init están disponibles.
OpenRC iniciará los servicios del sistema necesarios en el orden correcto al arrancar, los gestionará mientras el sistema esté en uso y los detendrá a la hora de apagarlo. Puede manejar los servicios o demonios instalados desde el repositorio de Gentoo, puede (de manera opcional) supervisar los procesos que ejecuta y tiene la posibilidad de lanzar los procesos en paralelo (siempre que sea posible) para reducir el tiempo de arranque.
OpenRC fue desarrollado para Gentoo, pero está diseñado para ser usado en otras distribuciones Linux y sistemas BSD. Por defecto, en Gentoo, OpenRC es lanzado por sysvinit.
Los servicios o demonios instalados desde fuera del repositorio Gentoo, como puede ser cualquier software descargado como código fuente y compilado manualmente, quizá necesite ser adaptado para ser compatible con OpenRC (que es, a veces, un proceso trivial).
Vea la sección de documentación de OpenRC para ver enlaces a la documentación dada por el mismo proyecto OpenRC. Vea el Manual para ver información sobre cómo funciona OpenRC con el sistema init.
Implementación
OpenRC no requiere de cambios grandes y fundamentales del sistema Unix-like tradicional. OpenRC se integra con el resto del software como un componente más de un sistema flexible y modular. Está diseñado para ser rápido, ligero, fácilmente configurable y adaptable. OpenRC solo tiene unas pocas dependencias básicas en componentes del núcleo del sistema.
Como sistema init moderno, OpenRC provee de bastantes funcionalidades útiles:
- Soporte para cgroups.
- Supervisión de procesos.
- Ejecución basada en dependencias con inicio paralelo de servicios.
- Resolución y ordenado automático de dependencias.
- Iniciación de initscripts de hardware.
- Configuración de valores ulimit y nice por servicio a través de la variable rc_ulimit.
- Permite scripts init complejos que lanzan múltiples componentes.
- Arquitectura modular y ajustable a la infraestructura existente.
- OpenRC tiene su propio sistema init opcional llamado openrc-init. Véase OpenRC/openrc-init para más detalles.
- OpenRC tiene su propio supervisor de procesos opcional. Véase OpenRC/supervise-daemon para más detalles.
Véase el artículo comparativa de sistemas init para más información en sistemas init.
Instalación
OpenRC generalmente no necesita ser instalado manualmente, y es proporcionado como parte de un profile durante la profile on instalación. Estará dentro del stage3 y será mantenido con las actualizaciones del sistema.
Ajustes USE
USE flags for sys-apps/openrc OpenRC manages the services, startup and shutdown of a host
+netifrc
|
enable Gentoo's network stack (net.* scripts) |
+sysvinit
|
control the dependency on sysvinit (experimental) |
audit
|
Enable support for Linux audit subsystem using sys-process/audit |
bash
|
enable the use of bash in service scripts (experimental) |
caps
|
Use Linux capabilities library to control privilege |
debug
|
Enable extra debug codepaths, like asserts and extra output. If you want to get meaningful backtraces see https://wiki.gentoo.org/wiki/Project:Quality_Assurance/Backtraces |
newnet
|
enable the new network stack (experimental) |
pam
|
Add support for PAM (Pluggable Authentication Modules) - DANGEROUS to arbitrarily flip |
s6
|
install s6-linux-init |
selinux
|
!!internal use only!! Security Enhanced Linux support, this must be set by the selinux profile or breakage will occur |
sysv-utils
|
Install sysvinit compatibility scripts for halt, init, poweroff, reboot and shutdown |
unicode
|
Add support for Unicode |
Si los ajustes USE son modificados, el paquete podría necesitar ser reconstruido para aplicar los cambios. Para los perfiles de OpenRC, sys-apps/openrc es considerado una dependencia del paquete virtual/service-manager, por lo que no debería ser añadido manualmente al set de paquetes (/var/lib/portage/world archivo world). La opción --oneshot
evita añadir OpenRC a este archivo.
root #
emerge --ask --oneshot sys-apps/openrc
Configuración
Archivos
- /etc/rc.conf
- El archivo de configuración global de OpenRC.
- Incluye comentarios exhaustivos que documentan la configuración de OpenRC.
- /etc/conf.d
- Contiene archivos de configuración para scripts init individuales.
Registros
OpenRC no guarda registros por defecto. Para registrar la información sobre OpenRC durante el arranque, descomente y ajuste la opción rc_logger /etc/rc.conf. Los registros se guardarán de manera predeterminada en /var/log/rc.log.
/etc/rc.conf
rc_logger="YES"
#rc_log_path="/var/log/rc.log"
Configuración de la red
OpenRC puede ser usado junto a uno, varios o ningún gestor de red. Por defecto, con los perfiles OpenRC de Gentoo, se utilizan scripts netifrc para gestionar las conexiones a la red.
Vea el artículo Network manager para una lista de opciones en gestión de red.
Comportamiento de dependencias
Cambiar las dependencias predeterminadas de los guiones de inicio (init scripts), podría ser necesario para configuraciones más complejas. Consulte /etc/rc.conf para ver cómo cambiar el comportamiento por defecto. Fíjese en la opción rc_depend_strict. También verá la flexibilidad de OpenRC con los ejemplos de red siguientes.
- Varias interfaces de red (ejemplo)
El servicio SSH debe aparecer en la red interna, siendo por ejemplo eth0 y nunca wlan0.
Sobreescriba la dependencia "net" de /etc/init.d/sshd y refínalo para depender de "net.eth0":
/etc/conf.d/sshd
rc_need="!net net.eth0"
- Multiple network interfaces in multiple runlevels (example)
The SSH service must start with eth0 (not wlan0) in "default" runlevel, but in "office" runlevel it must start with wlan0 (not eth0).
Mantén los ajustes predeterminados:
Translations:OpenRC/34/es
/etc/rc.conf
#rc_depend_strict="YES"
Crea enlaces simbólicos adicionales a sshd con los nombres de las interfaces de red:
root #
ln -s sshd /etc/init.d/sshd.eth0
root #
ln -s sshd /etc/init.d/sshd.wlan0
Los ajustes ahora se leen de /etc/conf.d/sshd.eth0 y /etc/conf.d/sshd.wlan0:
root #
cp /etc/conf.d/sshd /etc/conf.d/sshd.eth0
root #
cp /etc/conf.d/sshd /etc/conf.d/sshd.wlan0
Añade las dependencias:
Translations:OpenRC/40/es
root #
echo 'rc_need="!net net.eth0"' >> /etc/conf.d/sshd.eth0
root #
echo 'rc_need="!net net.wlan0"' >> /etc/conf.d/sshd.wlan0
En este ejemplo, 'net.eth0 y net.wlan0 leen sus ajustes desde /etc/conf.d/net o /etc/conf.d/net.office, dependiendo del nivel de ejecución. Añada todos los guiones de ejecución a los diferentes niveles de ejecución:
root #
rc-update add sshd.eth0 default
root #
rc-update add sshd.wlan0 office
root #
rc-update add net.eth0 default office
root #
rc-update add net.wlan0 default office
Para cambiar entre los niveles de ejecución "default" y "office" sin reiniciar el ordenador, cambie al nivel de ejecución "nonetwork" entre uno y otro. De esta manera las interfaces de red se detendrán y volverán a leer su configuración específica del nivel de ejecución. Esto funciona sobre todo cuando "nonetwork" es un nivel de ejecución apilado a los niveles "default" y "office", y el gestor de inicio de sesión y otros servicios no relacionados con la red se añaden únicamente al nivel "nonetwork".
default runlevel <---> nonetwork runlevel <---> office runlevel
root #
openrc nonetwork && openrc office
root #
openrc nonetwork && openrc default
Selección de un nivel de ejecución específico al arrancar
OpenRC lee la línea de comandos del kernel usada al arrancar, e iniciará el nivel de ejecución especificado por el parámetro softlevel si este es especificado. Si no se provee de un parámetro softlevel, se usará el nivel de ejecución default.
El siguiente ejemplo muestra una configuración de grub que permite elegir arrancar a los niveles de ejecución default o nonetwork:
/boot/grub/grub.conf
Example grub.conf (GRUB Legacy)title=Arranque normal
kernel (hd0,0)/boot/kernel-3.7.10-gentoo-r1 root=/dev/sda3
title=Arranque sin red
kernel (hd0,0)/boot/kernel-3.7.10-gentoo-r1 root=/dev/sda3 softlevel=nonetwork
Consulte más abajo para una descripción sobre cómo añadir niveles de ejecución adicionales.
Utilización
Niveles de ejecución
OpenRC puede ser controlado y configurado usando los comandos openrc, rc-update y rc-status.
Elimine un servicio del nivel de ejecución predeterminado (default), reemplazando <service>
por el nombre del servicio a eliminar:
root #
rc-update delete <service> default
Listado
No es necesario tener permisos de usuario root para listar los niveles de ejecución y servicios (guiones de ejecución de inicio) que tienen asignados.
Use rc-update show -v para mostrar todos los guiones de ejecución de inicio (init scripts) y su nivel de ejecución actual (si han sido añadidos a uno):
user $
rc-update show -v
Ejecutar rc-update o rc-update show mostrará solo los guiones de ejecución al inicio que han sido añadidos a un nivel de ejecución concreto.
De manera alternativa se puede utilizar el comando rc-status con la opción --servicelist
(-s
) para ver el estado de todos los servicios:
user $
rc-status --servicelist
Niveles de ejecución
Los niveles de ejecución de OpenRC son implementados como carpetas residentes en /etc/runlevels. Se pueden crear niveles adicionales de ejecución (indicado como <runlevel>
a continuación) usando:
root #
install -d /etc/runlevels/<runlevel>
Los niveles de ejecución adicionales pueden ayudar a la hora de ofrecer perfiles de arranque alternativos.
Niveles de ejecución apilados
Stacked runlevels are used to allow a runlevel to inherit the actions of one or more other runlevels. The command variant used to create stacked runlevels is rc-update -s. Adding a runlevel to another runlevel causes a dependency to be created such that any init scripts (services) in any dependent (stacked) runlevels are started or stopped when the target runlevel is started or stopped.
An usage example for using stacked runlevel on laptop to group networking services based on location is at OpenRC/Stacked runlevel.
Prefix
Gentoo Prefix installs Gentoo within an offset, known as a prefix, allowing users to install Gentoo in another location in the filesystem hierarchy, hence avoiding conflicts. Next to this offset, Gentoo Prefix runs unprivileged, meaning no root user or rights are required to use it.
By using an offset (the "prefix" location), it is possible for many "alternative" user groups to benefit from a large part of the packages in the Gentoo Linux Portage tree. Currently users of the following systems successfully run Gentoo Prefix: Mac OS X on PPC and x86, Linux on x86, x86_64 and ia64, Solaris 10 on Sparc, Sparc/64, x86 and x86_64, FreeBSD on x86, AIX on PPC, Interix on x86, Windows on x86 (with the help of Interix), HP-UX on PARISC and ia64.
OpenRC runscript already support prefix-installed daemons, during the Summer of Code 2012 work will be done to implement full secondary/session daemon behavior to complete the overall feature set provided by Prefix.
OpenRC/Prefix, a tutorial for trying it out.
Hotplug
OpenRC can be triggered by external events, such as new hardware from udev. This is what the configuration file says about hotplugged services:
/etc/rc.conf
rc_hotplug# rc_hotplug controls which services we allow to be hotplugged.
# A hotplugged service is one started by a dynamic dev manager when a matching
# hardware device is found.
# Hotplugged services appear in the "hotplugged" runlevel.
# If rc_hotplug is set to any value, we compare the name of this service
# to every pattern in the value, from left to right, and we allow the
# service to be hotplugged if it matches a pattern, or if it matches no
# patterns. Patterns can include shell wildcards.
# To disable services from being hotplugged, prefix patterns with "!".
# If rc_hotplug is not set or is empty, all hotplugging is disabled.
# Example - rc_hotplug="net.wlan !net.*"
# This allows net.wlan and any service not matching net.* to be hotplugged.
# Example - rc_hotplug="!net.*"
# This allows services that do not match "net.*" to be hotplugged.
CGroups support
OpenRC starting with version 0.12 has extended cgroups support. See OpenRC/CGroups for details. Since OpenRC 0.51, unified cgroups (v2) is enabled by default.
Chroot support
root #
mkdir -p /lib64/rc/init.d
root #
ln -s /lib64/rc/init.d /run/openrc
root #
touch /run/openrc/softlevel
root #
emerge --oneshot sys-apps/openrc
/etc/rc.conf
OpenRC config filerc_sys="prefix"
rc_controller_cgroups="NO"
rc_depend_strict="NO"
rc_need="!net !dev !udev-mount !sysfs !checkfs !fsck !netmount !logger !clock !modules"
The system may report the following message upon attempting to start a service:
- WARNING: <service> is already starting
This may be fixed by issuing the following command:
root #
rc-update --update
System integration
systemd compatibility
logind
Some setups require systemd-logind. Elogind can be a suitable replacement as a standalone logind running with OpenRC.
tmpfiles.d
systemd has a special tmpfiles.d file syntax for managing temporary files. sys-apps/systemd-tmpfiles is a standalone provider for OpenRC systems. Now deprecated, there is also sys-apps/opentmpfiles which provides (for now) a tmpfiles.d interpreter for OpenRC.
Both can also be used to manage volatile entries in /sys or /proc.
udev and mdev
udev and mdev are systems available on Gentoo to manage /dev. eudev used to be available as well, but has been removed. udev is available for OpenRC via the [udev sys-apps/systemd-utils[udev]] package, however should be able to work with both on Gentoo.
Older Gentoo installs used udev as the main virtual/udev provider. Based on bug #575718 this was changed to eudev, but it was changed back to udev in bug #807193. However, the rc service is still /etc/init.d/udev.
See mdev, for possible use, e.g. for embedded systems.
BusyBox integration
N.B. This section lacks information on how to actually use BusyBox with OpenRC.
Please note that there are currently many BusyBox applets that are incompatible with OpenRC, see bug #529086 for details. Be warned that using OpenRC with BusyBox may require some work to set up. BusyBox is more adapted to embedded use, see previous section about mdev.
BusyBox can be used to replace most of the userspace utilities needed by OpenRC (init, shell, awk, and other POSIX tools), by using a complete BusyBox as the shell for OpenRC [1], all the calls that normally would cause a fork/exec would be spared, improving the overall speed.
The SysV-init /etc/inittab file provided by Gentoo is not compatible with the BusyBox init. Here is an example inittab compatible with BusyBox:
/etc/inittab
Example inittab compatible with BusyBox init::sysinit:/sbin/openrc sysinit
::wait:/sbin/openrc boot
::wait:/sbin/openrc
BusyBox provides a number of applets that could be used to replace third party software like acpid or dhcp/dhcpcd.
See the OpenRC documentation on using BusyBox with OpenRC.
Troubleshooting
Respawning crashed services
OpenRC can return state of services to runlevel setting state, to provide stateful init scripts and automatic respawning.
To respawn crashed services from the default runlevel, run openrc: crashed services will be started and any manually-run services will be stopped. To keep manually-started services running, run openrc --no-stop or openrc -n, for short.
By default openrc will attempt to start crashed services, not to restart them. This can be controlled by the rc_crashed_stop (default NO) and rc_crashed_start (default YES) options in /etc/rc.conf.
Manually recovering crashed services
When a process crashes while starting, an error or warning message will be printed when trying to start, stop, or show the status of a service. For example, when using the "docker" service:
root #
rc-service docker status
* status: crashed
root #
rc-service docker start
* WARNING: docker has already been started
root #
rc-service docker stop
* Caching service dependencies ... [ ok ] * Stopping docker ... * Failed to stop docker [ !! ] * ERROR: docker failed to stop
To remedy this situation, zap the service:
root #
rc-service docker zap
See also
- OpenRC/CGroups — OpenRC includes support for cgroups.
- OpenRC/openrc-init — Open-RC's own init system
- OpenRC/Prefix — The following guideline applies to a Gentoo Prefix on RHEL-5.6 amd64 and on Debian 6.0 amd64, for other setups it should be similar.
- OpenRC/Stacked runlevel — a tutorial for setting up complicated networking with the help of stacked runlevel.
- OpenRC/supervise-daemon — OpenRC's daemon supervisor
- OpenRC/Users — an (incomplete) list of distributions and operating systems using OpenRC.
- /etc/local.d — /etc/local.d/ can contain small programs or light scripts to be run when the local service is started or stopped.
- Gentoo AMD64 Handbook - Initscript system
- The main OpenRC configuration file, /etc/rc.conf, contains extensive comments documenting OpenRC configuration.
External resources
OpenRC documentation
OpenRC has its own useful documentation, maintained by the OpenRC developers themselves. Be aware that Gentoo does not use all of OpenRC's functionality by default:
- README
- User Guide
- OpenRC init process guide - How to use OpenRC's own init system (not used by default in Gentoo).
- agetty guide - Setting up the agetty service in OpenRC (By default, ttys are spawned with sysvinit in Gentoo).
- Using runit with OpenRC
- Using S6 with OpenRC
- Using supervise-daemon - Optional process supervision.
- Using BusyBox with OpenRC
- Service script writing guide - For developers or packagers.
- NEWS - Important information about each release.
- HISTORY - History of how OpenRC came to be.
Man pages
- openrc(8) - Stops and starts services for the specified runlevel.
- openrc-run(8) - Interpreter used to process OpenRC service scripts.
- rc-service(8) - Locate and run an OpenRC service with the given arguments.
- rc-status(8) - Show status info about runlevels.
- rc-update(8) - Add and remove services to and from a runlevel.