Writing Systemd Service Units

I thought it would be great to have a central thread to compile information on systemd. Please feel free to post any examples of systemd units, or any other info relating to systemd on this thread.

The forum contains many different types of systemd units. If you are looking for a specific type of unit, I have categorized some common types to make examples easier to locate:


Networking:


Network - WiFi:

Intel iwlwifi

Atheros ath10k

Atheros ath10k

Realtek rtl8812au

Ralink rt2800usb


Network - Bluetooth:

Disable Bluetooth by Device ID

Bluetooth Suspend Service

Bluetooth Startup Service


Network - Wired:

Realtek R8168

Broadcom BCM57762 (Thunderbolt to Ethernet)

Ethtool Ethernet configuration service


Network - General:

Suspend/Resume Network Service (basic/simple)


Systemd Mount Units:


NFS Mount Units

NFS Mount Units


Video Related:


KDE Plasma Restart Service

KDE Kwin Compositor Restart Service


Systemd Timers:


Timer - misc

Media library timer


Miscilaneous Services:


Media library service

Clean-n-sleep service

Autoclean Service

i3 screen lock service

Screen Lock Services

USB Device Restart Service

Disable/Enable a device by USB bus path

USB Restart Service

USB Mouse & Keyboard Wake Up Service

Disable Wakeup Events

Hard Drive Idle Service

Disable tlp on suspend service

Touchpad suspend service (psmouse)

Touchpad suspend service (elan)


Here are further links with systemd information:

The ArchWiki - systemd

Red Hat - systemd-targets

Red Hat - systemd unit files

Systemd manpage

Systemd Predefined Targets


13 Likes
System freezing during sleep/suspend
Kernel 4.19.0-3. Not Network after suspending - Gnome Edition
Bluetooth preventing suspend
Trackpad and WIFI are disabled after waking HP laptop from Suspend
Bash script not completing in Application autostart
Having trouble setting up usb wificard
Surface Pro 1796 Wifi not resuming after suspend
[SOLVED] QCA6174 freez after suspend
Closing lid cause network deactivation
Prevent programs from blocking suspend mode
Regression in kernel 4.19.6 prevents my laptop to suspend
MacBook 12, 2017 Challenge: The quest for drivers
Suspend stopped working since a few days
[SOLVED] Laptop cannot resume from sleep
Laptop won't suspend
[SOLVED] WLAN interface -how to disable auto activation
Marvell 88W8897 - Wifi won't Reconnect After Losing Connection
Slow network Awaking from Suspend
Bash script interrupt for lid closed
Use closed laptop as a desktop with another monitor
[Solved] Video/Display Glitch on All Kernels above 4.14
R8168 parameter s5wol ignored
Cannot suspend without `rfkill block bluetooth`
how to use crontab as root
Dual monitor issue when going into power save (monitor off) and back.
BCM43142 - Wifi unavailable after computer suspends
New session button in KDE creates a blank session
Make 'Interference between Headphones and Mouse' Solution Permanent
Autostart script doesn't work
sysctl "dev.cdrom.autoclose=0" problem
[R8168] Wired network connection fails to connect after resume (from suspend)
Some devices failed to suspend, or early wake event detected
Internet Connection Preventing Computer From Suspending
HP Probook 430 G6 Touchpad issues
Manjaro gnome: Text messages shown during system shutdown.
Hardware issues after suspending/sleeping laptop
Apply /etc/X11/xorg.conf.d/whatever.conf upon modprobe/insmod
[SOLVED] BCM43228 - Delay reconnecting to Wi-Fi after resuming from standby
How to execute commands after hibernation?
Vetzki's PRIME tutorial discussion
Wireless USB keyboard/mouse not responding
Keyboard and mouse not working after suspend
Wifi issues on a Macbook Air
I can neither suspend or hibernate...I cannot wake up
How to fix lock screen after changing gdm to LightDM
How to fix lock screen after changing gdm to LightDM
SABnzbd, Sonarr, and NAS
(Solved) Lan not working at boot (JMicron PCI Express Gigabit Ethernet Adapter)
[SYSTEMD BUG?] Can't suspend after suspending one time after fresh boot
Kernel 4.19.0-3. Not Network after suspending - Gnome Edition
[Solved] Network Manager & ? Systemd problems after resume from suspend
[Solved] Network Manager & ? Systemd problems after resume from suspend
USB keyboard not detected during early userspace with autodetect and keyboard hooks present

