Files
magpie/internal/gui/port.go
T
yetone 9d0c9b41ea serve: follow an update put in where it runs from; a replaced magpie.real is magpie
acezan on Discord (Linux 5.15, 0.1.2959 to 0.1.2960): `magpie web` as a
system unit updated /root/.local/bin/magpie.real, and the user unit's
`magpie serve` (`magpie daemon install`) ran on for good from "magpie.real
(deleted)". The panel said an older magpie served the gateway, and its
"close it here" then said the port holder "isn't magpie" and left it.

Why serve stayed old: the app and `magpie web` follow the program they
started from (gui's followReplaced) and restart into an update; plain
`magpie serve` had no such look, and answered `magpie update`'s restart
ask (gateway.RestartPath) "unsupported". Nothing else can restart it
reliably: a system unit doesn't reach the user's `systemctl --user`, and
on a Mac the launch agent's serve (#4335) is the same serve. So serve now
looks itself (internal/cli/serve_follow.go): every 5s it checks its
program with update.Replaced; once replaced, it waits until the gateway
is idle (nothing in flight, 10s since the last end, as gui's idle rule;
after an hour, nothing in flight is enough), ends the plugin hosts and
runs the new program in its own place (update.Reexec: exec in place on
Unix, same PID, so systemd and launchd keep tracking it; a new process
on Windows). The restart ask now answers restarting/waiting/current. A
build that isn't a release never does it.

Why "not magpie": proc.IsMagpie judged the file name, and "magpie.real"
(the program the installer's wrapper script runs) didn't match. It now
trims ".real". And proc.RunsMagpie, used by the takeover and the port
check, also reads Go's build info of the running program (on Linux
through /proc/<pid>/exe, which still reads after the file is replaced)
and calls it magpie when its main package is github.com/yetone/magpie.
A process that isn't magpie is still never ended (the existing
"other-server" case passes unchanged).

Tests, each red on the old code:
- cli TestServeRestartsIntoAnUpdate: a copy of the test binary named
  magpie.real runs `serve` on a free port; a script renamed over it is
  run in its place with the same pid and args, and the old port stops
  answering. Old code: "serve ran on as the old version" after 40s.
- cli TestServeFollowWaitsForIdle: current / waiting / tool-chain gap /
  waitMost with a request in flight / idle / non-release.
- gui TestGatewayFixQuitsAReplacedMagpieReal: a fake older gateway named
  magpie.real, its file removed after start, is quit and the gateway
  served here. Old code: {OK:false Reason:not-magpie}, acezan's case.
- proc TestIsMagpie magpie.real case; TestRunsMagpieByItsBuild: a copy
  named server.real, its file removed, is told by its build (Linux
  /proc/<pid>/exe), and is not magpie with the real main path.

Run: the targeted tests above on Linux (wsl-run, magpie-desktop, -tags
nogui) and macOS (mote-run), all pass. Broken by hand on Linux: dropped
the ".real" trim, made RunsMagpie only IsMagpie, and set serve's follow
to nil; all four new tests went red (output above), restored after.
gofmt -l clean; go vet (darwin, GOOS=linux -tags nogui, GOOS=windows)
and builds on mote.

Not tried: a real systemd user unit or launch agent with a real update;
the Windows restart path (Reexec starts a new process) beyond vet; the
macOS TCC part of #4335 (this restarts the launch agent's serve into the
new bundle path only if that path is where it started from). #4335 stays
open, and ggbdpq's daemon.RestartReplaced patch there is not applied.
2026-11-04 23:55:14 +08:00

133 lines
4.0 KiB
Go

package gui
import (
"context"
"fmt"
"net"
"os"
"strconv"
"time"
"github.com/yetone/magpie/internal/agent"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/proc"
"github.com/yetone/magpie/internal/settings"
)
// portJSON is what setting the gateway's port did: the port it is on, the
// agents whose configs were moved with it, and what one couldn't be.
type portJSON struct {
Port int `json:"port"`
Moved []string `json:"moved,omitempty"`
Error string `json:"error,omitempty"`
}
// portFree says whether the gateway could listen at addr: nothing else
// does. A var so tests can say a port is taken.
var portFree = func(addr string) error {
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
return ln.Close()
}
// magpieOnPort says whether a magpie program of this user's listens on
// port: the one serving the gateway is then this computer's, whose port is
// set there. Not when the program listening is another one answering for
// a magpie inside a container (OrbStack Helper, docker-proxy) or none this
// user can see; when the processes can't be listed at all, it is taken to
// be one.
func magpieOnPort(port string) bool {
n, _ := strconv.Atoi(port)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
pids, err := proc.ListeningOn(ctx, n)
if err != nil {
return true
}
for _, pid := range pids {
if pid == os.Getpid() {
continue
}
if path, err := proc.Executable(pid); err == nil && proc.RunsMagpie(pid, path) {
return true
}
}
return false
}
// errPortTaken is a port another program listens on.
func errPortTaken(p int) error {
return fmt.Errorf("port %d is in use by another program: pick another one", p)
}
// setPort moves the gateway to port p (0 for the default) — the port in
// Settings' Gateway address (Magic_zero on Discord: 3425 was taken, and a port of one's
// own is easier to tell apart): it checks nothing listens there, saves it,
// moves the gateway this magpie serves (or starts it, when the port it was
// on was taken), and then every agent connected to magpie, whose configs
// have the gateway's URL in them. A magpie of this computer's serving the
// gateway has it moved there; one out of this one's reach — in a container
// (leslie_luo on Discord: an old magpie in OrbStack held 3425, so the port
// could be changed neither there nor here), another user's — is left on
// its port, and this one serves on the new one.
func setPort(p int) (portJSON, error) {
if err := settings.CheckPort(p); err != nil {
return portJSON{}, err
}
if a := os.Getenv("MAGPIE_ADDR"); a != "" {
return portJSON{}, fmt.Errorf("MAGPIE_ADDR=%s sets the gateway's address, which comes before Settings: unset it to set the port here", a)
}
want := p
if want == 0 {
want = settings.DefaultPort
}
cur := settings.Load()
was := cur.Port
if strconv.Itoa(want) == gateway.Port() {
if was != p {
cur.Port = p
if err := settings.Save(cur); err != nil {
return portJSON{}, err
}
}
return portJSON{Port: want}, nil
}
gw := served.Load()
if gw == nil && gateway.Running() && magpieOnPort(gateway.Port()) {
return portJSON{}, fmt.Errorf("another magpie serves the gateway at %s: set its port there, or quit it first", gateway.URL())
}
host := "127.0.0.1"
if cur.LAN {
host = "0.0.0.0"
}
if err := portFree(net.JoinHostPort(host, strconv.Itoa(want))); err != nil {
return portJSON{}, errPortTaken(want)
}
// the agents reaching the gateway where it is now, to move with it
on := agent.OnGateway()
cur.Port = p
if err := settings.Save(cur); err != nil {
return portJSON{}, err
}
if gw != nil {
if err := gw.Relisten(); err != nil {
back := settings.Load()
back.Port = was
_ = settings.Save(back)
return portJSON{}, errPortTaken(want)
}
} else {
// the port it was on was taken by something else: it serves now
serveGateway()
}
out := portJSON{Port: want}
moved, err := agent.Rewire(on)
out.Moved = moved
if err != nil {
out.Error = err.Error()
}
return out, nil
}