| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "os" |
| 8 | "os/exec" |
| 9 | "path/filepath" |
| 10 | "regexp" |
| 11 | "strings" |
| 12 | "syscall" |
| 13 | "testing" |
| 14 | "time" |
| 15 | |
| 16 | "the-valley/telemetry" |
| 17 | ) |
| 18 | |
| 19 | // pending fits its text to 80 columns when stdout is no terminal: a long |
| 20 | // title is cut short with …, and a branch or a handle is printed whole, |
| 21 | // even where the line it is on cannot fit. A stack of branches four deep |
| 22 | // is listed at one indentation, so its deepest entry has the room its |
| 23 | // second has. Nothing it prints is an escape code. |
| 24 | func TestPendingFitsEightyColumnsAndKeepsNamesWhole(t *testing.T) { |
| 25 | dir := t.TempDir() |
| 26 | t.Setenv("HOME", dir) |
| 27 | t.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "config")) |
| 28 | t.Setenv("GIT_CONFIG_NOSYSTEM", "1") |
| 29 | t.Setenv("VALLEY_KNOWN_SIGNERS", "") |
| 30 | origin, work := filepath.Join(dir, "origin.git"), filepath.Join(dir, "work") |
| 31 | sh := func(args ...string) { |
| 32 | t.Helper() |
| 33 | cmd := exec.Command("git", args...) |
| 34 | cmd.Dir = work |
| 35 | if out, err := cmd.CombinedOutput(); err != nil { |
| 36 | t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out) |
| 37 | } |
| 38 | } |
| 39 | if out, err := exec.Command("git", "init", "--quiet", "--bare", "--initial-branch=main", origin).CombinedOutput(); err != nil { |
| 40 | t.Fatalf("git init: %v\n%s", err, out) |
| 41 | } |
| 42 | if out, err := exec.Command("git", "clone", "--quiet", origin, work).CombinedOutput(); err != nil { |
| 43 | t.Fatalf("git clone: %v\n%s", err, out) |
| 44 | } |
| 45 | sh("config", "user.name", "a committer whose name is so long that the line it is on has to cut it short") |
| 46 | sh("config", "user.email", "committer@localhost") |
| 47 | sh("config", "valley.principal", "alice") |
| 48 | sh("checkout", "--quiet", "-b", "main") |
| 49 | sh("commit", "--quiet", "--allow-empty", "-m", "base") |
| 50 | sh("push", "--quiet", "origin", "main") |
| 51 | |
| 52 | long := "a-branch-whose-name-runs-on-well-past-the-eightieth-column-of-any-terminal-it-is-shown-in" |
| 53 | title := "a subject that says far more than one line has room for, " + strings.Repeat("and then some more ", 4) |
| 54 | sh("checkout", "--quiet", "-b", long, "main") |
| 55 | sh("commit", "--quiet", "--allow-empty", "-m", title+"on the long branch") |
| 56 | sh("push", "--quiet", "origin", long) |
| 57 | sh("checkout", "--quiet", "-b", "short", "main") |
| 58 | sh("commit", "--quiet", "--allow-empty", "-m", title) |
| 59 | sh("push", "--quiet", "origin", "short") |
| 60 | from := "main" |
| 61 | for _, layer := range []string{"1", "2", "3", "4"} { |
| 62 | sh("checkout", "--quiet", "-b", "layer-"+layer, from) |
| 63 | sh("commit", "--quiet", "--allow-empty", "-m", "layer "+layer+": "+title) |
| 64 | sh("push", "--quiet", "origin", "layer-"+layer) |
| 65 | from = "layer-" + layer |
| 66 | } |
| 67 | |
| 68 | t.Chdir(work) |
| 69 | var stdout, stderr bytes.Buffer |
| 70 | if code := run([]string{"ready", "--change", strings.Repeat("q", 32), "short"}, &stdout, &stderr, os.Exit); code != 0 { |
| 71 | t.Fatalf("ready: %s", stderr.String()) |
| 72 | } |
| 73 | stdout.Reset() |
| 74 | if code := run([]string{"pending", "--branches"}, &stdout, &stderr, os.Exit); code != 0 { |
| 75 | t.Fatalf("pending: %s", stderr.String()) |
| 76 | } |
| 77 | out := stdout.String() |
| 78 | if strings.Contains(out, "\x1b") { |
| 79 | t.Errorf("pending printed an escape code to no terminal:\n%s", out) |
| 80 | } |
| 81 | if !strings.Contains(out, "\n"+long+"\n") { |
| 82 | t.Errorf("the long branch is not whole, on a line of its own:\n%s", out) |
| 83 | } |
| 84 | if !strings.Contains(out, "\n 1 qqqq v1") { |
| 85 | t.Errorf("the change is not named by its whole handle and version:\n%s", out) |
| 86 | } |
| 87 | cut := 0 |
| 88 | for _, line := range strings.Split(strings.TrimSuffix(out, "\n"), "\n") { |
| 89 | if strings.Contains(line, long) { |
| 90 | continue |
| 91 | } |
| 92 | if columns(line) > 80 { |
| 93 | t.Errorf("a line is %d columns wide: %q", columns(line), line) |
| 94 | } |
| 95 | if strings.HasPrefix(strings.TrimLeft(line, " "), "a subject that says") { |
| 96 | if columns(line) != 80 || !strings.HasSuffix(line, "…") { |
| 97 | t.Errorf("a long title is not cut to 80 columns with …: %q", line) |
| 98 | } |
| 99 | cut++ |
| 100 | } |
| 101 | if strings.HasPrefix(line, "layer-4 ") && !strings.HasSuffix(line, "…") { |
| 102 | t.Errorf("the author is not cut short to keep the line within 80 columns: %q", line) |
| 103 | } |
| 104 | } |
| 105 | lines := strings.Split(out, "\n") |
| 106 | for layer, lead := range map[string]string{"4": " ", "3": " │ ", "2": " │ ", "1": " "} { |
| 107 | listed := false |
| 108 | for _, line := range lines { |
| 109 | if strings.HasPrefix(line, lead+"layer "+layer+": ") { |
| 110 | listed = true |
| 111 | if columns(line) != 80 || !strings.HasSuffix(line, "…") { |
| 112 | t.Errorf("layer %s's title is not cut to 80 columns with …: %q", layer, line) |
| 113 | } |
| 114 | } |
| 115 | } |
| 116 | if !listed { |
| 117 | t.Errorf("layer %s's title is not at %q:\n%s", layer, lead, out) |
| 118 | } |
| 119 | } |
| 120 | if !strings.Contains(out, "\n approving it lands the 3 below too\n") || strings.Contains(out, "on layer-") { |
| 121 | t.Errorf("the stack four deep is not one list, each layer on the next:\n%s", out) |
| 122 | } |
| 123 | if cut != 2 { |
| 124 | t.Errorf("%d titles were cut short, where the change's and the branch's should be:\n%s", cut, out) |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | // fit cuts by columns, not bytes: a wide character takes two, and a |
| 129 | // combining mark none. |
| 130 | func TestFitCountsColumns(t *testing.T) { |
| 131 | for _, c := range []struct { |
| 132 | s string |
| 133 | n int |
| 134 | want string |
| 135 | }{ |
| 136 | {"short", 10, "short"}, |
| 137 | {"exactly ten", 11, "exactly ten"}, |
| 138 | {"one word too many", 12, "one word to…"}, |
| 139 | {"漢字漢字漢字", 7, "漢字漢…"}, |
| 140 | {"café au lait", 5, "café au lait"[:6] + "…"}, |
| 141 | } { |
| 142 | if got := fit(c.s, c.n); got != c.want || columns(got) > c.n { |
| 143 | t.Errorf("fit(%q, %d) = %q, %d columns; want %q", c.s, c.n, got, columns(got), c.want) |
| 144 | } |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | // toolsOnPath puts on PATH, for the test, a shim for each tool named that |
| 149 | // logs each start to the file it returns and runs the real tool. It |
| 150 | // skips the test when a tool is missing, unless VALLEY_TEST_TOOLS is |
| 151 | // required. |
| 152 | func toolsOnPath(t *testing.T, dir string, tools ...string) (starts string) { |
| 153 | t.Helper() |
| 154 | bin, starts := filepath.Join(dir, "bin"), filepath.Join(dir, "starts") |
| 155 | if err := os.MkdirAll(bin, 0o755); err != nil { |
| 156 | t.Fatal(err) |
| 157 | } |
| 158 | for _, tool := range tools { |
| 159 | real, err := exec.LookPath(tool) |
| 160 | if err != nil { |
| 161 | if os.Getenv("VALLEY_TEST_TOOLS") == "required" { |
| 162 | t.Fatalf("no %s on PATH, and VALLEY_TEST_TOOLS=required", tool) |
| 163 | } |
| 164 | t.Skipf("no %s to run; the nix check provides one", tool) |
| 165 | } |
| 166 | shim := fmt.Sprintf("#!/bin/sh\necho %s >> '%s'\nexec '%s' \"$@\"\n", tool, starts, real) |
| 167 | if err := os.WriteFile(filepath.Join(bin, tool), []byte(shim), 0o755); err != nil { |
| 168 | t.Fatal(err) |
| 169 | } |
| 170 | } |
| 171 | t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")) |
| 172 | return starts |
| 173 | } |
| 174 | |
| 175 | // testSchema is the verification schema, read from the package's |
| 176 | // directory before a test changes to another. |
| 177 | var testSchema, _ = filepath.Abs(filepath.Join("..", "schema", "verification.cue")) |
| 178 | |
| 179 | // policyProject is a repository at root with its own origin, whose floor |
| 180 | // has one class requiring checks c-1 to c-<checks> of every path under |
| 181 | // src/, made the current directory. head pushes a branch off main that |
| 182 | // adds src/<branch> and readies it as the change id. |
| 183 | func policyProject(t *testing.T, root string, checks int) (sh func(...string), head func(branch, id string)) { |
| 184 | t.Helper() |
| 185 | t.Setenv("HOME", root) |
| 186 | t.Setenv("XDG_CONFIG_HOME", filepath.Join(root, "config")) |
| 187 | t.Setenv("GIT_CONFIG_NOSYSTEM", "1") |
| 188 | t.Setenv("VALLEY_KNOWN_SIGNERS", "") |
| 189 | t.Setenv("VALLEY_VERIFICATION_SCHEMA", testSchema) |
| 190 | origin, work := filepath.Join(root, "origin.git"), filepath.Join(root, "work") |
| 191 | sh = func(args ...string) { |
| 192 | t.Helper() |
| 193 | cmd := exec.Command("git", args...) |
| 194 | cmd.Dir = work |
| 195 | if out, err := cmd.CombinedOutput(); err != nil { |
| 196 | t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out) |
| 197 | } |
| 198 | } |
| 199 | if out, err := exec.Command("git", "init", "--quiet", "--bare", "--initial-branch=main", origin).CombinedOutput(); err != nil { |
| 200 | t.Fatalf("git init: %v\n%s", err, out) |
| 201 | } |
| 202 | if out, err := exec.Command("git", "clone", "--quiet", origin, work).CombinedOutput(); err != nil { |
| 203 | t.Fatalf("git clone: %v\n%s", err, out) |
| 204 | } |
| 205 | sh("config", "user.name", "operator") |
| 206 | sh("config", "user.email", "operator@example.org") |
| 207 | sh("config", "valley.principal", "operator") |
| 208 | sh("checkout", "--quiet", "-b", "main") |
| 209 | var floor strings.Builder |
| 210 | floor.WriteString("package verification\nfloor: {\n") |
| 211 | for i := 1; i <= checks; i++ { |
| 212 | fmt.Fprintf(&floor, "\tchecks: \"c-%d\": {runner: \"nix\", attribute: \"c-%d\"}\n", i, i) |
| 213 | fmt.Fprintf(&floor, "\tclasses: src: {paths: \"src/**\": true, requires: \"c-%d\": true}\n", i) |
| 214 | } |
| 215 | floor.WriteString("\tunclassified: \"c-1\": true\n}\n") |
| 216 | if err := os.MkdirAll(filepath.Join(work, "policy", "instance"), 0o755); err != nil { |
| 217 | t.Fatal(err) |
| 218 | } |
| 219 | if err := os.WriteFile(filepath.Join(work, "policy", "instance", "floor.cue"), []byte(floor.String()), 0o644); err != nil { |
| 220 | t.Fatal(err) |
| 221 | } |
| 222 | sh("add", ".") |
| 223 | sh("commit", "--quiet", "-m", "base") |
| 224 | sh("push", "--quiet", "origin", "main") |
| 225 | t.Chdir(work) |
| 226 | head = func(branch, id string) { |
| 227 | t.Helper() |
| 228 | sh("checkout", "--quiet", "-b", branch, "main") |
| 229 | if err := os.MkdirAll(filepath.Join(work, "src"), 0o755); err != nil { |
| 230 | t.Fatal(err) |
| 231 | } |
| 232 | if err := os.WriteFile(filepath.Join(work, "src", branch), []byte(branch+"\n"), 0o644); err != nil { |
| 233 | t.Fatal(err) |
| 234 | } |
| 235 | sh("add", ".") |
| 236 | sh("commit", "--quiet", "-m", branch) |
| 237 | sh("push", "--quiet", "origin", branch) |
| 238 | var stdout, stderr bytes.Buffer |
| 239 | if code := run([]string{"ready", "--change", id, branch}, &stdout, &stderr, os.Exit); code != 0 { |
| 240 | t.Fatalf("ready: %s", stderr.String()) |
| 241 | } |
| 242 | } |
| 243 | return sh, head |
| 244 | } |
| 245 | |
| 246 | // runCounted runs valley with args, and returns what it printed and how |
| 247 | // many processes the shims on PATH logged, by tool, and in all under "". |
| 248 | func runCounted(t *testing.T, starts string, args ...string) (string, map[string]int) { |
| 249 | t.Helper() |
| 250 | os.Remove(starts) |
| 251 | var stdout, stderr bytes.Buffer |
| 252 | if code := run(args, &stdout, &stderr, os.Exit); code != 0 { |
| 253 | t.Fatalf("%s: %s", strings.Join(args, " "), stderr.String()) |
| 254 | } |
| 255 | log, _ := os.ReadFile(starts) |
| 256 | started := map[string]int{} |
| 257 | for _, tool := range strings.Fields(string(log)) { |
| 258 | started[tool]++ |
| 259 | started[""]++ |
| 260 | } |
| 261 | return stdout.String(), started |
| 262 | } |
| 263 | |
| 264 | // pending reads the policy at main's tip once for a project, and asks cue |
| 265 | // no requirement's pin: the cue processes it starts, with --checks or |
| 266 | // without, are as many for a class requiring nine checks and four ready |
| 267 | // heads as for one requiring three and one head. |
| 268 | func TestPendingStartsCueOncePerProject(t *testing.T) { |
| 269 | dir := t.TempDir() |
| 270 | starts := toolsOnPath(t, dir, "cue") |
| 271 | |
| 272 | // project lists a project whose class requires checks c-1 to |
| 273 | // c-<checks>, with heads ready changes touching it. It returns what |
| 274 | // each listing printed and how many cue processes it started. |
| 275 | project := func(checks, heads int) (printed map[string]string, started map[string]int) { |
| 276 | t.Helper() |
| 277 | _, head := policyProject(t, filepath.Join(dir, fmt.Sprintf("%d-%d", checks, heads)), checks) |
| 278 | for i := 1; i <= heads; i++ { |
| 279 | head(fmt.Sprintf("head-%d", i), strings.Repeat(string(rune('p'+i)), 32)) |
| 280 | } |
| 281 | printed, started = map[string]string{}, map[string]int{} |
| 282 | for _, args := range [][]string{{"pending"}, {"pending", "--checks"}} { |
| 283 | listing := strings.Join(args, " ") |
| 284 | out, n := runCounted(t, starts, args...) |
| 285 | printed[listing], started[listing] = out, n["cue"] |
| 286 | } |
| 287 | return printed, started |
| 288 | } |
| 289 | |
| 290 | _, small := project(3, 1) |
| 291 | out, large := project(9, 4) |
| 292 | if want := "requires 9 quick checks, 0 slow"; strings.Count(out["pending --checks"], want) != 4 { |
| 293 | t.Fatalf("pending --checks does not say %q of each of four heads:\n%s", want, out["pending --checks"]) |
| 294 | } |
| 295 | for listing, n := range small { |
| 296 | if n == 0 || large[listing] != n { |
| 297 | t.Errorf("%s started %d cue processes for three checks and one head, and %d for nine and four heads", listing, n, large[listing]) |
| 298 | } |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | // pending starts as many git processes for a project with five landed |
| 303 | // changes, five withdrawn ones and five branches no change is on as for |
| 304 | // one with one of each, beside a draft: what the landed heads reach, what |
| 305 | // the branches reach, and what the heads a draft may include reach, is |
| 306 | // read in one batch each, however many there are. |
| 307 | func TestPendingStartsGitAsOftenWhateverItLists(t *testing.T) { |
| 308 | dir := t.TempDir() |
| 309 | starts := toolsOnPath(t, dir, "git", "cue") |
| 310 | project := func(n int) (string, int) { |
| 311 | t.Helper() |
| 312 | sh, head := policyProject(t, filepath.Join(dir, fmt.Sprint(n)), 1) |
| 313 | for i := 0; i < n; i++ { |
| 314 | branch := fmt.Sprintf("landed-%d", i) |
| 315 | head(branch, strings.Repeat(string(rune('p'+i)), 32)) |
| 316 | sh("checkout", "--quiet", "main") |
| 317 | sh("merge", "--quiet", "--ff-only", branch) |
| 318 | sh("push", "--quiet", "origin", "main") |
| 319 | } |
| 320 | for i := 0; i < n; i++ { |
| 321 | sh("checkout", "--quiet", "-b", fmt.Sprintf("stray-%d", i), "main") |
| 322 | sh("commit", "--quiet", "--allow-empty", "-m", fmt.Sprintf("stray %d", i)) |
| 323 | sh("push", "--quiet", "origin", "HEAD") |
| 324 | } |
| 325 | valley := func(args ...string) { |
| 326 | t.Helper() |
| 327 | var stdout, stderr bytes.Buffer |
| 328 | if code := run(args, &stdout, &stderr, os.Exit); code != 0 { |
| 329 | t.Fatalf("%s: %s", strings.Join(args, " "), stderr.String()) |
| 330 | } |
| 331 | } |
| 332 | for i := 0; i < n; i++ { |
| 333 | id := strings.Repeat(string(rune('u'+i)), 32) |
| 334 | head(fmt.Sprintf("withdrawn-%d", i), id) |
| 335 | valley("withdraw", id) |
| 336 | } |
| 337 | draft := strings.Repeat("z", 32) |
| 338 | head("draft", draft) |
| 339 | valley("unready", draft) |
| 340 | out, started := runCounted(t, starts, "pending") |
| 341 | return out, started["git"] |
| 342 | } |
| 343 | few, small := project(1) |
| 344 | many, large := project(5) |
| 345 | if !strings.Contains(few, "1 branch no change is on") || !strings.Contains(many, "5 branches no change is on") { |
| 346 | t.Fatalf("pending does not count the stray branches:\n%s\n%s", few, many) |
| 347 | } |
| 348 | if small == 0 || large != small { |
| 349 | t.Errorf("pending started git %d times for one landed change, withdrawn change and stray branch, and %d times for five of each", small, large) |
| 350 | } |
| 351 | } |
| 352 | |
| 353 | // A host that refuses the read of the worker's telemetry, as it does when |
| 354 | // the principal already has every bounded request it may have open, |
| 355 | // leaves main's line without the worker's runs: pending says why once, |
| 356 | // asks the host once, and prints main's line from the walk alone. |
| 357 | func TestPendingAsksARefusingHostOnce(t *testing.T) { |
| 358 | dir := t.TempDir() |
| 359 | starts := toolsOnPath(t, dir, "git", "cue") |
| 360 | refusal := `{"kind":"error","error":"operator already has 4 bounded requests open; try again when one ends"}` |
| 361 | ssh := fmt.Sprintf("#!/bin/sh\necho ssh >> '%s'\necho '%s'\n", starts, refusal) |
| 362 | if err := os.WriteFile(filepath.Join(dir, "bin", "ssh"), []byte(ssh), 0o755); err != nil { |
| 363 | t.Fatal(err) |
| 364 | } |
| 365 | followProject(t, filepath.Join(dir, "origin")) |
| 366 | |
| 367 | os.Remove(starts) |
| 368 | var stdout, stderr bytes.Buffer |
| 369 | if code := run([]string{"pending"}, &stdout, &stderr, os.Exit); code != 0 { |
| 370 | t.Fatalf("pending: %s", stderr.String()) |
| 371 | } |
| 372 | log, _ := os.ReadFile(starts) |
| 373 | if n := strings.Count(string(log), "ssh"); n != 1 { |
| 374 | t.Errorf("pending asked the refusing host %d times", n) |
| 375 | } |
| 376 | if n := strings.Count(stderr.String(), "refused"); n != 1 || strings.Count(stderr.String(), "\n") != 1 { |
| 377 | t.Errorf("pending said, of the refusal:\n%s", stderr.String()) |
| 378 | } |
| 379 | if !strings.HasPrefix(stdout.String(), "main ◐ clearing · f-1 due · covers ") { |
| 380 | t.Errorf("pending's main line, with the host refusing:\n%s", stdout.String()) |
| 381 | } |
| 382 | } |
| 383 | |
| 384 | // followProject is policyProject with a class that check f-1 follows, a |
| 385 | // landing on main that sets it due, and its telemetry read from an ssh |
| 386 | // host, so valley pending waits on the worker's telemetry for main's line. |
| 387 | func followProject(t *testing.T, root string) { |
| 388 | t.Helper() |
| 389 | sh, head := policyProject(t, root, 1) |
| 390 | sh("config", "valley.telemetry.remote", "ssh://git@valley-host/origin.git") |
| 391 | floor := "package verification\nfloor: {\n" + |
| 392 | "\tchecks: \"c-1\": {runner: \"nix\", attribute: \"c-1\"}\n" + |
| 393 | "\tchecks: \"f-1\": {runner: \"nix\", attribute: \"f-1\"}\n" + |
| 394 | "\tclasses: src: {paths: \"src/**\": true, requires: \"c-1\": true, follows: \"f-1\": true}\n" + |
| 395 | "\tunclassified: \"c-1\": true\n}\n" |
| 396 | if err := os.WriteFile(filepath.Join("policy", "instance", "floor.cue"), []byte(floor), 0o644); err != nil { |
| 397 | t.Fatal(err) |
| 398 | } |
| 399 | sh("commit", "--quiet", "-a", "-m", "follow f-1") |
| 400 | sh("push", "--quiet", "origin", "main") |
| 401 | head("landed", strings.Repeat("p", 32)) |
| 402 | sh("checkout", "--quiet", "main") |
| 403 | sh("merge", "--quiet", "--ff-only", "landed") |
| 404 | sh("push", "--quiet", "origin", "main") |
| 405 | } |
| 406 | |
| 407 | // A host that accepts the read of the worker's telemetry and then stalls |
| 408 | // does not hold valley pending, nor outlive it: with no follow check and |
| 409 | // nothing ready, nothing waits on the read, so pending cancels it as it |
| 410 | // returns, and no ssh it started is left running. |
| 411 | func TestPendingEndsAReadNobodyWaitsFor(t *testing.T) { |
| 412 | if _, err := os.Stat("/proc/self/stat"); err != nil { |
| 413 | t.Skip("no /proc to find a child left running in") |
| 414 | } |
| 415 | dir := t.TempDir() |
| 416 | toolsOnPath(t, dir, "git", "cue") |
| 417 | // ssh is the host: it says the answer's first line, and stalls as a |
| 418 | // sleep of a length nothing else in this process sleeps. |
| 419 | header := `{"kind":"header","host":"valley-host","format":"valley-telemetry/v1"}` |
| 420 | stall := fmt.Sprintf("#!/bin/sh\necho '%s'\nexec sleep 86399\n", header) |
| 421 | if err := os.WriteFile(filepath.Join(dir, "bin", "ssh"), []byte(stall), 0o755); err != nil { |
| 422 | t.Fatal(err) |
| 423 | } |
| 424 | sh, _ := policyProject(t, filepath.Join(dir, "origin"), 1) |
| 425 | sh("config", "valley.telemetry.remote", "ssh://git@valley-host/origin.git") |
| 426 | |
| 427 | began := time.Now() |
| 428 | var stdout, stderr bytes.Buffer |
| 429 | if code := run([]string{"pending"}, &stdout, &stderr, os.Exit); code != 0 { |
| 430 | t.Fatalf("pending: %s", stderr.String()) |
| 431 | } |
| 432 | // The read's own time limit is 30 s: a pending that waited for it |
| 433 | // would take that long. |
| 434 | if took := time.Since(began); took > 20*time.Second { |
| 435 | t.Errorf("pending took %s beside a stalled host", took) |
| 436 | } |
| 437 | if !strings.Contains(stdout.String(), "nothing needs you") || stderr.Len() != 0 { |
| 438 | t.Errorf("pending beside a stalled host printed:\n%s\nand said:\n%s", stdout.String(), stderr.String()) |
| 439 | } |
| 440 | stats, _ := filepath.Glob("/proc/[0-9]*/stat") |
| 441 | for _, stat := range stats { |
| 442 | data, err := os.ReadFile(stat) |
| 443 | if err != nil { |
| 444 | continue |
| 445 | } |
| 446 | f := strings.Fields(string(data[bytes.LastIndexByte(data, ')')+1:])) |
| 447 | cmdline, _ := os.ReadFile(filepath.Join(filepath.Dir(stat), "cmdline")) |
| 448 | if len(f) > 1 && f[1] == fmt.Sprint(os.Getpid()) && strings.Contains(string(cmdline), "86399") { |
| 449 | t.Errorf("pending left its ssh running: %s", filepath.Dir(stat)) |
| 450 | } |
| 451 | } |
| 452 | } |
| 453 | |
| 454 | // pending --checks reads a draft's checks only when --drafts lists the |
| 455 | // drafts. A listing starts attest only to read checks, once for each head |
| 456 | // to digest its tree. Without --drafts, two drafts start no attest, add |
| 457 | // nothing to what --checks starts, and change no row; with it, each |
| 458 | // draft's tree is digested and its block shows its checks. |
| 459 | func TestPendingReadsDraftChecksOnlyWhenListed(t *testing.T) { |
| 460 | dir := t.TempDir() |
| 461 | starts := toolsOnPath(t, dir, "git", "cue") |
| 462 | // attest logs its start as the shims do and answers with one digest: |
| 463 | // when origin holds no evidence, a listing asks it only to digest each |
| 464 | // head's tree, and the digest decides nothing. |
| 465 | stand := fmt.Sprintf("#!/bin/sh\necho attest >> '%s'\necho valley-tree-v1:0123\n", starts) |
| 466 | if err := os.WriteFile(filepath.Join(dir, "bin", "attest"), []byte(stand), 0o755); err != nil { |
| 467 | t.Fatal(err) |
| 468 | } |
| 469 | _, head := policyProject(t, filepath.Join(dir, "project"), 2) |
| 470 | head("ready-1", strings.Repeat("p", 32)) |
| 471 | // listing is pending with args and --checks: what it printed, its ages |
| 472 | // left out, since a row's age ticks, the attest processes it started, |
| 473 | // and how many processes --checks added. |
| 474 | ages := regexp.MustCompile(`(?m) +[0-9]+[smhd]$`) |
| 475 | listing := func(args ...string) (out string, attest, added int) { |
| 476 | t.Helper() |
| 477 | _, without := runCounted(t, starts, append([]string{"pending"}, args...)...) |
| 478 | out, with := runCounted(t, starts, append([]string{"pending", "--checks"}, args...)...) |
| 479 | return ages.ReplaceAllString(out, ""), with["attest"], with[""] - without[""] |
| 480 | } |
| 481 | before, attest, added := listing() |
| 482 | if attest != 1 { |
| 483 | t.Fatalf("pending --checks started attest %d times for one ready head", attest) |
| 484 | } |
| 485 | for _, id := range []string{"q", "r"} { |
| 486 | head("draft-"+id, strings.Repeat(id, 32)) |
| 487 | var stdout, stderr bytes.Buffer |
| 488 | if code := run([]string{"unready", strings.Repeat(id, 32)}, &stdout, &stderr, os.Exit); code != 0 { |
| 489 | t.Fatalf("unready: %s", stderr.String()) |
| 490 | } |
| 491 | } |
| 492 | after, drafted, addedNow := listing() |
| 493 | if drafted != attest || addedNow != added { |
| 494 | t.Errorf("with two drafts not listed, pending --checks started attest %d times, not %d, and --checks added %d processes, not %d", |
| 495 | drafted, attest, addedNow, added) |
| 496 | } |
| 497 | if want := before + "\n2 drafts · valley pending --drafts\n"; after != want { |
| 498 | t.Errorf("pending --checks printed, with two drafts:\n%s\nand with none:\n%s", after, before) |
| 499 | } |
| 500 | out, listed, _ := listing("--drafts") |
| 501 | if listed != attest+2 { |
| 502 | t.Errorf("pending --drafts --checks started attest %d times for one ready head and two drafts", listed) |
| 503 | } |
| 504 | for _, d := range []string{"qqqq v1 on draft-q 2 checks pending", "rrrr v1 on draft-r 2 checks pending"} { |
| 505 | if !strings.Contains(out, "\n"+d) { |
| 506 | t.Errorf("pending --drafts --checks does not open a block with %q:\n%s", d, out) |
| 507 | } |
| 508 | } |
| 509 | if n := strings.Count(out, "\n checks: 2 pending\n"); n != 2 { |
| 510 | t.Errorf("pending --drafts --checks gives %d drafts their checks line, not 2:\n%s", n, out) |
| 511 | } |
| 512 | } |
| 513 | |
| 514 | // pending --checks says when the worker's newest build of a pending |
| 515 | // check failed, for a ready change and for a draft alike, apart from a |
| 516 | // check whose failed build a later one passed and a check never built, and |
| 517 | // says where the worker's report is read. With --json, the check's state |
| 518 | // stays pending and the worker's report is beside it. A batch that failed |
| 519 | // before any check ran is said the same way. A host whose telemetry does |
| 520 | // not read leaves the listing as it is with no worker records. |
| 521 | func TestPendingSaysWhenTheWorkersBuildFailed(t *testing.T) { |
| 522 | dir := t.TempDir() |
| 523 | toolsOnPath(t, dir, "git", "cue") |
| 524 | // attest only digests each head's tree, since origin holds no |
| 525 | // evidence, and gives every head one digest: the worker's records |
| 526 | // about that tree are about the ready change's and the draft's. ssh |
| 527 | // answers the worker's read from a file, as the host would. |
| 528 | answer := filepath.Join(dir, "answer") |
| 529 | for tool, script := range map[string]string{ |
| 530 | "attest": "#!/bin/sh\necho valley-tree-v1:0123\n", |
| 531 | "ssh": fmt.Sprintf("#!/bin/sh\ncat '%s'\n", answer), |
| 532 | } { |
| 533 | if err := os.WriteFile(filepath.Join(dir, "bin", tool), []byte(script), 0o755); err != nil { |
| 534 | t.Fatal(err) |
| 535 | } |
| 536 | } |
| 537 | sh, head := policyProject(t, filepath.Join(dir, "origin"), 3) |
| 538 | sh("config", "valley.telemetry.remote", "ssh://git@valley-host/origin.git") |
| 539 | ready, draft := strings.Repeat("p", 32), strings.Repeat("q", 32) |
| 540 | head("ready-1", ready) |
| 541 | head("draft-1", draft) |
| 542 | var stdout, stderr bytes.Buffer |
| 543 | if code := run([]string{"unready", draft}, &stdout, &stderr, os.Exit); code != 0 { |
| 544 | t.Fatalf("unready: %s", stderr.String()) |
| 545 | } |
| 546 | |
| 547 | // records makes the host's answer: one page of the worker's records. |
| 548 | records := func(lines ...string) { |
| 549 | t.Helper() |
| 550 | page := `{"kind":"header","host":"valley-host","format":"valley-telemetry/v1"}` + "\n" |
| 551 | for i, l := range lines { |
| 552 | page += fmt.Sprintf(`{"kind":"record","stream":"worker","seq":%d,%s}`+"\n", i+1, l) |
| 553 | } |
| 554 | page += fmt.Sprintf(`{"kind":"end","cursor":"worker=0123456789abcdef:%d","truncated":false}`+"\n", len(lines)) |
| 555 | if err := os.WriteFile(answer, []byte(page), 0o644); err != nil { |
| 556 | t.Fatal(err) |
| 557 | } |
| 558 | } |
| 559 | at := func(ago time.Duration) string { return telemetry.Stamp(time.Now().Add(-ago)) } |
| 560 | // build is a check.result of the draft's version, as attest records |
| 561 | // one. |
| 562 | build := func(when, run, tree, check, result string) string { |
| 563 | return fmt.Sprintf(`"type":"check.result","time":%q,"run":%q,"project":"origin","change":%q,"version":1,"tree":%q,"check":%q,`+ |
| 564 | `"data":{"result":%q,"build_ms":1000,"eval_ms":4000,"log_bytes":10,"cached":false}`, when, run, draft, tree, check, result) |
| 565 | } |
| 566 | ages := regexp.MustCompile(`(?m) +[0-9]+[smhd]$| +[0-9]+ [a-z]+ ago · operator$`) |
| 567 | pending := func(args ...string) (string, string) { |
| 568 | t.Helper() |
| 569 | var stdout, stderr bytes.Buffer |
| 570 | if code := run(append([]string{"pending", "--checks", "--drafts"}, args...), &stdout, &stderr, os.Exit); code != 0 { |
| 571 | t.Fatalf("pending: %s", stderr.String()) |
| 572 | } |
| 573 | return ages.ReplaceAllString(stdout.String(), ""), stderr.String() |
| 574 | } |
| 575 | checksOf := func() map[string]*jsonVersionChecks { |
| 576 | t.Helper() |
| 577 | out, _ := pending("--json") |
| 578 | var doc jsonChanges |
| 579 | if err := json.Unmarshal([]byte(out), &doc); err != nil || len(doc.Repos) != 1 || doc.Repos[0].Drafts == nil { |
| 580 | t.Fatalf("pending --json printed no listing of one project (%v):\n%s", err, out) |
| 581 | } |
| 582 | checks := map[string]*jsonVersionChecks{} |
| 583 | for _, c := range append(doc.Repos[0].Changes, *doc.Repos[0].Drafts...) { |
| 584 | checks[c.ChangeID] = c.Versions[c.Active-1].Checks |
| 585 | } |
| 586 | if len(checks) != 2 { |
| 587 | t.Fatalf("pending --json lists %d changes, not the ready change and the draft:\n%s", len(checks), out) |
| 588 | } |
| 589 | return checks |
| 590 | } |
| 591 | see := " see: valley telemetry read --source worker --logs" |
| 592 | |
| 593 | records() |
| 594 | plain, _ := pending() |
| 595 | |
| 596 | // c-1's newest build failed; c-2 failed, then passed; c-3 was built |
| 597 | // only for another tree. |
| 598 | failed := at(5*time.Minute + 10*time.Second) |
| 599 | records(build(at(20*time.Minute), "r1", "0123", "c-1", "failed"), build(at(20*time.Minute), "r1", "0123", "c-2", "failed"), |
| 600 | build(failed, "r2", "0123", "c-1", "failed"), build(at(5*time.Minute), "r2", "0123", "c-2", "passed"), |
| 601 | build(at(time.Minute), "r3", "4567", "c-3", "failed")) |
| 602 | out, _ := pending() |
| 603 | says := "c-1 failed in the worker's build, 5m ago" |
| 604 | for _, want := range []string{ |
| 605 | "\n 1 pppp v1 ✗ " + says + "\n ready-1\n requires 3 quick checks, 0 slow\n" + |
| 606 | " checks: 3 pending (" + says + ")\n " + see + "\n", |
| 607 | "\nqqqq v1 on draft-1 ✗ " + says + "\n", |
| 608 | "\n requires 3 quick checks, 0 slow\n checks: 3 pending (" + says + ") in 2s (eval 4s)\n " + see + "\n", |
| 609 | } { |
| 610 | if !strings.Contains(out, want) { |
| 611 | t.Errorf("pending --checks --drafts does not say\n%s\nin:\n%s", want, out) |
| 612 | } |
| 613 | } |
| 614 | for id, c := range checksOf() { |
| 615 | if c == nil || c.State != checkPending || c.Worker != nil || len(c.Required) != 3 { |
| 616 | t.Fatalf("%s's checks are not three, pending, with no batch reported: %+v", id, c) |
| 617 | } |
| 618 | if q := c.Required[0]; q.State != checkPending || q.Worker == nil || *q.Worker != (jsonWorkerReport{Result: checkFailed, Time: failed, Run: "r2"}) { |
| 619 | t.Errorf("%s's c-1 is not pending with the worker's report of r2's failure: %+v", id, q) |
| 620 | } |
| 621 | for _, q := range c.Required[1:] { |
| 622 | if q.State != checkPending || q.Worker != nil { |
| 623 | t.Errorf("%s's %s is not pending with no worker's report: %+v", id, q.Name, q) |
| 624 | } |
| 625 | } |
| 626 | } |
| 627 | |
| 628 | // A batch that failed before any check ran recorded no check's result. |
| 629 | ended := at(time.Minute + 10*time.Second) |
| 630 | records(build(at(20*time.Minute), "r1", "0123", "c-1", "passed"), |
| 631 | fmt.Sprintf(`"type":"batch.end","time":%q,"run":"p1","project":"origin","change":%q,"version":1,"tree":"0123",`+ |
| 632 | `"data":{"result":"failed","attest_run":"r4","reason":"attest run r4: exit status 1"}`, ended, ready)) |
| 633 | out, _ = pending() |
| 634 | says = "the worker's batch failed, 1m ago" |
| 635 | if want := "\n 1 pppp v1 ✗ " + says + "\n ready-1\n requires 3 quick checks, 0 slow\n" + |
| 636 | " checks: 3 pending (" + says + ")\n " + see + "\n"; !strings.Contains(out, want) { |
| 637 | t.Errorf("pending --checks does not say\n%s\nin:\n%s", want, out) |
| 638 | } |
| 639 | for id, c := range checksOf() { |
| 640 | if c.Worker == nil || *c.Worker != (jsonWorkerReport{Result: checkFailed, Time: ended, Run: "r4"}) || c.State != checkPending { |
| 641 | t.Errorf("%s's checks do not carry the worker's report of the failed batch: %+v", id, c) |
| 642 | } |
| 643 | } |
| 644 | |
| 645 | // A host that refuses: the listing is as it is with no worker records. |
| 646 | if err := os.WriteFile(answer, []byte(`{"kind":"error","error":"operator holds no observe grant"}`+"\n"), 0o644); err != nil { |
| 647 | t.Fatal(err) |
| 648 | } |
| 649 | out, errs := pending() |
| 650 | if out != plain { |
| 651 | t.Errorf("with the worker's telemetry refused, pending printed:\n%s\nand with no worker records:\n%s", out, plain) |
| 652 | } |
| 653 | if n := strings.Count(errs, "no check lists its build times"); n != 1 { |
| 654 | t.Errorf("a refusing host was said %d times on stderr, not once:\n%s", n, errs) |
| 655 | } |
| 656 | for id, c := range checksOf() { |
| 657 | reported := c.Worker != nil |
| 658 | for _, q := range c.Required { |
| 659 | reported = reported || q.Worker != nil |
| 660 | } |
| 661 | if reported { |
| 662 | t.Errorf("with the worker's telemetry refused, %s carries a worker's report: %+v", id, c) |
| 663 | } |
| 664 | } |
| 665 | } |
| 666 | |
| 667 | // unheard opens a FIFO to write and closes it, so a reader still waiting |
| 668 | // on it reads nothing and ends. |
| 669 | func unheard(fifo string) { |
| 670 | if f, err := os.OpenFile(fifo, os.O_WRONLY|syscall.O_NONBLOCK, 0); err == nil { |
| 671 | f.Close() |
| 672 | } |
| 673 | } |