Files
magpie/internal/cli/daemon_cli.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

128 lines
3.3 KiB
Go

package cli
import (
"errors"
"fmt"
"strconv"
"time"
"github.com/yetone/magpie/internal/daemon"
"github.com/yetone/magpie/internal/gateway"
)
const daemonUsage = "usage: magpie daemon [install|uninstall|start|stop|restart|status]"
// daemonWait is how long install, start and restart wait for the gateway
// to answer before saying where its log is; a var for the tests.
var daemonWait = 5 * time.Second
// magpie daemon …: `magpie serve` as a service of the user's, started at
// boot or login and again when it stops (systemd --user, launchd).
func daemonCmd(args []string) error {
if len(args) > 1 {
return errors.New(daemonUsage)
}
cmd := "status"
if len(args) == 1 {
cmd = args[0]
}
var err error
switch cmd {
case "status":
return daemonStatus()
case "install":
err = daemon.Install()
case "uninstall", "remove":
if err := daemon.Uninstall(); err != nil {
return err
}
fmt.Println(green.Render("✓"), "the magpie service is removed")
return nil
case "start":
err = daemon.Start()
case "stop":
if err := daemon.Stop(); err != nil {
return err
}
fmt.Println(green.Render("✓"), "the magpie service is stopped")
return nil
case "restart":
err = daemon.Restart()
default:
return errors.New(daemonUsage)
}
if err != nil {
return err
}
st, _ := daemon.Get()
switch cmd {
case "install":
fmt.Println(green.Render("✓"), "magpie serves the gateway as a service, from boot or login, started again when it stops")
fmt.Println(muted.Render(" file "), st.File)
if a := daemon.Linger(); a != "" {
fmt.Println(amber.Render("!"), a)
}
default:
fmt.Println(green.Render("✓"), "the magpie service is "+cmd+"ed")
}
deadline := time.Now().Add(daemonWait)
for {
if o := gateway.ServedBy(); o.Running {
fmt.Println(green.Render("●"), "the gateway answers on", bold.Render(gateway.URL()))
return nil
}
if !time.Now().Before(deadline) {
break
}
time.Sleep(250 * time.Millisecond)
}
fmt.Println(amber.Render("!"), "the gateway doesn't answer on", gateway.URL(), "yet ·", st.Logs)
return nil
}
func daemonStatus() error {
st, err := daemon.Get()
if err != nil {
return err
}
served := gateway.ServedBy()
if !st.Installed {
fmt.Println("the magpie service isn't installed ·", muted.Render("magpie daemon install"))
if served.Running {
fmt.Println(muted.Render(" another magpie (the app, magpie serve) answers on"), gateway.URL())
}
return nil
}
mark, word := amber.Render("○"), "not running"
if st.Running {
mark, word = green.Render("●"), "running"
}
line := "the magpie service is " + word
if st.PID > 0 {
line += " · pid " + strconv.Itoa(st.PID)
}
fmt.Println(mark, line)
if st.State != "" {
fmt.Println(muted.Render(" state "), st.State)
}
if st.LastExit != "" {
fmt.Println(muted.Render(" last exit"), st.LastExit)
}
start := "at boot or login"
if !st.Enabled {
start = "only when started"
}
fmt.Println(muted.Render(" start "), start)
fmt.Println(muted.Render(" file "), st.File)
fmt.Println(muted.Render(" logs "), st.Logs)
if served.Running {
fmt.Println(muted.Render(" gateway"), "answers on", gateway.URL(), muted.Render(served.Version))
} else {
fmt.Println(muted.Render(" gateway"), "doesn't answer on", gateway.URL())
}
for _, a := range st.Advice {
fmt.Println(amber.Render("!"), a)
}
return nil
}