index.html :: rss :: github :: telegram :: email

systemd notes

20 Aug 2024

List all processed with their cgroups, lots of them are managed by systemd:

ps xawf -eo pid,user,cgroup,args

Useful unit file options

Restart=restart-always, RestartSec=2s: always restart the service no matter what exit code returned, restart after 2s.

OOMScoreAdjust=-500: adjust OOM score to a negative value, tells OOMKiller to kill processes with a higher score first. Useful for a system-critical things.

CPUSchedulingPolicy=idle: schedule the service only when a system is in idle state. Useful for less imprtant, periodic tasks like backups, or log rotation.

ReadOnlyDirectories=, InaccessibleDirectories=: control directories access for a process.

journalctl

Add SystemMaxUse=1G to the unit file to set the desired amount of logs for a service.

journalctl --disk-usage
journalctl --vacuum-size=1G
journalctl --list-boots

remote systemd management

Run systemctl commands on a remote machine, user@addr is the same as for ssh:

systemctl -H user@addr <args>

systemd-nspawn

systemd-nspawn is a "better chroot". Quite useful parameters are custom network config, readonly filesystem, ephemeral filesystem that does not keep changes.

How to run Debian stabe on your machine:

# download and unpack debian system into "debian-tree"
# note that "unstable" snapshot won't boot
sudo debootstrap --arch=amd64 --include=systemd,systemd-sysv,bash stable debian-tree/ http://ftp.am.debian.org/debian/      
# start the system
sudo systemd-nspawn --boot --network-veth -D debian-tree

see also:

-p | --port forward host's port into a concainer system.

-n | --network-veth create and attach network bridge interface into a container.

Split journals by namespaces

Add LogNamespace=xxx to your unit files in [Service] section, then read logs for a whole namespace usign journalctl --namespace xxx.

Custom termination signal

As well as ExecStart, there is also ExecStop, so it's possible to customize what systemctl stop service does:

ExecStop=/bin/kill -s SIGINT -$MAINPID & /bin/kill -s SIGINT -$MAINPID

Also, there is systemctl reload command, this is how its behavior might be customzied:

ExecReload=/usr/sbin/sshd -t
ExecReload=/bin/kill -HUP $MAINPID

Set environment variables

[Service]
Environment="KEY=value"
Environment="DEBUG=true"

Repeat Environment as much as you have to.