Ping CronMissed from systemd

On this page

A systemd service can report on itself without a wrapper script: ExecStartPre sends the start ping, and ExecStopPost sends the result using the exit status systemd already knows. The leading dash makes sure a failed ping never fails the unit.

What should a systemd service job send?

  • A request to /start before the work, so CronMissed can time the run and notice a job that never finishes.
  • A request to the plain URL when the work succeeded, or to /fail when it did not. /<exit status> works too: 0 is a success and any other number is a failure.
  • The end of the output in the request body, up to 100,000 bytes, so the alert shows the error without a trip to the server.

What are the unit files?

nightly-backup.service
[Unit]
Description=nightly-backup

[Service]
Type=oneshot
ExecStartPre=-/usr/bin/curl -fsS --max-time 10 --retry 5 --retry-connrefused -o /dev/null "https://ping.cronmissed.com/5f0c1b2e-7a3d-4c8e-9b61-2d4f8a7e3c10/start"
ExecStart=/usr/local/bin/backup.sh
ExecStopPost=-/bin/sh -c 'case "$$EXIT_STATUS" in [0-9]*) s=$$EXIT_STATUS ;; *) s=fail ;; esac; curl -fsS --max-time 10 --retry 5 --retry-connrefused -o /dev/null "https://ping.cronmissed.com/5f0c1b2e-7a3d-4c8e-9b61-2d4f8a7e3c10/$$s"'
nightly-backup.timer
[Unit]
Description=Run nightly-backup on schedule

[Timer]
OnCalendar=*-*-* 02:30:00 UTC
Persistent=true

[Install]
WantedBy=timers.target
  • The leading "-" keeps a failed ping from failing the unit. A unit killed by a signal reports a failure.

Keep the ping URL in an environment variable or a secret store, never in a public repository: the URL is the check's only credential.

How do I install and test them?

  1. Save both files in /etc/systemd/system, run systemctl daemon-reload, and enable the timer with systemctl enable --now nightly-backup.timer.
  2. Run systemctl start nightly-backup.service to test the service by hand.
  3. Run systemctl list-timers to see when the timer fires next.
  4. Read the unit's output with journalctl -u nightly-backup.service.

Sources

Questions and answers

Why $$ in the unit file?
systemd expands a single $ itself in unit files. Writing $$ passes a literal $ to the shell, which is what the status variable needs.
Should the ping URL be in the unit file?
It is better in an EnvironmentFile with restricted permissions, loaded with EnvironmentFile=, so the unit can be shared without the credential.
Create the check these snippets report to

Make a check, copy its ping URL into the snippet, and run the job once.

Start monitoring