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.
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
@@ -13,7 +14,22 @@ import (
|
||||
// off the network (testenv.Offline): the plugin tests start plugin hosts,
|
||||
// and a host started in a home without a models.dev catalog fetched the
|
||||
// real one for up to 30s (#1922).
|
||||
//
|
||||
// With MAGPIE_CLI_TEST_SERVE set, inside a test's sandbox, the test binary
|
||||
// is `magpie serve` of a released version (serve_update_test.go).
|
||||
func TestMain(m *testing.M) {
|
||||
if os.Getenv("MAGPIE_CLI_TEST_SERVE") != "" {
|
||||
if os.Getenv(testenv.Marker) == "" {
|
||||
os.Exit(2)
|
||||
}
|
||||
testenv.Offline()
|
||||
version = "0.1.9999"
|
||||
if err := serve(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
os.Exit(0)
|
||||
}
|
||||
os.Exit(testenv.RunIn(m, func(string) { testenv.Offline() }))
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"maps"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -18,6 +19,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/agent"
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
"github.com/yetone/magpie/internal/stats"
|
||||
@@ -1458,7 +1460,24 @@ func serve() error {
|
||||
fmt.Println(amber.Render("!"), x.Agent+":", x.Why)
|
||||
}
|
||||
}
|
||||
return s.ListenAndServe(context.Background())
|
||||
// an update put in where this runs from is restarted into
|
||||
// (serve_follow.go)
|
||||
ctx, stop := context.WithCancel(context.Background())
|
||||
defer stop()
|
||||
follow := newServeFollow(s, stop)
|
||||
if follow != nil {
|
||||
gateway.SetRestarter(follow.answer)
|
||||
go follow.run(ctx)
|
||||
}
|
||||
err := s.ListenAndServe(ctx)
|
||||
if exe := follow.restartTo(); exe != "" {
|
||||
// the plugin hosts end, waited for, first, as magpie web's
|
||||
// reexec does (#3285)
|
||||
plugin.EndHosts()
|
||||
log.Printf("magpie serve: restarting into %s", exe)
|
||||
return serveReexec(exe, os.Args[1:], os.Environ())
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// importCmd adds the provider a magpie://import link describes, after
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/update"
|
||||
)
|
||||
|
||||
// `magpie serve` follows an update put in where it runs from. An update
|
||||
// is put in by another magpie: `magpie web` or the app updating itself
|
||||
// from the same program, or `magpie update` in a terminal. None of them
|
||||
// restarted the gateway `magpie serve` keeps, as the service `magpie
|
||||
// daemon install` writes, a systemd user unit or a launch agent (acezan on
|
||||
// Discord: `magpie web` as a system unit updated itself, and the user
|
||||
// unit's serve ran on for good from "magpie.real (deleted)", the page
|
||||
// saying an older magpie served the gateway; #4335 on a Mac, where the
|
||||
// old bundle is deleted and TCC turns the process away from Desktop,
|
||||
// Documents and Downloads). The updater can't reliably restart it: a
|
||||
// system unit doesn't reach the user's systemctl, and the app may not be
|
||||
// running at all. So serve looks itself, as the app and magpie web do
|
||||
// (gui's followReplaced): once the program it started from is another
|
||||
// file, it waits until the gateway is idle, then runs the new program in
|
||||
// its own place, the same process under the same service manager or in
|
||||
// the same terminal. A build of one's own (not a release) never does,
|
||||
// since a rebuild in place would restart it.
|
||||
|
||||
// serveFollowTick is how often serve looks at its program on disk;
|
||||
// serveIdleSettle is how long nothing has ended before it counts as idle
|
||||
// (the gap of a tool chain, as gui's idleSettle); serveWaitMost is how
|
||||
// long it waits for that before it restarts once nothing is in flight,
|
||||
// however recent. Vars for the tests.
|
||||
var (
|
||||
serveFollowTick = 5 * time.Second
|
||||
serveIdleSettle = 10 * time.Second
|
||||
serveWaitMost = time.Hour
|
||||
)
|
||||
|
||||
// serveReexec runs the new program in serve's place; a var for the tests.
|
||||
var serveReexec = update.Reexec
|
||||
|
||||
// serveFollow watches exe, the program serve started from (started is its
|
||||
// os.Stat then), and calls stop once it has been replaced and busy says
|
||||
// the gateway is idle. Restart reports the program to run in this one's
|
||||
// place once stop has been called for it, "" otherwise.
|
||||
type serveFollow struct {
|
||||
exe string
|
||||
started os.FileInfo
|
||||
busy func() gateway.Busy
|
||||
released bool
|
||||
stop func()
|
||||
|
||||
mu sync.Mutex
|
||||
due time.Time // when the replaced program was first seen
|
||||
stopped bool
|
||||
}
|
||||
|
||||
// newServeFollow follows the program this process runs, for s; nil when
|
||||
// it can't be told (no path, or no file there).
|
||||
func newServeFollow(s *gateway.Server, stop func()) *serveFollow {
|
||||
exe, err := update.Executable()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
st, err := os.Stat(exe)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return &serveFollow{exe: exe, started: st, busy: s.Busy, released: update.Released(version), stop: stop}
|
||||
}
|
||||
|
||||
// run looks every serveFollowTick until ctx ends or serve is stopped.
|
||||
func (f *serveFollow) run(ctx context.Context) {
|
||||
if f == nil || !f.released {
|
||||
return
|
||||
}
|
||||
t := time.NewTicker(serveFollowTick)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
}
|
||||
if f.check(time.Now()) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// check stops serve when the program was replaced and the gateway is idle
|
||||
// at now; it reports whether it did.
|
||||
func (f *serveFollow) check(now time.Time) bool {
|
||||
if !update.Replaced(f.exe, f.started) {
|
||||
return false
|
||||
}
|
||||
f.mu.Lock()
|
||||
if f.due.IsZero() {
|
||||
f.due = now
|
||||
log.Printf("magpie serve: %s was updated; restarting into it once the gateway is idle", f.exe)
|
||||
}
|
||||
waited := now.Sub(f.due)
|
||||
f.mu.Unlock()
|
||||
b := f.busy()
|
||||
if b.Any() || now.Sub(b.Last) < serveIdleSettle && waited < serveWaitMost {
|
||||
return false
|
||||
}
|
||||
f.mu.Lock()
|
||||
f.stopped = true
|
||||
f.mu.Unlock()
|
||||
f.stop()
|
||||
return true
|
||||
}
|
||||
|
||||
// restartTo is the program to run in serve's place, "" when serve wasn't
|
||||
// stopped for an update.
|
||||
func (f *serveFollow) restartTo() string {
|
||||
if f == nil {
|
||||
return ""
|
||||
}
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if !f.stopped {
|
||||
return ""
|
||||
}
|
||||
return f.exe
|
||||
}
|
||||
|
||||
// answer is what `magpie update`'s ask (gateway.RestartPath) is told: serve
|
||||
// restarts into what it put in, at once when the gateway is idle (after
|
||||
// the answer is out), else once it is, as on its own next look; "current"
|
||||
// when nothing was put in where serve runs from, "unsupported" for a build
|
||||
// of one's own, restarted the way it was started.
|
||||
func (f *serveFollow) answer(string) gateway.RestartReply {
|
||||
switch {
|
||||
case f == nil || !f.released:
|
||||
return gateway.RestartReply{State: "unsupported"}
|
||||
case !update.Replaced(f.exe, f.started):
|
||||
return gateway.RestartReply{State: "current"}
|
||||
}
|
||||
b := f.busy()
|
||||
if !b.Any() && time.Since(b.Last) >= serveIdleSettle {
|
||||
go f.check(time.Now())
|
||||
return gateway.RestartReply{State: "restarting"}
|
||||
}
|
||||
return gateway.RestartReply{State: "waiting", Busy: &b}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
)
|
||||
|
||||
// serve restarts into an update only once the gateway is idle: nothing in
|
||||
// flight and nothing ended in the last serveIdleSettle, as the app's
|
||||
// restart to update waits (#577). After serveWaitMost it no longer waits
|
||||
// for that gap, but still never cuts a request in flight. A program not
|
||||
// replaced, or a build of one's own, is never restarted.
|
||||
func TestServeFollowWaitsForIdle(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
exe := filepath.Join(dir, "magpie")
|
||||
if err := os.WriteFile(exe, []byte("old"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st, err := os.Stat(exe)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var busy gateway.Busy
|
||||
stops := 0
|
||||
f := &serveFollow{exe: exe, started: st, busy: func() gateway.Busy { return busy }, released: true, stop: func() { stops++ }}
|
||||
now := time.Now()
|
||||
|
||||
if f.check(now) || stops != 0 || f.restartTo() != "" {
|
||||
t.Fatal("restarted with nothing put in")
|
||||
}
|
||||
if a := f.answer(""); a.State != "current" {
|
||||
t.Fatalf("magpie update's ask with nothing put in: %+v", a)
|
||||
}
|
||||
|
||||
if err := os.WriteFile(exe, []byte("the new version"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
busy = gateway.Busy{Requests: 1}
|
||||
if f.check(now) || stops != 0 {
|
||||
t.Fatal("restarted with a request in flight")
|
||||
}
|
||||
if a := f.answer(""); a.State != "waiting" || a.Busy == nil || a.Busy.Requests != 1 {
|
||||
t.Fatalf("magpie update's ask while busy: %+v", a)
|
||||
}
|
||||
busy = gateway.Busy{Last: now.Add(-time.Second)}
|
||||
if f.check(now) || stops != 0 {
|
||||
t.Fatal("restarted in a tool chain's gap")
|
||||
}
|
||||
// past serveWaitMost, the gap no longer holds it, a request still does
|
||||
busy = gateway.Busy{Requests: 1, Last: now}
|
||||
if f.check(now.Add(serveWaitMost+time.Minute)) || stops != 0 {
|
||||
t.Fatal("restarted with a request in flight, after waiting long")
|
||||
}
|
||||
busy = gateway.Busy{Last: now.Add(serveWaitMost)}
|
||||
if !f.check(now.Add(serveWaitMost+time.Minute)) || stops != 1 || f.restartTo() != exe {
|
||||
t.Fatalf("not restarted once nothing was in flight after waiting long: stops %d, restartTo %q", stops, f.restartTo())
|
||||
}
|
||||
|
||||
g := &serveFollow{exe: exe, started: st, busy: func() gateway.Busy { return gateway.Busy{} }, released: true, stop: func() { stops++ }}
|
||||
if !g.check(time.Now()) || stops != 2 || g.restartTo() != exe {
|
||||
t.Fatal("not restarted when idle at once")
|
||||
}
|
||||
|
||||
// a build of one's own: a rebuild in place isn't an update
|
||||
d := &serveFollow{exe: exe, started: st, busy: func() gateway.Busy { return gateway.Busy{} }, stop: func() { stops++ }}
|
||||
d.run(t.Context())
|
||||
if a := d.answer(""); a.State != "unsupported" || stops != 2 || d.restartTo() != "" {
|
||||
t.Fatalf("a build of one's own: %+v, stops %d", a, stops)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
//go:build !windows
|
||||
|
||||
package cli
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// `magpie serve` runs on as the new version once an update is put in where
|
||||
// it runs from (acezan on Discord: the service's serve ran on from
|
||||
// "magpie.real (deleted)" after `magpie web` updated the program they
|
||||
// share; #4335 on a Mac). Here the test binary, copied to magpie.real, is
|
||||
// a released serve on a port of the test's own; the update renames a new
|
||||
// program over it, a script that notes its pid and arguments. serve runs
|
||||
// it in its own place: the same pid, with serve's arguments.
|
||||
func TestServeRestartsIntoAnUpdate(t *testing.T) {
|
||||
self, err := os.Executable()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := os.ReadFile(self)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir := t.TempDir()
|
||||
bin := filepath.Join(dir, "magpie.real")
|
||||
if err := os.WriteFile(bin, b, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
addr := ln.Addr().String()
|
||||
ln.Close()
|
||||
|
||||
cmd := exec.Command(bin, "serve")
|
||||
cmd.Env = append(os.Environ(), "MAGPIE_CLI_TEST_SERVE=1", "MAGPIE_ADDR="+addr)
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ended := make(chan struct{})
|
||||
go func() { cmd.Wait(); close(ended) }()
|
||||
t.Cleanup(func() { cmd.Process.Kill(); <-ended })
|
||||
c := &http.Client{Timeout: 2 * time.Second}
|
||||
for deadline := time.Now().Add(30 * time.Second); ; time.Sleep(100 * time.Millisecond) {
|
||||
if res, err := c.Get("http://" + addr + "/v1/models"); err == nil {
|
||||
res.Body.Close()
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-ended:
|
||||
t.Fatal("serve ended before it served")
|
||||
default:
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("serve didn't answer")
|
||||
}
|
||||
}
|
||||
|
||||
// the update: a new program renamed over the old, as an update puts
|
||||
// it in; the running serve's file is now gone
|
||||
marker := filepath.Join(dir, "ran")
|
||||
next := filepath.Join(dir, "magpie.real.new")
|
||||
script := "#!/bin/sh\necho \"$$ $*\" > '" + marker + "'\nexec sleep 60\n"
|
||||
if err := os.WriteFile(next, []byte(script), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Rename(next, bin); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for deadline := time.Now().Add(40 * time.Second); ; time.Sleep(200 * time.Millisecond) {
|
||||
if got, err := os.ReadFile(marker); err == nil && strings.HasSuffix(string(got), "\n") {
|
||||
want := strconv.Itoa(cmd.Process.Pid) + " serve\n"
|
||||
if string(got) != want {
|
||||
t.Fatalf("the new program ran as %q, want %q: serve's own process, with its arguments", got, want)
|
||||
}
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-ended:
|
||||
t.Fatal("serve ended instead of running the update in its place")
|
||||
default:
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("serve ran on as the old version: the update put in where it runs from was never run")
|
||||
}
|
||||
}
|
||||
// and it let the gateway's port go for the new one
|
||||
if res, err := c.Get("http://" + addr + "/v1/models"); err == nil {
|
||||
res.Body.Close()
|
||||
t.Fatal("the old serve still answers on the gateway's port")
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,7 @@ import (
|
||||
// gateway at once; otherwise it restarts the gateway this one serves, or
|
||||
// starts it when none does. The page said only "quit that magpie", and the
|
||||
// user couldn't find which one it was. Only a process whose program is a
|
||||
// magpie (proc.IsMagpie, by the pid listening on the port and its path) is
|
||||
// magpie (proc.RunsMagpie, by the pid listening on the port and its program) is
|
||||
// ever ended; anything else is said, never touched.
|
||||
|
||||
// gatewayFixJSON is how a take-over or a restart went: what stood in the
|
||||
@@ -120,7 +120,7 @@ func startHere() gatewayFixJSON {
|
||||
}
|
||||
out.PID = pid
|
||||
out.Path, _ = proc.Executable(pid)
|
||||
if proc.IsMagpie(out.Path) {
|
||||
if proc.RunsMagpie(pid, out.Path) {
|
||||
// a magpie took it back as soon as the other quit
|
||||
out.Reason = "respawned"
|
||||
} else if proc.IsForwarder(out.Path) {
|
||||
@@ -159,7 +159,7 @@ func quitMagpieOnPort(version string) gatewayFixJSON {
|
||||
out.Reason, out.Error = "unseen", err.Error()
|
||||
return out
|
||||
}
|
||||
if !proc.IsMagpie(path) {
|
||||
if !proc.RunsMagpie(pid, path) {
|
||||
out.Reason = "not-magpie"
|
||||
if proc.IsForwarder(path) {
|
||||
out.Reason = "container"
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
//go:build !windows
|
||||
|
||||
package gui
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
)
|
||||
|
||||
// acezan on Discord: the service's `magpie serve` ran on from
|
||||
// /root/.local/bin/magpie.real after `magpie web` updated that file, and
|
||||
// the page's "close it here" said the process on the port "isn't magpie,
|
||||
// so magpie leaves it alone". It is: magpie.real is the program a wrapper
|
||||
// script named magpie runs, and Linux names it "magpie.real (deleted)"
|
||||
// once the update replaced it. The take-over now quits it and serves the
|
||||
// gateway here. A copy of the test binary stands in for it, its file
|
||||
// removed once it runs, as the update's rename leaves it.
|
||||
func TestGatewayFixQuitsAReplacedMagpieReal(t *testing.T) {
|
||||
h := t.TempDir()
|
||||
t.Setenv("HOME", h)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
|
||||
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
|
||||
port := freePort(t)
|
||||
addr := "127.0.0.1:" + strconv.Itoa(port)
|
||||
t.Setenv("MAGPIE_ADDR", addr)
|
||||
was := gateway.Version
|
||||
gateway.Version = "0.1.630"
|
||||
defer func() { gateway.Version = was }()
|
||||
served.Store(nil)
|
||||
oldQuit, oldKill, oldStart := quitWait, killWait, startWait
|
||||
quitWait, killWait, startWait = 3*time.Second, 2*time.Second, 5*time.Second
|
||||
defer func() { quitWait, killWait, startWait = oldQuit, oldKill, oldStart }()
|
||||
t.Cleanup(func() {
|
||||
gatewayMu.Lock()
|
||||
defer gatewayMu.Unlock()
|
||||
if served.Load() != nil && servedRun.stop != nil {
|
||||
servedRun.stop()
|
||||
<-servedRun.done
|
||||
}
|
||||
served.Store(nil)
|
||||
})
|
||||
|
||||
self, err := os.Executable()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := os.ReadFile(self)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bin := filepath.Join(t.TempDir(), "magpie.real")
|
||||
if err := os.WriteFile(bin, b, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cmd := exec.Command(bin, "-test.run=^$")
|
||||
cmd.Env = append(os.Environ(), "MAGPIE_TEST_FAKE_GATEWAY="+addr)
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ended := make(chan struct{})
|
||||
go func() { cmd.Wait(); close(ended) }()
|
||||
t.Cleanup(func() { cmd.Process.Kill(); <-ended })
|
||||
for deadline := time.Now().Add(10 * time.Second); gateway.ServedBy().Version != "0.1.550"; time.Sleep(50 * time.Millisecond) {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("the older magpie didn't answer")
|
||||
}
|
||||
}
|
||||
// the update replaced its file
|
||||
if err := os.Remove(bin); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if out := takeOverGateway(); !out.OK {
|
||||
t.Fatalf("take-over of magpie.real, its file replaced: %+v", out)
|
||||
}
|
||||
select {
|
||||
case <-ended:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the older magpie is still running")
|
||||
}
|
||||
if g := providersState().Gateway; !g.Mine || !g.Running {
|
||||
t.Fatalf("not served here after the take-over: %+v", g)
|
||||
}
|
||||
}
|
||||
@@ -50,7 +50,7 @@ func magpieOnPort(port string) bool {
|
||||
if pid == os.Getpid() {
|
||||
continue
|
||||
}
|
||||
if path, err := proc.Executable(pid); err == nil && proc.IsMagpie(path) {
|
||||
if path, err := proc.Executable(pid); err == nil && proc.RunsMagpie(pid, path) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,11 @@ package proc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"debug/buildinfo"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -41,10 +44,38 @@ func Terminate(pid int) error { return terminate(pid) }
|
||||
// Kill ends process pid at once. ErrDenied when this user may not.
|
||||
func Kill(pid int) error { return kill(pid) }
|
||||
|
||||
// RunsMagpie says whether process pid, running the program at path (as
|
||||
// Executable says), is a magpie: by the program's name (IsMagpie), or else
|
||||
// by what the program is, magpie's own main package, read from the build
|
||||
// information Go writes into it. A magpie under a name of the user's
|
||||
// (acezan on Discord: magpie.real, behind a wrapper script installed as
|
||||
// magpie) is still one, and on Linux this holds for one whose file an
|
||||
// update has since replaced, read through /proc/<pid>/exe: the panel had
|
||||
// called that magpie "not magpie" and left it holding the gateway's port.
|
||||
func RunsMagpie(pid int, path string) bool {
|
||||
if IsMagpie(path) {
|
||||
return true
|
||||
}
|
||||
file := path
|
||||
if runtime.GOOS == "linux" && pid > 0 {
|
||||
file = filepath.Join("/proc", strconv.Itoa(pid), "exe")
|
||||
}
|
||||
if file == "" {
|
||||
return false
|
||||
}
|
||||
bi, err := buildinfo.ReadFile(file)
|
||||
return err == nil && bi.Path == magpieMain
|
||||
}
|
||||
|
||||
// magpieMain is magpie's main package, as a build of it names itself; a
|
||||
// var for the tests, whose own binary is another package's.
|
||||
var magpieMain = "github.com/yetone/magpie"
|
||||
|
||||
// IsMagpie says whether the program at path is a magpie: magpie, its
|
||||
// magpie-* builds or dial, its name before; with .exe, and Windows' .old
|
||||
// for one replaced by an update while it ran, or .old-2 when that one was
|
||||
// still held.
|
||||
// still held; and magpie.real, the program a wrapper script named magpie
|
||||
// runs (acezan on Discord).
|
||||
func IsMagpie(path string) bool {
|
||||
if path == "" {
|
||||
return false
|
||||
@@ -58,6 +89,7 @@ func IsMagpie(path string) bool {
|
||||
n = strings.TrimSuffix(n, ".old")
|
||||
n = strings.TrimSuffix(n, ".new")
|
||||
n = strings.TrimSuffix(n, ".exe")
|
||||
n = strings.TrimSuffix(n, ".real")
|
||||
for _, name := range []string{"magpie", "dial"} {
|
||||
if n == name || strings.HasPrefix(n, name+"-") || strings.HasPrefix(n, name+"_") {
|
||||
return true
|
||||
|
||||
@@ -4,7 +4,10 @@ import (
|
||||
"context"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"runtime/debug"
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
@@ -76,9 +79,11 @@ func TestIsMagpie(t *testing.T) {
|
||||
"/home/u/magpie.old-2": true,
|
||||
"/home/u/dial.old-4": true,
|
||||
// the numbered suffix is an update's, not another program's
|
||||
`C:\Users\u\other-server.old-2`: false,
|
||||
`C:\Users\u\magpie.old-backup`: false,
|
||||
"/home/u/.local/bin/dial": true,
|
||||
`C:\Users\u\other-server.old-2`: false,
|
||||
`C:\Users\u\magpie.old-backup`: false,
|
||||
"/home/u/.local/bin/dial": true,
|
||||
// the program a wrapper script named magpie runs (acezan)
|
||||
"/root/.local/bin/magpie.real": true,
|
||||
"/opt/magpie-dev": true,
|
||||
"/usr/bin/python3": false,
|
||||
"/usr/bin/magpies": false,
|
||||
@@ -113,3 +118,68 @@ func TestIsForwarder(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A magpie is told by what its program is, not only its name: Go's build
|
||||
// information names magpie's main package. On Linux that is read from the
|
||||
// running process (/proc/<pid>/exe), so one whose file an update replaced
|
||||
// still reads as magpie (acezan on Discord). Here the test binary, copied
|
||||
// under another name and its file removed once it runs, stands in, with
|
||||
// magpieMain the test binary's own package.
|
||||
func TestRunsMagpieByItsBuild(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("a running program's file can't be removed on Windows")
|
||||
}
|
||||
bi, ok := debug.ReadBuildInfo()
|
||||
if !ok {
|
||||
t.Fatal("no build information in the test binary")
|
||||
}
|
||||
self, err := os.Executable()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := os.ReadFile(self)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bin := filepath.Join(t.TempDir(), "server.real")
|
||||
if err := os.WriteFile(bin, b, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cmd := exec.Command(bin, "-test.run=^$")
|
||||
cmd.Env = append(os.Environ(), "MAGPIE_PROC_SLEEP=1")
|
||||
stdin, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { stdin.Close(); cmd.Process.Kill(); cmd.Wait() })
|
||||
pid := cmd.Process.Pid
|
||||
|
||||
was := magpieMain
|
||||
defer func() { magpieMain = was }()
|
||||
magpieMain = bi.Path
|
||||
if !RunsMagpie(pid, bin) {
|
||||
t.Fatalf("%s, built from %s, not told as magpie", bin, bi.Path)
|
||||
}
|
||||
magpieMain = "github.com/yetone/magpie"
|
||||
if RunsMagpie(pid, bin) {
|
||||
t.Fatal("another program's build told as magpie")
|
||||
}
|
||||
if runtime.GOOS != "linux" {
|
||||
return
|
||||
}
|
||||
// the update's rename: the file is gone, the process runs on
|
||||
if err := os.Remove(bin); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path, err := Executable(pid)
|
||||
if err != nil || filepath.Base(path) != "server.real" {
|
||||
t.Fatalf("Executable of a replaced program: %q, %v", path, err)
|
||||
}
|
||||
magpieMain = bi.Path
|
||||
if !RunsMagpie(pid, path) {
|
||||
t.Fatal("a magpie whose file was replaced isn't told as magpie")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package proc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
@@ -12,7 +13,14 @@ import (
|
||||
// With MAGPIE_PROC_RAN set, the test binary stands in for a program a
|
||||
// probe asks its version (guiexe_windows_test.go): it notes that it was
|
||||
// started there and answers.
|
||||
//
|
||||
// With MAGPIE_PROC_SLEEP set, it runs until its stdin closes
|
||||
// (listener_test.go).
|
||||
func TestMain(m *testing.M) {
|
||||
if os.Getenv("MAGPIE_PROC_SLEEP") != "" {
|
||||
io.Copy(io.Discard, os.Stdin)
|
||||
os.Exit(0)
|
||||
}
|
||||
if ran := os.Getenv("MAGPIE_PROC_RAN"); ran != "" {
|
||||
if f, err := os.OpenFile(ran, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644); err == nil {
|
||||
fmt.Fprintln(f, os.Args[0])
|
||||
|
||||
Reference in New Issue
Block a user