The box and what it runs

An always-on local device at my house is the server for my own work. It runs two small web applications, a third service that an outside platform calls, and about ten scheduled jobs. It sits on a shelf with no monitor. Nobody logs in to it. I reach it over a mesh VPN and SSH.

That last fact decides how everything on it has to be scheduled, and I learned it by having a job not run.

Agents need a session that never exists

macOS has two kinds of scheduled job. A user agent lives in the user's own folder and runs inside that user's login session. A system daemon lives in the system folder, is owned by root, and runs whether anyone is logged in or not.

In August a job I put in my user's agent folder over SSH loaded without an error and never ran. who showed no console session, and with no console session the per-user domain those agents belong to does not exist. Loading the job into that domain directly failed with Domain does not support specified action.

So the rule on this box is short. Every service and every scheduled job is a system daemon. The definition file goes in /Library/LaunchDaemons/, owned by root. The system domain runs it. If the work does not need root, the definition names an ordinary user and the job drops to that user before it starts. The certificate renewal is the one job that runs as root, because the command it calls needs root.

What a daemon definition looks like

This is the shape of the definition for one of the web applications, with the names made generic:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
  "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key><string>com.example.app</string>
    <key>ProgramArguments</key>
    <array><string>/opt/app/bin/app-service.sh</string></array>
    <key>UserName</key><string>appuser</string>
    <key>RunAtLoad</key><true/>
    <key>KeepAlive</key><true/>
    <key>ThrottleInterval</key><integer>15</integer>
    <key>StandardOutPath</key><string>/opt/app/logs/app.log</string>
    <key>StandardErrorPath</key><string>/opt/app/logs/app.log</string>
</dict>
</plist>

RunAtLoad starts it at boot. KeepAlive starts it again whenever it exits, and ThrottleInterval keeps a crash loop from spinning faster than once every fifteen seconds. A scheduled job swaps KeepAlive for StartInterval (seconds) or StartCalendarInterval (a time of day). Three commands cover the whole lifecycle:

sudo launchctl bootstrap system /Library/LaunchDaemons/com.example.app.plist
sudo launchctl kickstart -k system/com.example.app   # restart it
launchctl print system/com.example.app               # state, last exit

Absolute everything

A daemon starts with almost nothing from your shell. Each of these has cost me time on this box:

  • Home is not your home. Under the system domain as root, ~ is root's home. The renewal job wrote its log to a path under ~ that did not exist for root.
  • The search path is minimal. Tools from a package manager are not on it, over non-interactive SSH or under a daemon. Call every binary by its full path, or set PATH and HOME in the definition's EnvironmentVariables.
  • Privacy grants follow the binary path. The interpreter needs Full Disk Access to read the external volume. A package update changed its resolved path, the grant stopped matching, and the service crash-looped at launch while the same command run by hand over SSH worked. I granted the new path and pinned the version.
  • Rotation must copy and truncate. The daemons hold their log files open. Renaming a log leaves the live process writing to the renamed file, so the daily rotation job copies and truncates instead.

The wrapper does the refusing

ProgramArguments points at a short wrapper, not at the application. The wrapper checks the one precondition that matters and refuses to start without it:

#!/bin/bash
set -u
/opt/app/bin/mount-data-volume.sh || true
if [[ ! -f /Volumes/data/app/app.db ]]; then
    echo "$(date) - ERROR - data volume not mounted; refusing to start" >&2
    exit 1
fi
source /opt/app/app.env
cd /opt/app
exec /opt/app/venv/bin/python3 app.py

Starting without the data volume would create an empty database on the boot disk and serve it as if nothing were wrong. A failed start is better. The exec replaces the wrapper with the application, so the scheduler watches the real process.

The watchdogs, in the order they earn their place

Restart on exit. KeepAlive is the first watchdog and it is free. It only catches a process that exits. It does nothing for one that is alive and stuck.

A health probe that sends a diagnosis. Every five minutes a daemon requests the application's health endpoint and looks for "status":"ok". It emails on a change of state only, plus one reminder every six hours while down, and the email carries the likely answer: mount state, the service's state, boot disk free space, the last five error lines. It does not restart anything. In October the application was alive but stuck on a database lock held by a second process. A restart would not have cleared that process. Killing it did. That story is in the SQLite post.

A mount guard. The external data volume drops out on its own, and scripts once wrote to the bare mount point on the boot disk with no error. One script now owns mounting and every wrapper calls it. The details are in the device-ID guard post.

Disk space. A daily check logs how full the boot disk and the data volume are, and emails when either passes 85 percent or the data volume is not mounted. I wrote it and committed it, and as of this week it is not loaded: the definition is not in the system folder and there is no log. A watchdog that is not installed is the same as none. It is next on the list.

Checks from outside. A watchdog on the box shares the box's network. On November 7 the probe saw the application go down at 10:12 and could not send the email, because it could not resolve the mail server's name. It sent the recovery at 10:17. For the two services reachable from the internet, Route 53 health checks run from outside my network and alarm to email, as described in the health check post. They check that the service answers, not the date on the certificate. The renewal job here once failed silently for twelve weeks, which is its own post. Its last run, on November 16, logged a certificate valid to December 20. The expiry check that post recommends, run from another machine, is not built yet.

One gap I know about

During the October lock incident the application's log went silent and the service was degraded for about a day and a half before the probe started to flap. Nothing alerts on a log that stops growing. A check on the log's modification time is cheap, and I have not added it.

If you are setting one up

  • On a box nobody logs in to, use system daemons only. A user agent will load and never run.
  • Name a non-root user in the definition unless the job truly needs root.
  • Absolute paths for every binary, script, log and config file. Set HOME and PATH explicitly if a script depends on them.
  • Point the definition at a wrapper that refuses to start when a precondition fails, and exec the real process.
  • Alert on a change of state, with the diagnosis in the message.
  • Put at least one check on a different network, and check the certificate's expiry date there.
  • Confirm each watchdog is loaded with launchctl print. Written is not running.