Files
magpie/internal/daemon/launchd.go
T
yetone 5617281f55 cli: magpie daemon install|uninstall|start|stop|restart|status keeps the gateway running as a service (HuanCheng on Discord)
What changed: a new internal/daemon package and `magpie daemon`, which run
`magpie serve` as the user's own service, with no window and no desktop
session.
- Linux: a systemd user unit at ~/.config/systemd/user/magpie.service
  (Restart=on-failure), driven by systemctl --user. status reads
  `systemctl --user show`, and says `sudo loginctl enable-linger $USER`
  when the user doesn't linger. su/sudo without the user's bus, no
  systemd, and WSL without systemd each get an error that says what to
  do.
- macOS: a launch agent, com.yetone.magpie.serve (RunAtLoad, KeepAlive on
  failure), loaded with launchctl bootstrap gui/$UID. Its log is
  ~/Library/Logs/magpie/serve.log.
- Windows and Android: refused, pointing to `magpie autostart on` (or to
  WSL).
- The service carries PATH, the proxy variables, MAGPIE_*, the XDG folders
  and the agents' folder variables from the install shell. The file is
  0600 because a proxy can hold a password. It runs magpie by its PATH
  name when that is the same file, so Homebrew's link survives updates.
  It refuses a go-build binary and an AppTranslocation copy.
- Install is refused while `magpie autostart` is on: the tray app serves
  the gateway too, and the two would crash-loop on the port.
- Docs: a reference.md section, and one sentence on the site's start page
  (en, zh, ja).

Why: users on headless Linux boxes asked for a supported way to keep
`magpie serve` up across reboots instead of hand-written units. The
existing `magpie autostart` needs a desktop session (an XDG autostart
entry).

What was run:
- gofmt -l; go vet on darwin, GOOS=linux -tags nogui, and GOOS=windows.
- go test ./internal/daemon ./internal/cli on macOS, at origin/main
  5b9530b56.
- The daemon tests cross-built for linux/arm64 and run in a Debian
  container.
- The tests use fake systemctl, launchctl and loginctl on PATH in a test
  home.
- Each guarantee was broken by hand and its test went red: the % escape,
  the autostart refusal, the 0600 chmod, the bootout before re-bootstrap,
  the go-build refusal, the bus advice, the last-exit filter and the
  PATH link.
- Real use on Linux: a Debian bookworm container running systemd as PID 1,
  with the linux/arm64 build, as an unprivileged user.
  - install: the gateway answered on :3425, and the unit was 0600.
  - kill -9: systemd restarted it 5s later.
  - Container restart with linger on: it came back by itself.
  - restart, stop, start and uninstall worked, and the unit and its wants
    link were gone afterwards.
  - Under sudo without XDG_RUNTIME_DIR it printed the bus advice.
- macOS: the darwin build ran `magpie daemon install` under a sandbox HOME
  with a fake launchctl. plutil -lint passed on the plist, and the calls
  were print and then bootstrap.

What wasn't: no real launch agent was loaded on a Mac (deliberately: never
on this machine), so launchd's own acceptance of the plist is checked
only by plutil. The linger advice was checked by the unit test, not seen
from a real SSH login. Windows was not run beyond vet.
2026-10-13 17:05:59 +08:00

167 lines
4.3 KiB
Go

package daemon
import (
"html"
"os"
"path/filepath"
"strconv"
"strings"
)
// launchd runs the service as a launch agent of the user's: started at
// login, and again when it stops with a failure.
type launchd struct{}
// Label is the launch agent's; the tray's at login is com.yetone.magpie.
const Label = "com.yetone.magpie.serve"
func home() string {
h, _ := os.UserHomeDir()
return h
}
func (launchd) file() string {
return filepath.Join(home(), "Library", "LaunchAgents", Label+".plist")
}
func logFile() string { return filepath.Join(home(), "Library", "Logs", "magpie", "serve.log") }
func (launchd) logs() string { return "tail -f " + strconv.Quote(logFile()) }
func domain() string { return "gui/" + strconv.Itoa(os.Getuid()) }
func service() string { return domain() + "/" + Label }
// plist is the launch agent for exe, with env set in it.
func plist(exe string, env []string) string {
s := func(v string) string { return "<string>" + html.EscapeString(v) + "</string>" }
var b strings.Builder
b.WriteString(`<?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">
<!-- Written by magpie daemon install; magpie daemon uninstall removes it. -->
<plist version="1.0">
<dict>
<key>Label</key>` + s(Label) + `
<key>ProgramArguments</key>
<array>` + s(exe) + s("serve") + `</array>
<key>RunAtLoad</key><true/>
<key>KeepAlive</key>
<dict><key>SuccessfulExit</key><false/></dict>
<key>ThrottleInterval</key><integer>5</integer>
<key>ProcessType</key><string>Background</string>
<key>StandardOutPath</key>` + s(logFile()) + `
<key>StandardErrorPath</key>` + s(logFile()) + `
`)
if len(env) > 0 {
b.WriteString("\t<key>EnvironmentVariables</key>\n\t<dict>\n")
for _, kv := range env {
k, v, _ := strings.Cut(kv, "=")
b.WriteString("\t\t<key>" + html.EscapeString(k) + "</key>" + s(v) + "\n")
}
b.WriteString("\t</dict>\n")
}
b.WriteString("</dict>\n</plist>\n")
return b.String()
}
func (l launchd) install(exe string, env []string) error {
if err := os.MkdirAll(filepath.Dir(l.file()), 0o755); err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(logFile()), 0o755); err != nil {
return err
}
if err := private(l.file(), []byte(plist(exe, env))); err != nil {
return err
}
// one loaded before runs the old plist until it is taken out
l.unload()
_, err := launchctl("bootstrap", domain(), l.file())
return err
}
func (l launchd) uninstall() error {
if _, err := os.Stat(l.file()); err != nil {
return nil
}
l.unload()
if err := os.Remove(l.file()); err != nil && !os.IsNotExist(err) {
return err
}
return nil
}
// loaded reports whether launchd has the agent, running or not.
func (launchd) loaded() bool {
_, err := launchctl("print", service())
return err == nil
}
// unload takes the agent out of launchd, stopping it; one not loaded is
// no failure.
func (l launchd) unload() {
if l.loaded() {
launchctl("bootout", service())
}
}
func (l launchd) start() error {
if !l.loaded() {
_, err := launchctl("bootstrap", domain(), l.file())
return err
}
_, err := launchctl("kickstart", service())
return err
}
// stop takes it out of launchd: stopped alone, KeepAlive would have it
// back. The next login, or start, loads it again.
func (l launchd) stop() error {
if !l.loaded() {
return nil
}
_, err := launchctl("bootout", service())
return err
}
func (l launchd) restart() error {
if !l.loaded() {
return l.start()
}
_, err := launchctl("kickstart", "-k", service())
return err
}
func (l launchd) status() (Status, error) {
// a plist in LaunchAgents is loaded at every login
st := Status{Enabled: true}
out, err := launchctl("print", service())
if err != nil {
st.State = "not loaded"
return st, nil
}
for _, line := range strings.Split(out, "\n") {
k, v, ok := strings.Cut(strings.TrimSpace(line), " = ")
if !ok {
continue
}
switch k {
case "state":
if st.State == "" {
st.State = v
}
case "pid":
if n, err := strconv.Atoi(v); err == nil && n > 0 {
st.PID = n
}
case "last exit code":
if v != "0" && !strings.HasPrefix(v, "(never") {
st.LastExit = v
}
}
}
st.Running = st.State == "running"
return st, nil
}
func launchctl(args ...string) (string, error) { return run("launchctl", args...) }