♻️ Quality: internal/serverstart without smells (3 → 0)
- Acquire with Lease.claim (under the lock: shared, not ours, or started — a hung one replaced) and liveRecord - start as launch (command, log, record) and waitHealthy; launched carries the record, the log path and the process's end - registry.go: the registry directory, records, leases and lock Checked: go test — start, share and stop with the last session, a server not mm's left alone, Ready's error, timeout, a server that stops at once, the command's error, a stale lock, Say/WaitFor. The hung-server replacement has no test of its own; its code moved unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
75a8140 parent: f0939b6 added
internal/serverstart/registry.go +124 -0 | new file mode 100644 | ||
| @@ -0,0 +1,124 @@ | ||
| 1 | +package serverstart | |
| 2 | + | |
| 3 | +// The registry of the servers mm started: one directory per address, its | |
| 4 | +// record (server.json), the leases of the mm processes using it, and the | |
| 5 | +// lock that serialises them. | |
| 6 | + | |
| 7 | +import ( | |
| 8 | + "context" | |
| 9 | + "encoding/json" | |
| 10 | + "errors" | |
| 11 | + "fmt" | |
| 12 | + "os" | |
| 13 | + "path/filepath" | |
| 14 | + "strconv" | |
| 15 | + "strings" | |
| 16 | + "time" | |
| 17 | +) | |
| 18 | + | |
| 19 | +// liveRecord is the recorded server, nil when there is none or when its | |
| 20 | +// process is gone (the stale record is removed). | |
| 21 | +func liveRecord(dir string) *record { | |
| 22 | + rec := readRecord(dir) | |
| 23 | + if rec != nil && !alive(rec.PID) { | |
| 24 | + removeRecord(dir) | |
| 25 | + return nil | |
| 26 | + } | |
| 27 | + return rec | |
| 28 | +} | |
| 29 | + | |
| 30 | +// registryDir is <StateDir>/<host>-<port>, with its leases directory. | |
| 31 | +func registryDir(o Options) (string, error) { | |
| 32 | + root := o.StateDir | |
| 33 | + if root == "" { | |
| 34 | + cache, err := os.UserCacheDir() | |
| 35 | + if err != nil { | |
| 36 | + return "", err | |
| 37 | + } | |
| 38 | + root = filepath.Join(cache, "mm", o.Server.Name) | |
| 39 | + } | |
| 40 | + name := strings.NewReplacer(":", "_", "/", "_", "\\", "_").Replace(o.Host) + "-" + strconv.Itoa(o.Port) | |
| 41 | + dir := filepath.Join(root, name) | |
| 42 | + return dir, os.MkdirAll(filepath.Join(dir, "leases"), 0o755) | |
| 43 | +} | |
| 44 | + | |
| 45 | +// liveLeases counts the leases whose process still runs, removing the | |
| 46 | +// others (a crashed mm). | |
| 47 | +func liveLeases(dir string) int { | |
| 48 | + entries, _ := os.ReadDir(filepath.Join(dir, "leases")) | |
| 49 | + n := 0 | |
| 50 | + for _, e := range entries { | |
| 51 | + pid, err := strconv.Atoi(e.Name()) | |
| 52 | + if err == nil && alive(pid) { | |
| 53 | + n++ | |
| 54 | + continue | |
| 55 | + } | |
| 56 | + _ = os.Remove(filepath.Join(dir, "leases", e.Name())) | |
| 57 | + } | |
| 58 | + return n | |
| 59 | +} | |
| 60 | + | |
| 61 | +func readRecord(dir string) *record { | |
| 62 | + data, err := os.ReadFile(filepath.Join(dir, "server.json")) | |
| 63 | + if err != nil { | |
| 64 | + return nil | |
| 65 | + } | |
| 66 | + var r record | |
| 67 | + if json.Unmarshal(data, &r) != nil || r.PID <= 0 { | |
| 68 | + return nil | |
| 69 | + } | |
| 70 | + return &r | |
| 71 | +} | |
| 72 | + | |
| 73 | +func writeRecord(dir string, r record) error { | |
| 74 | + data, err := json.MarshalIndent(r, "", " ") | |
| 75 | + if err != nil { | |
| 76 | + return err | |
| 77 | + } | |
| 78 | + return os.WriteFile(filepath.Join(dir, "server.json"), data, 0o644) | |
| 79 | +} | |
| 80 | + | |
| 81 | +func removeRecord(dir string) { _ = os.Remove(filepath.Join(dir, "server.json")) } | |
| 82 | + | |
| 83 | +// lock takes dir's lock file — created exclusively, holding our pid — and | |
| 84 | +// returns its release. A lock whose holder is gone, or older than | |
| 85 | +// lockStale, is taken over. | |
| 86 | +func lock(ctx context.Context, dir, name string) (func(), error) { | |
| 87 | + path := filepath.Join(dir, "lock") | |
| 88 | + ctx, cancel := context.WithTimeout(ctx, lockWait) | |
| 89 | + defer cancel() | |
| 90 | + for { | |
| 91 | + f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644) | |
| 92 | + if err == nil { | |
| 93 | + _, _ = f.WriteString(strconv.Itoa(os.Getpid())) | |
| 94 | + _ = f.Close() | |
| 95 | + return func() { _ = os.Remove(path) }, nil | |
| 96 | + } | |
| 97 | + if !errors.Is(err, os.ErrExist) { | |
| 98 | + return nil, err | |
| 99 | + } | |
| 100 | + if staleLock(path) { | |
| 101 | + _ = os.Remove(path) | |
| 102 | + continue | |
| 103 | + } | |
| 104 | + select { | |
| 105 | + case <-ctx.Done(): | |
| 106 | + return nil, fmt.Errorf("another mm is starting %s (lock %s)", name, path) | |
| 107 | + case <-time.After(Poll): | |
| 108 | + } | |
| 109 | + } | |
| 110 | +} | |
| 111 | + | |
| 112 | +func staleLock(path string) bool { | |
| 113 | + info, err := os.Stat(path) | |
| 114 | + if err != nil { | |
| 115 | + return false // gone meanwhile: retry | |
| 116 | + } | |
| 117 | + data, _ := os.ReadFile(path) | |
| 118 | + pid, err := strconv.Atoi(strings.TrimSpace(string(data))) | |
| 119 | + if err != nil { | |
| 120 | + // Being written right now, or garbage: only an old one is stale. | |
| 121 | + return time.Since(info.ModTime()) > lockStale | |
| 122 | + } | |
| 123 | + return !alive(pid) || time.Since(info.ModTime()) > lockStale | |
| 124 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,124 @@ | |||
| 1 | +package serverstart | ||
| 2 | + | ||
| 3 | +// The registry of the servers mm started: one directory per address, its | ||
| 4 | +// record (server.json), the leases of the mm processes using it, and the | ||
| 5 | +// lock that serialises them. | ||
| 6 | + | ||
| 7 | +import ( | ||
| 8 | + "context" | ||
| 9 | + "encoding/json" | ||
| 10 | + "errors" | ||
| 11 | + "fmt" | ||
| 12 | + "os" | ||
| 13 | + "path/filepath" | ||
| 14 | + "strconv" | ||
| 15 | + "strings" | ||
| 16 | + "time" | ||
| 17 | +) | ||
| 18 | + | ||
| 19 | +// liveRecord is the recorded server, nil when there is none or when its | ||
| 20 | +// process is gone (the stale record is removed). | ||
| 21 | +func liveRecord(dir string) *record { | ||
| 22 | + rec := readRecord(dir) | ||
| 23 | + if rec != nil && !alive(rec.PID) { | ||
| 24 | + removeRecord(dir) | ||
| 25 | + return nil | ||
| 26 | + } | ||
| 27 | + return rec | ||
| 28 | +} | ||
| 29 | + | ||
| 30 | +// registryDir is <StateDir>/<host>-<port>, with its leases directory. | ||
| 31 | +func registryDir(o Options) (string, error) { | ||
| 32 | + root := o.StateDir | ||
| 33 | + if root == "" { | ||
| 34 | + cache, err := os.UserCacheDir() | ||
| 35 | + if err != nil { | ||
| 36 | + return "", err | ||
| 37 | + } | ||
| 38 | + root = filepath.Join(cache, "mm", o.Server.Name) | ||
| 39 | + } | ||
| 40 | + name := strings.NewReplacer(":", "_", "/", "_", "\\", "_").Replace(o.Host) + "-" + strconv.Itoa(o.Port) | ||
| 41 | + dir := filepath.Join(root, name) | ||
| 42 | + return dir, os.MkdirAll(filepath.Join(dir, "leases"), 0o755) | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +// liveLeases counts the leases whose process still runs, removing the | ||
| 46 | +// others (a crashed mm). | ||
| 47 | +func liveLeases(dir string) int { | ||
| 48 | + entries, _ := os.ReadDir(filepath.Join(dir, "leases")) | ||
| 49 | + n := 0 | ||
| 50 | + for _, e := range entries { | ||
| 51 | + pid, err := strconv.Atoi(e.Name()) | ||
| 52 | + if err == nil && alive(pid) { | ||
| 53 | + n++ | ||
| 54 | + continue | ||
| 55 | + } | ||
| 56 | + _ = os.Remove(filepath.Join(dir, "leases", e.Name())) | ||
| 57 | + } | ||
| 58 | + return n | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +func readRecord(dir string) *record { | ||
| 62 | + data, err := os.ReadFile(filepath.Join(dir, "server.json")) | ||
| 63 | + if err != nil { | ||
| 64 | + return nil | ||
| 65 | + } | ||
| 66 | + var r record | ||
| 67 | + if json.Unmarshal(data, &r) != nil || r.PID <= 0 { | ||
| 68 | + return nil | ||
| 69 | + } | ||
| 70 | + return &r | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +func writeRecord(dir string, r record) error { | ||
| 74 | + data, err := json.MarshalIndent(r, "", " ") | ||
| 75 | + if err != nil { | ||
| 76 | + return err | ||
| 77 | + } | ||
| 78 | + return os.WriteFile(filepath.Join(dir, "server.json"), data, 0o644) | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +func removeRecord(dir string) { _ = os.Remove(filepath.Join(dir, "server.json")) } | ||
| 82 | + | ||
| 83 | +// lock takes dir's lock file — created exclusively, holding our pid — and | ||
| 84 | +// returns its release. A lock whose holder is gone, or older than | ||
| 85 | +// lockStale, is taken over. | ||
| 86 | +func lock(ctx context.Context, dir, name string) (func(), error) { | ||
| 87 | + path := filepath.Join(dir, "lock") | ||
| 88 | + ctx, cancel := context.WithTimeout(ctx, lockWait) | ||
| 89 | + defer cancel() | ||
| 90 | + for { | ||
| 91 | + f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644) | ||
| 92 | + if err == nil { | ||
| 93 | + _, _ = f.WriteString(strconv.Itoa(os.Getpid())) | ||
| 94 | + _ = f.Close() | ||
| 95 | + return func() { _ = os.Remove(path) }, nil | ||
| 96 | + } | ||
| 97 | + if !errors.Is(err, os.ErrExist) { | ||
| 98 | + return nil, err | ||
| 99 | + } | ||
| 100 | + if staleLock(path) { | ||
| 101 | + _ = os.Remove(path) | ||
| 102 | + continue | ||
| 103 | + } | ||
| 104 | + select { | ||
| 105 | + case <-ctx.Done(): | ||
| 106 | + return nil, fmt.Errorf("another mm is starting %s (lock %s)", name, path) | ||
| 107 | + case <-time.After(Poll): | ||
| 108 | + } | ||
| 109 | + } | ||
| 110 | +} | ||
| 111 | + | ||
| 112 | +func staleLock(path string) bool { | ||
| 113 | + info, err := os.Stat(path) | ||
| 114 | + if err != nil { | ||
| 115 | + return false // gone meanwhile: retry | ||
| 116 | + } | ||
| 117 | + data, _ := os.ReadFile(path) | ||
| 118 | + pid, err := strconv.Atoi(strings.TrimSpace(string(data))) | ||
| 119 | + if err != nil { | ||
| 120 | + // Being written right now, or garbage: only an old one is stale. | ||
| 121 | + return time.Since(info.ModTime()) > lockStale | ||
| 122 | + } | ||
| 123 | + return !alive(pid) || time.Since(info.ModTime()) > lockStale | ||
| 124 | +} | ||
modified
internal/serverstart/serverstart.go +66 -131 | @@ -25,8 +25,6 @@ package serverstart | ||
| 25 | 25 | |
| 26 | 26 | import ( |
| 27 | 27 | "context" |
| 28 | - "encoding/json" | |
| 29 | - "errors" | |
| 30 | 28 | "fmt" |
| 31 | 29 | "net/http" |
| 32 | 30 | "os" |
| @@ -117,21 +115,31 @@ func Acquire(ctx context.Context, o Options) (*Lease, error) { | ||
| 117 | 115 | } |
| 118 | 116 | base := BaseURL(o) |
| 119 | 117 | l := &Lease{dir: dir, name: o.Server.Name, emoji: o.Server.Emoji, report: o.Report} |
| 120 | - | |
| 121 | - unlock, err := lock(ctx, dir, o.Server.Name) | |
| 122 | - if err != nil { | |
| 118 | + ours, err := l.claim(ctx, o, base) | |
| 119 | + if err != nil || !ours { | |
| 123 | 120 | return nil, err |
| 124 | 121 | } |
| 125 | - rec := readRecord(dir) | |
| 126 | - if rec != nil && !alive(rec.PID) { | |
| 127 | - removeRecord(dir) | |
| 128 | - rec = nil | |
| 122 | + if o.Server.Ready != nil { | |
| 123 | + return l, o.Server.Ready(ctx, o, base) | |
| 124 | + } | |
| 125 | + return l, nil | |
| 126 | +} | |
| 127 | + | |
| 128 | +// claim takes a lease on the server under the registry's lock: on the one | |
| 129 | +// mm already started there, shared; else on a new one, started — a | |
| 130 | +// recorded server that no longer answers is hung, and replaced. ours is | |
| 131 | +// false when a server mm did not start answers: never stopped, no lease. | |
| 132 | +func (l *Lease) claim(ctx context.Context, o Options, base string) (ours bool, err error) { | |
| 133 | + unlock, err := lock(ctx, l.dir, o.Server.Name) | |
| 134 | + if err != nil { | |
| 135 | + return false, err | |
| 129 | 136 | } |
| 137 | + rec := liveRecord(l.dir) | |
| 130 | 138 | up := Healthy(base) |
| 131 | 139 | switch { |
| 132 | 140 | case up && rec == nil: |
| 133 | 141 | unlock() |
| 134 | - return nil, nil // not ours: never stopped | |
| 142 | + return false, nil // not ours: never stopped | |
| 135 | 143 | case up: |
| 136 | 144 | l.add() |
| 137 | 145 | unlock() |
| @@ -139,21 +147,16 @@ func Acquire(ctx context.Context, o Options) (*Lease, error) { | ||
| 139 | 147 | default: |
| 140 | 148 | if rec != nil { // ours, alive, not answering: hung — replace it |
| 141 | 149 | stop(rec.PID) |
| 142 | - removeRecord(dir) | |
| 150 | + removeRecord(l.dir) | |
| 143 | 151 | } |
| 144 | - if err := start(ctx, o, dir, base); err != nil { | |
| 145 | - unlock() | |
| 146 | - return nil, err | |
| 152 | + err := start(ctx, o, l.dir, base) | |
| 153 | + if err == nil { | |
| 154 | + l.add() | |
| 147 | 155 | } |
| 148 | - l.add() | |
| 149 | 156 | unlock() |
| 157 | + return err == nil, err | |
| 150 | 158 | } |
| 151 | - if o.Server.Ready != nil { | |
| 152 | - if err := o.Server.Ready(ctx, o, base); err != nil { | |
| 153 | - return l, err | |
| 154 | - } | |
| 155 | - } | |
| 156 | - return l, nil | |
| 159 | + return true, nil | |
| 157 | 160 | } |
| 158 | 161 | |
| 159 | 162 | // Release removes this process's lease and stops the server when no live |
| @@ -242,65 +245,78 @@ func RecordedPID(o Options) int { | ||
| 242 | 245 | return 0 |
| 243 | 246 | } |
| 244 | 247 | |
| 245 | -// registryDir is <StateDir>/<host>-<port>, with its leases directory. | |
| 246 | -func registryDir(o Options) (string, error) { | |
| 247 | - root := o.StateDir | |
| 248 | - if root == "" { | |
| 249 | - cache, err := os.UserCacheDir() | |
| 250 | - if err != nil { | |
| 251 | - return "", err | |
| 252 | - } | |
| 253 | - root = filepath.Join(cache, "mm", o.Server.Name) | |
| 254 | - } | |
| 255 | - name := strings.NewReplacer(":", "_", "/", "_", "\\", "_").Replace(o.Host) + "-" + strconv.Itoa(o.Port) | |
| 256 | - dir := filepath.Join(root, name) | |
| 257 | - return dir, os.MkdirAll(filepath.Join(dir, "leases"), 0o755) | |
| 258 | -} | |
| 259 | - | |
| 260 | 248 | // start launches the server detached from mm (its own process group, its |
| 261 | 249 | // output in the log file), records it and waits until /health answers. |
| 262 | 250 | func start(ctx context.Context, o Options, dir, base string) error { |
| 263 | - if o.Server.Command == nil { | |
| 264 | - return fmt.Errorf("%s: no start command", o.Server.Name) | |
| 265 | - } | |
| 266 | - bin, args, err := o.Server.Command(dir) | |
| 251 | + p, err := launch(o, dir) | |
| 267 | 252 | if err != nil { |
| 268 | 253 | return err |
| 269 | 254 | } |
| 255 | + o.Say("starting %s on %s (pid %d, log %s)", o.Server.Name, hostPort(o.Host, o.Port), p.rec.PID, p.log) | |
| 256 | + return waitHealthy(ctx, o, dir, base, p) | |
| 257 | +} | |
| 258 | + | |
| 259 | +// launched is a server just started: its record, its log file, and the | |
| 260 | +// end of its process. | |
| 261 | +type launched struct { | |
| 262 | + rec record | |
| 263 | + log string | |
| 264 | + exited <-chan error | |
| 265 | +} | |
| 266 | + | |
| 267 | +// launch starts the server's command, detached, its output in the log file, | |
| 268 | +// and records it. | |
| 269 | +func launch(o Options, dir string) (launched, error) { | |
| 270 | + bin, args, err := o.command(dir) | |
| 271 | + if err != nil { | |
| 272 | + return launched{}, err | |
| 273 | + } | |
| 270 | 274 | logPath := LogPath(o) |
| 271 | 275 | logFile, err := os.Create(logPath) |
| 272 | 276 | if err != nil { |
| 273 | - return err | |
| 277 | + return launched{}, err | |
| 274 | 278 | } |
| 275 | 279 | cmd := exec.Command(bin, args...) |
| 276 | 280 | cmd.Stdout, cmd.Stderr = logFile, logFile |
| 277 | 281 | detach(cmd) |
| 278 | - if err := cmd.Start(); err != nil { | |
| 279 | - _ = logFile.Close() | |
| 280 | - return fmt.Errorf("start %s: %w", bin, err) | |
| 281 | - } | |
| 282 | + err = cmd.Start() | |
| 282 | 283 | _ = logFile.Close() |
| 284 | + if err != nil { | |
| 285 | + return launched{}, fmt.Errorf("start %s: %w", bin, err) | |
| 286 | + } | |
| 283 | 287 | exited := make(chan error, 1) |
| 284 | 288 | go func() { exited <- cmd.Wait() }() // reaps it if it ends while mm runs |
| 285 | 289 | rec := record{PID: cmd.Process.Pid, Binary: bin, Args: args, Started: time.Now()} |
| 286 | 290 | if err := writeRecord(dir, rec); err != nil { |
| 287 | 291 | stop(rec.PID) |
| 288 | - return err | |
| 292 | + return launched{}, err | |
| 289 | 293 | } |
| 290 | - name := o.Server.Name | |
| 291 | - o.Say("starting %s on %s (pid %d, log %s)", name, hostPort(o.Host, o.Port), rec.PID, logPath) | |
| 294 | + return launched{rec: rec, log: logPath, exited: exited}, nil | |
| 295 | +} | |
| 292 | 296 | |
| 297 | +// command is the server's start command for dir. | |
| 298 | +func (o Options) command(dir string) (string, []string, error) { | |
| 299 | + if o.Server.Command == nil { | |
| 300 | + return "", nil, fmt.Errorf("%s: no start command", o.Server.Name) | |
| 301 | + } | |
| 302 | + return o.Server.Command(dir) | |
| 303 | +} | |
| 304 | + | |
| 305 | +// waitHealthy waits until /health answers: an error when the process stops | |
| 306 | +// at once, or when o.Timeout passes (the server is then stopped). | |
| 307 | +func waitHealthy(ctx context.Context, o Options, dir, base string, p launched) error { | |
| 308 | + name, logPath := o.Server.Name, p.log | |
| 293 | 309 | done := o.WaitFor("Starting " + name + "…") |
| 294 | 310 | defer done() |
| 295 | 311 | ctx, cancel := context.WithTimeout(ctx, o.Timeout) |
| 296 | 312 | defer cancel() |
| 297 | 313 | for !Healthy(base) { |
| 298 | 314 | select { |
| 299 | - case err := <-exited: | |
| 315 | + case err := <-p.exited: | |
| 300 | 316 | removeRecord(dir) |
| 301 | 317 | return fmt.Errorf("%s stopped at once (%v) — see %s", name, err, logPath) |
| 302 | 318 | case <-ctx.Done(): |
| 303 | - stop(rec.PID) | |
| 319 | + stop(p.rec.PID) | |
| 304 | 320 | removeRecord(dir) |
| 305 | 321 | return fmt.Errorf("%s did not answer within %s — see %s", name, o.Timeout, logPath) |
| 306 | 322 | case <-time.After(Poll): |
| @@ -328,84 +344,3 @@ func hostPort(host string, port int) string { | ||
| 328 | 344 | } |
| 329 | 345 | return host + ":" + strconv.Itoa(port) |
| 330 | 346 | } |
| 331 | - | |
| 332 | -// liveLeases counts the leases whose process still runs, removing the | |
| 333 | -// others (a crashed mm). | |
| 334 | -func liveLeases(dir string) int { | |
| 335 | - entries, _ := os.ReadDir(filepath.Join(dir, "leases")) | |
| 336 | - n := 0 | |
| 337 | - for _, e := range entries { | |
| 338 | - pid, err := strconv.Atoi(e.Name()) | |
| 339 | - if err == nil && alive(pid) { | |
| 340 | - n++ | |
| 341 | - continue | |
| 342 | - } | |
| 343 | - _ = os.Remove(filepath.Join(dir, "leases", e.Name())) | |
| 344 | - } | |
| 345 | - return n | |
| 346 | -} | |
| 347 | - | |
| 348 | -func readRecord(dir string) *record { | |
| 349 | - data, err := os.ReadFile(filepath.Join(dir, "server.json")) | |
| 350 | - if err != nil { | |
| 351 | - return nil | |
| 352 | - } | |
| 353 | - var r record | |
| 354 | - if json.Unmarshal(data, &r) != nil || r.PID <= 0 { | |
| 355 | - return nil | |
| 356 | - } | |
| 357 | - return &r | |
| 358 | -} | |
| 359 | - | |
| 360 | -func writeRecord(dir string, r record) error { | |
| 361 | - data, err := json.MarshalIndent(r, "", " ") | |
| 362 | - if err != nil { | |
| 363 | - return err | |
| 364 | - } | |
| 365 | - return os.WriteFile(filepath.Join(dir, "server.json"), data, 0o644) | |
| 366 | -} | |
| 367 | - | |
| 368 | -func removeRecord(dir string) { _ = os.Remove(filepath.Join(dir, "server.json")) } | |
| 369 | - | |
| 370 | -// lock takes dir's lock file — created exclusively, holding our pid — and | |
| 371 | -// returns its release. A lock whose holder is gone, or older than | |
| 372 | -// lockStale, is taken over. | |
| 373 | -func lock(ctx context.Context, dir, name string) (func(), error) { | |
| 374 | - path := filepath.Join(dir, "lock") | |
| 375 | - ctx, cancel := context.WithTimeout(ctx, lockWait) | |
| 376 | - defer cancel() | |
| 377 | - for { | |
| 378 | - f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644) | |
| 379 | - if err == nil { | |
| 380 | - _, _ = f.WriteString(strconv.Itoa(os.Getpid())) | |
| 381 | - _ = f.Close() | |
| 382 | - return func() { _ = os.Remove(path) }, nil | |
| 383 | - } | |
| 384 | - if !errors.Is(err, os.ErrExist) { | |
| 385 | - return nil, err | |
| 386 | - } | |
| 387 | - if staleLock(path) { | |
| 388 | - _ = os.Remove(path) | |
| 389 | - continue | |
| 390 | - } | |
| 391 | - select { | |
| 392 | - case <-ctx.Done(): | |
| 393 | - return nil, fmt.Errorf("another mm is starting %s (lock %s)", name, path) | |
| 394 | - case <-time.After(Poll): | |
| 395 | - } | |
| 396 | - } | |
| 397 | -} | |
| 398 | - | |
| 399 | -func staleLock(path string) bool { | |
| 400 | - info, err := os.Stat(path) | |
| 401 | - if err != nil { | |
| 402 | - return false // gone meanwhile: retry | |
| 403 | - } | |
| 404 | - data, _ := os.ReadFile(path) | |
| 405 | - pid, err := strconv.Atoi(strings.TrimSpace(string(data))) | |
| 406 | - if err != nil { | |
| 407 | - // Being written right now, or garbage: only an old one is stale. | |
| 408 | - return time.Since(info.ModTime()) > lockStale | |
| 409 | - } | |
| 410 | - return !alive(pid) || time.Since(info.ModTime()) > lockStale | |
| 411 | -} | |
| @@ -25,8 +25,6 @@ package serverstart | |||
| 25 | 25 | ||
| 26 | import ( | 26 | import ( |
| 27 | "context" | 27 | "context" |
| 28 | - "encoding/json" | ||
| 29 | - "errors" | ||
| 30 | "fmt" | 28 | "fmt" |
| 31 | "net/http" | 29 | "net/http" |
| 32 | "os" | 30 | "os" |
| @@ -117,21 +115,31 @@ func Acquire(ctx context.Context, o Options) (*Lease, error) { | |||
| 117 | } | 115 | } |
| 118 | base := BaseURL(o) | 116 | base := BaseURL(o) |
| 119 | l := &Lease{dir: dir, name: o.Server.Name, emoji: o.Server.Emoji, report: o.Report} | 117 | l := &Lease{dir: dir, name: o.Server.Name, emoji: o.Server.Emoji, report: o.Report} |
| 120 | - | 118 | + ours, err := l.claim(ctx, o, base) |
| 121 | - unlock, err := lock(ctx, dir, o.Server.Name) | 119 | + if err != nil || !ours { |
| 122 | - if err != nil { | ||
| 123 | return nil, err | 120 | return nil, err |
| 124 | } | 121 | } |
| 125 | - rec := readRecord(dir) | 122 | + if o.Server.Ready != nil { |
| 126 | - if rec != nil && !alive(rec.PID) { | 123 | + return l, o.Server.Ready(ctx, o, base) |
| 127 | - removeRecord(dir) | 124 | + } |
| 128 | - rec = nil | 125 | + return l, nil |
| 126 | +} | ||
| 127 | + | ||
| 128 | +// claim takes a lease on the server under the registry's lock: on the one | ||
| 129 | +// mm already started there, shared; else on a new one, started — a | ||
| 130 | +// recorded server that no longer answers is hung, and replaced. ours is | ||
| 131 | +// false when a server mm did not start answers: never stopped, no lease. | ||
| 132 | +func (l *Lease) claim(ctx context.Context, o Options, base string) (ours bool, err error) { | ||
| 133 | + unlock, err := lock(ctx, l.dir, o.Server.Name) | ||
| 134 | + if err != nil { | ||
| 135 | + return false, err | ||
| 129 | } | 136 | } |
| 137 | + rec := liveRecord(l.dir) | ||
| 130 | up := Healthy(base) | 138 | up := Healthy(base) |
| 131 | switch { | 139 | switch { |
| 132 | case up && rec == nil: | 140 | case up && rec == nil: |
| 133 | unlock() | 141 | unlock() |
| 134 | - return nil, nil // not ours: never stopped | 142 | + return false, nil // not ours: never stopped |
| 135 | case up: | 143 | case up: |
| 136 | l.add() | 144 | l.add() |
| 137 | unlock() | 145 | unlock() |
| @@ -139,21 +147,16 @@ func Acquire(ctx context.Context, o Options) (*Lease, error) { | |||
| 139 | default: | 147 | default: |
| 140 | if rec != nil { // ours, alive, not answering: hung — replace it | 148 | if rec != nil { // ours, alive, not answering: hung — replace it |
| 141 | stop(rec.PID) | 149 | stop(rec.PID) |
| 142 | - removeRecord(dir) | 150 | + removeRecord(l.dir) |
| 143 | } | 151 | } |
| 144 | - if err := start(ctx, o, dir, base); err != nil { | 152 | + err := start(ctx, o, l.dir, base) |
| 145 | - unlock() | 153 | + if err == nil { |
| 146 | - return nil, err | 154 | + l.add() |
| 147 | } | 155 | } |
| 148 | - l.add() | ||
| 149 | unlock() | 156 | unlock() |
| 157 | + return err == nil, err | ||
| 150 | } | 158 | } |
| 151 | - if o.Server.Ready != nil { | 159 | + return true, nil |
| 152 | - if err := o.Server.Ready(ctx, o, base); err != nil { | ||
| 153 | - return l, err | ||
| 154 | - } | ||
| 155 | - } | ||
| 156 | - return l, nil | ||
| 157 | } | 160 | } |
| 158 | 161 | ||
| 159 | // Release removes this process's lease and stops the server when no live | 162 | // Release removes this process's lease and stops the server when no live |
| @@ -242,65 +245,78 @@ func RecordedPID(o Options) int { | |||
| 242 | return 0 | 245 | return 0 |
| 243 | } | 246 | } |
| 244 | 247 | ||
| 245 | -// registryDir is <StateDir>/<host>-<port>, with its leases directory. | ||
| 246 | -func registryDir(o Options) (string, error) { | ||
| 247 | - root := o.StateDir | ||
| 248 | - if root == "" { | ||
| 249 | - cache, err := os.UserCacheDir() | ||
| 250 | - if err != nil { | ||
| 251 | - return "", err | ||
| 252 | - } | ||
| 253 | - root = filepath.Join(cache, "mm", o.Server.Name) | ||
| 254 | - } | ||
| 255 | - name := strings.NewReplacer(":", "_", "/", "_", "\\", "_").Replace(o.Host) + "-" + strconv.Itoa(o.Port) | ||
| 256 | - dir := filepath.Join(root, name) | ||
| 257 | - return dir, os.MkdirAll(filepath.Join(dir, "leases"), 0o755) | ||
| 258 | -} | ||
| 259 | - | ||
| 260 | // start launches the server detached from mm (its own process group, its | 248 | // start launches the server detached from mm (its own process group, its |
| 261 | // output in the log file), records it and waits until /health answers. | 249 | // output in the log file), records it and waits until /health answers. |
| 262 | func start(ctx context.Context, o Options, dir, base string) error { | 250 | func start(ctx context.Context, o Options, dir, base string) error { |
| 263 | - if o.Server.Command == nil { | 251 | + p, err := launch(o, dir) |
| 264 | - return fmt.Errorf("%s: no start command", o.Server.Name) | ||
| 265 | - } | ||
| 266 | - bin, args, err := o.Server.Command(dir) | ||
| 267 | if err != nil { | 252 | if err != nil { |
| 268 | return err | 253 | return err |
| 269 | } | 254 | } |
| 255 | + o.Say("starting %s on %s (pid %d, log %s)", o.Server.Name, hostPort(o.Host, o.Port), p.rec.PID, p.log) | ||
| 256 | + return waitHealthy(ctx, o, dir, base, p) | ||
| 257 | +} | ||
| 258 | + | ||
| 259 | +// launched is a server just started: its record, its log file, and the | ||
| 260 | +// end of its process. | ||
| 261 | +type launched struct { | ||
| 262 | + rec record | ||
| 263 | + log string | ||
| 264 | + exited <-chan error | ||
| 265 | +} | ||
| 266 | + | ||
| 267 | +// launch starts the server's command, detached, its output in the log file, | ||
| 268 | +// and records it. | ||
| 269 | +func launch(o Options, dir string) (launched, error) { | ||
| 270 | + bin, args, err := o.command(dir) | ||
| 271 | + if err != nil { | ||
| 272 | + return launched{}, err | ||
| 273 | + } | ||
| 270 | logPath := LogPath(o) | 274 | logPath := LogPath(o) |
| 271 | logFile, err := os.Create(logPath) | 275 | logFile, err := os.Create(logPath) |
| 272 | if err != nil { | 276 | if err != nil { |
| 273 | - return err | 277 | + return launched{}, err |
| 274 | } | 278 | } |
| 275 | cmd := exec.Command(bin, args...) | 279 | cmd := exec.Command(bin, args...) |
| 276 | cmd.Stdout, cmd.Stderr = logFile, logFile | 280 | cmd.Stdout, cmd.Stderr = logFile, logFile |
| 277 | detach(cmd) | 281 | detach(cmd) |
| 278 | - if err := cmd.Start(); err != nil { | 282 | + err = cmd.Start() |
| 279 | - _ = logFile.Close() | ||
| 280 | - return fmt.Errorf("start %s: %w", bin, err) | ||
| 281 | - } | ||
| 282 | _ = logFile.Close() | 283 | _ = logFile.Close() |
| 284 | + if err != nil { | ||
| 285 | + return launched{}, fmt.Errorf("start %s: %w", bin, err) | ||
| 286 | + } | ||
| 283 | exited := make(chan error, 1) | 287 | exited := make(chan error, 1) |
| 284 | go func() { exited <- cmd.Wait() }() // reaps it if it ends while mm runs | 288 | go func() { exited <- cmd.Wait() }() // reaps it if it ends while mm runs |
| 285 | rec := record{PID: cmd.Process.Pid, Binary: bin, Args: args, Started: time.Now()} | 289 | rec := record{PID: cmd.Process.Pid, Binary: bin, Args: args, Started: time.Now()} |
| 286 | if err := writeRecord(dir, rec); err != nil { | 290 | if err := writeRecord(dir, rec); err != nil { |
| 287 | stop(rec.PID) | 291 | stop(rec.PID) |
| 288 | - return err | 292 | + return launched{}, err |
| 289 | } | 293 | } |
| 290 | - name := o.Server.Name | 294 | + return launched{rec: rec, log: logPath, exited: exited}, nil |
| 291 | - o.Say("starting %s on %s (pid %d, log %s)", name, hostPort(o.Host, o.Port), rec.PID, logPath) | 295 | +} |
| 292 | 296 | ||
| 297 | +// command is the server's start command for dir. | ||
| 298 | +func (o Options) command(dir string) (string, []string, error) { | ||
| 299 | + if o.Server.Command == nil { | ||
| 300 | + return "", nil, fmt.Errorf("%s: no start command", o.Server.Name) | ||
| 301 | + } | ||
| 302 | + return o.Server.Command(dir) | ||
| 303 | +} | ||
| 304 | + | ||
| 305 | +// waitHealthy waits until /health answers: an error when the process stops | ||
| 306 | +// at once, or when o.Timeout passes (the server is then stopped). | ||
| 307 | +func waitHealthy(ctx context.Context, o Options, dir, base string, p launched) error { | ||
| 308 | + name, logPath := o.Server.Name, p.log | ||
| 293 | done := o.WaitFor("Starting " + name + "…") | 309 | done := o.WaitFor("Starting " + name + "…") |
| 294 | defer done() | 310 | defer done() |
| 295 | ctx, cancel := context.WithTimeout(ctx, o.Timeout) | 311 | ctx, cancel := context.WithTimeout(ctx, o.Timeout) |
| 296 | defer cancel() | 312 | defer cancel() |
| 297 | for !Healthy(base) { | 313 | for !Healthy(base) { |
| 298 | select { | 314 | select { |
| 299 | - case err := <-exited: | 315 | + case err := <-p.exited: |
| 300 | removeRecord(dir) | 316 | removeRecord(dir) |
| 301 | return fmt.Errorf("%s stopped at once (%v) — see %s", name, err, logPath) | 317 | return fmt.Errorf("%s stopped at once (%v) — see %s", name, err, logPath) |
| 302 | case <-ctx.Done(): | 318 | case <-ctx.Done(): |
| 303 | - stop(rec.PID) | 319 | + stop(p.rec.PID) |
| 304 | removeRecord(dir) | 320 | removeRecord(dir) |
| 305 | return fmt.Errorf("%s did not answer within %s — see %s", name, o.Timeout, logPath) | 321 | return fmt.Errorf("%s did not answer within %s — see %s", name, o.Timeout, logPath) |
| 306 | case <-time.After(Poll): | 322 | case <-time.After(Poll): |
| @@ -328,84 +344,3 @@ func hostPort(host string, port int) string { | |||
| 328 | } | 344 | } |
| 329 | return host + ":" + strconv.Itoa(port) | 345 | return host + ":" + strconv.Itoa(port) |
| 330 | } | 346 | } |
| 331 | - | ||
| 332 | -// liveLeases counts the leases whose process still runs, removing the | ||
| 333 | -// others (a crashed mm). | ||
| 334 | -func liveLeases(dir string) int { | ||
| 335 | - entries, _ := os.ReadDir(filepath.Join(dir, "leases")) | ||
| 336 | - n := 0 | ||
| 337 | - for _, e := range entries { | ||
| 338 | - pid, err := strconv.Atoi(e.Name()) | ||
| 339 | - if err == nil && alive(pid) { | ||
| 340 | - n++ | ||
| 341 | - continue | ||
| 342 | - } | ||
| 343 | - _ = os.Remove(filepath.Join(dir, "leases", e.Name())) | ||
| 344 | - } | ||
| 345 | - return n | ||
| 346 | -} | ||
| 347 | - | ||
| 348 | -func readRecord(dir string) *record { | ||
| 349 | - data, err := os.ReadFile(filepath.Join(dir, "server.json")) | ||
| 350 | - if err != nil { | ||
| 351 | - return nil | ||
| 352 | - } | ||
| 353 | - var r record | ||
| 354 | - if json.Unmarshal(data, &r) != nil || r.PID <= 0 { | ||
| 355 | - return nil | ||
| 356 | - } | ||
| 357 | - return &r | ||
| 358 | -} | ||
| 359 | - | ||
| 360 | -func writeRecord(dir string, r record) error { | ||
| 361 | - data, err := json.MarshalIndent(r, "", " ") | ||
| 362 | - if err != nil { | ||
| 363 | - return err | ||
| 364 | - } | ||
| 365 | - return os.WriteFile(filepath.Join(dir, "server.json"), data, 0o644) | ||
| 366 | -} | ||
| 367 | - | ||
| 368 | -func removeRecord(dir string) { _ = os.Remove(filepath.Join(dir, "server.json")) } | ||
| 369 | - | ||
| 370 | -// lock takes dir's lock file — created exclusively, holding our pid — and | ||
| 371 | -// returns its release. A lock whose holder is gone, or older than | ||
| 372 | -// lockStale, is taken over. | ||
| 373 | -func lock(ctx context.Context, dir, name string) (func(), error) { | ||
| 374 | - path := filepath.Join(dir, "lock") | ||
| 375 | - ctx, cancel := context.WithTimeout(ctx, lockWait) | ||
| 376 | - defer cancel() | ||
| 377 | - for { | ||
| 378 | - f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644) | ||
| 379 | - if err == nil { | ||
| 380 | - _, _ = f.WriteString(strconv.Itoa(os.Getpid())) | ||
| 381 | - _ = f.Close() | ||
| 382 | - return func() { _ = os.Remove(path) }, nil | ||
| 383 | - } | ||
| 384 | - if !errors.Is(err, os.ErrExist) { | ||
| 385 | - return nil, err | ||
| 386 | - } | ||
| 387 | - if staleLock(path) { | ||
| 388 | - _ = os.Remove(path) | ||
| 389 | - continue | ||
| 390 | - } | ||
| 391 | - select { | ||
| 392 | - case <-ctx.Done(): | ||
| 393 | - return nil, fmt.Errorf("another mm is starting %s (lock %s)", name, path) | ||
| 394 | - case <-time.After(Poll): | ||
| 395 | - } | ||
| 396 | - } | ||
| 397 | -} | ||
| 398 | - | ||
| 399 | -func staleLock(path string) bool { | ||
| 400 | - info, err := os.Stat(path) | ||
| 401 | - if err != nil { | ||
| 402 | - return false // gone meanwhile: retry | ||
| 403 | - } | ||
| 404 | - data, _ := os.ReadFile(path) | ||
| 405 | - pid, err := strconv.Atoi(strings.TrimSpace(string(data))) | ||
| 406 | - if err != nil { | ||
| 407 | - // Being written right now, or garbage: only an old one is stale. | ||
| 408 | - return time.Since(info.ModTime()) > lockStale | ||
| 409 | - } | ||
| 410 | - return !alive(pid) || time.Since(info.ModTime()) > lockStale | ||
| 411 | -} | ||