systemd - Création d'un service

Création :

Contenu de la page

Références :

Sommaire

1 - Creating new systemd services

This example shows how to create a unit file for a custom service. Custom unit files are located in /etc/systemd/system/ and have a .service extension. For example, a custom foo service uses /etc/systemd/system/foo.service unit file.

Prerequisites

Procedure

This procedure creates a basic configuration file to control the foo service.

  1. Create and edit the new configuration file:

    # nano /etc/systemd/system/foo.service
  2. The next few steps describe each section its parameters to add to the file:

    1. The [Unit] section provides basic information about the service. The foo service uses the following parameters:

      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.

3 -

Common service parameters

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.

1 - Vérification

Unit file verification

After creating a new unit file, it can be helpful to verify that its syntax is correct. This is what the verify subcommand does. It can list directives that are spelled incorrectly and call out missing service units:

[root@david ~]# systemd-analyze verify /etc/systemd/system/backup.service

Adhering to the Unix/Linux philosophy that "silence is golden," a lack of output messages means that there are no errors in the scanned file.


Exemples

1 - Autologin en mode console

$ su -l -c 'adduser kiosk'
Mot de passe : <Entrer_mot_passe_root>
$ cat /etc/systemd/system/getty@tty1.service.d/autologin.conf 
[Service]
ExecStart=
ExecStart=-/sbin/agetty --autologin kiosk --noclear %I $TERM
$ sudo systemctl set-default multi-user.target
$ sudo reboot

2 - Modifier le fichier .bashrc de l'utilisateur kiosk

$ ls -l /dev/fb0
crw-rw---- 1 root video 29, 0 9 déc. 16:36 /dev/fb0
$ su -l -c 'adduser kiosk video'
# Test de la connexion internet avec wget
while ! wget -a --spider http://google.com>&/dev/null; do echo "échec de la connexion internet"; done ; echo "succès de la connexion internet"
# ou bien

# Test de la connexion internet (ipv4 seulement, 3 secondes d'attente max réponse) avec ping
# while ! ping -c 1 -W 3 -4 9.8.8.8 >&/dev/null ; do echo "échec de la connexion internet";done ; echo "succès de la connexion à internet"


# Lancer la page internet
links2 -g http://papy-tux.legtux.org
$ su -l -c 'systemctl restart getty@tty1.service


#!/bin/bash

while ! wget --spider http://google.com >&/dev/null ; do
echo échec
sleep 1
done

echo succès


3 - ou bien si le service ne fait pas appel à l'affichage console : Démarrer un service au démarrage après login automatique

(kiosk)$ cat ~/kiosk.sh
#!/bin/bash
# Commande
.....

$ chmod +x ~/kiok.sh
$ cat /etc/systemd/system/kiosk.service

[Unit]
Description=Détection coupure internet
After=network-online.target

[Service]
ExecStart=/home/kiosk/kiosk.sh
WorkingDirectory=/home/kiosk
StandardOutput=inherit
StanadardError=inherit
Restart=always
User=kiosk

[Install]
WantedBy=multi-user.target
$ sudo systemd-analyze verify /etc/systemd/system/kiosk.service
$ sudo systemctl daemon-reload
$ sudo systemctl start kiosk.service
$ sudo systemctl enable kiosk.service




Services utilisateur

Il est possible d'utiliser un service au niveau utilisateur, dans ce cas, les fichiers de configuration se trouvent dans ~/.config/systemd/user/

Pour un service utilisateur il faut ajouter aux commandes le paramètre –user :

$ systemctl --user enable <nom du service>.service
$ systemctl --user start <nom du service>.service
$ systemctl --user status <nom du service>.service
$ systemctl --user verify <nom du service>.service

Pour créer un service utilisateur :

systemctl --user edit <nom du service>.service --full --force

Pour éditer un service utilisateur :

systemctl --user edit <nom du service>.service --full

Pour ajouter une surcharge (drop-in) sur un service utilisateur :

systemctl --user edit <nom du service>.service