Commit cc943387 by PLN (Algolia)

linux: systemd user-unit integration for the agent

devname agent install on Linux writes ~/.config/systemd/user/
devname.service (env-python3 ExecStart, Restart=on-failure,
WantedBy=default.target) and enables it — no root for the daemon; the
README documents the two one-time options for binding low ports
(sysctl ip_unprivileged_port_start or setcap on caddy), linger for
boot-time start, and plain 'devname serve' for other inits. doctor and
agent status are platform-aware; the unit is covered by a test.
parent 0eb423be
...@@ -27,19 +27,52 @@ unprivileged process can bind a low port on macOS). ...@@ -27,19 +27,52 @@ unprivileged process can bind a low port on macOS).
## Install ## Install
Requirements: macOS (launchd agent), [Caddy](https://caddyserver.com), Python 3. Requirements: macOS or Linux, [Caddy](https://caddyserver.com), Python 3.
For https: [mkcert](https://github.com/FiloSottile/mkcert) with a trusted root For https: [mkcert](https://github.com/FiloSottile/mkcert) with a trusted root
(`mkcert -install`). (`mkcert -install`).
```bash ```bash
git clone <this repo> && cd devname git clone https://git.nech.pl/pln/devname.git && cd devname
sudo cp bin/devname /usr/local/bin/devname && sudo chmod +x /usr/local/bin/devname sudo cp bin/devname /usr/local/bin/devname && sudo chmod +x /usr/local/bin/devname
devname agent install # supervisor integration, see below
devname agent install # one launchd agent (label DEVNAME_LABEL, default: devname)
devname ensure myapp # myapp.localhost — allocated or adopted, Caddy reloaded devname ensure myapp # myapp.localhost — allocated or adopted, Caddy reloaded
devname doctor # check the whole chain devname doctor # check the whole chain
``` ```
### macOS — launchd
One launchd agent (`pl.nech.devname`, label overridable via `DEVNAME_LABEL`)
runs `devname serve`: Caddy as a supervised child plus the index server.
macOS lets an unprivileged process bind a low port only on the wildcard
address, which is exactly what devname does — no privileges needed.
### Linux — systemd (user unit)
`devname agent install` writes `~/.config/systemd/user/devname.service` and
starts it — no root for the daemon itself:
```bash
devname agent install # unit + daemon-reload + enable --now
devname agent status # is-active
loginctl enable-linger $USER # optional: run at boot without a login session
```
Binding `:80`/`:443` as an unprivileged user needs one of (pick one, once):
```bash
sudo sysctl net.ipv4.ip_unprivileged_port_start=80 # or 0
sudo setcap cap_net_bind_service=+ep "$(command -v caddy)"
```
`*.localhost` resolves to loopback through systemd-resolved (most distros);
without it, add the names to `/etc/hosts` yourself.
### Other inits
`devname serve` is a plain foreground process — wrap it in whatever your
system uses (OpenRC `supervise-daemon`, runit, a tmux window). It renders the
Caddyfile, starts Caddy, serves the index page, and cleans up on SIGTERM.
## Commands ## Commands
``` ```
......
...@@ -429,6 +429,50 @@ def launchd_loaded(): ...@@ -429,6 +429,50 @@ def launchd_loaded():
return subprocess.run(["launchctl", "print", f"gui/{os.getuid()}/{LABEL}"], capture_output=True).returncode == 0 return subprocess.run(["launchctl", "print", f"gui/{os.getuid()}/{LABEL}"], capture_output=True).returncode == 0
def systemd_unit():
"""User unit: the daemon never needs root; only binding :80/:443 does
(one sysctl or a setcap on caddy — see README)."""
return f"""[Unit]
Description=devname: stable local names for dev servers
After=network-online.target
Wants=network-online.target
[Service]
ExecStart=/usr/bin/env python3 {os.path.abspath(__file__)} serve
Restart=on-failure
RestartSec=2
[Install]
WantedBy=default.target
"""
def systemd_active():
r = subprocess.run(["systemctl", "--user", "is-active", "devname.service"], capture_output=True, text=True)
return r.returncode == 0 and r.stdout.strip() == "active"
def agent_loaded():
return systemd_active() if sys.platform.startswith("linux") else launchd_loaded()
def cmd_agent_linux(a):
if a.action == "status":
print("active" if systemd_active() else "not active")
return 0 if systemd_active() else 1
unit_dir = os.path.expanduser("~/.config/systemd/user")
os.makedirs(unit_dir, exist_ok=True)
with open(os.path.join(unit_dir, "devname.service"), "w") as fh:
fh.write(systemd_unit())
for cmd in (["systemctl", "--user", "daemon-reload"],
["systemctl", "--user", "enable", "--now", "devname.service"]):
r = subprocess.run(cmd, capture_output=True, text=True)
if r.returncode:
raise Err("systemctl --user failed: " + r.stderr.strip()[-200:])
print("devname: systemd user unit installed and started", file=sys.stderr)
return 0
def cmd_doctor(a): def cmd_doctor(a):
ok = True ok = True
...@@ -437,7 +481,10 @@ def cmd_doctor(a): ...@@ -437,7 +481,10 @@ def cmd_doctor(a):
ok = ok and good ok = ok and good
print(("PASS " if good else "FAIL ") + text) print(("PASS " if good else "FAIL ") + text)
line(os.path.exists(CADDY), f"caddy at {CADDY}") line(os.path.exists(CADDY), f"caddy at {CADDY}")
line(launchd_loaded(), f"launchd agent {LABEL} loaded") if sys.platform.startswith("linux"):
line(agent_loaded(), "systemd user unit devname.service active")
else:
line(launchd_loaded(), f"launchd agent {LABEL} loaded")
line(os.path.exists(ADMIN_SOCK), "caddy admin socket present") line(os.path.exists(ADMIN_SOCK), "caddy admin socket present")
try: try:
urllib.request.urlopen(urllib.request.Request("http://127.0.0.1/", headers={"Host": "doctor.invalid"}), timeout=3) urllib.request.urlopen(urllib.request.Request("http://127.0.0.1/", headers={"Host": "doctor.invalid"}), timeout=3)
...@@ -464,6 +511,8 @@ def cmd_doctor(a): ...@@ -464,6 +511,8 @@ def cmd_doctor(a):
def cmd_agent(a): def cmd_agent(a):
if sys.platform.startswith("linux"):
return cmd_agent_linux(a)
if a.action == "status": if a.action == "status":
print("loaded" if launchd_loaded() else "not loaded") print("loaded" if launchd_loaded() else "not loaded")
return 0 return 0
......
...@@ -151,3 +151,12 @@ class DevnameTests(unittest.TestCase): ...@@ -151,3 +151,12 @@ class DevnameTests(unittest.TestCase):
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
def test_systemd_unit_is_well_formed(self):
unit = self.dn.systemd_unit()
self.assertIn("[Unit]", unit)
self.assertIn("[Service]", unit)
self.assertIn("[Install]", unit)
self.assertIn(" serve", unit) # the same entrypoint the plist runs
self.assertIn("WantedBy=default.target", unit) # user unit, not system
self.assertNotIn("launchctl", unit)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment