386. Writing a service
This page is for an administrator who wants a program of their own to start at boot and be restarted when it dies, and for a developer adding a service to KDOS. KDOS has no systemd units: a service is a script in /etc/init.d that rcS (the boot sequence) starts at boot and that the service command manages, with its daemon kept alive by the supervisor ksvc. It covers the two places such a script can live. On one running machine, you write it into /etc/init.d by hand. In the KDOS tree, it goes into fs/etc/init.d/ when it belongs to the base system, or into a port’s build.sh when it belongs to that port’s package. Managing a service once it exists is on Services.
Installation
Nothing extra is needed. The supervisor is ksvc, from kdos-tools, and /etc/init.d/service_helper, from the base filesystem, gives a script the functions it calls. A daemon from a package you build yourself is installed with kpkg like any other port; see kpkg and Anatomy of a kpkg install.
A script added by hand to a running installed system belongs to no package: kdos why reports that no package owns it, and no package upgrade replaces or removes it. On the live medium it is kept only when a persistence store exists (kdos persist).
Configuration
The contract
rcS, rcK and service agree on what a service script is. Each rule below is read from the code that enforces it:
| Rule | Enforced by | When broken |
|---|---|---|
The file is /etc/init.d/NN_<name>.sh: two digits, an underscore, the name, .sh |
rcS, rcK, ksvc |
The script is never run and service does not find it |
| The file is executable | rcS, rcK, service list |
The script is skipped without a word, and service start fails without a message |
It takes start, stop and status, and prints a usage line and exits 1 for anything else |
the shipped scripts; service passes the verb through |
service commands do nothing useful |
start exits 0 when it started the service or deliberately skipped it, non-zero only on a failure |
rcS |
The splash marks the stage failed and shows the last six lines of output |
A skip prints [SKIP] <name>: <reason> and exits 0 |
the shipped scripts | The boot log says nothing about why the service is down |
A daemon runs in the foreground under supervise |
ksvc |
The supervisor sees the parent exit as soon as the daemon forks, and starts it again every five seconds |
start returns once the daemon is launched, or, for a daemon that owns a bus name, once it holds the name (wait_bus_name, at most ten seconds) |
rcS, which waits for each script |
The boot stops at that stage |
The <name> passed to supervise is letters, digits, _, - and ., at most 64 characters |
ksvc |
ksvc refuses it: bad service name |
NN places the script in the boot order. Pick a number above every script whose service yours needs: above 22_syslog to log through syslog from the first line, above 30_network and 42_networkmanager for the network, above 40_dbus for the system bus.
service_helper
# service_helper - Shared service management functions
# Source this file from individual service scripts via:
# . /etc/init.d/service_helper
#
# Thin wrappers over ksvc, which is C, and wait_bus_name. The supervisor must
# lead its own process group so that stopping it signals the group and the
# daemon goes with it; a respawn loop in a backgrounded shell subshell leads no
# group, and stopping it leaves the daemon running while reporting success.
#
# The command is an argument vector: `supervise foo /usr/sbin/foo --flag`, not
# one string that a later unquoted expansion would re-split.
#
# `supervise --final-exit N foo ...` names an exit status restarting cannot
# change — "not supported on this machine", "nothing here to watch": on it the
# supervisor stops instead of restarting the daemon every five seconds for ever.
#
# `supervise --facility NAME foo ...` sends the daemon's forwarded output to
# syslog under that facility instead of `daemon`, so syslog.conf files it with
# what the daemon logs itself: 41_polkitd.sh passes `authpriv`.
#
# `supervise --stop-grace SECS foo ...` is how long `stop_service` waits for
# the daemon to exit after SIGTERM before it sends SIGKILL; five seconds when
# not given. A daemon whose clean shutdown writes data out names a longer one.
#
# `supervise --restart-with OTHER foo ...` restarts foo's daemon whenever the
# daemon of the supervised service OTHER is restarted or stopped, and holds
# each start while OTHER's daemon is between two runs. 42_networkmanager.sh
# passes `dbus`: NetworkManager does not exit when its bus goes away.
#
# `supervise` on a name whose supervisor is alive starts nothing and prints
# `[SKIP] <name>: already supervised`, so `service start` on a running service
# is safe to repeat. Nor does it start one beside a daemon whose supervisor
# was killed: it waits for that daemon for the stop grace, then refuses with
# `[FAIL]`, and `stop_service` ends the daemon.
supervise() {
ksvc supervise "$@"
}
stop_service() {
ksvc stop-supervised "$1"
}
check_status() {
ksvc check "$1"
}
# `wait_bus_name NAME` returns 0 once NAME has an owner on the system bus, or
# 1 after ten seconds, saying so. A script whose daemon owns a bus name calls
# it after `supervise`, so the scripts after it in the order find the name
# taken. A daemon the supervisor runs ships no D-Bus activation file — the bus
# would otherwise start a second, unsupervised copy for a caller that came
# early, and the supervised one could then never take its name — so a call
# made before the name is owned is refused with ServiceUnknown instead.
# org.freedesktop.DBus has an owner as soon as the bus accepts connections.
wait_bus_name() {
local i
for ((i = 0; i < 100; i++)); do
dbus-send --system --print-reply --dest=org.freedesktop.DBus / \
org.freedesktop.DBus.NameHasOwner "string:$1" 2>/dev/null |
grep -q 'boolean true' && return 0
sleep 0.1
done
echo "[WARN] $1 is not on the system bus after 10 seconds"
return 1
}
supervise takes an argument vector, not a string: write supervise mydaemon /usr/sbin/mydaemon --foreground, each word its own argument. The options of ksvc supervise, --final-exit among them, are in ksvc and service.
A script in the base system
fs/etc/init.d/52_smartd.sh is the base system’s pattern with one addition, the exit statuses the supervisor is not to restart:
. /etc/init.d/service_helper
NAME="smartd"
DAEMON="/usr/sbin/smartd"
# THE DISK-HEALTH WATCHER. smartd polls every SATA, SAS and NVMe disk that
# answers SMART every thirty minutes and logs to the system log a failing
# health check, pending or uncorrectable sectors, new entries in the drive's
# error log and failed self-tests. /etc/smartd.conf is upstream's and ships
# as a bare DEVICESCAN; a `-m` or `-M exec` line there adds a route beyond the
# log.
#
# -n keeps it in the foreground, which is what `supervise` needs.
#
# THREE EXITS ARE FINAL. 17 is "no devices to monitor" — a virtual machine, or
# a machine whose disks do not answer SMART — and 2 and 6 are a smartd.conf it
# cannot parse or cannot read. Restarting changes none of them, and without
# `--final-exit` the supervisor would log each one every five seconds.
case "$1" in
start)
if [ ! -x "$DAEMON" ]; then
echo "[SKIP] $NAME: $DAEMON not found"
exit 0
fi
echo "[KDOS] Starting $NAME..."
supervise --final-exit 2 --final-exit 6 --final-exit 17 "$NAME" \
"$DAEMON" -n
;;
stop)
stop_service "$NAME"
;;
status)
check_status "$NAME"
;;
*)
echo "Usage: $0 {start|stop|status}"
exit 1
;;
esac
A script in a port
A port writes its script from build.sh, in a quoted heredoc whose delimiter is KDOS_SH, so the script is part of the recipe and testing/preflight.sh can check it. The ngircd port’s script skips until the server has a configuration file and an account, and runs the daemon as that account:
install -d "$PKG/etc/init.d"
cat > "$PKG/etc/init.d/79_ngircd.sh" <<'KDOS_SH'
#!/bin/bash
. /etc/init.d/service_helper
NAME="ngircd"
DAEMON="/usr/sbin/ngircd"
CONF="/etc/ngircd.conf"
case "$1" in
start)
[ ! -x "$DAEMON" ] && { echo "[SKIP] $NAME: $DAEMON not found"; exit 0; }
if [ ! -s "$CONF" ]; then
echo "[SKIP] $NAME: no $CONF (/usr/share/doc/ngircd/sample-ngircd.conf is the template)"
exit 0
fi
if ! getent passwd ngircd >/dev/null; then
echo "[SKIP] $NAME: no ngircd account (the port's postinstall makes it)"
exit 0
fi
echo "[KDOS] Starting $NAME..."
supervise "$NAME" setpriv --reuid=ngircd --regid=ngircd \
--init-groups "$DAEMON" -n -f "$CONF"
;;
stop) stop_service "$NAME" ;;
status) check_status "$NAME" ;;
*) echo "Usage: $0 {start|stop|status}"; exit 1 ;;
esac
KDOS_SH
chmod 755 "$PKG/etc/init.d/79_ngircd.sh"
ports/core/servers/ngircd/build.sh, lines 22–51
The account comes from the port’s postinstall.sh, which runs on the target at every install and writes under PKG_ROOT:
root="${PKG_ROOT:-/}"
grep -q '^ngircd:' "$root/etc/group" 2>/dev/null || groupadd -R "$root" -r ngircd
grep -q '^ngircd:' "$root/etc/passwd" 2>/dev/null || \
useradd -R "$root" -r -g ngircd -d /nonexistent -s /sbin/nologin ngircd
ports/core/servers/ngircd/postinstall.sh, lines 20–23
Why a script lives in the recipe and not beside it, and the rules a postinstall.sh keeps, are in Shipping a script the port carries and postinstall.sh.
Usage
Adding a service to one machine
Choose the number and the name. List what is there:
ls /etc/init.dWrite the script as root. This one starts a daemon at
/usr/local/sbin/mydaemonthat stays in the foreground when given--foreground; replace the three names with yours:#!/bin/bash . /etc/init.d/service_helper NAME="mydaemon" DAEMON="/usr/local/sbin/mydaemon" case "$1" in start) if [ ! -x "$DAEMON" ]; then echo "[SKIP] $NAME: $DAEMON not found" exit 0 fi echo "[KDOS] Starting $NAME..." supervise "$NAME" "$DAEMON" --foreground ;; stop) stop_service "$NAME" ;; status) check_status "$NAME" ;; *) echo "Usage: $0 {start|stop|status}" exit 1 ;; esacSave it as
/etc/init.d/90_mydaemon.sh.Make it executable:
sudo chmod 755 /etc/init.d/90_mydaemon.shStart it and check it:
sudo service start mydaemon service status mydaemon sudo cat /run/kdos-svc.mydaemon.logOn the first start the log’s first line is the supervisor’s
[KDOS] (mydaemon) Starting: /usr/local/sbin/mydaemon.Stop it, and check that the daemon is gone with the supervisor:
sudo service stop mydaemon pgrep -a mydaemonpgrepshould print nothing.The service starts at every boot from here on. To keep it installed but off, run
sudo service disable mydaemon.
Adding a service to the tree
Base system. Put the script at
fs/etc/init.d/NN_<name>.shand make it executable in git (mode100755). Copy it into the build root and repack the image, on your machine:make build BUILD_ARGS="--phases 10_bootstrap,70_image --steps 10_bootstrap:000_file_system.sh"See The file system.
A port. Write the script into the port’s
build.shas above,install -d "$PKG/etc/init.d"first andchmod 755after, and an account, if it needs one, intopostinstall.sh. Rebuild the port and repack:make build BUILD_ARGS="--phases <phase>,70_image --rebuild <port>"Check the wiring, on your machine:
testing/preflight.shIt refuses a script under
fs/etc/init.dthat is not executable or not recorded in git as100755, and one whoseDAEMON=line names akdos-*program that nobuild.shinstalls. In a port, it reads every heredoc opened with<<'KDOS_SH', refuses one that does not parse underbash -nand, when a build tree exists, one whose commands are on no image.A service that listens on the network also needs a firewall rule; see Adding your own rules.
Tips
- Keep the daemon in the foreground. Every shipped script passes the daemon’s own switch for it:
-Dforsshd,-Fforsyslogd,-nforsmartd,-dforchronyd,--no-daemonforthermald. - The daemon needs no pid file. The supervisor writes its own process id to
/run/kdos-svc.<name>.pid, where<name>is the first argument ofsupervise, andstopandstatuslook for a supervisor at the id that file names; no daemon writes a file of that name, so a daemon’s own/run/<name>.pidcannot replace it. Nothing reads the daemon’s file either. Turn it off when the daemon can (70_sshd.shpassessshd-o PidFile=none), or move it beside the daemon’s other run files (22_syslog.shpassessyslogd-P /run/syslogd/syslogd.pid). A daemon that refuses to start while its pid file exists, as babeld does, must have it turned off, or one killed outright leaves a file that stops every restart. - Skip in the script, before supervising. A daemon that cannot run on this machine and exits is restarted every five seconds for as long as the machine is up. Test for what it needs (a device, a kernel feature, a configuration file) first, and print
[SKIP]with the reason. - Name a final exit. When only the daemon itself can tell that it has nothing to do, find the exit status it uses for that and pass
--final-exit <code>tosupervise. - Name a stop grace when shutting down takes time.
stopsendsSIGTERM, waits for the daemon to exit, and sendsSIGKILLafter five seconds. A daemon that writes data out before it exits — a database flushing its buffers, a file server waiting for its children — passes--stop-grace <seconds>tosupervise:76_postgresql.shpasses 30. - Run as an account, not as root, with
setpriv --reuid=<user> --regid=<group> --init-groupsin front of the daemon, as79_ngircd.shdoes. Test for the account first, as it does, withgetent passwd <user>(from musl-utils). - Start every long-running process through
supervise, never with&. The supervisor points its own output and the daemon’s at its log forwarder and its input at/dev/null, sosudo service start mydaemon | tee out.txtreturns as soon as the script does. A process the script backgrounds itself keeps the script’s output open for as long as it lives, so a pipeline reading that output waits as long, and nothing restarts the process when it dies.rcSwrites each script’s output to/run/kdos-init.<name>.logand prints the file afterwards. - A daemon that owns a system-bus name ships no D-Bus activation file. Delete the one its build installs in
/usr/share/dbus-1/system-services/from the port’sbuild.sh, as the polkit and modemmanager ports do, and endstartwithwait_bus_name <name>aftersupervise. With the file, a client that calls the name before the supervised daemon holds it, or while it restarts, makes the bus start a second copy outside the supervisor; the supervised one then cannot take the name and is restarted every five seconds for as long as the other copy runs. - Name the daemon by its full path, as every shipped script does. Under
rcSandrcKthePATHincludes/usr/local, but a script started byserviceinherits thePATHof whatever ran it. - Per-machine state, such as a host key or a database created on first start, belongs in the init script, not in the package: whatever a package or a
postinstall.shwrites while the image is built is the same on every machine installed from it.70_sshd.shrunsssh-keygen -Afor this.
Troubleshooting
service says Error: Service '<name>' not found. The file name is wrong: it must be two digits, _, the name and .sh.
rcS never runs the script, service list does not show it, and service start prints nothing. The file is not executable. ls -l /etc/init.d/ must show -rwxr-xr-x.
The boot stops at the script’s stage. start did not return. Either the daemon was started in the foreground without supervise, or the script waits on a pipe that a process it backgrounded still holds open. Boot with emergency (see Init and runlevels), make the script non-executable with chmod -x, and reboot.
The supervisor’s log shows Exited with code 127. The supervisor could not execute the command: the path is wrong or the file is not executable. supervise runs the command through execvp, so a bare name is looked up in PATH.
The daemon exits at once and restarts every five seconds. Most often it forked into the background and the supervisor saw the parent exit: the log repeats [KDOS] (<name>) Exited with code 0. Restarting in 5s..., a clean exit, after each Starting: line. Add the daemon’s foreground switch. Otherwise read its own complaint in /run/kdos-svc.<name>.log (sudo less; the file is root’s, mode 0640).
service stop reports Stopped, but a process of the daemon keeps running. A child of the daemon left the supervisor’s process group (one that calls setsid itself does): stop signals the group and the daemon’s own pid, never such a child. While the service runs, compare the process groups:
cat /run/kdos-svc.<name>.pid
ps -eo pid,pgid,args | grep <daemon>
The first number is the supervisor’s, and every process of the service should show it in the PGID column.
After the system bus restarts, the daemon runs on but answers nothing on the bus. It does not exit when its bus connection closes, so its supervisor never restarts it, and service status still says [ OK ]. Supervise it with supervise --restart-with dbus <name> …, as 42_networkmanager.sh does: the supervisor then restarts it once the new bus is up.
testing/preflight.sh reports KDOS_SH heredoc: and a syntax error. The script inside the port’s heredoc does not parse under bash -n; the message after the colon is bash’s, and its line number counts from the first line after <<'KDOS_SH'. Keep the delimiter quoted, <<'KDOS_SH': an unquoted one lets $1 and $PATH expand while the recipe runs, and preflight.sh does not read such a heredoc at all.
testing/preflight.sh reports KDOS_SH heredoc runs '<command>', which is on no image. A line of the script starts with a program that is in no bin or sbin directory of the build tree. Add the port that installs it to the recipe’s depends, or call a program the image has.
Known gaps
Known gaps lists nothing for this topic. For a script added to the tree: A clone does not check what it pushes unless you enable the hook.
See also
- Adding a root daemon: the rules KDOS’s own daemons keep
- The shape they share: supervision, logging and skipping
- ksvc and service:
superviseand its options - Shipping a script the port carries: the
KDOS_SHheredoc - Services, Init and runlevels, Logs