Files
magpie/internal/daemon/launchd.go
T
yetone 58ea9cade8 daemon: a launch agent written as Background is mended to Standard (#2961)
The commit before writes ProcessType Standard for new installs. Every
agent already installed kept Background until the user ran `magpie
daemon install` again, which no one is told to do. Now `magpie serve`
rewrites that one line of the installed launch agent as it starts
(daemon.Mend), leaving the rest of the user's install as it is, and
says so in the log. launchd reads the file when it loads the agent, not on
a kickstart: so it is taken up at the next login, or at `magpie daemon
restart`, which now takes the agent out and loads it again instead of
`kickstart -k` (and `start` does the same when it mends the file).

This is the same class as #6261: the gateway's process held to
background priority by macOS while agents wait on it.

Run:
- TestLaunchdOldAgentMended: an installed agent rewritten to the old
  Background line is mended byte for byte to what Install writes, 0600,
  with no launchctl call from Mend; Restart boots it out before loading
  it; on Linux nothing is touched. TestLaunchdInstall's restart now
  expects bootout, then load. Broken by hand (mended never mends):
  red at "Mend: the plist is" and "want a bootout first".
- TestLaunchdInstall (plutil -lint on darwin), the whole daemon package,
  vet on darwin, linux, windows: ok; and the package run named in 6261's commit: all ok (gateway 908s, plugin 159s, cli 52s) at base 7eecbcc56; at the pushed head (rebased on 459d668b3, which touches none of these files) build, gofmt, linux and windows vet, and awake, daemon, cli tests ok again

- Real launchd on mote (macOS 27.2), a throwaway agent of its own label
  running /bin/sleep: as Background, launchctl print says "spawn type =
  background (5)" and ps pri 4, the band #6261's app was napped into.
  The file rewritten to Standard and `kickstart -k`: still background
  (5), pri 4. bootout + bootstrap: "spawn type = daemon (3)", pri 20.
  So a kickstart doesn't take the mended file up, and restart's reload
  does.

Not tried: a real `magpie daemon install` on mote (it would take the
gateway's port from the other sessions there).
2026-11-13 21:31:01 +08:00

204 lines
5.7 KiB
Go

package daemon
import (
"html"
"log"
"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 running exe with args, with env set in it.
// ProcessType is Standard, not Background: the gateway is on the request
// path of interactive agents, and Background throttles it on macOS.
func plist(exe string, args, 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) + strings.Join(mapped(args, s), "") + `</array>
<key>RunAtLoad</key><true/>
<key>KeepAlive</key>
<dict><key>SuccessfulExit</key><false/></dict>
<key>ThrottleInterval</key><integer>5</integer>
` + processType + `
<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, args, 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, args, 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.mended() {
l.unload()
}
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
}
// restart takes the agent out and loads it again: launchd reads the file
// when it loads it, not on a kickstart, so a file mended or changed since
// (Mend, as the service started) is what runs.
func (l launchd) restart() error {
l.unload()
return l.start()
}
// oldProcessType is what an agent written before #2961 runs the gateway
// as, and processType what plist writes now.
const (
oldProcessType = "<key>ProcessType</key><string>Background</string>"
processType = "<key>ProcessType</key><string>Standard</string>"
)
// mended rewrites an agent written before #2961, which ran the gateway as
// Background, to run it as Standard, and says whether it did. It changes
// that line alone: the rest is the user's install. launchd takes it up
// when it next loads the agent: at the next login, or a start or restart.
func (l launchd) mended() bool {
b, err := os.ReadFile(l.file())
if err != nil || !strings.Contains(string(b), oldProcessType) {
return false
}
if err := private(l.file(), []byte(strings.Replace(string(b), oldProcessType, processType, 1))); err != nil {
log.Printf("daemon: can't rewrite %s to run the gateway as Standard: %v", l.file(), err)
return false
}
return true
}
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 mapped(xs []string, f func(string) string) []string {
out := make([]string, len(xs))
for i, x := range xs {
out[i] = f(x)
}
return out
}
func launchctl(args ...string) (string, error) { return run("launchctl", args...) }