Understanding and administering systemd

Learn the basic principles of the systemd init system: how to configure it and use it to administer the system.

Comprendiendo systemd

Systemd es un administrador del sistema y los servicios para Linux, compatible con scripts de inicio SysV y LSB. Systemd proporciona:

  • Capacidades agresivas de paralelización

  • Usa socket y activación D-Bus para el inicio de los servicios

  • Ofrece arranque de demonios a demanda, mantiene rastreo de los procesos usando Linux cgroups

  • Soporta instantáneas y restauración del estado del sistema

  • Mantiene puntos de montaje y automontaje

  • Implementa un elaborado servicio de control lógico transaccional basado en la dependencia.

El comando systemctl en la principal herramienta para administrar systemd. Combina la funcionalidad de los comandos service y chkconfig de SysVinit en una herramienta que usted puede usar para habilitar o deshabilitar servicios permanentemente o solo para la sesión actual.

Systemd gestiona las llamadas unidades, que son representaciones de los recursos y servicios del sistema. La siguiente lista muestra los tipos de unidades que systemd puede gestionar:

servicio

Un servicio en el sistema, incluyendo las instrucciones para arrancar, reiniciar y parar el servicio.

socket

Un socket de red asociado con un servicio.

dispositivo

Un dispositivo gestionado específicamente con systemd.

mount

Un punto de montaje gestionado con systemd.

automount

Un punto de montaje montado automáticamente en el arranque.

swap

Espacio swap en el sistema.

target

Un punto de sincronización para otras unidades. Utilizado usualmente para iniciar servicios habilitados en el arranque.

ruta

Una ruta para activación basada en ruta. Por ejemplo, usted puede iniciar servicios en base al estado de una ruta, como si existe o no.

temporizador

Un temporizador para planificar la activación de otra unidad.

instantánea

Una instantánea del estado actual de systemd. Usado normalmente para revertir después de realizar cambios temporales en systemd.

slice

Restricción de recursos a través de nodos Grupo de Control Linux (cgroups).

alcance

Información desde las interfaces bus systemd. Normalmente usado para gestionar procesos externos al sistema.

Starting, stopping, and querying systemd services

You can perform various management tasks to control systemd services using the systemctl command. The following is a set of example commands to demonstrate how to use systemctl to manage systemd services.

Requisitos previos

Usted debe haber accedido con un usuario con permisos a nivel de administrador.

Procedimiento

The following commands control the foo service:

  • Activate a service immediately:

    # systemctl start foo
  • Deactivate a service immediately:

    # systemctl stop foo
  • Restart a service:

    # systemctl restart foo
  • Show the status of a service including, whether it is running or not:

    # systemctl status foo
  • Enable a service to be started on boot:

    # systemctl enable foo
  • Disable a service to not start during boot:

    # systemctl disable foo
  • Prevent a service from starting dynamically or even manually unless unmasked:

    # systemctl mask foo
  • Check if a service is enabled or not:

    # systemctl is-enabled foo

Información Relacionada

  • Run man systemctl for more details.

Modificando servicios systemd existentes

Este ejemplo muestra cómo modificar un servicio existente. La modificación del servicio se almacena dentro de /etc/systemd/system, en un único archivo o en un subdirectorio que lleva el nombre del servicio. Por ejemplo este procedimiento modifica el servicio httpd.

Requisitos previos

  • Usted debe haber accedido con un usuario con permisos a nivel de administrador.

  • Usted tiene configurado un servidor httpd corriendo a través de systemd.

Procedimiento

  1. Los servicios systemd pueden ser modificados usando el comando systemctl edit.

    # systemctl edit httpd.service

    Esto crea un archivo de anulación /etc/systemd/system/httpd.service.d/override.conf y lo abre en su editor de texto. Todo lo que ponga en este archivo será añadido al archivo de servicio existente.

  2. Añada su configuración personal. Por ejemplo:

    [Service]
    Restart=always
    RestartSec=30

    Para reemplazar una opción que pueda ser ajustada múltiples veces, debe limpiarla primero, de otro modo el archivo de anulación añadirá la opción una segunda vez.

    [Service]
    ExecStart=
    ExecStart=<new command>
  3. Guarde el archivo. Systemd cargará automáticamente la nueva configuración de servicio.

  4. Reiniciar el servicio httpd:

    # systemctl restart httpd

Para reemplazar completamente (en lugar de solo añadir/modificar) un archivo de servicio existente, use systemctl edit --full, p. ej. systemctl edit --full httpd.service. Esto creará /etc/systemctl/system/httpd.service, que será usado en lugar del archivo de servicio existente.

Información Relacionada

Creando nuevos servicios systemd

