Skip to content

systemd

holzkohlengrill edited this page Dec 15, 2023 · 17 revisions

Contents

  1. Contents
  2. Systemd general
    1. Editing services/timers/...
  3. Systemd services
    1. Example .service file
  4. Systemd timers (cron alternative)
    1. .timer example
    2. Enable & Start service+timer
    3. Restart and reload
    4. Additional information
  5. Automount
    1. mnt-data.mount
    2. mnt-data.automount
    3. Using fstab
      1. Device
      2. Options
        1. A quick word about some options
          1. fuseblk
          2. user_id & group_id
          3. blkszie
        2. To keep an overview let's see the lsblk output:
        3. The /dev/sdc1 fstab entry looks like this:
      3. Dump
      4. Fsck - File System Check
      5. Misc

Systemd general

Editing services/timers/...

Use the systemd functions (I personally don't like this method because you do not see what you edit):

sudo systemctl edit zpa-news.timer

Or just edit the whole file:

sudo systemctl edit --full zpa-news.timer

Systemd services

  • /lib/systemd/system: .service files installed by system
  • /etc/systemd/system: .service files added/edited by user (need root privileges)

Example .service file

[Unit]
Description=ZPA news emailer

[Service]
Type=simple
User=marcel
ExecStart=/usr/bin/python3 /home/marcel/PycharmProjects/zpa-news/zpa-news.py

# Working directory defaults to the execution point (=root directory); we need to change our working directory in order to use relative path to the script $
WorkingDirectory=/home/marcel/PycharmProjects/news-emailer/


[Install]
WantedBy=multi-user.target

-> DynamicUser might be interesting (see also here why it also adds security; here you'll find also a nice article about this keyword)

Use systemd-analyze verify serviceFile.service to check for errors

Systemd timers (cron alternative)

Management through .timer-files (aka Timer-Unit-Files). Its structure is similar to .ini files. First you need a service to time it.

List all timers

systemctl list-timers --all

.timer example

[Unit]
Description=ZPA news emailer timer

[Timer]
OnCalendar=*-*-* 19:54:00
# Unit is optional if .service has a different name than .timer
Unit=zpa-news.service

[Install]
WantedBy=multi-user.target

Regarding the OnCalendar syntax see here.

Enable & Start service + timer

You have to do both start and enable a timer:

systemctl enable serviceName.service timerName.timer
systemctl start serviceName.service timerName.timer

Restart and reload

After a systemd file was change it has to be restarted. Also the daemon has to be reloaded (however systemd will tell you in case you forgot: Warning: serviceName.service changed on disk. Run 'systemctl daemon-reload' to reload units.):

systemctl restart serviceName
systemctl daemon-reload

Additional information

Automount

Let systemd automatically mount your drives (-> hot-plug and mount).

To be sure to mount the correct disk we use UUIDs (a UUID is created during formatting). To get the UUIDs of all drives type:

  • sudo blkid (only mounted drives)
  • lsblk -o name,mountpoint,label,size,uuid or lsblk -f

Manually you would mount via UUID like this: sudo mount UUID=1CD0AF0C0975E9BA /mnt/data/.

In /etc/systemd/system we have to create two files:

  1. One that setups the mount (-> mnt-data.mount),
  2. a second that performs the automount (-> mnt-data.automount).

The naming is a bit particular. You have to name the file after the directory path it is mounted later (replace slashes with dashes (see here for more details about naming))

In our case the files would look like:

mnt-data.mount

[Unit]
Description=Data mount

[Mount]
What=/dev/disk/by-uuid/1CD0AF0C0975E9BA
Where=/mnt/data
Type=ntfs-3g

[Install]
WantedBy=multi-user.target
  • NFS
    • Type=nfs
    • `What=nfs.yourNfsURL.com:/data/
  • Auto-deduce type
    • Type=auto

Type cat /proc/filesystems to the the available file system types.

mnt-data.automount

[Unit]
Description=Automount data

[Automount]
Where=/mnt/data

[Install]
WantedBy=multi-user.target

Reload the daemon to notify about new files via: systemctl daemon-reload

Finally start and enable the *.automount file: systemctl enable mnt-data.automount (*.mount can stay disabled)).

If it was successfull systemctl status mnt-data.mount should show you a message like this:

# TODO

This does not work if systemd gets confused like umounting a device manually; there is a bug report which will hopefully resolve this issue in the near future


Using fstab

As an alternative you could use the good old way via fstab:

Inspect /etc/fstab:

cat /etc/fstab
# Format
# <device>      <mountPoint> <type> <options>                           <dump> <fsck>
  /dev/sda1     /mnt/data    ext4   defaults,relatime,data=ordered      0      2
# ...

Device

You have several options to add a device to fstab:

Example in fstab Description Useful commands
/dev/sda1 Kernel name descriptors lsblk
LABEL=DATA FS Labels lsblk -f (-f prints additional fs info)
UUID=c0a8d6e6-2c39-4a6c-80e8-0c94f7e77545 UUID lsblk -f, sudo blkid
PARTLABEL=DATA GPT partition LABEL ls -l /dev/disk/by-partlabel, sudo blkid
PARTUUID=31daffc5-01 GPT partition UUID; if in format SSSSSSSS-PP it is a pseudo PARTUUID for MBR ls -l /dev/disk/by-partuuid, sudo blkid

Options

  • The order of options matters
  • user/users imply noexec, nosuid, nodev unless overwritten by subsequent options
Option Description
defaults = rw, suid, dev, exec, auto, nouser, async ,relatime
auto Mount on boot
nofail Skip if disk not available; might prevent boot hangs
user Any user can mount; umount only by mounter
users Any user can (u)mount
ro/rw read-only / read-write
loop Mount as loop/block device
x-gvfs-show Show drive in the filemanagers sidebar
sync sync (empty buffer and write to disk) after each write
async Puffer writes (can lead to data loss if drive is removed before write)
nouser root can (u)mount only
noauto Do NOT mount on boot
noexec/exec (Do not) Permit execution of binary files
remount Remount (e.g. revoke write permissions: remount,ro)
sw As swap
x-systemd.automount Mount (by systemd) on first access/usage
x-systemd.idle-timeout=ss If idle for ss seconds unmount (by systemd) partition

For ext4-specific options refer to the Ext4 Filesystem documentation.

To check all currently applied mounting options see the output of mount | column -t:

$ mount -l | column -t
proc         on  /proc                            type  proc         (rw,nosuid,nodev,noexec,relatime)                                                     
sys          on  /sys                             type  sysfs        (rw,nosuid,nodev,noexec,relatime)                                                     
dev          on  /dev                             type  devtmpfs     (rw,nosuid,relatime,size=1011620k,nr_inodes=252905,mode=755)                          
run          on  /run                             type  tmpfs        (rw,nosuid,nodev,relatime,mode=755)                                                   
/dev/sda2    on  /                                type  ext4         (rw,relatime)                                                                         [AntergosRoot]
# ...
tmpfs        on  /tmp                             type  tmpfs        (rw,nosuid,nodev)                                                                     
/dev/sda1    on  /boot                            type  ext4         (rw,relatime,data=ordered)                                                            [AntergosBoot]
tmpfs        on  /run/user/1000                   type  tmpfs        (rw,nosuid,nodev,relatime,size=204064k,mode=700,uid=1000,gid=1001)  
/dev/sdc1    on  /mnt/test_2                      type  fuseblk      (rw,nosuid,nodev,relatime,user_id=0,group_id=0,allow_other,blksize=4096,x-gvfs-show)  [testdisk_2]
/dev/sdb1    on  /mnt/Data                        type  fuseblk      (rw,nosuid,nodev,relatime,user_id=0,group_id=0,allow_other,blksize=4096)              [Data]

A quick word about some options

fuseblk

Shows an NTFS partition reported from mount (and others). FUSE means file system in userspace.

user_id & group_id

Specifies the numeric uid/gid of the mount owner. This option should not be specified by the filesystem owner. It is set by libfuse (or, if libfuse is not used, must be set by the filesystem itself).

From http://man7.org/linux/man-pages/man8/mount.fuse.8.html (formatting added)

blkszie

Set the block size for the filesystem. This option is only valid for 'fuseblk' type mounts. The default is 512. In most cases, this option should not be specified by the filesystem owner but set internally by the filesystem.

From http://man7.org/linux/man-pages/man8/mount.fuse.8.html (formatting added)

To keep an overview let's see the lsblk output:

$ lsblk 
NAME   MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
sda      8:0    0   80G  0 disk 
|-sda1   8:1    0  511M  0 part /boot
|-sda3   8:3    0    1K  0 part 
|-sda2   8:2    0 75.6G  0 part /
`-sda5   8:5    0  3.9G  0 part [SWAP]
sdc      8:32   0    8G  0 disk 
`-sdc1   8:33   0    8G  0 part /mnt/test_2
# ...

The /dev/sdc1 fstab entry looks like this:

UUID=1CD0AF0C0975E9BA /mnt/test_2 ntfs defaults,auto,nofail,x-gvfs-show 0 2

Dump

Whether it should be checked by the dump utility (1=True; 0=False/Disabled).

Dump is a back-up command for ext file systems. Normally there is no need to enable this (see here why).

Fsck - File System Check

Sets the order for file system checks during boot time.

Value Usage
0 Check disabled (e.g. swap)
1 Root device
2 Other partitions
... Higher numbers in order to avoid parallel check (e.g. paging)

Setting multiple partitions to the same value (like 2) allows fsck to potentially parallelise filesystem checks.

Misc

  • If a device was not mounted (for whatsoever reason) you can mount all unmouted drives (stated in fstab) with mount -a.
  • Escape whitespaces with \040 in /etc/fstab
  • Don't forget to create the mount point directories before using in fstab
  • In-memory (RAM/Swap) temporary directories with tempfs (useful for caching, ...)
    • See here how to sync your tmpfs (link to full article) to a persistant storage using a systemd service
  • Mounting a folder into a folder using fstab (see here)
Clone this wiki locally