### PHP-FPM setup commands: daemon-reload, start, enable socket
Source: https://github.com/systemd/systemd/blob/main/docs/DAEMON_SOCKET_ACTIVATION.md
Commands to reload systemd, start the socket, and enable it to start at boot. After these, the service will be activated on demand.
```sh
sudo systemctl --system daemon-reload
sudo systemctl start my-php-fpm-pool.socket
sudo systemctl enable my-php-fpm-pool.socket
```
--------------------------------
### Sample systemd boot console output
Source: https://github.com/systemd/systemd/blob/main/docs/index.md
Example of systemd boot output showing service start and target reach messages. The output includes status lines with [OK] indicators and progress messages. It ends with a login prompt.
```text
Welcome to Fedora 20 (Heisenbug)!
[ OK ] Reached target Remote File Systems.
[ OK ] Listening on Delayed Shutdown Socket.
[ OK ] Listening on /dev/initctl Compatibility Named Pipe.
[ OK ] Reached target Paths.
[ OK ] Reached target Encrypted Volumes.
[ OK ] Listening on Journal Socket.
Mounting Huge Pages File System...
Mounting POSIX Message Queue File System...
Mounting Debug File System...
Starting Journal Service...
[ OK ] Started Journal Service.
Mounting Configuration File System...
Mounting FUSE Control File System...
[ OK ] Created slice Root Slice.
[ OK ] Created slice User and Session Slice.
[ OK ] Created slice System Slice.
[ OK ] Reached target Slices.
[ OK ] Reached target Swap.
Mounting Temporary Directory...
[ OK ] Reached target Local File Systems (Pre).
Starting Load Random Seed...
Starting Load/Save Random Seed...
[ OK ] Mounted Huge Pages File System.
[ OK ] Mounted POSIX Message Queue File System.
[ OK ] Mounted Debug File System.
[ OK ] Mounted Configuration File System.
[ OK ] Mounted FUSE Control File System.
[ OK ] Mounted Temporary Directory.
[ OK ] Started Load Random Seed.
[ OK ] Started Load/Save Random Seed.
[ OK ] Reached target Local File Systems.
Starting Recreate Volatile Files and Directories...
Starting Trigger Flushing of Journal to Persistent Storage...
[ OK ] Started Recreate Volatile Files and Directories.
Starting Record System Reboot/Shutdown in UTMP...
[ OK ] Started Trigger Flushing of Journal to Persistent Storage.
[ OK ] Started Record System Reboot/Shutdown in UTMP.
[ OK ] Reached target System Initialization.
[ OK ] Reached target Timers.
[ OK ] Listening on D-Bus System Message Bus Socket.
[ OK ] Reached target Sockets.
[ OK ] Reached target Basic System.
Starting Permit User Sessions...
Starting D-Bus System Message Bus...
[ OK ] Started D-Bus System Message Bus.
Starting Login Service...
Starting Cleanup of Temporary Directories...
[ OK ] Started Permit User Sessions.
[ OK ] Started Cleanup of Temporary Directories.
Starting Console Getty...
[ OK ] Started Console Getty.
[ OK ] Reached target Login Prompts.
[ OK ] Started Login Service.
[ OK ] Reached target Multi-User System.
Fedora release 20 (Heisenbug)
Kernel 3.9.2-200.fc18.x86_64 on an x86_64 (console)
fedora login:
```
--------------------------------
### Example loader.conf and entry configuration files
Source: https://github.com/systemd/systemd/blob/main/docs/BOOT.md
These examples show the format for the loader configuration file and entry configuration files. The loader.conf sets a timeout and default pattern. Entry files define title, version, machine-id, linux, initrd, and options.
```plaintext
/boot/loader/loader.conf
timeout 3
default 6a9857a393724b7a981ebb5b8495b9ea-*
```
```plaintext
/boot/loader/entries/6a9857a393724b7a981ebb5b8495b9ea-3.8.0-2.fc19.x86_64.conf
title Fedora 19 (Rawhide)
version 3.8.0-2.fc19.x86_64
machine-id 6a9857a393724b7a981ebb5b8495b9ea
linux /6a9857a393724b7a981ebb5b8495b9ea/3.8.0-2.fc19.x86_64/linux
initrd /6a9857a393724b7a981ebb5b8495b9ea/3.8.0-2.fc19.x86_64/initrd
options root=UUID=f8f83f73-df71-445c-87f7-31f70263b83b quiet
```
```plaintext
/boot/loader/entries/custom-kernel.conf
title My kernel
efi /bzImage
options root=PARTUUID=084917b7-8be2-4e86-838d-f771a9902e08
```
```plaintext
/boot/loader/entries/custom-kernel-initrd.conf
title My kernel with initrd
linux /bzImage
initrd /initrd.img
options root=PARTUUID=084917b7-8be2-4e86-838d-f771a9902e08 quiet
```
--------------------------------
### Start a service and see generic failure message
Source: https://github.com/systemd/systemd/blob/main/docs/DEBUGGING.md
Run systemctl start foo.service to attempt to start the service. On failure, systemctl prints a generic error message directing you to the journal and systemctl status.
```sh
# systemctl start foo.service
Job failed. See system journal and 'systemctl status' for details.
```
--------------------------------
### Enable and start a serial getty
Source: https://github.com/systemd/systemd/blob/main/docs/FAQ.md
Instantiates and starts a new serial getty service for a specific port.
```sh
# systemctl enable serial-getty@ttyS2.service
# systemctl start serial-getty@ttyS2.service
```
--------------------------------
### Compile command for addrtest.c with pkg-config
Source: https://github.com/systemd/systemd/blob/main/docs/WRITING_RESOLVER_CLIENTS.md
Shell command to compile the C example, assuming the source is saved as addrtest.c. Uses pkg-config to get the cflags and libs for libsystemd.
```bash
gcc addrtest.c -o addrtest -Wall `pkg-config --cflags --libs libsystemd`
```
--------------------------------
### Compiling the DNS resolver example
Source: https://github.com/systemd/systemd/blob/main/docs/WRITING_RESOLVER_CLIENTS.md
Use this command to compile the source file rrtest.c, ensuring the libsystemd development headers and libraries are linked.
```bash
gcc rrtest.c -o rrtest -Wall `pkg-config --cflags --libs libsystemd`
```
--------------------------------
### Example Log Fields for Portable Service with Extensions
Source: https://github.com/systemd/systemd/blob/main/docs/PORTABLE_SERVICES.md
This example shows the log fields generated for a portable service named app0 using two extensions and a base layer.
```text
PORTABLE=app0.raw
PORTABLE_ROOT=base.raw
PORTABLE_ROOT_NAME_AND_VERSION=debian_10
PORTABLE_EXTENSION=app0.raw
PORTABLE_EXTENSION_NAME_AND_VERSION=app_0
PORTABLE_EXTENSION=app1.raw
PORTABLE_EXTENSION_NAME_AND_VERSION=app_1
```
--------------------------------
### Example unit file with LoadCredential and Environment
Source: https://github.com/systemd/systemd/blob/main/docs/CREDENTIALS.md
Defines a service that loads a credential from /etc/myfoobarcredential.txt and sets an environment variable pointing to it using the %d specifier.
```ini
…
[Service]
ExecStart=/usr/bin/myservice.sh
LoadCredential=foobar:/etc/myfoobarcredential.txt
Environment=FOOBARPATH=%d/foobar
…
```
--------------------------------
### Manager.StartTransientUnit()
Source: https://github.com/systemd/systemd/blob/main/docs/CONTROL_GROUP_INTERFACE.md
Creates and starts a transient unit (scope, service, or slice) in the cgroup tree and queues a start job for it.
```APIDOC
### Interface
`org.freedesktop.systemd1.Manager`
### Method
`StartTransientUnit(String name, String mode, Array of (String, Variant) properties, Array aux) -> (ObjectPath job)`
### Parameters
- **name** (`String`) - Required - The full unit name under which the unit is known. Must be unique during the runtime of the unit.
- **mode** (`String`) - Required - Start mode, usually `replace` or `fail`.
- **properties** (`Array of (String, Variant)`) - Required - Initial properties to set for the unit. Supported properties include `Description`, `Slice`, dependency types, `RemainAfterExit`, `ExecStart` (for service units), `TimeoutStopUSec` and `PIDs` (for scope units), and resource control properties (`CPUAccounting`, `CPUShares`, `BlockIOAccounting`, `BlockIOWeight`, `BlockIOReadBandwidth`, `BlockIOWriteBandwidth`, `BlockIODeviceWeight`, `MemoryAccounting`, `MemoryLimit`, `DevicePolicy`, `DeviceAllow`).
- **aux** (`Array`) - Required - Currently unused; pass as an empty array.
### Return Value
- **job** (`ObjectPath`) - Object path to a `Job` object queued for the start of the unit.
```
--------------------------------
### Instantiate portable services with systemd templating
Source: https://github.com/systemd/systemd/blob/main/docs/PORTABLE_SERVICES.md
Use regular systemd unit templating with portable services. Attach the image with portablectl, then enable and start each instance with systemctl. The ellipsis indicates additional instances can be added similarly.
```bash
# portablectl attach foobar_0.7.23.raw
# systemctl enable --now foobar@instancea.service
# systemctl enable --now foobar@instanceb.service
…
```
--------------------------------
### List running services with systemctl
Source: https://github.com/systemd/systemd/blob/main/docs/TIPS_AND_TRICKS.md
Run `systemctl` without arguments to display a table of all loaded units, including their load state, active state, and description. The output is truncated with '...' in the example.
```sh
$ systemctl
UNIT LOAD ACTIVE SUB JOB DESCRIPTION
accounts-daemon.service loaded active running Accounts Service
atd.service loaded active running Job spooling tools
avahi-daemon.service loaded active running Avahi mDNS/DNS-SD Stack
bluetooth.service loaded active running Bluetooth Manager
colord-sane.service loaded active running Daemon for monitoring attached scanners and registering them with colord
colord.service loaded active running Manage, Install and Generate Color Profiles
crond.service loaded active running Command Scheduler
cups.service loaded active running CUPS Printing Service
dbus.service loaded active running D-Bus System Message Bus
...
```
--------------------------------
### Enable service on boot
Source: https://github.com/systemd/systemd/blob/main/docs/FAQ.md
Enables a service to start at boot by creating a symlink in the multi-user.target.wants directory and reloading the systemd manager configuration.
```sh
# ln -sf /usr/lib/systemd/system/foobar.service /etc/systemd/system/multi-user.target.wants/foobar.service
# systemctl daemon-reload
```
--------------------------------
### System Logging Service Unit File
Source: https://github.com/systemd/systemd/blob/main/docs/SYSLOG.md
Install this unit file for your syslog daemon. It requires syslog.socket, starts the daemon with -n, and sets StandardOutput=null. Do not ship your own socket units for /dev/log or /run/systemd/journal/syslog.
```ini
[Unit]
Description=System Logging Service
Requires=syslog.socket
[Service]
ExecStart=/usr/sbin/syslog-ng -n
StandardOutput=null
[Install]
Alias=syslog.service
WantedBy=multi-user.target
```
--------------------------------
### Compile and Run take_BSD_lock
Source: https://github.com/systemd/systemd/blob/main/docs/BLOCK_DEVICE_LOCKING.md
Commands to compile the example C file with gcc, linking against libsystemd (version 251 or newer required), and to run it, showing successful locking and the failure when the device is already locked by flock.
```bash
$ gcc -o take_BSD_lock -lsystemd take_BSD_lock.c
```
```bash
$ ./take_BSD_lock /dev/sda1
Successfully took a BSD lock: /dev/sda
```
```bash
$ flock -x /dev/sda ./take_BSD_lock /dev/sda1
Failed to take a BSD lock on /dev/sda: Resource temporarily unavailable
```
--------------------------------
### Configure corporate VPN using resolvectl
Source: https://github.com/systemd/systemd/blob/main/docs/RESOLVED-VPNS.md
Example shell commands to configure a corporate VPN interface, setting specific search/routing domains, disabling the default route, and assigning DNS servers.
```bash
resolvectl domain corporate0 '~corp-company.example' '~2.0.192.in-addr.arpa'
resolvectl default-route corporate0 false
resolvectl dns corporate0 192.0.2.1
```
--------------------------------
### System user record example
Source: https://github.com/systemd/systemd/blob/main/docs/USER_RECORD.md
A reasonable user record for a system user, including uid, gid, disposition, and locked fields.
```json
{
"userName" : "httpd",
"uid" : 473,
"gid" : 473,
"disposition" : "system",
"locked" : true
}
```
--------------------------------
### PHP-FPM reactivation commands: stop and start socket
Source: https://github.com/systemd/systemd/blob/main/docs/DAEMON_SOCKET_ACTIVATION.md
Commands to stop the socket and service, then start the socket again to reset PHP-FPM's shutdown state and allow reactivation.
```sh
sudo systemctl stop my-php-fpm-pool.socket my-php-fpm-pool.service
sudo systemctl start my-php-fpm-pool.socket
```
--------------------------------
### Host OS sysupdate component example (class="sysupdate")
Source: https://github.com/systemd/systemd/blob/main/docs/APPSTREAM_BUNDLE.md
Extends existing appstream metadata for the host OS with a changelog. Tells the software center that the host OS should be updated using the 'host' target for systemd-sysupdated.
```xml
com.example.OS
This release includes various bug fixes and performance improvements
```
--------------------------------
### Configure privacy VPN using resolvectl
Source: https://github.com/systemd/systemd/blob/main/docs/RESOLVED-VPNS.md
Example shell commands to configure a privacy VPN interface, routing all traffic through the VPN and assigning a public DNS server.
```bash
resolvectl domain privacy0 '~.'
resolvectl default-route privacy0 true
resolvectl dns privacy0 8.8.8.8
```
--------------------------------
### Sysext component example (class="extension")
Source: https://github.com/systemd/systemd/blob/main/docs/APPSTREAM_BUNDLE.md
Defines a sysext named 'devel' to be presented by the software center. It will be updated via systemd-sysupdated's 'extension:devel' target and treated as a plugin for the operating system.
```xml
com.example.Develcom.example.OSDevelopment ToolsTools essential to develop Example OSgccg++makeautoconfcmakemesonninjaExample, inc.devel
```
--------------------------------
### Check for stuck jobs with systemctl list-jobs
Source: https://github.com/systemd/systemd/blob/main/docs/DEBUGGING.md
Lists jobs; those marked 'running' must complete before 'waiting' jobs can start.
```sh
systemctl list-jobs
```
--------------------------------
### Blocking lock example (Inhibit with 'block')
Source: https://github.com/systemd/systemd/blob/main/docs/INHIBITOR_LOCKS.md
Pseudo code showing how to take a blocking lock using Inhibit with mode 'block'. The lock is held during critical work and released by closing the file descriptor.
```c
fd = Inhibit("shutdown:idle", "Package Manager", "Upgrade in progress...", "block");
/* ...
do your work
... */
close(fd);
```
--------------------------------
### Build, run, and test systemd executables with mkosi
Source: https://github.com/systemd/systemd/blob/main/docs/HACKING.md
Use these commands to generate signing keys, set up the build with meson, compile, check the systemctl version, and run unit tests. The meson setup disables the BPF framework because bpftool detection inside mkosi box is broken on Ubuntu Noble and older.
```sh
$ mkosi -f genkey # Generate signing keys once.
$ mkosi -f box -- meson setup -Dbpf-framework=disabled build # bpftool detection inside mkosi box is broken on Ubuntu Noble and older
$ mkosi -f box -- meson compile -C build
$ mkosi -f box -- build/systemctl --version
$ mkosi -f box -- meson test -C build --print-errorlogs -q # Run the unit tests
```
--------------------------------
### Install Rust toolchain from distribution packages
Source: https://github.com/systemd/systemd/blob/main/docs/HACKING.md
Install rustc, bindgen, rustfmt, and clippy outside of mkosi using the package manager for Debian 13, Fedora, Arch Linux, or openSUSE Tumbleweed.
```sh
apt install rustc bindgen rustfmt rust-clippy # Debian 13
```
```sh
dnf install rust bindgen-cli rustfmt clippy # Fedora
```
```sh
pacman -S rust rust-bindgen # Arch Linux
```
```sh
zypper install rust rust-bindgen # openSUSE Tumbleweed
```
--------------------------------
### Complete regular group record example
Source: https://github.com/systemd/systemd/blob/main/docs/GROUP_RECORD.md
A more complete group record for a regular group, including a binding with a gid, a disposition of "regular", and a status entry with service io.systemd.Home.
```json
{
"groupName" : "grobie",
"binding" : {
"6b18704270e94aa896b003b4340978f1" : {
"gid" : 60232
}
}
},
"disposition" : "regular",
"status" : {
"6b18704270e94aa896b003b4340978f1" : {
"service" : "io.systemd.Home"
}
}
}
```
--------------------------------
### Portable service component example (class="portable")
Source: https://github.com/systemd/systemd/blob/main/docs/APPSTREAM_BUNDLE.md
Defines a portable service named 'foobar' to be presented by the software center. It will be updated via systemd-sysupdated's 'portable:foobar' target, marked as an urgent update, and presented with a display name, description, and custom icon.
```xml
com.example.FoobarFoobar ServiceService that does foo to barhttps://example.com/products/foobar/logo.svghttps://example.com/products/foobarcom.example.FoobarExample, inc.
This release fixes a major security vulnerability. Please update ASAP.
CVE-2024-28153
Initial release!
foobar
```
--------------------------------
### Example Datagram Serialization
Source: https://github.com/systemd/systemd/blob/main/docs/JOURNAL_NATIVE_PROTOCOL.md
A sample encoded message demonstrating common fields and the use of both serialization methods, including handling newline characters.
```text
PRIORITY=3\n
SYSLOG_FACILITY=3\n
CODE_FILE=src/foobar.c\n
CODE_LINE=77\n
BINARY_BLOB\n
\004\000\000\000\000\000\000\000xx\nx\n
CODE_FUNC=some_func\n
SYSLOG_IDENTIFIER=footool\n
MESSAGE=Something happened.\n
```
--------------------------------
### ResolveHostname() C example with sd-bus
Source: https://github.com/systemd/systemd/blob/main/docs/WRITING_RESOLVER_CLIENTS.md
C program that opens the system bus and calls ResolveHostname with AF_UNSPEC and interface index 0. It parses the returned array of (ifindex, family, address) tuples and prints each address and the canonical name. Requires libsystemd and a running systemd-resolved.
```c
#include
#include
#include
#include
#include
#include
int main(int argc, char*argv[]) {
sd_bus_error error = SD_BUS_ERROR_NULL;
sd_bus_message *reply = NULL;
const char *canonical;
sd_bus *bus = NULL;
uint64_t flags;
int r;
r = sd_bus_open_system(&bus);
if (r < 0) {
fprintf(stderr, "Failed to open system bus: %s\n", strerror(-r));
goto finish;
}
r = sd_bus_call_method(bus,
"org.freedesktop.resolve1",
"/org/freedesktop/resolve1",
"org.freedesktop.resolve1.Manager",
"ResolveHostname",
&error,
&reply,
"isit",
0, /* Network interface index where to look (0 means any) */
argc >= 2 ? argv[1] : "www.github.com", /* Hostname */
AF_UNSPEC, /* Which address family to look for */
UINT64_C(0)); /* Input flags parameter */
if (r < 0) {
fprintf(stderr, "Failed to resolve hostname: %s\n", error.message);
sd_bus_error_free(&error);
goto finish;
}
r = sd_bus_message_enter_container(reply, 'a', "(iiay)");
if (r < 0)
goto parse_failure;
for (;;) {
char buf[INET6_ADDRSTRLEN];
int ifindex, family;
const void *data;
size_t length;
r = sd_bus_message_enter_container(reply, 'r', "iiay");
if (r < 0)
goto parse_failure;
if (r == 0) /* Reached end of array */
break;
r = sd_bus_message_read(reply, "ii", &ifindex, &family);
if (r < 0)
goto parse_failure;
r = sd_bus_message_read_array(reply, 'y', &data, &length);
if (r < 0)
goto parse_failure;
r = sd_bus_message_exit_container(reply);
if (r < 0)
goto parse_failure;
printf("Found IP address %s on interface %i.\n", inet_ntop(family, data, buf, sizeof(buf)), ifindex);
}
r = sd_bus_message_exit_container(reply);
if (r < 0)
goto parse_failure;
r = sd_bus_message_read(reply, "st", &canonical, &flags);
if (r < 0)
goto parse_failure;
printf("Canonical name is %s\n", canonical);
goto finish;
parse_failure:
fprintf(stderr, "Parse failure: %s\n", strerror(-r));
finish:
sd_bus_message_unref(reply);
sd_bus_flush_close_unref(bus);
return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
}
```
--------------------------------
### Minimal system group record example
Source: https://github.com/systemd/systemd/blob/main/docs/GROUP_RECORD.md
A minimal group record for a system group, showing the required groupName and gid fields along with a status entry. The service value is io.systemd.NameServiceSwitch.
```json
{
"groupName" : "systemd-resolve",
"gid" : 193,
"status" : {
"6b18704270e94aa896b003b4340978f1" : {
"service" : "io.systemd.NameServiceSwitch"
}
}
}
```
--------------------------------
### Configure VSCode launch configuration to debug systemd-boot
Source: https://github.com/systemd/systemd/blob/main/docs/HACKING.md
Use this cppdbg launch configuration to attach gdb to a QEMU session started with -s. It relies on the debug-sd-boot.sh script and a serial pipe to set up breakpoints.
```json
{
"name": "systemd-boot",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/build/src/boot/efi/systemd-bootx64.efi",
"cwd": "${workspaceFolder}",
"MIMode": "gdb",
"miDebuggerServerAddress": ":1234",
"setupCommands": [
{ "text": "shell mkfifo /tmp/sdboot.{in,out}" },
{ "text": "shell qemu-system-x86_64 [...] -s -serial pipe:/tmp/sdboot" },
{ "text": "shell ${workspaceFolder}/tools/debug-sd-boot.sh ${workspaceFolder}/build/src/boot/efi/systemd-bootx64.efi /tmp/sdboot.out systemd-boot.gdb" },
{ "text": "source /tmp/systemd-boot.gdb" },
]
}
```
--------------------------------
### Delay lock example (Inhibit with 'delay')
Source: https://github.com/systemd/systemd/blob/main/docs/INHIBITOR_LOCKS.md
Pseudo code showing how to take a delay lock using Inhibit with mode 'delay'. The lock is taken when opening a document, released on PrepareForSleep(true) after saving, and reacquired on PrepareForSleep(false).
```c
int fd = -1;
takeLock() {
if (fd >= 0)
return;
fd = Inhibit("sleep", "Word Processor", "Save any unsaved data in time...", "delay");
}
onDocumentOpen(void) {
takeLock();
}
onPrepareForSleep(bool b) {
if (b) {
saveData();
if (fd >= 0) {
close(fd);
fd = -1;
}
} else
takeLock();
}
```
--------------------------------
### Delay network-online.target until host reachable
Source: https://github.com/systemd/systemd/blob/main/docs/NETWORK_ONLINE.md
A systemd service unit that delays network-online.target until a specific host is reachable. It uses a oneshot service with RemainAfterExit=yes and a shell loop that pings example.com every second until success. The unit is ordered after nss-lookup.target and before network-online.target, and is installed as WantedBy=network-online.target.
```ini
[Unit]
DefaultDependencies=no
After=nss-lookup.target
Before=network-online.target
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=sh -c 'until ping -c 1 example.com; do sleep 1; done'
[Install]
WantedBy=network-online.target
```
--------------------------------
### Query UID boundaries with pkg-config variables
Source: https://github.com/systemd/systemd/blob/main/docs/UIDS-GIDS.md
Run these commands to see the system's UID allocation boundaries. The output shown is an example; actual values vary by system. The container_uid_base_max variable encodes the maximum UID base, but the maximum UID used is that value plus 65535.
```shell
$ pkg-config --variable=system_uid_max systemd
999
$ pkg-config --variable=greeter_uid_min systemd
60578
$ pkg-config --variable=greeter_uid_max systemd
60705
$ pkg-config --variable=dynamic_uid_min systemd
61184
$ pkg-config --variable=dynamic_uid_max systemd
65519
$ pkg-config --variable=container_uid_base_min systemd
524288
$ pkg-config --variable=container_uid_base_max systemd
1878982656
$ pkg-config --variable=foreign_uid_base systemd
2147352576
```
--------------------------------
### Example unit file with SetCredentialEncrypted
Source: https://github.com/systemd/systemd/blob/main/docs/CREDENTIALS.md
Shows a unit file snippet that uses SetCredentialEncrypted= to pass an encrypted credential named 'foobar' to the service. The service runs systemd-creds cat foobar to output the decrypted credential.
```ini
…
[Service]
ExecStart=/usr/bin/systemd-creds cat foobar
SetCredentialEncrypted=foobar: \
k6iUCUh0RJCQyvL8k8q1UyAAAAABAAAADAAAABAAAAC1lFmbWAqWZ8dCCQkAAAAAgAAAA \
AAAAAALACMA0AAAACAAAAAAfgAg9uNpGmj8LL2nHE0ixcycvM3XkpOCaf+9rwGscwmqRJ \
cAEO24kB08FMtd/hfkZBX8PqoHd/yPTzRxJQBoBsvo9VqolKdy9Wkvih0HQnQ6NkTKEdP \
HQ08+x8sv5sr+Mkv4ubp3YT1Jvv7CIPCbNhFtag1n5y9J7bTOKt2SQwBOAAgACwAAABIA \
ID8H3RbsT7rIBH02CIgm/Gv1ukSXO3DMHmVQkDG0wEciABAAII6LvrmL60uEZcp5qnEkx \
SuhUjsDoXrJs0rfSWX4QAx5PwfdFuxPusgEfTYIiCb8a/W6RJc7cMweZVCQMbTARyIAAA \
AAJt7Q9F/Gz0pBv1Lc4Dpn1WpebyBBm+vQ5N/lSKW2XSm8cONwCopxpDc7wJjXg7OTR6r \
xGCpIvGXLt3ibwJl81woLya2RRjIvc/R2zNm/yWzZAjiOLPih4SuHthqiX98ey8PUmZJB \
VGXglCZFjBx+d7eCqTIdghtp5pkDGwMJT6pjw4FfyFK2nJPawFKPAqzw9DK2iYttFeXi5 \
19xCfLBH9NKS/idlYXrhp+XIEtsr26s4lx5y10Goyc3qDOR3RD2cuZj0gHwV35hhhhcCz \
JaYytef1X/YL+7fYH5kuE4rxSksoUuA/LhtjszBeGbcbIT+O8SuvBJHLKTSHxPL8FTyk3 \
L4FSkEHs0rYwUIkKmnGohDdsYrMJ2fjH3yDNBP16aD1+f/Nuh75cjhUnGsDLt9K4hGg== \
…
```
--------------------------------
### Include order and logging function in source.h and source.c
Source: https://github.com/systemd/systemd/blob/main/docs/CODING_STYLE.md
Shows the recommended include ordering: external headers first, then exported sd- headers, then internal headers, each group alphabetized. The example pairs a header declaration with its implementation that logs via log_error().
```c
// source.h
#include "forward.h"
void my_function_that_logs(size_t sz);
// source.c
#include "source.h"
#include "log.h"
void my_function_that_logs(size_t sz) {
log_error("oops: %zu", sz);
}
```
--------------------------------
### Example systemd.credentials userdata payload
Source: https://github.com/systemd/systemd/blob/main/docs/CREDENTIALS.md
This JSON object is passed as the instance's user data via the cloud's provisioning interface. It contains a systemd.credentials array with entries specifying credential names and values. Each entry must have a name and one of text, data, or encrypted.
```json
{
"systemd.credentials": [
{
"name": "mycred",
"text": "supersecret"
},
{
"name": "mybinarycred",
"data": "YmFyCg=="
}
]
}
```
--------------------------------
### Create sgdb script to run gdb as root via pkexec
Source: https://github.com/systemd/systemd/blob/main/docs/HACKING.md
Create this executable file named `sgdb` in the root of the systemd repository. vscode's `miDebuggerPath` is then set to `${workspaceFolder}/sgdb` so gdb starts as root via pkexec, prompting for the root password graphically.
```sh
#!/bin/sh
exec pkexec gdb "$@"
```
--------------------------------
### systemd --test --system --unit=foobar.target
Source: https://github.com/systemd/systemd/blob/main/docs/TIPS_AND_TRICKS.md
Use this command to have systemd calculate the initial transaction it would execute on boot for the specified target (foobar.target). Note that this is mostly a debugging tool and should not be used in scripts.
```sh
$ systemd --test --system --unit=foobar.target
```
--------------------------------
### Boot VM with qemu and pass credential via SMBIOS
Source: https://github.com/systemd/systemd/blob/main/docs/CREDENTIALS.md
Use qemu to boot a VM and pass a credential via SMBIOS OEM strings. The credential is set to 'mycred=supersecret'.
```shell
qemu-system-x86_64 \
-machine type=q35,accel=kvm,smm=on \
-smp 2 \
-m 1G \
-cpu host \
-nographic \
-nodefaults \
-serial mon:stdio \
-drive if=none,id=hd,file=test.raw,format=raw \
-device virtio-scsi-pci,id=scsi \
-device scsi-hd,drive=hd,bootindex=1 \
-smbios type=11,value=io.systemd.credential:mycred=supersecret
```
--------------------------------
### Journal Export Format entry example
Source: https://github.com/systemd/systemd/blob/main/docs/JOURNAL_EXPORT_FORMATS.md
Example of a journal entry in the binary Journal Export Format, showing field assignments and a binary MESSAGE field.
```text
__CURSOR=s=bcce4fb8ffcb40e9a6e05eee8b7831bf;i=5ef603;b=ec25d6795f0645619ddac9afdef453ee;m=545242e7049;t=50f1202
__REALTIME_TIMESTAMP=1423944916375353
__MONOTONIC_TIMESTAMP=5794517905481
_BOOT_ID=ec25d6795f0645619ddac9afdef453ee
_TRANSPORT=journal
_UID=1001
_GID=1001
_CAP_EFFECTIVE=0
_SYSTEMD_OWNER_UID=1001
_SYSTEMD_SLICE=user-1001.slice
_MACHINE_ID=5833158886a8445e801d437313d25eff
_HOSTNAME=bupkis
_AUDIT_LOGINUID=1001
_SELINUX_CONTEXT=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
CODE_LINE=1
CODE_FUNC=
SYSLOG_IDENTIFIER=python3
_COMM=python3
_EXE=/usr/bin/python3.4
_AUDIT_SESSION=35898
_SYSTEMD_CGROUP=/user.slice/user-1001.slice/session-35898.scope
_SYSTEMD_SESSION=35898
_SYSTEMD_UNIT=session-35898.scope
MESSAGE
^G^@^@^@^@^@^@^@foo
bar
CODE_FILE=
_PID=16853
_CMDLINE=python3 -c from systemd import journal; journal.send("foo\nbar")
_SOURCE_REALTIME_TIMESTAMP=1423944916372858
```
--------------------------------
### Avoid circular header dependency between manager.h and unit.h
Source: https://github.com/systemd/systemd/blob/main/docs/CODING_STYLE.md
Bad example: manager.h and unit.h mutually include each other, creating a circular header dependency. Use the good example instead to break the cycle.
```c
// manager.h
typedef struct Manager Manager;
#include "unit.h"
struct Manager {
Unit *unit;
};
// unit.h
typedef struct Unit Unit;
#include "manager.h"
struct Unit {
Manager *manager;
};
```
--------------------------------
### Build the project
Source: https://github.com/systemd/systemd/blob/main/docs/RELEASE.md
Run this command to build the project.
```bash
ninja -C build
```
--------------------------------
### Configure service to wait for network-online.target
Source: https://github.com/systemd/systemd/blob/main/docs/NETWORK_ONLINE.md
Add these lines to the .service file to delay boot until the network management software reports the network is up. This pulls in network-online.target and orders the service after it.
```ini
After=network-online.target
Wants=network-online.target
```
--------------------------------
### Migrate home directory with homectl with and rsync
Source: https://github.com/systemd/systemd/blob/main/docs/CONVERTING_TO_HOMED.md
Mounts the new home directory and copies the contents of the old home directory into it using rsync, removing source files as they are copied. The new home directory is the working directory of the rsync process.
```bash
homectl with foobar -- rsync -aHANUXv --remove-source-files /home/foobar.saved/ .
```
--------------------------------
### Else block on same line as closing brace
Source: https://github.com/systemd/systemd/blob/main/docs/CODING_STYLE.md
Start the else block on the same line as the closing brace of the if block.
```c
if (foobar) {
find();
waldo();
} else
dont_find_waldo();
```
--------------------------------
### Pass credentials to qemu-system-x86_64 VM
Source: https://github.com/systemd/systemd/blob/main/docs/CREDENTIALS.md
Boots a disk image via qemu and passes the root password and default locale using SMBIOS. The credentials are propagated to systemd-sysusers.service and systemd-firstboot.service, but only if the settings in /etc/ are unset.
```bash
qemu-system-x86_64 \
-machine type=q35,accel=kvm,smm=on \
-smp 2 \
-m 1G \
-cpu host \
-nographic \
-nodefaults \
-serial mon:stdio \
-drive if=none,id=hd,file=test.raw,format=raw \
-device virtio-scsi-pci,id=scsi \
-device scsi-hd,drive=hd,bootindex=1 \
-smbios type=11,value=io.systemd.credential:passwd.hashed-password.root=$(mkpasswd mysecret) \
-smbios type=11,value=io.systemd.credential:firstboot.locale=C.UTF-8
```
--------------------------------
### Build and upload documentation on -stable branch
Source: https://github.com/systemd/systemd/blob/main/docs/RELEASE.md
Run this command on the -stable branch to build and upload the documentation.
```bash
ninja -C build doc-sync
```
--------------------------------
### Boot container with systemd-nspawn and set credential
Source: https://github.com/systemd/systemd/blob/main/docs/CREDENTIALS.md
Use systemd-nspawn to boot a container image and set a credential. The credential is passed to the container's systemd instance.
```shell
systemd-nspawn --set-credential=mycred:supersecret -i test.raw -b
```
--------------------------------
### Configure systemd DefaultLimitCORE
Source: https://github.com/systemd/systemd/blob/main/docs/COREDUMP.md
Creates a configuration file in /etc/systemd/system.conf.d/ to set the default core limit to infinity.
```console
$ mkdir -p /etc/systemd/system.conf.d
$ cat >/etc/systemd/system.conf.d/50-coredump.conf </etc/sysctl.d/50-coredump.conf <