Este ejemplo muestra cómo crear un archivo de unidad para un servicio personalizado. Los archivos de unidad personalizados se localizan en /etc/systemd/system/ y tienen una extensión .service. Por ejemplo un archivo de unidad personalizado del servicio foo utiliza /etc/systemd/system/foo.service.

Requisitos previos

  • Usted debe haber accedido con un usuario con permisos a nivel de administrador.

Procedimiento

Este procedimiento crea un archivo básico de configuración para controlar el servicio foo.

  1. Crear y editar un nuevo archivo de configuración:

    # nano /etc/systemd/system/foo.service
  2. Los siguientes pasos describen en cada sección los parámetros para añadir al archivo:

    1. La sección [Unit] suministra información básica sobre el servicio. El servicio foo utiliza los siguientes parámetros:

      Description

      A string describing the unit. Systemd displays this description next to the unit name in the user interface.

      After

      Defines a relationship with a second unit. If you activate the unit, systemd activates it only after the second one. For example, the foo service might require network connectivity, which means the foo services specifies network.target as an After= condition.

      The resulting [Unit] section looks like this:

      [Unit]
      Description=My custom service
      After=network.target
    2. The [Service] section provides instructions on how to control the service. The foo service uses the following parameters:

      Type

      Defines the type of systemd service. In this example, the foo service is a simple service, which starts the service without any special consideration.

      ExecStart

      The command to run to start the service. This includes the full path to the command and arguments to modify the service.

      The resulting [Service] section looks like this:

      [Service]
      Type=simple
      ExecStart=/usr/bin/sleep infinity
    3. The [Install] section provides instructions on how systemd installs the service. The foo service uses the following parameters:

      WantedBy

      Defines which service triggers the custom service if enabled with systemctl enable. This is mostly used for starting the custom service on boot. In this example, foo.service uses multi-user.target, which starts foo.service when systemd loads multi-user.target on boot.

  3. The full foo.service file contains the following contents:

    [Unit]
    Description=My custom service
    After=network.target
    
    [Service]
    Type=simple
    ExecStart=/usr/bin/sleep infinity
    
    [Install]
    WantedBy=multi-user.target

    Save the file.

  4. To make systemd aware of the new service, reload its service files

    # systemctl daemon-reload
  5. Start the custom foo service:

    # systemctl start foo
  6. Check the status of the service to ensure the service is running:

    $ systemctl status foo
    ● foo.service - My custom service
       Loaded: loaded (/etc/systemd/system/foo.service; static; vendor preset: disabled)
       Active: active (running) since Thu 2017-12-14 14:09:12 AEST; 6s ago
     Main PID: 31837 (sleep)
        Tasks: 1 (limit: 4915)
       CGroup: /system.slice/foo.service
               └─31837 /usr/bin/sleep infinity
    
    Dec 14 14:09:12 dansmachine systemd[1]: Started My custom service.

Información Relacionada

Converting SysVinit services to systemd

Older versions of Fedora use SysVinit scripts to manage services. This section provides some guidelines on how to convert a SysVinit script to a systemd equivalent.

Requisitos previos

  • Usted debe haber accedido con un usuario con permisos a nivel de administrador.

  • You have a custom SysVinit script to convert to a systemd configuration.

Procedimiento

  1. Identify the runlevels in your SysVinit script. This is usually defined with chkconfig directive in the commented section at the beginning of the script. For example, the following indicates the service is using runlevels 3, 4, and 5:

    # chkconfig: 235 20 80

    systemd uses targets instead of runlevels. Use the table in Converting SysVinit services to systemd to map the runlevels to targets. In this example, runlevels 2, 3, and 5 are all multi-user runlevels, so the systemd service can use the following:

    [Install]
    WantedBy=multi-user.target

    If you enable the custom systemd service to start at boot (systemctl enable foo.service), systemd loads the service when loading the multi-user.target at boot time.

  2. Identify the dependent services and targets. For example, if the custom service requires network connectivity, specify the network.target as a dependency:

    [Unit]
    Description=My custom service
    After=network.target
  3. Identify the command used to start the service in the SysVinit script and convert this to the systemd equivalent. For example, the script might contain a start function in the following format:

    start() {
      echo "Starting My Custom Service..."
      /usr/bin/myservice -D
    }

    In this example, the /usr/bin/myservice command is the custom service command set to daemonize with the -D option. Set the ExecStart parameter to use this command:

    [Service]
    ExecStart=/usr/bin/myservice -D
  4. Check the SysVinit script to see if the service uses a special command to restart the service. For example, the script might contain a reboot function that reloads the service:

    reboot() {
      echo "Reloading My Custom Service..."
      /usr/bin/myservice reload
    }

    In this example, the /usr/bin/myservice command is the custom service command and reloads the service using the reload subcommand. Set the ExecReload parameter to use this command:

    [Service]
    ExecReload=/usr/bin/myservice reload

    Alternatively, you can omit ExecReload and use the default behavior, which kills the service and starts it again.

  5. Check the SysVinit script to see if the service uses a special command to stop the service. For example, the script might contain a stop function that reloads the service:

    reboot() {
      echo "Stopping My Custom Service..."
      /usr/bin/myservice shutdown
    }

    In this example, the /usr/bin/myservice command is the custom service command and stop the service gracefully using the shutdown subcommand. Set the ExecStop parameter to use this command:

    [Service]
    ExecStop=/usr/bin/myservice shutdown

    Alternatively, you can omit ExecStop and use the default behavior, which kills the service.

  6. Review the SysVinit script and identify any additional parameters or functions. Use systemd parameters to replicate any identified SysVinit functions that might be relevant to your service.

