|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "net" |
| 8 | + "net/http" |
| 9 | + "os" |
| 10 | + "os/exec" |
| 11 | + "path/filepath" |
| 12 | + "regexp" |
| 13 | + "strconv" |
| 14 | + "strings" |
| 15 | + "syscall" |
| 16 | + "testing" |
| 17 | + "time" |
| 18 | + |
| 19 | + "github.com/coder/websocket" |
| 20 | +) |
| 21 | + |
| 22 | +// TestSessionsSurviveDaemonRestart is the whole feature, end to end, against |
| 23 | +// the real binary: spawn a session through a real daemon, SIGTERM the |
| 24 | +// daemon, start a new one, and find the same session — same id, same child |
| 25 | +// process, scrollback intact. Skipped under -short because it builds the |
| 26 | +// binary and runs two daemons. |
| 27 | +func TestSessionsSurviveDaemonRestart(t *testing.T) { |
| 28 | + if testing.Short() { |
| 29 | + t.Skip("builds the flue binary and runs real daemons") |
| 30 | + } |
| 31 | + |
| 32 | + // The config dir must sit shallow enough for the holder socket path; a |
| 33 | + // nested t.TempDir can blow the platform's sockaddr limit. |
| 34 | + xdg, err := os.MkdirTemp("", "fe") |
| 35 | + if err != nil { |
| 36 | + t.Fatalf("MkdirTemp: %v", err) |
| 37 | + } |
| 38 | + t.Cleanup(func() { os.RemoveAll(xdg) }) |
| 39 | + |
| 40 | + // Not xdg/flue: config.Dir wants to create a directory by that name. |
| 41 | + bin := filepath.Join(xdg, "bin", "flue") |
| 42 | + if err := os.MkdirAll(filepath.Dir(bin), 0o755); err != nil { |
| 43 | + t.Fatal(err) |
| 44 | + } |
| 45 | + build := exec.Command("go", "build", "-o", bin, ".") |
| 46 | + if out, err := build.CombinedOutput(); err != nil { |
| 47 | + t.Fatalf("go build: %v\n%s", err, out) |
| 48 | + } |
| 49 | + |
| 50 | + port := freePort(t) |
| 51 | + env := append(os.Environ(), "XDG_CONFIG_HOME="+xdg) |
| 52 | + |
| 53 | + daemon1 := startDaemon(t, bin, port, env) |
| 54 | + token := readToken(t, xdg) |
| 55 | + |
| 56 | + // A child that names its own pid is the witness: the same line after |
| 57 | + // the restart proves the same process, not a lookalike. |
| 58 | + ws := dialWS(t, port, token) |
| 59 | + send(t, ws, map[string]any{ |
| 60 | + "type": "spawn", "reqId": 1, "cols": 80, "rows": 24, "cwd": "/", |
| 61 | + "cmd": []string{"/bin/sh", "-c", `echo "MARK-$$"; exec sleep 300`}, |
| 62 | + }) |
| 63 | + sessionID := awaitAttached(t, ws) |
| 64 | + backlog := awaitMark(t, ws) |
| 65 | + childPid := pidFromMark(t, backlog) |
| 66 | + ws.Close(websocket.StatusNormalClosure, "") |
| 67 | + |
| 68 | + // The restart: graceful SIGTERM, as a service manager would deliver it. |
| 69 | + if err := daemon1.Process.Signal(syscall.SIGTERM); err != nil { |
| 70 | + t.Fatalf("SIGTERM daemon: %v", err) |
| 71 | + } |
| 72 | + if _, err := daemon1.Process.Wait(); err != nil { |
| 73 | + t.Fatalf("daemon did not exit: %v", err) |
| 74 | + } |
| 75 | + |
| 76 | + daemon2 := startDaemon(t, bin, port, env) |
| 77 | + defer func() { |
| 78 | + _ = daemon2.Process.Signal(syscall.SIGTERM) |
| 79 | + _, _ = daemon2.Process.Wait() |
| 80 | + }() |
| 81 | + |
| 82 | + infos, err := fetchSessions(port, token) |
| 83 | + if err != nil { |
| 84 | + t.Fatalf("fetchSessions: %v", err) |
| 85 | + } |
| 86 | + var found bool |
| 87 | + for _, s := range infos { |
| 88 | + if s.ID == sessionID { |
| 89 | + found = true |
| 90 | + if s.State != "running" { |
| 91 | + t.Fatalf("session %s State = %q after restart, want running", s.ID, s.State) |
| 92 | + } |
| 93 | + } |
| 94 | + } |
| 95 | + if !found { |
| 96 | + t.Fatalf("session %s is gone after the restart; got %+v", sessionID, infos) |
| 97 | + } |
| 98 | + |
| 99 | + if err := syscall.Kill(childPid, 0); err != nil { |
| 100 | + t.Fatalf("child %d is dead after the restart: %v", childPid, err) |
| 101 | + } |
| 102 | + |
| 103 | + ws2 := dialWS(t, port, token) |
| 104 | + defer ws2.Close(websocket.StatusNormalClosure, "") |
| 105 | + send(t, ws2, map[string]any{"type": "attach", "id": sessionID, "lastSeq": 0, "reqId": 2}) |
| 106 | + backlog2 := awaitMark(t, ws2) |
| 107 | + if pid2 := pidFromMark(t, backlog2); pid2 != childPid { |
| 108 | + t.Fatalf("marker pid changed across restart: %d then %d", childPid, pid2) |
| 109 | + } |
| 110 | + |
| 111 | + // Retire the session so nothing outlives the test. |
| 112 | + send(t, ws2, map[string]any{"type": "close", "id": sessionID}) |
| 113 | + deadline := time.Now().Add(5 * time.Second) |
| 114 | + for syscall.Kill(childPid, 0) == nil { |
| 115 | + if time.Now().After(deadline) { |
| 116 | + t.Fatalf("child %d survived the close", childPid) |
| 117 | + } |
| 118 | + time.Sleep(20 * time.Millisecond) |
| 119 | + } |
| 120 | +} |
| 121 | + |
| 122 | +func freePort(t *testing.T) int { |
| 123 | + t.Helper() |
| 124 | + ln, err := net.Listen("tcp", "127.0.0.1:0") |
| 125 | + if err != nil { |
| 126 | + t.Fatalf("Listen: %v", err) |
| 127 | + } |
| 128 | + port := ln.Addr().(*net.TCPAddr).Port |
| 129 | + ln.Close() |
| 130 | + return port |
| 131 | +} |
| 132 | + |
| 133 | +func startDaemon(t *testing.T, bin string, port int, env []string) *exec.Cmd { |
| 134 | + t.Helper() |
| 135 | + cmd := exec.Command(bin, "serve", "--port", strconv.Itoa(port)) |
| 136 | + cmd.Env = env |
| 137 | + cmd.Stdout = os.Stderr |
| 138 | + cmd.Stderr = os.Stderr |
| 139 | + if err := cmd.Start(); err != nil { |
| 140 | + t.Fatalf("start daemon: %v", err) |
| 141 | + } |
| 142 | + deadline := time.Now().Add(10 * time.Second) |
| 143 | + for { |
| 144 | + conn, err := net.DialTimeout("tcp", fmt.Sprintf("127.0.0.1:%d", port), 200*time.Millisecond) |
| 145 | + if err == nil { |
| 146 | + conn.Close() |
| 147 | + return cmd |
| 148 | + } |
| 149 | + if time.Now().After(deadline) { |
| 150 | + t.Fatal("daemon never bound its port") |
| 151 | + } |
| 152 | + time.Sleep(50 * time.Millisecond) |
| 153 | + } |
| 154 | +} |
| 155 | + |
| 156 | +func readToken(t *testing.T, xdg string) string { |
| 157 | + t.Helper() |
| 158 | + b, err := os.ReadFile(filepath.Join(xdg, "flue", "token")) |
| 159 | + if err != nil { |
| 160 | + t.Fatalf("read token: %v", err) |
| 161 | + } |
| 162 | + return strings.TrimSpace(string(b)) |
| 163 | +} |
| 164 | + |
| 165 | +func dialWS(t *testing.T, port int, token string) *websocket.Conn { |
| 166 | + t.Helper() |
| 167 | + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 168 | + t.Cleanup(cancel) |
| 169 | + ws, _, err := websocket.Dial(ctx, fmt.Sprintf("ws://127.0.0.1:%d/ws", port), &websocket.DialOptions{ |
| 170 | + HTTPHeader: http.Header{"X-Flue-Token": []string{token}}, |
| 171 | + }) |
| 172 | + if err != nil { |
| 173 | + t.Fatalf("ws dial: %v", err) |
| 174 | + } |
| 175 | + ws.SetReadLimit(1 << 22) |
| 176 | + return ws |
| 177 | +} |
| 178 | + |
| 179 | +func send(t *testing.T, ws *websocket.Conn, msg map[string]any) { |
| 180 | + t.Helper() |
| 181 | + b, _ := json.Marshal(msg) |
| 182 | + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 183 | + defer cancel() |
| 184 | + if err := ws.Write(ctx, websocket.MessageText, b); err != nil { |
| 185 | + t.Fatalf("ws write %v: %v", msg["type"], err) |
| 186 | + } |
| 187 | +} |
| 188 | + |
| 189 | +// awaitAttached reads until the attached control message and returns the |
| 190 | +// session id it names. |
| 191 | +func awaitAttached(t *testing.T, ws *websocket.Conn) string { |
| 192 | + t.Helper() |
| 193 | + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 194 | + defer cancel() |
| 195 | + for { |
| 196 | + typ, b, err := ws.Read(ctx) |
| 197 | + if err != nil { |
| 198 | + t.Fatalf("ws read awaiting attached: %v", err) |
| 199 | + } |
| 200 | + if typ != websocket.MessageText { |
| 201 | + continue |
| 202 | + } |
| 203 | + var m struct { |
| 204 | + Type string `json:"type"` |
| 205 | + ID string `json:"id"` |
| 206 | + Msg string `json:"msg"` |
| 207 | + } |
| 208 | + if json.Unmarshal(b, &m) != nil { |
| 209 | + continue |
| 210 | + } |
| 211 | + if m.Type == "error" { |
| 212 | + t.Fatalf("daemon answered error: %s", m.Msg) |
| 213 | + } |
| 214 | + if m.Type == "attached" { |
| 215 | + return m.ID |
| 216 | + } |
| 217 | + } |
| 218 | +} |
| 219 | + |
| 220 | +// awaitMark accumulates stream output until the MARK-<pid> line is whole. |
| 221 | +// Output frames are binary; everything else is control chatter to skip. |
| 222 | +func awaitMark(t *testing.T, ws *websocket.Conn) string { |
| 223 | + t.Helper() |
| 224 | + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 225 | + defer cancel() |
| 226 | + var out strings.Builder |
| 227 | + for { |
| 228 | + typ, b, err := ws.Read(ctx) |
| 229 | + if err != nil { |
| 230 | + t.Fatalf("ws read awaiting mark: %v (have %q)", err, out.String()) |
| 231 | + } |
| 232 | + if typ == websocket.MessageBinary { |
| 233 | + out.Write(b) |
| 234 | + } |
| 235 | + if markRE.MatchString(out.String()) { |
| 236 | + return out.String() |
| 237 | + } |
| 238 | + } |
| 239 | +} |
| 240 | + |
| 241 | +var markRE = regexp.MustCompile(`MARK-(\d+)`) |
| 242 | + |
| 243 | +func pidFromMark(t *testing.T, s string) int { |
| 244 | + t.Helper() |
| 245 | + m := markRE.FindStringSubmatch(s) |
| 246 | + if m == nil { |
| 247 | + t.Fatalf("no MARK line in %q", s) |
| 248 | + } |
| 249 | + pid, err := strconv.Atoi(m[1]) |
| 250 | + if err != nil { |
| 251 | + t.Fatalf("bad pid in mark: %v", err) |
| 252 | + } |
| 253 | + return pid |
| 254 | +} |
0 commit comments