Entender y administrar systemd

Christopher Engelhard, Kamil Páral, Caleb McKee Versión unknown Last review: 2020-08-05
Aprender los principios básicos del sistema de inicio systemd: como configurarlo y usarlo para administrar el sistema.

Entender 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

  • Admite la creación de 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:

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

device (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 (de intercambio) en el sistema.

target

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

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

timer (temporizador)

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

snapshot (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).

scope (alcance)

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

Iniciar, detener y consultar servicios systemd

Usted puede llevar a cabo diversas tareas de administración para controlar los servicios systemd utilizando el comando systemctl. Lo siguiente es un conjunto de los comandos ejemplo para demostrar como usar systemctl para administrar servicios systemd.

Requisitos previos

Usted tiene que acceder con un usuario con permisos a nivel de administrador.

Procedimiento

Los siguientes comando controlan el servicio foo:

  • Activar un servicio inmediatamente:

    # systemctl start foo
  • Desactivar un servicio inmediatamente:

    # systemctl stop foo
  • Reiniciar un servicio:

    # systemctl restart httpd
  • Mostrar el estado de un servicio, incluyendo si está corriendo o no:

    # systemctl status foo
  • Habilitar un servicio para ser iniciado en el arranque:

    # systemctl enable foo
  • Deshabilitar un servicio para que no se inicie durante el arranque:

    # systemctl disable foo
  • Evitar que un servicio se inicie dinámicamente o incluso manualmente a no ser que esté desenmascarado:

    # systemctl mask foo
  • Verificar si un servicio está habilitado o no:

    # systemctl is-enabled foo

Información Relacionada

  • Ejecute man systemctl para más detalles.

Modificar servicios systemd existentes

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

Requisitos previos

  • Usted tiene que acceder con un usuario con permisos a nivel de administrador.

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

Procedimiento

  1. Los servicios Systemd pueden ser modificador 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 del 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, por ejemplo 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

Crear nuevos servicios systemd

Este ejemplo muestra como crear un archivo de unidad para un servicio personalizado. Los archivos personalizados de unidad se ubican en`/etc/systemd/system/` y tienen una extensión .service. Por ejemplo, un servicio personalizado foo utiliza el archivo de unidad /etc/systemd/system/foo.service.

Requisitos previos

  • Usted tiene que acceder con un usuario con permisos a nivel de administrador.

Procedimiento

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

  1. Cree y edite el nuevo archivo de configuración:

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

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

      Description

      Una cadena que describe la unidad. Systemd muestra esta descripción cerca del nombre de la unidad en la interfaz de usuario.

      After

      Define una relación con una segunda unidad. Si usted activa la unidad, systemd la activa solo después de la segunda. Por ejemplo, el servicio foo podría requerir conectividad de red, lo que significa que el servicio foo especifica network.target como una condición After= .

      La sección [Unit] resultante se ve como esto:

      [Unit]
      Description=My custom service
      After=network.target
    2. La sección [Service] proporciona instrucciones sobre como controlar el servicio. El servicio`foo` utiliza los siguientes parámetros:

      Type

      Define el tipo de servicio systemd. En este ejemplo, el servicio foo es un servicio simple, el cual inicia el servicio sin ninguna consideración especial.

      ExecStart

      El comando para ejecutar el inicio del servicio. Esto incluye la ruta completa al comando y los argumentos que modifican el servicio.

      La sección [Service] resultante se parece a esto:

      [Service]
      Type=simple
      ExecStart=/usr/bin/sleep infinity
    3. La sección [Install] proporciona instrucciones sobre como systemd instala el servicio.. El servicio foo usa los siguientes parámetros:

      WantedBy

      Define que servicio dispara el servicio personalizado si está habilitado con systemctl enable. Esto se utiliza mayormente para iniciar el servicio personalizado en el arranque. En este ejemplo, foo.service usa multi-user.target, el cual inicia`foo.service` cuando systemd carga multi-user.target en el arranque.

  3. El archivo completo`foo.service` tiene los siguientes contenidos:

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

    Guarde el archivo.

  4. Para hacer que systemd esté atento al nuevo servicio, recargue sus archivos de servicio

    # systemctl daemon-reload
  5. Inicie el servicio personalizado foo:

    # systemctl start foo
  6. Verifique el estado del servicio para asegurar que el servicio está corriendo:

    $ 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

Convirtiendo los servicios SysVinit a systemd

Los versiones más antiguas de Fedora usan scripts SysVinit para administrar los servicios. Esta sección proporciona algunas directrices sobre como convertir un script SysVinit a un systemd equivalente.

Requisitos previos

  • Usted tiene que acceder con un usuario con permisos a nivel de administrador.

  • Usted tiene un script SysVinit personalizado para convertir a una configuración systemd.

Procedimiento

  1. Identifique los niveles de ejecución en su script SysVinit. Esto está definido normalmente con la directiva chkconfig en la sección comentada al principio del script. Por ejemplo, lo siguiente indica que el servicio está usando los niveles de ejecución 3, 4 y 5:

    # chkconfig: 235 20 80

    systemd utiliza objetivos en lugar de niveles de ejecución. Use la tabla en [converting-sysvinit-services] para mapear los niveles de ejecución a objetivos. En este ejemplo, los niveles de ejecución 2, 3 y 5 son niveles de ejecución multiusuario, de modo que el servicio systemd puede usar lo siguiente:

    [Install]
    WantedBy=multi-user.target

    Si usted habilita el servicio systemd para que inicie al arranque (systemctl enable foo.service), systemd carga el servicio cuando carga el multi-user.target en el momento del arranque.

  2. Identifique los servicios dependientes y los objetivos. Por ejemplo, si el servicio personalizado requiere conectividad de red, especifique network.target como dependencia:

    [Unit]
    Description=My custom service
    After=network.target
  3. Identifique el comando usado para iniciar el servicio en el script SysVinit y convertir esto al systemd equivalente. Por ejemplo, el script podría contener una función start en el siguiente formato:

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

    En este ejemplo, el comando /usr/bin/myservice es el comando de servicio personalizado configurado para demonizar con la opción -D. Establezca el parámetro ExecStart para usar este comando:

    [Service]
    ExecStart=/usr/bin/myservice -D
  4. Verifique el script SysVinit para ver si el servicio usa un comando especial para reiniciar el servicio. Por ejemplo, el script podría contener una función reboot que recarga el servicio:

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

    En este ejemplo, el comando /usr/bin/myservice es el comando del servicio personalizado y recarga el servicio usando el subcomando reload. Establezca el parámetro ExecReload para usar este comando:

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

    Alternativamente, puede omitir ExecReload y usar el comportamiento predeterminado, que mata el servicio y lo inicia otra vez.

  5. Verifique el script SysVinit para ver si el servicio usa un comando especial para parar el servicio. Por ejemplo, el script podría contener una función stop que recarga el servicio:

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

    En este ejemplo, el comando /usr/bin/myservice es el comando del servicio personalizado y detiene el servicio correctamente usando el subcomando shutdown. Establezca el parámetro ExecStop para usar este comando:

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

    Alternativamente, puede omitir ExecStop y usar el comportamiento predeterminado, que mata el servicio.

  6. Revise el script SysVinit e identifique cualquier parámetro adicional o funciones. Use parámetros systemd para replicar cualquier función SysVinit identificada que podría ser relevante para su servicio.

Información Relacionada

Parámetros de servicio común

Unit Parameters

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

This list is a summarized version. For a full list of these parameters and their descriptions, run man systemd.unit.

Description

A free-form string describing the service.

Documentation

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.

This list is a summarized version. For a full list of these parameters and their descriptions, run 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.

This list is a summarized version. For a full list of these parameters and their descriptions, run 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.

Mapeo de niveles de ejecución a objetivos

Los objetivos Systemd sirven a un propósito similar que los niveles de ejecución SysVinit pero actúan un poco diferente. Cada objetivo tiene un nombre en lugar de un número y cada uno sirve a un propósito específico. Systemd implementa algunos objetivos heredando todos los servicios de otro objetivo y añadiéndole servicios adicionales. Algunos objetivos systemd imitan los niveles de ejecución comunes de sysvinit, lo que significa que puede cambiar de objetivo con el familiar comando telinit RUNLEVEL. Los niveles de ejecución que asignaron un propósito específico en las instalaciones básicas de Fedora (0, 1, 3, 5 y 6) tienen un mapeo 1:1 con un objetivo específico systemd.

Sin embargo, este no es el caso de los niveles de ejecución definidos por el usuario 2 y 4. Para hacer uso de estos niveles de ejecución, cree un nuevo objetivo systemd con un nombre como /etc/systemd/system/$YOURTARGET`que toma uno de los niveles de ejecución existentes como base haga un directorio `/etc/systemd/system/$YOURTARGET.wants y después un enlace simbólico a los servicios adicionales para habilitar este directorio.

Los siguiente es un mapeo de los niveles de ejecución SysVinit a los objetivos systemd.

Tabla 1. Mapeo de nivel de ejecución a objetivo
Nivel de ejecución Sysvinit Objetivo systemd Notas

0

runlevel0.target, poweroff.target

Para el sistema.

1, s, single

runlevel1.target, rescue.target

Modo usuarios único.

2, 4

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

Definido por el usuario/Niveles de ejecución específicos del sitio. Predeterminado, idéntico a 3.

3

runlevel3.target, multi-user.target

Multi-user, non-graphical. Los usuarios pueden acceder normalmente por medio de múltiples consolas o por red.

5

runlevel5.target, graphical.target

Multiusuario, gráfico. Normalmente tiene todos los servicios del nivel de ejecución 3 más acceso gráfico.

6

runlevel6.target, reboot.target

Reinicio

emergency

emergency.target

Shell de emergencia

Distribuir instrucciones del servicio

The following table demonstrates the systemd equivalent of SysVinit commands.

All recent versions of systemctl assume the .service suffix if left off the service name. For example, systemctl start frobozz.service is the same as systemctl start frobozz.
Sysvinit Command systemd Command Notes

service frobozz start

systemctl start frobozz

Used to start a service (not reboot persistent)

service frobozz stop

systemctl stop frobozz

Used to stop a service (not reboot persistent)

service frobozz restart

systemctl restart frobozz

Used to stop and then start a service

service frobozz reload

systemctl reload frobozz

When supported, reloads the config file without interrupting pending operations.

service frobozz condrestart

systemctl condrestart frobozz

Restarts if the service is already running.

service frobozz status

systemctl status frobozz

Tells whether a service is currently running.

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

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

Used to list the services that can be started or stopped
Used to list all the services and other units

chkconfig frobozz on

systemctl enable frobozz

Turn the service on, for start at next boot, or other trigger.

chkconfig frobozz off

systemctl disable frobozz

Turn the service off for the next reboot, or any other trigger.

chkconfig frobozz

systemctl is-enabled frobozz

Used to check whether a service is configured to start or not in the current environment.

chkconfig --list

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

Print a table of services that lists which runlevels each is configured on or off

chkconfig --list | grep 5:on

systemctl list-dependencies graphical.target

Print a table of services that will be started when booting into graphical mode

chkconfig frobozz --list

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

Used to list what levels this service is configured on or off

chkconfig frobozz --add

systemctl daemon-reload

Used when you create a new service file or modify any configuration

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