Open main menu

DAVE Developer's Wiki β

Changes

XELK-AN-008: How to use systemd on an Embedded system

8,765 bytes added, 15:06, 16 February 2023
Wired interface
{{AppliesToAxelEsatta}}
{{AppliesToAxelLite}}
{{AppliesToAXEL Lite AN}}
{{AppliesToSMARX AN}}
{{AppliesToSBCX}}
{{AppliesToSBC Axel AN}}
{{InfoBoxBottom}}
Starting from [[Axel_Embedded_Linux_Kit_(XELK)#XELK_4.0.0|XELK 4.0.0]] the root file system generated by NXP Yocto recipes produces a root file system using [https://www.freedesktop.org/wiki/Software/systemd/ systemd].
Systemd systemd is a ''System and Service Manager'' which has enough different settings and configuration from systemV SystemV(SysV) which was used on all XELK BSPs up to [[Axel_Embedded_Linux_Kit_(XELK)#XELK_3.0.0|XELK 3.0.0]].
{{ImportantMessage|text=This application note '''is not a complete systemd user's guide''' but collects some useful hints that can be used for getting familiar with Systemdsystemd. There is a plenty of documentation and User's Guide available for systemd, but some simple example examples - that can be found here below - may simplify the systemd approach for beginners.}}
== Brief description Architecture ==Systemd manages not only services but many different objects called '''Unit'''. Unit are related to the resources that systemd can manage. Unit configurations are defined into the ''Unit files''.
Units categoris Here below, a picture (identified by from [https://en.wikipedia.org/wiki/Systemd#Core_components_and_libraries wikipedia]) showing the file extension) main systemd components: [[File: Systemd_components.png]] == Configuring systemd == The most used commands on a Linux embedded system arethe commands used for:start a service, looking at logging, evalutate the boot time and configuring the network interface.
In the following paragraphs, there are the related commands used for these tasks.service .target .socket .device .mount .automount .swap .path .timer .snapshot .slice .scope
Major insteresting Units are '''=== Manage services''' and '''targets'''. They will be analyzed in the following paragraphs.===
== Services ==<code>systemctl</code> is the main command utility and primary tool for managing the systemd daemons/services such as ''start, restart, stop, enable, disable, reload & status''.
It is possible to display all '''started''' services with the following userspace command:
systemctl -t service --all
=== Other useful = service commands ====
Starting a service from userspace:
systemctl disable ''<service_name>''
== Targets == mask a service ====
Targets are used by systemd There is a third level for having stopping a synchronization mechanism between different services at boot time or during runtime changesservice other than ''stop'' and ''disable'': it is the command <code>mask</code>.
They can be used for set It stops the system service and it will not possible to start it again using ''start''. Using <code>systemctl</code> it is possbile to ''mask/unmask'' a new state.service:
All services linked to a ''target'' are linked to the modification to the same target<pre>root@imx6qxelk:~# systemctl mask emergencyCreated symlink /etc/systemd/system/emergency. These can be seen in a similar way of SystemV ''runlevels'' with many other added functionalitiesservice → /dev/null.</pre>
=== Target and runlevels ===If we will try to start it:<pre>root@imx6qxelk:~# systemctl start emergencyFailed to start emergency.service: Unit emergency.service is masked.</pre>
Here below there is In this way, the service will not be used as a list of power on/off targets and related SystemV runlevels:dependency in the ''Unit''
{| class="wikitable"The reverse command is <code>unmask</code>:|-<pre>! Description !! SystemV (runlevel) !! Systemd (target)root@imx6qxelk:~# systemctl unmask emergency|-| System halt || 0 || runlevel0.target, poweroff.target|-| Single user mode || 1, s, single || runlevel1.target, rescue.target|-| Multi user || 2 || runlevel2.target, multi-user.target|-| Multi user with network || 3 || runlevel3.target, multi-user.target|-| Experimental || 4 || runlevel4.target, multi-user.target|-| Multi user with network, graphical mode || 5 || runlevel5.target, graphical.target|-| Reboot || 6 || runlevel6Removed /etc/systemd/system/emergency.target, rebootservice.target|}</pre>
<code>multi-user</code> target can be identified as the <code>runlevel 3</code>.==== Migrating from SystemV to systemd ====
On the ===== start =====
/etc/systemd/systemConsidering a SystemV <code>script</code> executing the ''start()''function as in the following example:<target_namepre>''start() { echo "Starting My Custom Service..target.wants" /usr/bin/myservice -D}</pre>
directory there The related command is a list of services related executed in the custom service <code>/usr/bin/myservice</code> with the same '''-D''' parameter. It is possibile to that target. For exampleuse the <code>ExecStart=</code>:
<pre>
root@imx6qxelk:~# ls /etc/systemd[Service]ExecStart=/systemusr/multi-user.target.wantsbin/atd.service busybox-syslog.service gpuconfig.service ofono.service systemd-networkd.serviceavahi-daemon.service connman.service mytest.service psplash-quit.service systemd-resolved.servicebusybox-klogd.service crond.service ntpdate.service remotemyservice -fs.targetD
</pre>
=== Active targets == restart =====
It is possible to display all active targets withThe same SystemV script may use special commands for restarting the service like <code>reboot()</code> function:
systemctl -t target<pre>reboot() { echo "Reloading My Custom Service..." /usr/bin/myservice reload}</pre>
Changing a targetwhich is equivalent to use <code>ExecReload=</code>:
systemctl isolate graphical<pre>[Service]ExecReload=/usr/bin/myservice reload</pre>
The actual target is shown with:===== stop =====
systemctl get-defaultThe <code>stop()</code> function in the script will become <code>ExecStop=</code>:
Changing the default targetSystemV:
systemctl set-default multi-user<pre>stop() { echo "Stopping My Custom Service..." /usr/bin/myservice shutdown}</pre>
== Unit files ==For a complete information on '''Unit''' please look to the [httpssystemd://www.freedesktop.org/software/systemd/man/systemd.unit.html documentation page]
Here below you can find an extract for the main used topics and configuration descriptions.<pre>[Service]ExecStop=/usr/bin/myservice shutdown</pre>
=== Location Path Configuring the network interfaces===
Units are configured by One of the most systemd configuration used is the ''systemd'Network configuration''' using configuration files that can be found in different directories. Each of them has different priority and behaviour:
* <code>/lib/==== Wired interface ====systemd/system</code>uses a slightly different configuration mechanism than SystemV. The configuration file is the following one with an example of configuration:
This directory stores a copy of configuration files. This is the default destination for new installed configuration file. Typically files in this directory should not be modified by the user/etc/systemd/network/20-eth0.network
* <code>/etc/systemd/system</codepre>[Match]Name=eth0
This is # Prevent the directory where to store a new ''Unit'' or to modify an existing one. The files present in this directory have interface loading if the highest priority.kernel boots from nfsKernelCommandLine=!nfsroot
* <code>/run/systemd/system</code>[Network]The files present in this directory have higher priority only respect the ones on <code>/lib/systemd/system</code>Address=192. Systemd creates these configuration files dinamically at runtime; modification on this directory can be used for testing a runtime behaviour for a ''Unit'' but all modifications will be lost at next boot168.0.120Gateway=192.168.0.254DNS=192.168.0.1#DNS=8.8.8.8
=== [Unit] section options ===</pre>
This section is used for defining the metadata and relations between different ''Unit'Note:'''
Please find below The DNS is used only if the main properties description:<code>systemd-resolved</code> service is enabled and the <code>/etc/resolv.conf</code> has a symbolic link to <code>/run/systemd/resolve/stub-resolv.conf</code>
Description=: <pre>ln -sf /run/systemd/resolve/stub-resolv.conf /etc/resolv.conf</pre>
Name and functionActivate the new network configuration restarting the <code>systemd</code> services:
Documentation=: systemctl restart systemd-networkd systemctl restart systemd-resolved
URI for the documentation==== Wireless interface ====
Requires===== wpa_supplicant =====wpa_supplicant provides different services on systemd:
List of * <code>wpa_supplicant.service</code> uses D-Bus, recommended with the ''UnitsNetworkManager'' dependencies* <code>wpa_supplicant@interface. For successfully executing this service</code> uses the interface name (like ''Unit'', all listed dependency should be activated without errors, otherwise this Unit return ''failwlan0'') as parameter and executes the wpa_supplicant daemon on that interface. The configuration file is <code>/etc/wpa_supplicant/wpa_supplicant-interface.conf</code>
Wants=For enabling the interface at boot time it is required to ''enable'' the service:
Similar to a ''Requires'' but weaker. If the ''Unit'' listed are not found or return fail, this ''Unit'' are executed anyway. this is the recommended method to be used. systemctl enable wpa_supplicant@interface
BindsTo=:==== wlan configuration example =====
Similar to Assuming ''Requireswlan0'' but it does a Stop for as the ''Unit'' when wireless interface name, the listed ''Unit'' configuration file examples are terminated.the following one:
Before=:/etc/systemd/network/wlan0.network
The ''Unit'' listed will not be executed until this ''Unit'' will not change to ''started''<pre>[Match]Name=wlan0[Network]# Uncomment for DHCP#DHCP=yesAddress=192. This is used for an order of Units executions168.1.120Gateway=192.168.1.254DNS=8.8.8.8
After=:</pre>
The ''Unit'' listed will be started before this ''Unit''. This is used for an order of Units executions /etc/wpa_supplicant/wpa_supplicant-wlan0.conf
Conflicts<pre>ctrl_interface=/var/run/wpa_supplicanteapol_version=1ap_scan=1fast_reauth=1
The ''Unit'' listed cannot be executed simultaneously to this ''Unit''.network={ ssid="SSID1" psk="password1" priority=1}network={ ssid="SSID2" psk="password2" priority=2}</pre>
=== [Install] section options ===For automatically creating the network configuration, the following command can be used:
This section is optional but is commonly used for defining a ''Unit'' behaviour when it will be executed during ''enable'' or ''disable'' commands wpa_passphrase <ESSID> <passphrase> >> /etc/wpa_supplicant/wpa_supplicant-wlan0.conf
WantedBy=Then, the service should be enabled on the ''wlan0'' interface for let systemd to start it using the (just) created configuration file <code>wpa_supplicant-wlan0.conf</code>:
This is similar to the <code>Wants=</code> on ''[Unit]'' section but allows to mantain the top ''Unit'' more ''clean''. systemctl enable wpa_supplicant@wlan0
When the ''Unit'' will be enabled, a directory on <code>/etc/== Logging with systemd/system</code> will be created with the ''Unit'' name adding (<code>.wantsjournalctl</code> to the name. Inside this directoty a symbolic link to the ''Unit'' is created.) ==
Example:systemd has its own logging process called <code>journal</code> avoiding to start the ''syslog'' daemon. For the status information it is possible to use <code>journalctl</code>.
* current ''Unit'' has <code>WantedBy=multi-user.targetjournalctl</code> * ha many command line switches, to customize its behavior and filter log data (a directory <code>good reference can be found [https://etcwww.digitalocean.com/systemdcommunity/systemtutorials/multihow-to-use-journalctl-user.target.wants</code> will be created * the symbolic link to the ''Unit'' will be created inside the new directory* disabling the ''Unit'' the symbolic link is deleted -view-and the relation is then removed.-manipulate-systemd-logs here]
RequiredBy=:For example, to display the new log messages (similar to <code>tail -f /var/log/messages</code>) add the <code>-f</code> option
This is similar to With <code>WantedBy=-p</code> but a dependency cause a it''fail'' if not satisfied. When s possible to set the log ''Unit'' is enabled, a directory with added ''.requirespriority'' will be created
Also=:journalctl -p LEVEL
When Where <code>LEVEL</code> can be the ''Unit'' is enabled, also number or keyword of the listed Units are enabled toofollowing table (sorted from higher to lower priority).Specifying a priority will display messages marked with that priority or higher
{| class=== Specific sections ==="wikitable"|-! Value !! Keyword |-| 0 || emerg |-| 1 || alert |-| 2|| crit |-| 3|| err |-| 4|| warning |-| 5|| notice |-| 6|| info |-| 7|| debug |}''<time>''User can filter by arbitrary time limits using the <code>--since</code> and <code>--until</code> options, which restrict the entries displayed to those after or before the given time, respectively. E.g.:
Some ''Unit'' have specific sections based on their characteristic. The most important is the section '''Service''' related to the Unit <codepre>root@imx6qxelk:/home# journalctl --since "20 min ago" -- Logs begin at Wed 2019-06-26 13:22:41 UTC, end at Mon 2019-07-08 13:22:01 UTC. --Jul 08 13:11:54 imx6qxelk kernel: ERROR: v4l2 capture: slave not found!Jul 08 13:11:54 imx6qxelk kernel: ERROR: v4l2 capture: slave not found!Jul 08 13:11:54 imx6qxelk kernel[551]: [ 3157.796945] ERROR: v4l2 capture: slave not found!Jul 08 13:11:54 imx6qxelk kernel[551]: [ 3157.801690] ERROR: v4l2 capture: slave not found!Jul 08 13:11:54 imx6qxelk kernel: ERROR: v4l2 capture: slave not found!Jul 08 13:11:54 imx6qxelk kernel: ERROR: v4l2 capture: slave not found!Jul 08 13:11:54 imx6qxelk kernel[551]: [ 3157.859371] ERROR: v4l2 capture: slave not found!Jul 08 13:11:54 imx6qxelk kernel[551]: [ 3157.service864406] ERROR: v4l2 capture: slave not found!</codepre>
Please find more information at For displaying the [https:log related to a specific ''Unit'', use the <code>-u<//wwwcode> option, e.freedesktopg.org/software/systemd/man/systemd.service.html# documentation page]:
==== <pre>root@imx6qxelk:/home# journalctl -u systemd-networkd -- Logs begin at Wed 2019-06-26 13:22:41 UTC, end at Mon 2019-07-08 13:25:01 UTC. --Jul 05 11:02:13 imx6qxelk systemd-networkd[Service572] section ====: Enumeration completedJul 05 11:02:13 imx6qxelk systemd-networkd[572]: eth0: IPv6 enabled for interface: SuccessJul 05 11:02:15 imx6qxelk systemd-networkd[572]: eth0: Gained carrierJul 05 11:02:16 imx6qxelk systemd-networkd[572]: eth0: Gained IPv6LLJul 05 11:02:29 imx6qxelk systemd-networkd[572]: eth0: Configured</pre>
Used for providing configurations for For displaying the ''services''.log related to a specific <code>/dev</code> device, just add it to the command line:
===== Type =====<pre>root@imx6qxelk:~# journalctl /dev/fb0-- Logs begin at Wed 2019-06-26 13:22:41 UTC, end at Thu 2019-07-11 09:07:01 UTC. --Jun 26 13:22:41 imx6qxelk kernel: mxc_sdc_fb fb@0: registered mxc display driver ldbJun 26 13:22:41 imx6qxelk kernel: mxc_sdc_fb fb@0: using reserved memory region at 0x8e000000, size 2 MiBJun 26 13:22:41 imx6qxelk kernel: mxc_sdc_fb fb@0: assigned reserved memory node splashscreenJun 26 13:22:41 imx6qxelk kernel: mxc_sdc_fb fb@0: using memory region 0x8e000000 0x8e1fffff</pre>
For displaying the log related to a user ID, use <code>Type_UID=</code> uses one of the (main) following values:parameter
simple<pre>root@imx6qxelk:~# id messagebusuid=995(messagebus) gid=993(messagebus) groups=993(messagebus)root@imx6qxelk:~# journalctl _UID=993-- Logs begin at Wed 2019-06-26 13:22:41 UTC, end at Thu 2019-07-11 09:14:01 UTC. --Jul 10 14:42:48 imx6qxelk systemd-timesyncd[423]: Network configuration changed, trying to establish connection.Jul 10 14:43:02 imx6qxelk systemd-timesyncd[423]: Network configuration changed, trying to establish connection.Jul 11 07:38:31 imx6qxelk systemd-timesyncd[423]: Synchronized to time server 216.239.35.8:123 (time3.google.com).</pre>
Default configuration for a service when specified <code>ExecStarts=</code>= Analyze the boot time==
forkingBoot time analysis is one of the most important and interesting activity for an embedded system:systemd provide an userspace command called <code>systemd-analyze</code> to help in this (hard) task
the process will call a The <code>fork()systemd-analyze</code> when starts causing the father to exit. This informs systemd that command list how many services are running on the process is still alive even if system and how long they took for starting at the father has been terminatedlast boot.
oneshot<code>systemd-analyze</code> provides a good level of boot time information for further optimizations:
the process has a very short execution === time and then systemd should wait for its termination before continuing with other Units. this is the default configuration if <code>ExecStarts=</code> is not specified.==
dbus:The <code>time</code> parameter gives the total amount of seconds used for starting the kernel and reaching the userspace.
the Unit will acquire the name on the D<pre>root@imx6qxelk:~# systemd-Busanalyze time Startup finished in 5.109s (kernel) + 4.771s (userspace) = 9. systemd will continue to process the other Units880s</pre>
notify=== blame ===The <code>blame</code> parameter gives the list of started services and how long they took for starting:
the <pre>root@imx6qxelk:~# systemd-analyze blame 3.608s dev-mmcblk0p2.device 547ms systemd-remount-fs.service 545ms systemd-vconsole-setup.service 544ms kmod-static-nodes.service 503ms systemd-udev-trigger.service 426ms systemd-journal-flush.service will notify when completely initialized 407ms tmp. Systemd will wait for the notification before continuing with the following Unitsmount 371ms systemd-logind.service 327ms systemd-journald.service 317ms systemd-networkd.service 275ms systemd-timesyncd.service 257ms systemd-sysctl.service 204ms ofono.service 203ms systemd-modules-load.service 194ms sys-kernel-config.mount 188ms sys-kernel-debug.mount 177ms sshd.socket 161ms psplash-start.service 138ms systemd-random-seed.service 138ms sys-fs-fuse-connections.mount 129ms systemd-udevd.service 129ms systemd-update-utmp.service 128ms systemd-tmpfiles-setup-dev.service 124ms rc-local.service 98ms systemd-tmpfiles-setup.service 91ms psplash-quit.service 90ms systemd-resolved.service 89ms systemd-backlight@backlight:backlight.service 63ms dev-mmcblk0p1.device 41ms var-volatile.mount 33ms systemd-update-utmp-runlevel.service</pre>
idle:=== critical-chain ===The <code>critical-chain</code> parameter shows the startup process flow and the time consumed by each service.
the service will not be executed until all active jobs are dispatched.Here below a picture showing an example of critical path:
===== Other options =====[[File:Systemd-analyze-critical-chain.png|800px]]
ExecStarts=: = Services and targets ==systemd manages not only services but many different objects called '''Unit'''. Unit are related to the resources that systemd can manage. Unit configurations are defined into the ''Unit files''.
Specifiy the full path and parameters for executing a service. If preceded Units categoris (identified by a "-" this inform that the command failure can be accepted.file extension) are:
ExecStartsPre=: .service .target .socket .device .mount .automount .swap .path .timer .snapshot .slice .scope
used for adding more commands to be executed before starting the main processMajor interesting Units are '''services''' and '''targets'''. May They will be used multiple times specifying analyzed in the complete path and command parametersfollowing paragraphs.
ExecReload=:== Targets ===
commands to be executed Targets are used by systemd for reloading the service configurationhaving a synchronization mechanism between different services at boot time or during run-time changes.
ExecStop=:They can be used for set the system to a new state.
commands required for stopping All services linked to a ''target'' are linked to the servicemodification to the same target. If missing, the service will These can be killedseen in a similar way of SystemV ''runlevels'' with many other added functionalities.
==== Target and ExecStopPostrunlevels ====:
commands to be executed after the service has been stopped..Here below there is a list of power on/off targets and related SystemV runlevels:
RestartSec{| class=:"wikitable"|-! Description !! SystemV (runlevel) !! systemd (target)|-| System halt || 0 || runlevel0.target, poweroff.target|-| Single user mode || 1, s, single || runlevel1.target, rescue.target|-| Multi user || 2 || runlevel2.target, multi-user.target|-| Multi user with network || 3 || runlevel3.target, multi-user.target|-| Experimental || 4 || runlevel4.target, multi-user.target|-| Multi user with network, graphical mode || 5 || runlevel5.target, graphical.target|-| Reboot || 6 || runlevel6.target, reboot.target|}
time to sleep (seconds) before restarting <code>multi-user</code> target can be identified as the service<code>runlevel 3</code>.
Restart=Into the following directory:
restart conditions for /etc/systemd to be checked before restarting the service (if terminated)/system/''<target_name>''. Can be set to "always","on-success", "on-failure", "on-abnormal", "on-abort", or "on-watchdog"target. wants
TimeoutSec=:there is a list of services related to that target.
time to sleep during ''start'' or ''stop'' before considering the process failed on start or stop. Start and stop timeout can be set with different values using <code>TimeoutStartSec=</code> nad e <code>TimeoutStopSec=</code> === Creating a new service === For creating a new service the following file has to be created:  /etc/systemd/system/''<service_name>''.service ==== Service example ==== The following paragraph shows how to create a new service called '''myservice''' executing a command (in our case ''iperf3'') /etc/systemd/system/myservice.service
<pre>
[Unit]Description=My ServiceAfter=network.targetStartLimitIntervalSec=0 [Service]Type=simpleRestart=0RestartSec=1User=rootExecStart=@imx6qxelk:~# ls /etc/usrsystemd/binsystem/iperf3 multi-suser.target.wants/atd.service busybox-syslog.service gpuconfig.service ofono.service systemd-networkd.service[Install]avahi-daemon.service connman.service mytest.service psplash-quit.service systemd-resolved.serviceWantedBy=multibusybox-klogd.service crond.service ntpdate.service remote-userfs.target
</pre>
===== Basic settings =Active targets ====
After It is possible to display all active targets with:
The executed command (''iperf3'') requires the network interface to be already active, so we use <code>After</code> for this purpose. systemctl -t target
RestartChanging a target
This is configured with ''0'' for disabling the service after it has been run. systemctl isolate graphical
RestartSecThe actual target is shown with:
time sleep before restarting the service; systemctl get-default value is 100ms.
UserChanging the default target:
configures the '' systemctl set-default multi-user'' or ''group'' used for executing the service.
ExecStart=== Unit files ===For a complete information on '''Unit''' please look to the [https://www.freedesktop.org/software/systemd/man/systemd.unit.html documentation page]
command to be executed when Here below you can find an extract for the service will be started (in our case ''iperf3'')main used topics and configuration descriptions.
WantedBy==== Location Path ====
defines which target is used related to the service startedUnits are configured by ''systemd'' using configuration files that can be found in different directories. Each of them has different priority and behaviour:
{| class===== running "wikitable"|-! Path !! Description|-| <code>/lib/systemd/system</code> || This directory stores a copy of configuration files: this is the default destination for new installed configuration file. Typically files in this directory should not be modified by the user.|-| <code>/etc/systemd/system</code> || This is the directory where to store a new ''Unit'' or to modify an existing one. The files present in this directory have the highest priority.|-| <code>/run/systemd/system</code> || The files present in this directory have higher priority only respect the ones on <code>/lib/systemd/system</code>. Systemd creates these configuration files dinamically at runtime; modification on this directory can be used for testing a runtime behaviour for a service =====''Unit'' but all modifications will be lost at next boot.|}
Starting the service from userspace:==== [Unit] section options ====
systemctl start myserviceThis section is used for defining the metadata and relations between different ''Unit''
Starting Please find below the service at boot timemain properties description:
systemctl enable myservice{| class="wikitable"|-! Property !! Function|-| Description=: || Name and function|-| Documentation=: || URI for the documentationvv|-| Requires=: || List of ''Units'' dependencies. For successfully executing this ''Unit'', all listed dependency should be activated without errors, otherwise this Unit return ''fail''.|-| Wants=: || Similar to a ''Requires'' but weaker. If the ''Unit'' listed are not found or return fail, this ''Unit'' are executed anyway. this is the recommended method to be used.|-| BindsTo=: || Similar to ''Requires'' but it does a Stop for the ''Unit'' when the listed ''Unit'' are terminated.|-| Before=: || The ''Unit'' listed will not be executed until this ''Unit'' will not change to ''started''. This is used for an order of Units executions.|-| After=: || The ''Unit'' listed will be started before this ''Unit''. This is used for an order of Units executions.|-| Conflicts=: || The ''Unit'' listed cannot be executed simultaneously to this ''Unit''.|}
=== From SystemV to Systemd = [Install] section options ====
==== start ====This section is optional but is commonly used for defining a ''Unit'' behaviour when it will be executed during ''enable'' or ''disable'' commands.
Considering a SystemV {| class="wikitable"|-! Property !! Function|-| WantedBy=: || This is similar to the <code>scriptWants=</code> executing on ''[Unit]'' section but allows to mantain the top ''Unit''start()more ''clean'' function as in the following example:<pre>start() { echo "Starting My Custom Service..." /usr/bin/myservice -D}</pre>
The related command is executed in When the custom service ''Unit'' will be enabled, a directory on <code>/usretc/binsystemd/myservicesystem</code> will be created with the same '''-D'Unit'' parameter. It is possibile to use the name adding <code>ExecStart=.wants</code>:to the name. Inside this directoty a symbolic link to the ''Unit'' is created.
<pre>[Service]ExecStart=/usr/bin/myservice -D</pre>Example:
* current ''Unit'' has <code>WantedBy==== restart ====multi-user.target</code> * a directory <code>/etc/systemd/system/multi-user.target.wants</code> will be created * the symbolic link to the ''Unit'' will be created inside the new directory* disabling the ''Unit'' the symbolic link is deleted and the relation is then removed.
The same SystemV script may use special commands for restarting the service like |-| RequiredBy=: || This is similar to <code>reboot()WantedBy=</code> functionbut a dependency cause a ''fail'' if not satisfied. When the ''Unit'' is enabled, a directory with added ''.requires'' will be created|-| Also=:|| When the ''Unit'' is enabled, also the listed Units are enabled too.|}
<pre>reboot() { echo "Reloading My Custom Service..." /usr/bin/myservice reload}</pre>==== Specific sections ====
which Some ''Unit'' have specific sections based on their characteristic. The most important is equivalent the section '''Service''' related to use the Unit <code>ExecReload=.service</code>:
<pre>Please find more information at the [Service]ExecReload=https://www.freedesktop.org/usrsoftware/binsystemd/myservice reload<man/pre>systemd.service.html# documentation page]
==== stop = [Service] section =====
The <code>stop()</code> function in Used for providing configurations for the script will become <code>ExecStop=</code>:''services''.
SystemV:====== Type ======
<precode>stop() { echo "Stopping My Custom Service..." /usr/bin/myservice shutdown}Type=</precode>uses one of the (main) following values:
Systemd{| class="wikitable"|-! Value !! Description|-| simple || Default configuration for a service when specified <code>ExecStarts=</code>|-| forking || the process will call a <code>fork()</code> when starts causing the father to exit. This informs systemd that the process is still alive even if the father has been terminated.|-| oneshot:|| the process has a very short execution time and then systemd should wait for its termination before continuing with other Units. this is the default configuration if <code>ExecStarts=</code> is not specified.|-| dbus || the Unit will acquire the name on the D-Bus. systemd will continue to process the other Units|-| notify || the service will notify when completely initialized. systemd will wait for the notification before continuing with the following Units|-| idle || the service will not be executed until all active jobs are dispatched.|}
<pre>[Service]ExecStop=/usr/bin/myservice shutdown</pre>===== Other options ======
{| class="wikitable"|-! Value !! Description|-| ExecStarts= Network Configuration : || Specifiy the full path and parameters for executing a service. If preceded by a "-" this inform that the command failure can be accepted.|-| ExecStartsPre=: || used for adding more commands to be executed before starting the main process. May be used multiple times specifying the complete path and command parameters.|-| ExecReload=: || commands to be executed for reloading the service configuration.|-| ExecStop=: || commands required for stopping the service. If missing, the service will be killed.|-| ExecStopPost=: || commands to be executed after the service has been stopped..|-| RestartSec=: || time to sleep (seconds) before restarting the service.|-| Restart=: || restart conditions for systemd to be checked before restarting the service (if terminated). Can be set to "always","on-success", "on-failure", "on-abnormal", "on-abort", or "on-watchdog". |-| TimeoutSec=: || time to sleep during ''start'' or ''stop'' before considering the process failed on start or stop. Start and stop timeout can be set with different values using <code>TimeoutStartSec=</code> and <code>TimeoutStopSec=</code>|}
One of the most systemd configuration used is the '''Network configuration'''.== Putting it all together: create a new service ==
=== wired interface ===systemd uses For creating a slightly different configuration mechanism than SystemV. The configuration file is new service the following one with an example of configurationfile has to be created:
/etc/systemd/networksystem/eth0''<service_name>''.networkservice
<pre>[Match]Name=eth0 # Prevent the interface loading if the kernel boots from nfsKernelCommandLine=!nfsroot [Network]Address=192.168.0.120GatewayService example =192.168.0.254DNS=192.168.0.1#DNS=8.8.8.8
The following paragraph shows how to create a new service called <code>iperf3</precode>executing the iperf3 command in server mode
'''Note:''' The DNS is used only if the <code>systemd-resolved</code> service is enabled and the <code> /etc/resolv.conf</code> has a symbolic link to <code>/run/systemd/resolvesystem/stub-resolviperf3.conf</code>service
<pre>
ln -sf /run/systemd/resolve/stub-resolv.conf /etc/resolv[Unit]Description=iperf3 server modeAfter=network.conftarget</pre>StartLimitIntervalSec=0
=== wireless interface === ==== wpa_supplicant ====wpa_supplicant provides different services on systemd: * <code>wpa_supplicant.service</code> uses D-Bus, recommended with the ''NetworkManager''* <code>wpa_supplicant@interface.service</code> uses the interface name (like ''wlan0'') as parameter and executes the wpa_supplicant daemon on that interface. The configuration file is <code>/etc/wpa_supplicant/wpa_supplicant-interface.conf</code> For enabling the interface at boot time it is required to ''enable'' the service  systemctl enable wpa_supplicant@interface ==== Configuration example ==== Assuming ''wlan0'' as the wireless interface name, the configuration file examples are the following one:  /etc/systemd/network/wlan0.network <pre>[MatchService]NameType=wlan0simple[Network]# Uncomment for DHCP#DHCPRestart=yes0AddressRestartSec=192.168.1.120GatewayUser=192.168.1.254rootDNSExecStart=8.8.8.8/usr/bin/iperf3 -s
[Install]
WantedBy=multi-user.target
</pre>
/etc/wpa_supplicant/wpa_supplicant-wlan0.conf=== Basic settings ===
{| class="wikitable"|-! Parameter !! Description|-| After || The executed command (''iperf3'') requires the network interface to be already active, so we use <precode>After</code> for this purpose.ctrl_interface=/var/|-| Restart || This is configured with ''0'' for disabling the service after it has been run/wpa_supplicant.|-| RestartSec || time sleep before restarting the service; default value is 100ms.|-| User || configures the ''user'' or ''group'' used for executing the service.|-| ExecStart || command to be executed when the service will be started (in our case ''iperf3'').eapol_version=1|-ap_scan=1| WantedBy || defines which target is used related to the service started. fast_reauth=1|}
network={ ssid="SSID1" psk="password1" priorityRunning a service =1}network={ ssid="SSID2" psk="password2" priority=2}</pre>
For automatically creating Starting the network configuration, the following command can be usedservice from userspace:
wpa_passphrase <ESSID> <passphrase> >> /etc/wpa_supplicant/wpa_supplicant-wlan0.confsystemctl start iperf3
Then, Starting the sergice should be enabled on the ''wlan0'' interface for instructing systemd to start it using the (just) created configuration file <code>wpa_supplicant-wlan0.conf</code>service at boot time:
systemctl enable wpa_supplicant@wlan0iperf3
8,221
edits