Originally when I started writing units I read that the units should be made executable. As scripts need to be executable that made perfect sense to me. However, after more research I found that is not required for systemd units, and it is erroneous to set them as executable.

This basic stuff that I have gathered so far:

Recommended Permissions For Systemd Unit Files

System-wide service units should be located in:

/etc/systemd/system

Systemd unit files (and any associated scripts) should have permissions set to 0644 (rw- r-- r--).

Recommended Directories For Systemd Unit Files

Directory For Systemd Unit Files Executed At The System Level.

The recommended location to put "system-wide" unit files is:

/etc/systemd/system 

This is the preferred location for the system administrator to add new system-wide services. Unit files found in this directory location take precedence over any of the other locations on the file system. If you need to modify the system's copy of a unit file, putting a replacement in this directory is the safest and most flexible way to do this.

Directory For Systemd Unit Files Executed At The User Level:

The preferred location to put "USER" unit files is:

~/.config/systemd/user

You should also enable lingering for any user services that need to be available at startup.

loginctl enable-linger $USER

Recommended Directories For Systemd Executed External Scripts

Recommended Directory For External Scripts Executed At The System-Wide Level:

/usr/local/sbin

Scripts located in this directory can only be run by root as it is the system binary directory.

Recommended directories for external scripts executed at a user level by systemd units

One location that can be used for scripts to be run by all "users" is:

/usr/local/bin. 

The preferred location to store scripts that are run as a standard user by systemd is:

~/.local/bin
4 Likes

There was a recent multi-post series on (i think) linux.com on systemd units and such.
I find them pretty straight-forward … but its always good to have nice docs around.
Lemme see if I can find it… ah there we go :

  1. Basic Services: Writing Systemd Services for Fun and Profit
  2. More Advanced Services: Beyond Starting and Stopping
  3. Device-aware services: Reacting to Change
  4. Paths: Monitoring Files and Directories
  5. Timers 1: Setting Up a Timer
  6. Timers 2: Timers: Three Use Cases
  7. Sockets: systemd’s “Socket” Units
10 Likes

(edit)

This is a revised version of the r8168 suspend service that I originally wrote. It requires no external scripts, and only a single service file is required for suspend and resume operations.


Suspend issues with the r8168 adapter can often be resolved by simply switching to the r8169 kernel driver.

It is generally better to use the r8169 kernel driver rather than the r8168 driver.

You can easily switch to the r8169 kernel driver with this command:

sudo mhwd -r pci network-r8168 

Reboot after the driver uninstall is complete.

The r8169 kernel driver should be automatically loaded after you reboot. If after switching to the r8169 driver you are still experiencing suspend issues you can create a service to hopefully resolve problems related to your adapter.

You can check which Realtek driver is loaded with this command:

lsmod | grep r816

How to create a service to automatically disable your network components at suspend, and re-enable them at resume:

Network Restart Service

Create the following file with a root capable text editor:

/etc/systemd/system/network-restart.service

Add the following contents to the file:

#/etc/systemd/system/network-restart.service
#sudo systemctl enable network-restart.service
#sudo systemctl start network-restart.service
#sudo systemctl stop network-restart.service
#sudo systemctl disable network-restart.service
#systemctl status network-restart.service

[Unit]
Description=Network Suspend/Resume Service 
Before=sleep.target
StopWhenUnneeded=yes

[Service]
User=root
Type=oneshot
RemainAfterExit=yes
ExecStartPre=-/usr/bin/sudo -u $USER /bin/bash -lc 'nmcli networking off'
ExecStart=/usr/bin/sleep 1
ExecStart=-/usr/bin/systemctl stop NetworkManager
ExecStart=/usr/bin/sleep 1
ExecStart=-/usr/bin/ip link set enp2s0 down
ExecStart=/usr/bin/sleep 1
ExecStart=-/usr/bin/modprobe -r r8169
ExecStop=-/usr/bin/modprobe r8169
ExecStop=/usr/bin/sleep 2
ExecStop=-/usr/bin/ip link set enp2s0 up
ExecStop=/usr/bin/sleep 2
ExecStop=-/usr/bin/systemctl start NetworkManager
ExecStop=/usr/bin/sleep 1
ExecStop=-/usr/bin/sudo -u $USER /bin/bash -lc 'nmcli networking on'

[Install]
WantedBy=sleep.target

The sleep units in the service may be reduced, (or eliminated) if you do not like the delay it creates. Be aware though, that doing so may reduce the reliability of the service.