Información Relacionada

Parámetros comunes de servicio

Parámetros de la Unidad

Esta sección contiene parámetros que puede utilizar en la sección [Unidad] de un servicio. Estos parámetros son comunes a otras unidades systemd.

Esta lista es una versión resumida. Para una lista completa de estos parámetros y sus unidades, ejecute man systemd.unit.

Descripción

Una cadena de formato libre describiendo el servicio.

Documentación

A space-separated list of URIs referencing documentation for this service or its configuration. Accepted are only URIs of the following types: http://, https://, file:, info:, man:.

Requires

Configures requirement dependencies on other services. If this service gets activated, the units listed here are activated too. If one of the dependent services fails to activate, systemd does not start this service. This option may be specified more than once or you can specify multiple space-separated units.

Wants

Similar to Requires, except failed units do not have any effect on the service.

BindsTo

Similar to Requires, except stopping the dependent units also stops the service.

PartOf

Similar to Requires, except the stopping and restarting dependent units also stop and restart the service.

Conflicts

A space-separated list of unit names that, if running, cause the service not to run.

Before, After

A space-separated list of unit names that configures the ordering of dependencies between services.

OnFailure

A space-separated list of unit names that are activated when this service enters a failed state.

Install Parameters

This section contains parameters you can use in the [Install] section of a service. These parameters are common to other systemd units.

Esta lista es una versión resumida. Para una lista completa de estos parámetros y sus unidades, ejecute man systemd.unit.

Alias

A space-separated list of additional names this service shall be installed under. The names listed here must have the same suffix (i.e. type) as the service filename.

RequiredBy, WantedBy

Defines the service as dependent of another service. This usually define the target to trigger an enabled service to run. These options are analogous to the Requires and Wants in the [Units] section.

Also

Additional units to install or uninstall when this service is installed or uninstalled.

Service Parameters

This section contains parameters you can use in the [Service] section of a service unit. These parameters are specific only to systemd service units.

Esta lista es una versión resumida. Para una lista completa de estos parámetros y sus unidades, ejecute man systemd.unit.

Type

Configures the process start-up type for this service service:

  • simple - The service starts as the main process. This is the default.

  • forking - The service calls forked processes and run as part of the main daemon.

  • oneshot - Similar to simple, except the process must exit before systemd starts follow-up services.

  • dbus - Similar to simple, except the daemon acquires a name of the D-Bus bus.

  • notify - Similar to simple, except the daemon sends a notification message using sd_notify or an equivalent call after starting up.

  • idle - Similar to simple, except the execution of the service is delayed until all active jobs are dispatched.

RemainAfterExit

A boolean value that specifies whether the service shall be considered active even if all its processes exited. Defaults to no.

GuessMainPID

A boolean value that specifies whether systemd should guess the main PID of a service if it cannot be determined reliably. This option is ignored unless Type=forking is set and PIDFile is not set. Defaults to yes.

PIDFile

An absolute filename pointing to the PID file of this daemon. Use of this option is recommended for services where Type=forking. Systemd reads the PID of the main process of the daemon after start-up of the service. Systemd does not write to the file configured here, although it removes the file after the service has shut down.

BusName

A D-Bus bus name to reach this service. This option is mandatory for services where Type=dbus.

ExecStart

The commands and arguments executed when the service starts.

ExecStartPre, ExecStartPost

Additional commands that are executed before or after the command in ExecStart.

ExecReload

The commands and arguments to execute when the service reloads.

ExecStop

The commands and arguments to execute when the service stops.

ExecStopPost

Additional commands to execute after the service stops.

RestartSec

The time in seconds to sleep before restarting a service.

TimeoutStartSec

The time in seconds to wait for the service to start.

TimeoutStopSec

The time in seconds to wait for the service to stop.

TimeoutSec

A shorthand for configuring both TimeoutStartSec and TimeoutStopSec simultaneously.

