diff --git a/internal/gui/api.go b/internal/gui/api.go index b3171d2f6..aed444244 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -121,8 +121,12 @@ func settingsState() settingsJSON { var onDock func(bool) // Handler serves the embedded UI and the JSON API. -// gw is the gateway this process serves, or nil when another magpie has it. +// gw is the gateway this process serves, or nil when another magpie has it +// (for now: see startBackend). func Handler(w Windows, gw *gateway.Server) http.Handler { + if gw != nil { + served.Store(gw) + } mux := http.NewServeMux() mux.Handle("/", devPage(http.FileServer(http.FS(staticFS())))) devRoutes(mux) @@ -258,7 +262,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { } writeJSON(rw, state()) }) - providerRoutes(mux, w, gw) + providerRoutes(mux, w) importRoutes(mux) usageRoutes(mux) backupRoutes(mux, w) diff --git a/internal/gui/app.go b/internal/gui/app.go index 3dee8eb0b..98f22a3ca 100644 --- a/internal/gui/app.go +++ b/internal/gui/app.go @@ -314,18 +314,18 @@ func Run(version string, showMain bool, link string) error { return h.app.Run() } +// served is the gateway this process serves, nil while another magpie +// has it. +var served atomic.Pointer[gateway.Server] + // startBackend starts what serves the page and the agents: the gateway, // unless another magpie has it (then that one serves and this one only -// shows its status, and gw is nil), and the model lists kept warm. +// shows its status, and gw is nil — until that one is gone: a magpie left +// running from before an update, a magpie serve in a terminal), and the +// model lists kept warm. func startBackend() (gw *gateway.Server) { - if !gateway.Running() { - gw = gateway.New() - go func() { - if err := gw.ListenAndServe(context.Background()); err != nil { - log.Println("gateway:", err) - } - }() - } + gw = serveGateway() + go watchGateway() // Model lists are fetched, never compiled in: whatever the agents can see // comes from the models.dev catalog plus each vendor's own /models answer. // Keep both halves warm without making the user click anything. @@ -359,6 +359,35 @@ func startBackend() (gw *gateway.Server) { return gw } +var gatewayWatch = 15 * time.Second + +// watchGateway takes the gateway up once the magpie that had it is gone. +func watchGateway() { + for { + time.Sleep(gatewayWatch) + if served.Load() == nil && !gateway.Running() { + serveGateway() + } + } +} + +// serveGateway starts the gateway here when no magpie has it: the one +// started, or nil. +func serveGateway() *gateway.Server { + if gateway.Running() { + return nil + } + gw := gateway.New() + served.Store(gw) + go func() { + if err := gw.ListenAndServe(context.Background()); err != nil { + log.Println("gateway:", err) + served.CompareAndSwap(gw, nil) // another took the port first + } + }() + return gw +} + // singleInstance makes a second launch hand over to this one, off the Mac. // The id covers the executable and the config dir, so a build elsewhere or // a sandboxed HOME runs on its own. diff --git a/internal/gui/importapps.go b/internal/gui/importapps.go index 6310a5168..8cde87f34 100644 --- a/internal/gui/importapps.go +++ b/internal/gui/importapps.go @@ -4,7 +4,6 @@ import ( "encoding/json" "net/http" - "github.com/yetone/magpie/internal/gateway" "github.com/yetone/magpie/internal/provider" ) @@ -12,7 +11,7 @@ import ( // the page lists them, keys masked, and posts back the ones the user // picked; the keys are read again here, never sent to the page. -func importAppsRoutes(mux *http.ServeMux, gw *gateway.Server) { +func importAppsRoutes(mux *http.ServeMux) { mux.HandleFunc("GET /api/importapps", func(rw http.ResponseWriter, r *http.Request) { sources := provider.ImportSources() for i := range sources { @@ -37,6 +36,6 @@ func importAppsRoutes(mux *http.ServeMux, gw *gateway.Server) { writeJSON(rw, struct { Added []string `json:"added"` State any `json:"state"` - }{added, providersState(gw)}) + }{added, providersState()}) }) } diff --git a/internal/gui/providers.go b/internal/gui/providers.go index a0454d7e5..537dd23ed 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -221,7 +221,7 @@ func providerInfo(p provider.Provider, agents []*agent.Agent) providerJSON { return out } -func providersState(gw *gateway.Server) providersJSON { +func providersState() providersJSON { agents := agent.Detected() s := providersJSON{Providers: []providerJSON{}, Presets: []presetJSON{}, Excluded: []excludedJSON{}} for _, x := range provider.Excluded() { @@ -256,7 +256,7 @@ func providersState(gw *gateway.Server) providersJSON { } s.Gateway.Groups = append(s.Gateway.Groups, g) } - if gw != nil { + if gw := served.Load(); gw != nil { s.Gateway.Running, s.Gateway.Mine = true, true s.Gateway.Calls = gw.Recent() } else { @@ -279,12 +279,12 @@ func ago(t time.Time) string { } } -func providerRoutes(mux *http.ServeMux, w Windows, gw *gateway.Server) { - importAppsRoutes(mux, gw) - traceRoutes(mux, gw) +func providerRoutes(mux *http.ServeMux, w Windows) { + importAppsRoutes(mux) + traceRoutes(mux) groupRoutes(mux) mux.HandleFunc("GET /api/providers", func(rw http.ResponseWriter, r *http.Request) { - writeJSON(rw, providersState(gw)) + writeJSON(rw, providersState()) }) // a picture for a provider, picked in the editor: kept by content before // the provider is saved, which then points at it. The page sends it as @@ -468,7 +468,7 @@ func providerRoutes(mux *http.ServeMux, w Windows, gw *gateway.Server) { http.NotFound(rw, r) return } - writeJSON(rw, providersState(gw)) + writeJSON(rw, providersState()) }) // How much of its allowance each of an agent's accounts has used. mux.HandleFunc("GET /api/login/usage", func(rw http.ResponseWriter, r *http.Request) { @@ -500,7 +500,7 @@ func providerRoutes(mux *http.ServeMux, w Windows, gw *gateway.Server) { fail(rw, err) return } - writeJSON(rw, providersState(gw)) + writeJSON(rw, providersState()) }) // A provider's several keys: add one, put one in use, name or remove it. mux.HandleFunc("POST /api/keys/{action}", func(rw http.ResponseWriter, r *http.Request) { @@ -545,7 +545,7 @@ func providerRoutes(mux *http.ServeMux, w Windows, gw *gateway.Server) { cancel() } } - writeJSON(rw, providersState(gw)) + writeJSON(rw, providersState()) }) // Adding a subscription: magpie opens the vendor's sign-in in the // browser and the window follows it until the account is in. diff --git a/internal/gui/takeover_test.go b/internal/gui/takeover_test.go new file mode 100644 index 000000000..72c1a941e --- /dev/null +++ b/internal/gui/takeover_test.go @@ -0,0 +1,45 @@ +package gui + +import ( + "net" + "net/http" + "testing" + "time" + + "github.com/yetone/magpie/internal/gateway" +) + +// A magpie that found the gateway taken serves it once the one that had it +// is gone (one left running from before an update, a magpie serve). +func TestGatewayTakenOver(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Setenv("MAGPIE_ADDR", ln.Addr().String()) + other := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Write([]byte(`{"name":"magpie"}`)) + })} + go other.Serve(ln) + defer served.Store(nil) + if serveGateway() != nil { + t.Fatal("served over another magpie") + } + old := gatewayWatch + gatewayWatch = 50 * time.Millisecond + defer func() { gatewayWatch = old }() + go watchGateway() + time.Sleep(200 * time.Millisecond) + if served.Load() != nil { + t.Fatal("took the gateway while the other had it") + } + other.Close() + for deadline := time.Now().Add(5 * time.Second); served.Load() == nil || !gateway.Running(); time.Sleep(50 * time.Millisecond) { + if time.Now().After(deadline) { + t.Fatal("the gateway wasn't taken up") + } + } +} diff --git a/internal/gui/trace.go b/internal/gui/trace.go index ec9232cae..5c9d4cef5 100644 --- a/internal/gui/trace.go +++ b/internal/gui/trace.go @@ -18,8 +18,9 @@ type traceJSON struct { // traceRoutes serves the routing trace for the Gateway view to play: it // waits up to 25 s for something to change after the seq it is given, so // the page hears of a request as it happens. -func traceRoutes(mux *http.ServeMux, gw *gateway.Server) { +func traceRoutes(mux *http.ServeMux) { mux.HandleFunc("GET /api/gateway/trace", func(rw http.ResponseWriter, r *http.Request) { + gw := served.Load() out := traceJSON{TraceState: gateway.TraceState{Routes: []gateway.Route{}}, Mine: gw != nil} if gw != nil { after, _ := strconv.ParseInt(r.URL.Query().Get("after"), 10, 64) diff --git a/internal/gui/update.go b/internal/gui/update.go index aa5df7ecf..4901ab9f0 100644 --- a/internal/gui/update.go +++ b/internal/gui/update.go @@ -5,6 +5,7 @@ import ( "errors" "log" "net/http" + "os" "path/filepath" "runtime" "sync" @@ -25,10 +26,11 @@ type updater struct { state string // checking | latest | downloading | ready | available | source | error latest *update.Release err string - bundle string // the .app to replace, "" when not in one or stuck - stuck string // why the .app can't be replaced where it is (update.Stuck) - exe string // off the Mac: the binary to replace, "" when not writable - retry bool // error: the download failed, and may be tried again + bundle string // the .app to replace, "" when not in one or stuck + stuck string // why the .app can't be replaced where it is (update.Stuck) + exe string // off the Mac: the binary to replace, "" when not writable + self os.FileInfo // exe as this process started from it + retry bool // error: the download failed, and may be tried again staged string done int64 // downloading: bytes so far, of total (0 when unknown) total int64 @@ -60,7 +62,9 @@ func (u *updater) start() { } else if runtime.GOOS != "darwin" { if exe, err := update.Executable(); err == nil && (update.Writable(filepath.Dir(exe)) || update.CanElevate()) { u.exe = exe - update.RemoveOld(exe) // what the last updates on Windows moved aside + u.self, _ = os.Stat(exe) + update.RemoveOld(exe) // what the last updates on Windows moved aside + update.RemoveStaleNew(exe) // what a magpie left running downloaded again } } go func() { @@ -112,6 +116,13 @@ func (u *updater) run() { case u.bundle == "" && u.exe == "": u.state = "available" // the user fetches it from the release page return + case u.replaced(): + // another magpie put the update in already: a restart is all + u.state = "ready" + if u.onReady != nil { + go u.onReady(rel.Version) + } + return } u.state, u.done, u.total = "downloading", 0, 0 u.mu.Unlock() @@ -145,6 +156,13 @@ func (u *updater) run() { func (u *updater) install(ask bool) bool { u.mu.Lock() defer u.mu.Unlock() + if u.replaced() { + // another magpie updated the binary after this one started: it is + // in, and swapping this one's download in would move it aside (the + // download is left: it may be the other's, staged at the same name) + u.staged = "" + return true + } if u.staged == "" { return false } @@ -172,6 +190,12 @@ func (u *updater) install(ask bool) bool { return true } +// replaced is whether the binary was updated by another magpie since this +// one started, which runs on from where it was moved aside. +func (u *updater) replaced() bool { + return u.exe != "" && update.Replaced(u.exe, u.self) +} + func (u *updater) json() updateJSON { u.mu.Lock() defer u.mu.Unlock() diff --git a/internal/update/replaced_test.go b/internal/update/replaced_test.go new file mode 100644 index 000000000..88da9457a --- /dev/null +++ b/internal/update/replaced_test.go @@ -0,0 +1,42 @@ +package update + +import ( + "os" + "path/filepath" + "testing" + "time" +) + +func TestReplacedAndStaleNew(t *testing.T) { + dir := t.TempDir() + exe := filepath.Join(dir, "magpie.exe") + os.WriteFile(exe, []byte("v1"), 0o755) + started, _ := os.Stat(exe) + if Replaced(exe, started) { + t.Fatal("replaced before anything happened") + } + // another magpie moves it aside and puts the new one in + os.Rename(exe, exe+".old") + os.WriteFile(exe, []byte("v2 build"), 0o755) + if !Replaced(exe, started) { + t.Fatal("not seen as replaced") + } + // the same size, a later time + os.WriteFile(exe, []byte("v1"), 0o755) + os.Chtimes(exe, time.Now(), started.ModTime().Add(time.Minute)) + if !Replaced(exe, started) { + t.Fatal("a same-size update not seen") + } + + // a .new that is exe over again goes; another stays + os.WriteFile(exe+".new", []byte("v1"), 0o755) + RemoveStaleNew(exe) + if _, err := os.Stat(exe + ".new"); !os.IsNotExist(err) { + t.Fatal("a .new the same as exe was kept") + } + os.WriteFile(exe+".new", []byte("v3"), 0o755) + RemoveStaleNew(exe) + if _, err := os.Stat(exe + ".new"); err != nil { + t.Fatal("a different .new was removed") + } +} diff --git a/internal/update/update.go b/internal/update/update.go index 90a875253..9665eb1c4 100644 --- a/internal/update/update.go +++ b/internal/update/update.go @@ -391,6 +391,41 @@ func RemoveOld(exe string) { } } +// Replaced reports whether exe is no longer the binary that was there when +// this process looked (started, from os.Stat): another magpie installed an +// update over it, and this one runs from where it was moved aside. +func Replaced(exe string, started os.FileInfo) bool { + now, err := os.Stat(exe) + return err == nil && started != nil && (now.Size() != started.Size() || !now.ModTime().Equal(started.ModTime())) +} + +// RemoveStaleNew removes exe.new when it is exe over again: the update a +// magpie left running from before it downloaded once more. +func RemoveStaleNew(exe string) { + staged := exe + ".new" + a, err1 := os.Stat(exe) + b, err2 := os.Stat(staged) + if err1 != nil || err2 != nil || a.Size() != b.Size() { + return + } + if ha, hb := fileHash(exe), fileHash(staged); ha != "" && ha == hb { + os.Remove(staged) + } +} + +func fileHash(path string) string { + f, err := os.Open(path) + if err != nil { + return "" + } + defer f.Close() + h := sha256.New() + if _, err := io.Copy(h, f); err != nil { + return "" + } + return hex.EncodeToString(h.Sum(nil)) +} + // InstallBinaryAsAdmin is InstallBinary with the administrator's password. func InstallBinaryAsAdmin(staged, exe string) error { err := asAdmin("mv -f " + shellQuote(staged) + " " + shellQuote(exe))