Once you have created and saved the service file, enable the service:

sudo systemctl enable network-restart.service

Then reboot the computer.


For others wishing to adapt this service to their installation (if different than above).

If your adapter's designation is different than “enp2s0” you will need to substitute you own adapter’s ID into the service file.

If you are using a different driver module you will also need to substitute it in place of “r8168” or “r8169” in the service file.

R8169 is the currently the recommended driver for this adapter. The r8168 driver should generally be uninstalled through Manjaro Settings Manger or the terminal command given above. I would highly suggest switching to the r8169 kernel module rather than using the r8168 driver. You can substitute "r8168" or "r8169" in the above service file depending on which driver you are using.

You can find your adapter driver/module and device ID to substitute in the service with the following command:

inxi -n

Alternate steps to ensure the r8169 driver is loaded:


Follow the instructions below to remove the r8168 driver.

Uninstall the linuxXXX-r8168 driver:

Open Manjaro Settings Manager -> Hardware configuration -> Network controller

Right click on the RTL8111/8168/8411 ethernet device and select “Remove”.

After the uninstall process has finished, restart.

After you restart, the r8169 kernel module should now be automatically loaded.

You can check which Realtek driver is now loaded with this command:

lsmod | grep r816

Only r8169 should be present in the output, (r8168 should not appear there)

If the r8169 kernel module is not loaded automatically when you reboot (after uninstalling r8168) then do this:

Open any file located in /etc/modprobe.d and ensure there is no reference to r8169.

Any file that contains the line:

blacklist r8169

Change to:

blacklist r8168

Save the edited conf file with root permissions, and then reboot

Alternately, you may delete the conf file entirely, (if it only contains the entry "blacklist r8169").

Example:

If /etc/modprobe.d contains a file named r8169_blacklist.conf then you can delete it with this command:

sudo rm /etc/modprobe.d/r8169_blacklist.conf

Be very careful, you do not make any errors when using the "rm" command with sudo privileges.

Reboot after making any changes to files in /etc/modprobe.d.


6 Likes

Arguably one of my favourite features in Linux. Mostly use it to launch my docker containers. :smiley:

1 Like

Who always thinks that up?
Installed in pamac as “systemd-ui” = Terminal = no
In the Whisker-menu you can find it as “systemadm” = Terminal = yes
Headline in the GUI = “systemd System Manager”
Please, please more corporate identity :wink:

really? edit: really.
I think I need simple examples (in german :wink: )
and mkdir -p ~/.config/systemd/user/ really user? or $USER = sgs?

Nice weekend and peace on earth :slight_smile:

ok, $ systemctl daemon-reload,
after reboot one example work. @xabbu :slight_smile: thanks.

I have a problem with that sleep thing. It is just hopefull thinking that the former process has finished after a while successfully. Every critical (actually all processes) should be evaluated for success or not. In your example you start with a sleep 20 and after loading the module another 3. Heck, why? If something like loading a module would take this much time there is seriously something wrong. If it does not load after 1 second it surely won’t after an hr. Thus I prefer a single script, that has to be executable, fired by the unit file, and this script can then unload its problems in the journal. BTW: The unit file itself does not have to be executable but the binaries and scripts it starts.
Just my thoughts

I didn’t think that all over. Is it not so, that systemd reads that unit file and fires one ExecStart after the other? So you would have a “sleep 20” running a “modprobe” then a “sleep 3” and so on. You cannot picture this commands as a script that executes the next command when the one before has finished. They are all hangin in there at the same time independent from each other.
Tell me, if i am wrong.

I will not argue your experiences calvous. I respect your opinion. I imagine hardware is a factor that makes something work on one machine, but not another.

I can only tell you from working on this stuff for a little while now with users on the forum you do run onto instances where the timing does factor into whether the modules are reloaded successfully.

Mostly reloading of modules will fail if an unload/reload is done without a time delay. Same with raising the adapter and loading the modules. Restarting network manager can also fail on a restart command without a delay between.

The 20 seconds delay is probably far more than required, but a lot of stuff is happening at once when coming out of suspend. I think a bit of a delay helps when bringing up the network again. In this instance I thought it best to start with a big delay so the service unit would be sucessful the on the first attempt. Some users get very frustrated if things don’t work right off the bat, then they throw in the towell, (when it would probably work if they just stuck with it). I informed the user after it was working that the times could probably be trimmed down, and left it to the user to do the fine tuning.

