norboten · cheat sheet

A job that cannot fail cannot be trusted — cheat sheet

python, boot-systemd
import sys, urllib.request, json, os, tempfile, http.client

urllib.request.urlopen(url, timeout=10)          # always a timeout
# HTTPError (4xx/5xx), URLError, TimeoutError are OSError; JSONDecodeError is ValueError
try:
    data = fetch()
except (OSError, ValueError, http.client.HTTPException) as e:
    print(f"job: {e}", file=sys.stderr)
    sys.exit(1)

fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path))   # same filesystem as the target
with os.fdopen(fd, "w") as f:
    json.dump(data, f); f.flush(); os.fsync(f.fileno())
os.chmod(tmp, 0o644)
os.replace(tmp, path)                            # atomic swap

if __name__ == "__main__":
    sys.exit(main())                             # return value → exit status
$ systemctl list-timers NAME.timer              # last and next run
$ sudo journalctl -u NAME.service -b            # what the job printed this boot
$ systemctl show NAME.service -p Result -p ExecMainStatus
$ systemctl cat NAME.service                    # unit, drop-ins, EnvironmentFile path
$ sudo ss -ltnp                                 # who listens on which port
$ curl -sS URL; echo "exit=$?"                  # 7 = could not connect
$ stat -c '%i %a' FILE                          # inode and mode: in place or replaced?
$ timeout 20 CMD; echo "exit=$?"                # 124 = killed by timeout
$ python3 -m http.server -d DIR PORT            # serve files for a test