Running a service using systemctl (Linux)

Linux distributions are moving away from their old System V-style startup processes to a newer mechanism, the systemd daemon, and its associated systemctl command-line tool. Services managed by systemd/systemctl require, at a minimum, a configuration file that defines startup and shutdown processes, a type definition that controls how those processes will be handled by the OS, and whatever executables are needed to start or stop the service processes. A bare-bones testdaemon.service configuration file could be as simple as the following:

[Unit]
Description=testdaemon: a simple service example written in Python

[Service]
Type=forking
ExecStart=/usr/bin/python /usr/local/bin/testdaemon.py
ExecStop=/usr/bin/pkill -f testdaemon.py

In the preceding code, the following apply:

  • The Unit/Description entry is simply a short description of the service, often nothing more than a name.

  • Service/Type defines how the startup process will be handled by the systemd daemon. In this case, the execution will be forked, so that whatever process called it is no longer associated with it, and can terminate without stopping the service itself.

  • Service/ExecStart defines a process for starting the service, in this case, by executing the testdaemon.py file as a Python script.

  • Service/ExecStop defines a process for stopping the service, in this case, by killing all of the processes with testdaemon.py in their name.

Assuming that the actual testdaemon class can be imported from some installed package, the testdaemon.py script that starts the service can be as simple as the following:

#!/usr/bin/env python

# - Import the service-class
    from some_package import testdaemon
# - The location of the config-file
    config_file = '/path/to/config.yaml'
# - Create an instance of the service class
    d = testdaemon(config_file)
# - Start it.
    d.start()

With both of those files in place, the commands for starting, restarting, and stopping the service from the command line are, respectively, as follows:

systemctl start testdaemon.service

systemctl restart testdaemon.service

systemctl stop testdaemon.service

The services managed by systemd must be enabled in order to start at boot, as follows:

systemctl enable testdaemon.service

The preceding command requires that an install specification be added to the corresponding systemd .service file, as follows:

...
ExecStop=/usr/bin/pkill -f testdaemon.py

[Install]
WantedBy=multi-user.target

There are a lot of other options available to systemd service configurations, but these bare-bones settings will allow a service to be auto-started and managed with standard command-line tools.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.154.18