diff --git a/docs/lld/17-preview-pane.md b/docs/lld/17-preview-pane.md index 44e1c043..ef02ec8a 100644 --- a/docs/lld/17-preview-pane.md +++ b/docs/lld/17-preview-pane.md @@ -333,3 +333,9 @@ The bridge commands (`livepreview/bridge_cmd.go`) dispatch real events: the poin The gateway sends `/preview//...` to the node that runs the workspace the token names. That node used to come only from the route table (`RouteHome`), which the workers fill with their announcements and empty with a "closed" announcement. A session that moved (to a worker, back to the gateway, after a worker was away) can leave the old entry behind, so the Preview kept asking the node that no longer ran the program: "Nothing is running yet" with the program listening on the other node (reported with logs from a gateway and a worker). `Router.homeBackend` now asks the registry first (`SessionRegistry.HomeOwner`: the live session that uses the home), drops a route entry that disagrees with it, and falls back to the route table only when no live session uses the home. The same helper serves the `homedir` of a shared session's file requests (`routed`). Test: `TestThePreviewFollowsTheSessionWhenItMovedAndTheRouteIsStale`. An admin's REPL listens on the machine's real network, where the site itself is, so the Preview refuses the server's own port for it (`isOwnPort`, `errOwnPort`) instead of showing the site in the frame. + +**The dialer tries each place (2026-11-23).** `previewDialer` found the processes of the workspace (one for each network) and chose ONE place for every port: a single unsandboxed process in the server's own network (an admin's terminal opened in a user's workspace) sent every port to the machine's real network, where the program of a sandboxed REPL is not and the site itself is (on a worker, whose own server listens on 8080, a Preview of 8080 showed OpenREPL; any other port gave 502). Now each place is tried in turn and the first that connects wins: the namespace of each REPL that has one (`DialIn`), then the emulation's socket for the processes in the server's network, then the real network, only when a process is unsandboxed and never for the server's own port (`errOwnPort`). The facts come from `previewProc`, which the tests replace: `TestAnUnsandboxedProcessDoesNotHideAnEmulatedProgram`, `TestAProgramInAnotherNamespaceIsReachedBeforeTheRealNetwork`. + +A server that the Genie agent starts with its `bash` action does not survive that action (the shell and everything it started are killed when the call ends: its description says to use `terminal_type` for a program that must keep running). The Preview of such a program says "Nothing is listening" or "Your program has stopped" because it is gone. + +**The registry names a home by its directory name (2026-11-23).** `SessionRegistry` keeps the home as `donadjdc` (`Config.HomeOf`), while the Preview's token and the route table carry the path `/home/openrepl/donadjdc`. The first version of `homeBackend` asked the registry for the path only, so it never found the session and fell back to the stale route: the Preview still went to the worker after the session moved back to the gateway (reproduced on a local gateway and worker: the worker answered `no process of donadjdc was found`). It now asks for the path and for its base name. The test uses the registry's real naming and fails without the fix. diff --git a/src/gateway/router.go b/src/gateway/router.go index 8e2d4085..306d0487 100644 --- a/src/gateway/router.go +++ b/src/gateway/router.go @@ -5,6 +5,7 @@ import ( "errors" "log" "net/http" + "path/filepath" "sort" "strings" "sync" @@ -402,7 +403,14 @@ func (rt *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) { // workers announced, and an entry stays when a move leaves no "closed" announcement behind (reported: the Preview kept asking the worker that // no longer ran the program, "Nothing is running yet"), so it is the fallback, and an entry that disagrees with the registry is dropped. func (rt *Router) homeBackend(home string) (string, bool) { - if id, ok := rt.registry.HomeOwner(home); ok { + // The registry names a home by its directory name ("donadjdc", Config.HomeOf), the Preview's token and the route table by its path + // ("/home/openrepl/donadjdc"): ask for both (the first version asked for the path only, never found the session, and fell back to the stale + // route; seen on a gateway and a worker after a session moved back to the gateway). + owner, ok := rt.registry.HomeOwner(home) + if !ok { + owner, ok = rt.registry.HomeOwner(filepath.Base(home)) + } + if id, ok := owner, ok; ok { if stale, found := rt.routes.Lookup(RouteHome, home); found && stale != id { rt.routes.Delete(RouteHome, home, stale) } diff --git a/src/gateway/router_preview_move_test.go b/src/gateway/router_preview_move_test.go index 3b2322b1..85e505bc 100644 --- a/src/gateway/router_preview_move_test.go +++ b/src/gateway/router_preview_move_test.go @@ -19,7 +19,8 @@ func TestThePreviewFollowsTheSessionWhenItMovedAndTheRouteIsStale(t *testing.T) tok, _ := livepreview.NewToken("secret", home, time.Now(), time.Hour) // the worker announced the home; then the session moved to the gateway rt.Routes().Set(RouteHome, home, "worker-b") - rt.registry.Create(Identity{Key: "u:donadjdc", UID: "donadjdc", Home: home}, LocalID) + // the registry names a home by its directory name (Config.HomeOf), the token and the routes by its path + rt.registry.Create(Identity{Key: "u:donadjdc", UID: "donadjdc", Home: "donadjdc"}, LocalID) do(rt, "GET", "/preview/"+tok+"/p/8000/", nil) if b.hits != 0 || len(site.paths) != 1 { t.Fatalf("the Preview went to the old worker: b=%d site=%v", b.hits, site.paths) @@ -31,7 +32,7 @@ func TestThePreviewFollowsTheSessionWhenItMovedAndTheRouteIsStale(t *testing.T) rt2 := newTestRouter(&recorder{}, "/", &countingPicker{id: "worker-a"}) w := &named{id: "worker-a"} rt2.AddBackend(w) - rt2.registry.Create(Identity{Key: "u:donadjdc", UID: "donadjdc", Home: home}, "worker-a") + rt2.registry.Create(Identity{Key: "u:donadjdc", UID: "donadjdc", Home: "donadjdc"}, "worker-a") do(rt2, "GET", "/preview/"+tok+"/p/8000/", nil) if w.hits != 1 { t.Errorf("the Preview did not go to the worker that runs the session: %d", w.hits) diff --git a/src/server/preview.go b/src/server/preview.go index 10d1c3d4..5eddb8b9 100644 --- a/src/server/preview.go +++ b/src/server/preview.go @@ -230,61 +230,103 @@ var errNoIsolation = errors.New("a program can be previewed only where each work // the server, or of another visitor, would then be reachable). func previewDialer(home string) livepreview.Dialer { return func(ctx context.Context, port int) (net.Conn, error) { - pids := livepreview.FindPIDs(home) + pids := previewProc.find(home) + var tried []string // what was attempted and how it ended, for the log of a Preview that fails + fail := func(err error) (net.Conn, error) { + logPreviewFailure(home, port, pids, tried, err) + return nil, err + } + emu := func() (net.Conn, error) { + var d net.Dialer + c, err := d.DialContext(ctx, "unix", netemu.Name(netemu.WorkspaceID(home), "t", uint16(port))) + tried = append(tried, fmt.Sprintf("emulation: %v", err)) + return c, err + } if len(pids) == 0 { // No process was found by its HOME or its helper. Under the network emulation the program's socket has a name that holds only the // workspace and the port, so it can be reached without knowing a process: a REPL that /proc did not show (a process the server may // not read) must not hide a program that is listening (reported: "Nothing is running yet" with `python -m http.server` running). if netEmuActive() { - var d net.Dialer - if c, err := d.DialContext(ctx, "unix", netemu.Name(netemu.WorkspaceID(home), "t", uint16(port))); err == nil { + if c, err := emu(); err == nil { logNoProcess(home, port, true) return c, nil } } logNoProcess(home, port, false) - return nil, livepreview.ErrNoProgram + return fail(livepreview.ErrNoProgram) } // each REPL of a workspace may have a network of its own: the program is in the one that listens on the port var lastErr error own := false admin := false // a REPL with no sandbox at all (an admin's) listens on the machine's real network for _, pid := range pids { - if livepreview.SameNetwork(pid) { + if previewProc.same(pid) { own = true - if containers.NetEmuActive() && livepreview.Unsandboxed(pid) { + if netEmuActive() && previewProc.unsandboxed(pid) { admin = true } continue } - c, err := livepreview.DialIn(fmt.Sprintf("/proc/%d/ns/net", pid), port, 10*time.Second) + c, err := previewProc.dialIn(pid, port) + tried = append(tried, fmt.Sprintf("namespace of %d: %v", pid, err)) if err == nil { return c, nil } lastErr = err } if lastErr != nil && !own { - return nil, lastErr + return fail(lastErr) + } + if !own { + return fail(errNoIsolation) + } + // The processes in the server's own network. A workspace can hold both kinds at once (an admin's terminal opened in a user's workspace, the + // transient helper of a fork): the emulation's socket is tried first (a sandboxed REPL's program), then the real network (an unsandboxed + // one's), so that the one kind does not hide the other. (Before, one unsandboxed process sent every port to the real network, where the + // program was not and the site itself is.) + if netEmuActive() { + c, err := emu() + if err == nil { + return c, nil + } + lastErr = err } if admin { - // an admin's REPL listens on the machine's real network, where the site itself is: its own port is not a program to preview + // the real network is where the site itself listens: its own port is not a program to preview if isOwnPort(port) { - return nil, errOwnPort + tried = append(tried, "real network: the port of the site itself") + return fail(errOwnPort) } var d net.Dialer - return d.DialContext(ctx, "tcp", fmt.Sprintf("127.0.0.1:%d", port)) - } - if containers.NetEmuActive() { - var d net.Dialer - return d.DialContext(ctx, "unix", netemu.Name(netemu.WorkspaceID(home), "t", uint16(port))) + c, err := d.DialContext(ctx, "tcp", fmt.Sprintf("127.0.0.1:%d", port)) + tried = append(tried, fmt.Sprintf("real network: %v", err)) + if err != nil { + return fail(err) + } + return c, nil } if lastErr != nil { - return nil, lastErr + return fail(lastErr) } - return nil, errNoIsolation + return fail(errNoIsolation) } } +// previewProc is what the dialer asks of /proc and of the namespaces; the tests replace it. +var previewProc = struct { + find func(home string) []int + same func(pid int) bool + unsandboxed func(pid int) bool + dialIn func(pid, port int) (net.Conn, error) +}{ + find: livepreview.FindPIDs, + same: livepreview.SameNetwork, + unsandboxed: livepreview.Unsandboxed, + dialIn: func(pid, port int) (net.Conn, error) { + return livepreview.DialIn(fmt.Sprintf("/proc/%d/ns/net", pid), port, 10*time.Second) + }, +} + // previewPorts lists the ports a workspace's programs listen on, from the sockets of its own network. The proxy's own port (LLD 16 // "Egress") is the server's listener, not a program of the user: it is not listed. func previewPorts(home string) []int { @@ -430,3 +472,29 @@ func logNoProcess(home string, port int, reached bool) { noProcessSeen[home] = time.Now() log.Printf("preview: no process of %s was found for port %d (the emulation's socket answered: %v)", filepath.Base(home), port, reached) } + +var ( + previewFailMu sync.Mutex + previewFailSeen = map[string]time.Time{} +) + +// logPreviewFailure says, at most once in 30 seconds for a workspace and port, why a Preview could not reach the program: the processes that were +// found (with their network: "same" is the server's own) and each attempt with how it ended. A Preview that fails with no word in the log cannot +// be told from a program that is not there (reported: 502 on every port after a session moved to a worker). +func logPreviewFailure(home string, port int, pids []int, tried []string, err error) { + key := fmt.Sprintf("%s|%d", home, port) + previewFailMu.Lock() + defer previewFailMu.Unlock() + if len(previewFailSeen) > 512 { + previewFailSeen = map[string]time.Time{} + } + if time.Since(previewFailSeen[key]) < 30*time.Second { + return + } + previewFailSeen[key] = time.Now() + facts := make([]string, 0, len(pids)) + for _, pid := range pids { + facts = append(facts, fmt.Sprintf("%d(same=%v unsandboxed=%v)", pid, previewProc.same(pid), previewProc.unsandboxed(pid))) + } + log.Printf("preview: %s port %d failed: %v; processes %v; tried %v; emulation %v", filepath.Base(home), port, err, facts, tried, netEmuActive()) +} diff --git a/src/server/preview_dialer_test.go b/src/server/preview_dialer_test.go index 99b8fe5d..e1b11cf6 100644 --- a/src/server/preview_dialer_test.go +++ b/src/server/preview_dialer_test.go @@ -44,3 +44,60 @@ func TestThePreviewReachesAnEmulatedProgramWhenNoProcessWasFound(t *testing.T) { t.Errorf("no emulation: %v", fmt.Sprint(err)) } } + +// A workspace with an unsandboxed process in the server's network (an admin's terminal opened in it) and a REPL under the emulation: the program of +// the emulated REPL must be reached; before, the unsandboxed process sent every port to the real network. +func TestAnUnsandboxedProcessDoesNotHideAnEmulatedProgram(t *testing.T) { + home := t.TempDir() + oldProc, oldEmu := previewProc, netEmuActive + defer func() { previewProc, netEmuActive = oldProc, oldEmu }() + netEmuActive = func() bool { return true } + previewProc.find = func(string) []int { return []int{100, 200} } + previewProc.same = func(int) bool { return true } + previewProc.unsandboxed = func(pid int) bool { return pid == 100 } // 100 is an admin's, 200 is under the emulation + l, err := net.Listen("unix", "@"+netemu.Name(netemu.WorkspaceID(home), "t", 8000)[1:]) + if err != nil { + t.Skip("no abstract sockets here:", err) + } + defer l.Close() + go func() { + if c, err := l.Accept(); err == nil { + c.Close() + } + }() + c, err := previewDialer(home)(context.Background(), 8000) + if err != nil { + t.Fatalf("the emulated program was not reached: %v", err) + } + c.Close() + // the site's own port is never shown for the admin's real network + noteOwnPort("8080") + defer func() { ownPortsMu.Lock(); delete(ownPorts, 8080); ownPortsMu.Unlock() }() + if _, err := previewDialer(home)(context.Background(), 8080); err != errOwnPort { + t.Errorf("the site's own port: %v", err) + } +} + +// A REPL in a network namespace of its own (a worker with cgroups) and an admin's process in the server's: each is tried +func TestAProgramInAnotherNamespaceIsReachedBeforeTheRealNetwork(t *testing.T) { + home := t.TempDir() + oldProc, oldEmu := previewProc, netEmuActive + defer func() { previewProc, netEmuActive = oldProc, oldEmu }() + netEmuActive = func() bool { return true } + previewProc.find = func(string) []int { return []int{100, 300} } + previewProc.same = func(pid int) bool { return pid == 100 } + previewProc.unsandboxed = func(int) bool { return true } + client, server := net.Pipe() + defer client.Close() + defer server.Close() + previewProc.dialIn = func(pid, port int) (net.Conn, error) { + if pid == 300 && port == 8000 { + return client, nil + } + return nil, fmt.Errorf("nothing in the namespace of %d on %d", pid, port) + } + c, err := previewDialer(home)(context.Background(), 8000) + if err != nil || c != client { + t.Fatalf("the program of the other namespace: %v", err) + } +}