That was my reasoning, maybe I’m completely wrong. As it is, I’m the oly one on the forum helping users solve their suspend issues by writing a service unit. Im only just starting out, so its all a learning experience. Of course I’ll make some errors along the way , thats how we all learn. That’s also why I opened this thread, to get ideas, input, and feedback from others.

The commands are run one after the another. And only if the one before was successful.

A simple test.

$ cat /home/xabbu/.config/systemd/user/test1.service
[Unit]
Description=Test sleep

[Service]
Type=oneshot
ExecStart=/usr/bin/date 
ExecStart=/usr/bin/sleep 20
ExecStart=/usr/bin/date 
ExecStart=/usr/bin/sleep 3
ExecStart=/usr/bin/date 
ExecStart=/usr/bin/sleep 3
ExecStart=/usr/bin/date 

started with systemctl --user start test1.service after a daemon-reload.

The output of systemctl --user status test1.service

● test1.service - Test sleep
   Loaded: loaded (/home/xabbu/.config/systemd/user/test1.service; static; vendor preset: enabled)
   Active: inactive (dead)

Okt 05 12:10:15 Tartaros systemd[1082]: Starting Test sleep...
Okt 05 12:10:15 Tartaros date[2075]: Fr 5. Okt 12:10:15 CEST 2018
Okt 05 12:10:35 Tartaros date[2100]: Fr 5. Okt 12:10:35 CEST 2018
Okt 05 12:10:38 Tartaros date[2103]: Fr 5. Okt 12:10:38 CEST 2018
Okt 05 12:10:41 Tartaros date[2109]: Fr 5. Okt 12:10:41 CEST 2018
Okt 05 12:10:41 Tartaros systemd[1082]: Started Test sleep.
2 Likes

Thanks, I frankly did not expect this. Much more stuff to read.

User output from the service file i posted. Everything fired off sequentially, (and worked beautifully, if i must say so myself).

kdemeoz@GA-Z97-HD3-Tower ~]$ systemctl status network-resume.service
● network-resume.service - Turn network on at resume
   Loaded: loaded (/etc/systemd/system/network-resume.service; enabled; vendor preset: disabled)
   Active: active (exited) since Fri 2018-10-05 12:15:46 AEST; 37s ago
  Process: 5455 ExecStart=/usr/bin/systemctl start NetworkManager (code=exited, status=0/SUCCESS)
  Process: 5411 ExecStart=/usr/bin/sleep 3 (code=exited, status=0/SUCCESS)
  Process: 5406 ExecStart=/usr/bin/ip link set enp2s0 up (code=exited, status=0/SUCCESS)
  Process: 5352 ExecStart=/usr/bin/sleep 3 (code=exited, status=0/SUCCESS)
  Process: 5344 ExecStart=/usr/bin/modprobe r8169 (code=exited, status=0/SUCCESS)
  Process: 4899 ExecStart=/usr/bin/sleep 20 (code=exited, status=0/SUCCESS)
 Main PID: 5455 (code=exited, status=0/SUCCESS)
[kdemeoz@GA-Z97-HD3-Tower ~]$ 

No offense. You’ve asked for input. I just outlined my thoughts. Even though @xabbu showed me different on my second answer, I still would put it into one script. This way you have more control over things. But @gohlip already said it: I am OLD :sob:

1 Like

IIRC this is advised in systemd manuals as well. Better use scripts for sequential commands.

I actually find it far faster when testing to use a separate script as well. Far quicker to use a script that is user writable for testing purposes. The problem with external scripts is when you have ask a user to create separate scripts, and unit files, then set permissions for all (in the terminal), guess what happens. Their eyes glaze over at all the stuff they have to do, and they give up.

So, its kind a a juggling game to actually get users to do the work required to fix their issue. The more work, the more likely they’ll just give up and go back to Ubuntu.

They all want their issue fixed, but they just dont want to have to work for it. I wrote up a set of service units (no scripts) for a user a couple days ago. Waste of effort, too much work for him to even bother trying. That gets very frustrating.

1 Like

Common old chum…Oh…I mean young buddy.
Since this subject is still open, I’ll be brief.
I mean “Old World” thinking, not “Old” people. Okay? Happy?
Here, have a lollipop. :lollipop: Don’t cry. :grin:

1 Like

sniff, thank you…

1 Like

True justification, though I got this topic as learning/testing testbed…
All is right…

Absolutely, any thoughts on the subject are appreciated.

I wouldn’t trust that user; she’s bonkers.

1 Like

Forum kindly sponsored by Bytemark