RuntimeMaxSec

A maximum time in seconds for the service to run. Pass infinity (the default) to configure no runtime limit.

Restart

Configures whether to restart the service when the service’s process exits, is killed, or reaches a timeout:

  • no - The service will not be restarted. This is the default.

  • on-success - Restart only when the service process exits cleanly (exit code 0).

  • on-failure - Restart only when the service process does not exit cleanly (node-zero exit code).

  • on-abnormal - Restart if the process terminates with a signal or when a timeout occurs.

  • on-abort - Restart if the process exits due to an uncaught signal not specified as a clean exit status.

  • always - Always restart.

Mapping runlevels to targets

Systemd targets serve a similar purpose to SysVinit runlevels but act a little differently. Each target has a name instead of a number and each serves a specific purpose. Systemd implements some targets by inheriting all of the services of another target and adding additional services to it. Some systemd targets mimic the common sysvinit runlevels, which means you can switch targets with the familiar telinit RUNLEVEL command. The runlevels assigned a specific purpose on vanilla Fedora installs (0, 1, 3, 5, and 6) have a 1:1 mapping with a specific systemd target.

However, this is not the case for user-defined runlevels 2 and 4. To make use of those runlevels, create a new named systemd target such as /etc/systemd/system/$YOURTARGET that takes one of the existing runlevels as a base, make a directory /etc/systemd/system/$YOURTARGET.wants, and then symlink the additional services to enable into that directory.

The following is a mapping of SysVinit runlevels to systemd targets.

Table 1. Runlevel to target mapping
Sysvinit Runlevel systemd Target Notes

0

runlevel0.target, poweroff.target

Halt the system.

1, s, single

runlevel1.target, rescue.target

Single user mode.

2, 4

runlevel2.target, runlevel4.target, multi-user.target

User-defined/Site-specific runlevels. By default, identical to 3.

3

runlevel3.target, multi-user.target

Multi-user, non-graphical. Users can usually login via multiple consoles or via the network.

5

runlevel5.target, graphical.target

Multi-user, graphical. Usually has all the services of runlevel 3 plus a graphical login.

6

runlevel6.target, reboot.target

Reboot

emergency

emergency.target

Emergency shell

Mapeo de comandos de servicio

La siguiente tabla muestra el equivalente systemd de los comandos SysVinit.

Todas las versiones recientes de systemctl asumen el sufijo .service si se deja fuera el nombre del servicio. Por ejemplo, systemctl start frobozz.service es lo mismo que systemctl start frobozz.
Comando Sysvinit Comando systemd Notas

service frobozz start

systemctl start frobozz

Usado para arrancar un servicio (no se mantiene en el reinicio)

service frobozz stop

systemctl stop frobozz

Usado para parar un servicio (no se mantienen en el reinicio)

service frobozz restart

systemctl restart frobozz

Usado para parar y después arrancar un servicio

service frobozz reload

systemctl reload frobozz

Cuando está soportado, recarga el archivo config file sin interrumpir las operaciones pendientes.

service frobozz condrestart

systemctl condrestart frobozz

Reinicia si el servicio ya está corriendo.

service frobozz status

systemctl status frobozz

Le dice si un servicio está actualmente corriendo.

ls /etc/rc.d/init.d/

systemctl o systemctl list-unit-files --type=service o
ls /lib/systemd/system/*.service /etc/systemd/system/*.service

Usado para listar los servicios que pueden ser iniciados o parados
Usado para listar todos los servicios y otras unidades

chkconfig frobozz on

systemctl enable frobozz

Enciendo el servicio para iniciarse en el próximo arranque u otro disparador.

chkconfig frobozz off

systemctl disable frobozz

Apaga el servicio para el próximo reinicio u otro disparador.

chkconfig frobozz

systemctl is-enabled frobozz

Usado para comprobar si un servicio está configurado para arrancar o no en el entorno actual.

chkconfig --list

systemctl list-unit-files --type=service o ls /etc/systemd/system/*.wants/

Imprime una tabla de servicios que lista que niveles de ejecución están configurados para activar o desactivar

chkconfig --list | grep 5:on

systemctl list-dependencies graphical.target

Imprime una tabla de los servicios que serán iniciados cuando se arranque en modo gráfico

chkconfig frobozz --list

ls /etc/systemd/system/*.wants/frobozz.service

Usado para listar en que niveles está configurado este servicio para activar o desactivar

chkconfig frobozz --add

systemctl daemon-reload

Usado cuando usted crea un nuevo fichero de servicio o modifica cualquier configuración

All /sbin/service and /sbin/chkconfig commands listed in the table continue to work on systemd-based systems and are translated to native equivalents as necessary. The only exception is chkconfig --list.

Recursos Adicionales