| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "os" |
| 8 | "os/exec" |
| 9 | "path/filepath" |
| 10 | "slices" |
| 11 | "strings" |
| 12 | "testing" |
| 13 | "time" |
| 14 | ) |
| 15 | |
| 16 | // hostLines prints nothing for healthy sources, one host entry with its |
| 17 | // collector reason and see command for a single-unit failure or non-unit |
| 18 | // state, each failing unit under the source when several fail, and caps |
| 19 | // the unit list at maxHostUnits with "and N more". |
| 20 | func TestHostLinesRendering(t *testing.T) { |
| 21 | plain := terminal{width: 80} |
| 22 | |
| 23 | if got := plain.hostLines(nil); len(got) != 0 { |
| 24 | t.Errorf("healthy hostLines = %q, want empty", got) |
| 25 | } |
| 26 | |
| 27 | one := plain.hostLines([]jsonHostSource{{ |
| 28 | Source: "mirrors", |
| 29 | State: "failed", |
| 30 | Reason: "valley-publish@app.service: activating, result exit-code, status 1", |
| 31 | Units: []string{"valley-publish@app.service"}, |
| 32 | }}) |
| 33 | wantOne := strings.Join([]string{ |
| 34 | "host mirrors failed · valley-publish@app.service: activating, result exit-code, status 1", |
| 35 | " see: valley telemetry read --source mirrors --logs", |
| 36 | }, "\n") |
| 37 | if got := strings.Join(one, "\n"); got != wantOne { |
| 38 | t.Errorf("one failed source:\n got:\n%s\nwant:\n%s", got, wantOne) |
| 39 | } |
| 40 | |
| 41 | several := plain.hostLines([]jsonHostSource{{ |
| 42 | Source: "mirrors", |
| 43 | State: "failed", |
| 44 | Reason: "valley-publish@app.service: activating, result exit-code, status 1", |
| 45 | Units: []string{ |
| 46 | "valley-publish@app.service", |
| 47 | "valley-publish@docs.service", |
| 48 | "valley-publish@site.service", |
| 49 | }, |
| 50 | }}) |
| 51 | wantSeveral := strings.Join([]string{ |
| 52 | "host mirrors failed · valley-publish@app.service: activating, result exit-code, status 1", |
| 53 | " valley-publish@app.service", |
| 54 | " valley-publish@docs.service", |
| 55 | " valley-publish@site.service", |
| 56 | " see: valley telemetry read --source mirrors --logs", |
| 57 | }, "\n") |
| 58 | if got := strings.Join(several, "\n"); got != wantSeveral { |
| 59 | t.Errorf("several failing units:\n got:\n%s\nwant:\n%s", got, wantSeveral) |
| 60 | } |
| 61 | |
| 62 | capped := plain.hostLines([]jsonHostSource{{ |
| 63 | Source: "mirrors", |
| 64 | State: "failed", |
| 65 | Reason: "valley-publish@api.service: failed, result exit-code, status 1", |
| 66 | Units: []string{ |
| 67 | "valley-publish@api.service", |
| 68 | "valley-publish@app.service", |
| 69 | "valley-publish@blog.service", |
| 70 | "valley-publish@docs.service", |
| 71 | "valley-publish@site.service", |
| 72 | "valley-publish@tools.service", |
| 73 | "valley-publish@web.service", |
| 74 | }, |
| 75 | }}) |
| 76 | wantCapped := strings.Join([]string{ |
| 77 | "host mirrors failed · valley-publish@api.service: failed, result exit-code, status 1", |
| 78 | " valley-publish@api.service", |
| 79 | " valley-publish@app.service", |
| 80 | " valley-publish@blog.service", |
| 81 | " valley-publish@docs.service", |
| 82 | " valley-publish@site.service", |
| 83 | " and 2 more", |
| 84 | " see: valley telemetry read --source mirrors --logs", |
| 85 | }, "\n") |
| 86 | if got := strings.Join(capped, "\n"); got != wantCapped { |
| 87 | t.Errorf("capped failing units:\n got:\n%s\nwant:\n%s", got, wantCapped) |
| 88 | } |
| 89 | |
| 90 | nonUnit := plain.hostLines([]jsonHostSource{ |
| 91 | { |
| 92 | Source: "worker", |
| 93 | State: "stale", |
| 94 | Reason: "run p1 recorded no end and no unit of the source is running: it was interrupted", |
| 95 | Units: []string{"valley-worker.service"}, |
| 96 | }, |
| 97 | { |
| 98 | Source: "remote-receiver", |
| 99 | State: "unavailable", |
| 100 | Reason: "receiver has reported nothing: this host has no observation of the source", |
| 101 | Units: []string{}, |
| 102 | }, |
| 103 | }) |
| 104 | wantNonUnit := strings.Join([]string{ |
| 105 | "host worker stale · run p1 recorded no end and no unit of the source is running: it was interrupted", |
| 106 | " see: valley telemetry read --source worker --logs", |
| 107 | "host remote-receiver unavailable · receiver has reported nothing: this host has no observation of the source", |
| 108 | " see: valley telemetry read --source remote-receiver --logs", |
| 109 | }, "\n") |
| 110 | if got := strings.Join(nonUnit, "\n"); got != wantNonUnit { |
| 111 | t.Errorf("stale and unavailable:\n got:\n%s\nwant:\n%s", got, wantNonUnit) |
| 112 | } |
| 113 | |
| 114 | // Styled terminal highlights source name in bold and state in colour. |
| 115 | styled := terminal{width: 80, bold: true}.hostLines([]jsonHostSource{{ |
| 116 | Source: "mirrors", |
| 117 | State: "failed", |
| 118 | Reason: "valley-publish@app.service: failed, result exit-code, status 1", |
| 119 | Units: []string{"valley-publish@app.service"}, |
| 120 | }}) |
| 121 | if !strings.Contains(styled[0], "\x1b[1mmirrors\x1b[0m") || !strings.Contains(styled[0], "\x1b[31mfailed\x1b[0m") { |
| 122 | t.Errorf("styled host line = %q", styled[0]) |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | // parseHostSources keeps only failed, stale and unavailable sources, |
| 127 | // extracts failing units by the collector's rule, sanitizes control |
| 128 | // characters, and rejects errors or truncated answers. |
| 129 | func TestParseHostSources(t *testing.T) { |
| 130 | answer := strings.Join([]string{ |
| 131 | `{"kind":"header","host":"valley-host","format":"valley-telemetry/v1"}`, |
| 132 | `{"kind":"source","name":"worker","state":"idle","detail":"no open run","unit_states":[{"Id":"valley-worker.service","LoadState":"loaded","ActiveState":"inactive","Result":"success"}]}`, |
| 133 | `{"kind":"source","name":"integrator","state":"active","detail":"a unit is running","unit_states":[{"Id":"valley-integrator@app.service","LoadState":"loaded","ActiveState":"active","Result":"success"}]}`, |
| 134 | `{"kind":"source","name":"bus","state":"disabled","detail":"not enabled in this host's configuration"}`, |
| 135 | `{"kind":"source","name":"mirrors","state":"failed","detail":"valley-publish@app.service: activating, result exit-code, status 1\n\u001b[31mextra","unit_states":[` + |
| 136 | `{"Id":"valley-publish@ok.service","LoadState":"loaded","ActiveState":"inactive","Result":"success"},` + |
| 137 | `{"Id":"valley-publish@app.service","LoadState":"loaded","ActiveState":"activating","Result":"exit-code","ExecMainStatus":"1"},` + |
| 138 | `{"Id":"valley-publish@site.service","LoadState":"loaded","ActiveState":"failed","Result":"exit-code","ExecMainStatus":"2"}]}`, |
| 139 | `{"kind":"source","name":"backup","state":"stale","detail":"nothing received since 2026-01-01T00:00:00Z"}`, |
| 140 | `{"kind":"source","name":"remote-receiver","state":"unavailable","detail":"receiver has reported nothing: this host has no observation of the source"}`, |
| 141 | `{"kind":"end","truncated":false}`, |
| 142 | }, "\n") + "\n" |
| 143 | |
| 144 | got, err := parseHostSources(strings.NewReader(answer)) |
| 145 | if err != nil { |
| 146 | t.Fatalf("parseHostSources: %v", err) |
| 147 | } |
| 148 | if len(got) != 3 { |
| 149 | t.Fatalf("got %d entries, want 3: %+v", len(got), got) |
| 150 | } |
| 151 | if got[0].Source != "mirrors" || got[0].State != "failed" || |
| 152 | !slices.Equal(got[0].Units, []string{"valley-publish@app.service", "valley-publish@site.service"}) || |
| 153 | strings.ContainsAny(got[0].Reason, "\n\x1b") { |
| 154 | t.Errorf("mirrors = %+v", got[0]) |
| 155 | } |
| 156 | if got[1].Source != "backup" || got[1].State != "stale" || got[1].Units == nil || len(got[1].Units) != 0 { |
| 157 | t.Errorf("backup = %+v", got[1]) |
| 158 | } |
| 159 | if got[2].Source != "remote-receiver" || got[2].State != "unavailable" || got[2].Units == nil || len(got[2].Units) != 0 { |
| 160 | t.Errorf("remote-receiver = %+v", got[2]) |
| 161 | } |
| 162 | |
| 163 | if _, err := parseHostSources(strings.NewReader(`{"kind":"error","error":"alice does not hold the observe grant"}` + "\n")); err == nil { |
| 164 | t.Error("parseHostSources accepted an error line") |
| 165 | } |
| 166 | if _, err := parseHostSources(strings.NewReader(`{"kind":"header"}` + "\n" + `{"kind":"source","name":"mirrors","state":"failed","detail":"x"}` + "\n")); err == nil { |
| 167 | t.Error("parseHostSources accepted an answer without end") |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | // valley pending surfaces failed, stale and unavailable host sources |
| 172 | // above needs you and in --json host_sources, prints nothing for healthy |
| 173 | // sources, prints nothing and adds no warning without the observe grant |
| 174 | // or with no collector, and prints host entries once under --all. |
| 175 | func TestPendingHostSources(t *testing.T) { |
| 176 | dir := t.TempDir() |
| 177 | t.Setenv("HOME", dir) |
| 178 | t.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "config")) |
| 179 | t.Setenv("XDG_CACHE_HOME", filepath.Join(dir, "cache")) |
| 180 | t.Setenv("GIT_CONFIG_NOSYSTEM", "1") |
| 181 | t.Setenv("VALLEY_KNOWN_SIGNERS", "") |
| 182 | t.Setenv("VALLEY_VERIFICATION_SCHEMA", testSchema) |
| 183 | _, hasCue := exec.LookPath("cue") |
| 184 | |
| 185 | bin := filepath.Join(dir, "bin") |
| 186 | if err := os.MkdirAll(bin, 0o755); err != nil { |
| 187 | t.Fatal(err) |
| 188 | } |
| 189 | answerFile := filepath.Join(dir, "sources.jsonl") |
| 190 | failFile := filepath.Join(dir, "ssh.fail") |
| 191 | logFile := filepath.Join(dir, "ssh.log") |
| 192 | sshScript := fmt.Sprintf(`#!/bin/sh |
| 193 | echo "$*" >> '%s' |
| 194 | if [ -e '%s' ]; then |
| 195 | echo 'ssh: connect to host valley-host port 22: Connection refused' >&2 |
| 196 | exit 255 |
| 197 | fi |
| 198 | case "$*" in |
| 199 | *"valley-telemetry sources"*) |
| 200 | cat '%s' |
| 201 | ;; |
| 202 | *) |
| 203 | echo '{"kind":"header","host":"valley-host","format":"valley-telemetry/v1"}' |
| 204 | echo '{"kind":"end","cursor":"worker=0123456789abcdef:0","truncated":false}' |
| 205 | ;; |
| 206 | esac |
| 207 | `, logFile, failFile, answerFile) |
| 208 | if err := os.WriteFile(filepath.Join(bin, "ssh"), []byte(sshScript), 0o755); err != nil { |
| 209 | t.Fatal(err) |
| 210 | } |
| 211 | t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")) |
| 212 | |
| 213 | // Two projects served beside one instance, so --all lists both. |
| 214 | reposDir := filepath.Join(dir, "srv") |
| 215 | if err := os.MkdirAll(reposDir, 0o755); err != nil { |
| 216 | t.Fatal(err) |
| 217 | } |
| 218 | runGit := func(cwd string, args ...string) string { |
| 219 | t.Helper() |
| 220 | cmd := exec.Command("git", args...) |
| 221 | cmd.Dir = cwd |
| 222 | out, err := cmd.CombinedOutput() |
| 223 | if err != nil { |
| 224 | t.Fatalf("git %s in %s: %v\n%s", strings.Join(args, " "), cwd, err, out) |
| 225 | } |
| 226 | return strings.TrimSpace(string(out)) |
| 227 | } |
| 228 | for _, name := range []string{"instance.git", "app.git", "site.git"} { |
| 229 | runGit(reposDir, "init", "--quiet", "--bare", "--initial-branch=main", filepath.Join(reposDir, name)) |
| 230 | } |
| 231 | // Seed instance with refs/the-valley/projects listing app and site. |
| 232 | instWork := filepath.Join(dir, "inst-work") |
| 233 | runGit(dir, "clone", "--quiet", filepath.Join(reposDir, "instance.git"), instWork) |
| 234 | runGit(instWork, "config", "user.name", "operator") |
| 235 | runGit(instWork, "config", "user.email", "operator@example.org") |
| 236 | if err := os.MkdirAll(filepath.Join(instWork, "policy", "instance"), 0o755); err != nil { |
| 237 | t.Fatal(err) |
| 238 | } |
| 239 | floor := "package verification\nfloor: {\n\tchecks: \"c-1\": {runner: \"nix\", attribute: \"c-1\"}\n\tclasses: src: {paths: \"src/**\": true, requires: \"c-1\": true}\n\tunclassified: \"c-1\": true\n}\n" |
| 240 | if err := os.WriteFile(filepath.Join(instWork, "policy", "instance", "floor.cue"), []byte(floor), 0o644); err != nil { |
| 241 | t.Fatal(err) |
| 242 | } |
| 243 | runGit(instWork, "add", ".") |
| 244 | runGit(instWork, "commit", "--quiet", "-m", "instance") |
| 245 | runGit(instWork, "push", "--quiet", "origin", "main") |
| 246 | listBlob := bareGit(t, filepath.Join(reposDir, "instance.git"))("app\nsite\n", "hash-object", "-w", "--stdin") |
| 247 | bareGit(t, filepath.Join(reposDir, "instance.git"))("", "update-ref", projectsRef, listBlob) |
| 248 | |
| 249 | // Seed app and site, each pointing policy/valley at instance.git. |
| 250 | var appWork string |
| 251 | for _, name := range []string{"app", "site"} { |
| 252 | w := filepath.Join(dir, name+"-work") |
| 253 | runGit(dir, "clone", "--quiet", filepath.Join(reposDir, name+".git"), w) |
| 254 | runGit(w, "config", "user.name", "operator") |
| 255 | runGit(w, "config", "user.email", "operator@example.org") |
| 256 | if err := os.MkdirAll(filepath.Join(w, "policy"), 0o755); err != nil { |
| 257 | t.Fatal(err) |
| 258 | } |
| 259 | if err := os.WriteFile(filepath.Join(w, "policy", "valley"), []byte(filepath.Join(reposDir, "instance.git")+"\n"), 0o644); err != nil { |
| 260 | t.Fatal(err) |
| 261 | } |
| 262 | runGit(w, "add", ".") |
| 263 | runGit(w, "commit", "--quiet", "-m", name) |
| 264 | runGit(w, "push", "--quiet", "origin", "main") |
| 265 | if name == "app" { |
| 266 | appWork = w |
| 267 | } |
| 268 | } |
| 269 | t.Chdir(appWork) |
| 270 | |
| 271 | writeAnswer := func(lines ...string) { |
| 272 | t.Helper() |
| 273 | os.Remove(failFile) |
| 274 | body := `{"kind":"header","host":"valley-host","format":"valley-telemetry/v1"}` + "\n" + |
| 275 | strings.Join(lines, "\n") + "\n" + |
| 276 | `{"kind":"end","truncated":false}` + "\n" |
| 277 | if err := os.WriteFile(answerFile, []byte(body), 0o644); err != nil { |
| 278 | t.Fatal(err) |
| 279 | } |
| 280 | } |
| 281 | runPending := func(args ...string) (string, string) { |
| 282 | t.Helper() |
| 283 | var stdout, stderr bytes.Buffer |
| 284 | if code := run(append([]string{"pending"}, args...), &stdout, &stderr, os.Exit); code != 0 { |
| 285 | t.Fatalf("pending %v exited %d: %s", args, code, stderr.String()) |
| 286 | } |
| 287 | return stdout.String(), stderr.String() |
| 288 | } |
| 289 | parseJSON := func(out string) jsonChanges { |
| 290 | t.Helper() |
| 291 | var doc jsonChanges |
| 292 | if err := json.Unmarshal([]byte(out), &doc); err != nil { |
| 293 | t.Fatalf("pending --json: %v\n%s", err, out) |
| 294 | } |
| 295 | if doc.HostSources == nil { |
| 296 | t.Fatalf("pending --json missing host_sources:\n%s", out) |
| 297 | } |
| 298 | return doc |
| 299 | } |
| 300 | |
| 301 | // 1. Local non-SSH origin (no telemetry remote): no ssh called, no host entry, no warning. |
| 302 | os.Remove(logFile) |
| 303 | out, baseErrs := runPending() |
| 304 | if hasCue == nil && baseErrs != "" { |
| 305 | t.Errorf("local origin unexpected stderr: %q", baseErrs) |
| 306 | } |
| 307 | if out != "nothing needs you\n" { |
| 308 | t.Errorf("local origin: out=%q errs=%q", out, baseErrs) |
| 309 | } |
| 310 | if _, err := os.Stat(logFile); err == nil { |
| 311 | t.Error("local origin invoked ssh") |
| 312 | } |
| 313 | jout, jerrs := runPending("--json") |
| 314 | if doc := parseJSON(jout); len(*doc.HostSources) != 0 || jerrs != "" { |
| 315 | t.Errorf("local origin --json: host_sources=%+v errs=%q", *doc.HostSources, jerrs) |
| 316 | } |
| 317 | |
| 318 | // Point telemetry at an ssh host for the remaining cases. |
| 319 | runGit(appWork, "config", "valley.telemetry.remote", "ssh://git@valley-host/app.git") |
| 320 | |
| 321 | // 2. Healthy sources (idle, active, disabled): prints nothing, host_sources is []. |
| 322 | writeAnswer( |
| 323 | `{"kind":"source","name":"worker","state":"idle","detail":"no open run"}`, |
| 324 | `{"kind":"source","name":"integrator","state":"active","detail":"a unit is running"}`, |
| 325 | `{"kind":"source","name":"bus","state":"disabled","detail":"not enabled in this host's configuration"}`, |
| 326 | ) |
| 327 | out, errs := runPending() |
| 328 | if out != "nothing needs you\n" || errs != baseErrs { |
| 329 | t.Errorf("healthy: out=%q errs=%q (base %q)", out, errs, baseErrs) |
| 330 | } |
| 331 | jout, _ = runPending("--json") |
| 332 | if doc := parseJSON(jout); len(*doc.HostSources) != 0 { |
| 333 | t.Errorf("healthy --json: host_sources=%+v", *doc.HostSources) |
| 334 | } |
| 335 | |
| 336 | // 3. One failed source (one failing unit): shown above needs you and in --json. |
| 337 | writeAnswer( |
| 338 | `{"kind":"source","name":"worker","state":"idle","detail":"no open run"}`, |
| 339 | `{"kind":"source","name":"mirrors","state":"failed","detail":"valley-publish@app.service: activating, result exit-code, status 1","unit_states":[{"Id":"valley-publish@app.service","LoadState":"loaded","ActiveState":"activating","Result":"exit-code","ExecMainStatus":"1"}]}`, |
| 340 | ) |
| 341 | out, errs = runPending() |
| 342 | wantOne := "host mirrors failed · valley-publish@app.service: activating, result exit-code, status 1\n" + |
| 343 | " see: valley telemetry read --source mirrors --logs\n" + |
| 344 | "\n" + |
| 345 | "nothing needs you\n" |
| 346 | if out != wantOne || errs != baseErrs { |
| 347 | t.Errorf("one failed source:\n got:\n%s\nwant:\n%s\nerrs=%q", out, wantOne, errs) |
| 348 | } |
| 349 | jout, _ = runPending("--json") |
| 350 | doc := parseJSON(jout) |
| 351 | if len(*doc.HostSources) != 1 || (*doc.HostSources)[0].Source != "mirrors" || (*doc.HostSources)[0].State != "failed" || |
| 352 | (*doc.HostSources)[0].Reason != "valley-publish@app.service: activating, result exit-code, status 1" || |
| 353 | !slices.Equal((*doc.HostSources)[0].Units, []string{"valley-publish@app.service"}) { |
| 354 | t.Errorf("one failed source --json: %+v\nraw: %s", *doc.HostSources, jout) |
| 355 | } |
| 356 | |
| 357 | // 4. --all across app and site: host entry printed once, sources read once. |
| 358 | os.Remove(logFile) |
| 359 | out, errs = runPending("--all") |
| 360 | if out != wantOne || (hasCue == nil && errs != "") { |
| 361 | t.Errorf("--all with one failed source:\n got:\n%s\nwant:\n%s\nerrs=%q", out, wantOne, errs) |
| 362 | } |
| 363 | sshLog, _ := os.ReadFile(logFile) |
| 364 | if n := strings.Count(string(sshLog), "valley-telemetry sources"); n != 1 { |
| 365 | t.Errorf("--all ran sources %d times, want 1:\n%s", n, sshLog) |
| 366 | } |
| 367 | |
| 368 | // 5. Several failing units (3 failing, 1 healthy): each failing unit named. |
| 369 | writeAnswer( |
| 370 | `{"kind":"source","name":"mirrors","state":"failed","detail":"valley-publish@app.service: activating, result exit-code, status 1","unit_states":[` + |
| 371 | `{"Id":"valley-publish@ok.service","LoadState":"loaded","ActiveState":"inactive","Result":"success"},` + |
| 372 | `{"Id":"valley-publish@app.service","LoadState":"loaded","ActiveState":"activating","Result":"exit-code","ExecMainStatus":"1"},` + |
| 373 | `{"Id":"valley-publish@docs.service","LoadState":"loaded","ActiveState":"failed","Result":"exit-code","ExecMainStatus":"1"},` + |
| 374 | `{"Id":"valley-publish@site.service","LoadState":"loaded","ActiveState":"failed","Result":"exit-code","ExecMainStatus":"2"}]}`, |
| 375 | ) |
| 376 | out, errs = runPending() |
| 377 | wantSeveral := "host mirrors failed · valley-publish@app.service: activating, result exit-code, status 1\n" + |
| 378 | " valley-publish@app.service\n" + |
| 379 | " valley-publish@docs.service\n" + |
| 380 | " valley-publish@site.service\n" + |
| 381 | " see: valley telemetry read --source mirrors --logs\n" + |
| 382 | "\n" + |
| 383 | "nothing needs you\n" |
| 384 | if out != wantSeveral || errs != baseErrs { |
| 385 | t.Errorf("several failing units:\n got:\n%s\nwant:\n%s\nerrs=%q", out, wantSeveral, errs) |
| 386 | } |
| 387 | jout, _ = runPending("--json") |
| 388 | doc = parseJSON(jout) |
| 389 | if len(*doc.HostSources) != 1 || !slices.Equal((*doc.HostSources)[0].Units, []string{ |
| 390 | "valley-publish@app.service", "valley-publish@docs.service", "valley-publish@site.service", |
| 391 | }) { |
| 392 | t.Errorf("several failing units --json: %+v", *doc.HostSources) |
| 393 | } |
| 394 | |
| 395 | // 6. Capped failing units (7 failing): first 5 named, then "and 2 more"; --json carries all 7. |
| 396 | var unitJSON []string |
| 397 | var allUnits []string |
| 398 | for _, p := range []string{"api", "app", "blog", "docs", "site", "tools", "web"} { |
| 399 | u := fmt.Sprintf("valley-publish@%s.service", p) |
| 400 | allUnits = append(allUnits, u) |
| 401 | unitJSON = append(unitJSON, fmt.Sprintf(`{"Id":%q,"LoadState":"loaded","ActiveState":"failed","Result":"exit-code","ExecMainStatus":"1"}`, u)) |
| 402 | } |
| 403 | writeAnswer( |
| 404 | `{"kind":"source","name":"mirrors","state":"failed","detail":"valley-publish@api.service: failed, result exit-code, status 1","unit_states":[` + |
| 405 | strings.Join(unitJSON, ",") + `]}`, |
| 406 | ) |
| 407 | out, errs = runPending() |
| 408 | wantCapped := "host mirrors failed · valley-publish@api.service: failed, result exit-code, status 1\n" + |
| 409 | " valley-publish@api.service\n" + |
| 410 | " valley-publish@app.service\n" + |
| 411 | " valley-publish@blog.service\n" + |
| 412 | " valley-publish@docs.service\n" + |
| 413 | " valley-publish@site.service\n" + |
| 414 | " and 2 more\n" + |
| 415 | " see: valley telemetry read --source mirrors --logs\n" + |
| 416 | "\n" + |
| 417 | "nothing needs you\n" |
| 418 | if out != wantCapped || errs != baseErrs { |
| 419 | t.Errorf("capped failing units:\n got:\n%s\nwant:\n%s\nerrs=%q", out, wantCapped, errs) |
| 420 | } |
| 421 | jout, _ = runPending("--json") |
| 422 | doc = parseJSON(jout) |
| 423 | if len(*doc.HostSources) != 1 || !slices.Equal((*doc.HostSources)[0].Units, allUnits) { |
| 424 | t.Errorf("capped failing units --json: %+v", *doc.HostSources) |
| 425 | } |
| 426 | |
| 427 | // 7. No observe grant: no host entry, no warning on stderr, host_sources is []. |
| 428 | if err := os.WriteFile(answerFile, []byte(`{"kind":"error","error":"alice does not hold the observe grant"}`+"\n"), 0o644); err != nil { |
| 429 | t.Fatal(err) |
| 430 | } |
| 431 | out, errs = runPending() |
| 432 | if out != "nothing needs you\n" || errs != baseErrs { |
| 433 | t.Errorf("no observe grant: out=%q errs=%q (base %q)", out, errs, baseErrs) |
| 434 | } |
| 435 | jout, jerrs = runPending("--json") |
| 436 | if doc := parseJSON(jout); len(*doc.HostSources) != 0 || jerrs != "" { |
| 437 | t.Errorf("no observe grant --json: host_sources=%+v errs=%q", *doc.HostSources, jerrs) |
| 438 | } |
| 439 | |
| 440 | // 8. No collector (ssh fails): no host entry, no warning on stderr, host_sources is []. |
| 441 | if err := os.WriteFile(failFile, []byte("1\n"), 0o644); err != nil { |
| 442 | t.Fatal(err) |
| 443 | } |
| 444 | out, errs = runPending() |
| 445 | if out != "nothing needs you\n" || errs != baseErrs { |
| 446 | t.Errorf("no collector: out=%q errs=%q (base %q)", out, errs, baseErrs) |
| 447 | } |
| 448 | jout, jerrs = runPending("--json") |
| 449 | if doc := parseJSON(jout); len(*doc.HostSources) != 0 || jerrs != "" { |
| 450 | t.Errorf("no collector --json: host_sources=%+v errs=%q", *doc.HostSources, jerrs) |
| 451 | } |
| 452 | } |
| 453 | |
| 454 | // A host that accepts the sources request and stalls is bounded by |
| 455 | // hostSourcesTimeout, prints no host entry or warning, and leaves no ssh |
| 456 | // process running. |
| 457 | func TestPendingBoundsAStalledHostSourcesRead(t *testing.T) { |
| 458 | if _, err := os.Stat("/proc/self/stat"); err != nil { |
| 459 | t.Skip("no /proc to find a child left running in") |
| 460 | } |
| 461 | prev := hostSourcesTimeout |
| 462 | hostSourcesTimeout = 250 * time.Millisecond |
| 463 | defer func() { hostSourcesTimeout = prev }() |
| 464 | |
| 465 | dir := t.TempDir() |
| 466 | toolsOnPath(t, dir, "git", "cue") |
| 467 | ssh := "#!/bin/sh\necho '{\"kind\":\"header\",\"host\":\"valley-host\",\"format\":\"valley-telemetry/v1\"}'\nexec sleep 86395\n" |
| 468 | if err := os.WriteFile(filepath.Join(dir, "bin", "ssh"), []byte(ssh), 0o755); err != nil { |
| 469 | t.Fatal(err) |
| 470 | } |
| 471 | sh, _ := policyProject(t, filepath.Join(dir, "origin"), 1) |
| 472 | sh("config", "valley.telemetry.remote", "ssh://git@valley-host/origin.git") |
| 473 | |
| 474 | began := time.Now() |
| 475 | var stdout, stderr bytes.Buffer |
| 476 | if code := run([]string{"pending"}, &stdout, &stderr, os.Exit); code != 0 { |
| 477 | t.Fatalf("pending: %s", stderr.String()) |
| 478 | } |
| 479 | if took := time.Since(began); took > 5*time.Second { |
| 480 | t.Errorf("pending took %s beside a stalled sources read", took) |
| 481 | } |
| 482 | if stdout.String() != "nothing needs you\n" || stderr.Len() != 0 { |
| 483 | t.Errorf("pending beside a stalled sources read printed %q and stderr %q", stdout.String(), stderr.String()) |
| 484 | } |
| 485 | stats, _ := filepath.Glob("/proc/[0-9]*/stat") |
| 486 | for _, stat := range stats { |
| 487 | data, err := os.ReadFile(stat) |
| 488 | if err != nil { |
| 489 | continue |
| 490 | } |
| 491 | f := strings.Fields(string(data[bytes.LastIndexByte(data, ')')+1:])) |
| 492 | cmdline, _ := os.ReadFile(filepath.Join(filepath.Dir(stat), "cmdline")) |
| 493 | if len(f) > 1 && f[1] == fmt.Sprint(os.Getpid()) && strings.Contains(string(cmdline), "86395") { |
| 494 | t.Errorf("pending left its sources ssh running: %s", filepath.Dir(stat)) |
| 495 | } |
| 496 | } |
| 497 | } |