| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "context" |
| 6 | "fmt" |
| 7 | "net" |
| 8 | "os" |
| 9 | "os/exec" |
| 10 | "path/filepath" |
| 11 | "strconv" |
| 12 | "strings" |
| 13 | "syscall" |
| 14 | "testing" |
| 15 | "time" |
| 16 | |
| 17 | "the-valley/telemetry" |
| 18 | ) |
| 19 | |
| 20 | // A host or a proxy that says far more on ssh's stderr than a read keeps |
| 21 | // costs it no more than sshSaidLimit bytes: the read's error carries the |
| 22 | // last of what was said, which says why it failed. |
| 23 | func TestAReadKeepsTheLastOfWhatSSHSaid(t *testing.T) { |
| 24 | dir := t.TempDir() |
| 25 | toolsOnPath(t, dir) |
| 26 | ssh := "#!/bin/sh\nhead -c 1048576 /dev/zero | tr '\\0' x >&2\necho ' the host went away' >&2\nexit 255\n" |
| 27 | if err := os.WriteFile(filepath.Join(dir, "bin", "ssh"), []byte(ssh), 0o755); err != nil { |
| 28 | t.Fatal(err) |
| 29 | } |
| 30 | _, err := readPage(context.Background(), sshDest{host: "valley-host"}, "") |
| 31 | if err == nil || !strings.HasSuffix(err.Error(), "x the host went away") || len(err.Error()) > sshSaidLimit+200 { |
| 32 | t.Errorf("the read said %d bytes, ending %q", len(fmt.Sprint(err)), fmt.Sprint(err)[max(len(fmt.Sprint(err))-60, 0):]) |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | // One valley pending runs its older worker-history pages and its host |
| 37 | // sources read at once, and a host whose collector gives the principal |
| 38 | // telemetry.BoundedSlots bounded slots admits every one: every page's |
| 39 | // build and the sources answer are read, none refused. Each concurrent |
| 40 | // read joins a barrier and tells it whether it took a slot; an admitted |
| 41 | // one keeps its slot and answers only once every concurrent read has |
| 42 | // told, so the slots held when the last one tells are held at once, and |
| 43 | // every one must be. |
| 44 | func TestAHistoryReadFitsTheBoundedSlots(t *testing.T) { |
| 45 | dir, bin := t.TempDir(), t.TempDir() |
| 46 | if err := os.Symlink(os.Args[0], filepath.Join(bin, "ssh")); err != nil { |
| 47 | t.Fatal(err) |
| 48 | } |
| 49 | t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")) |
| 50 | t.Setenv("FAKE_SSH_POOL", dir) |
| 51 | barrier, err := net.Listen("unix", filepath.Join(dir, "barrier")) |
| 52 | if err != nil { |
| 53 | t.Fatal(err) |
| 54 | } |
| 55 | older := costRecords/telemetry.MaxReadLimit - 1 |
| 56 | concurrent := older + 1 // older history pages + sources |
| 57 | held := make(chan int, 1) |
| 58 | go func() { |
| 59 | var joined []net.Conn |
| 60 | defer func() { |
| 61 | for _, c := range joined { |
| 62 | c.Close() |
| 63 | } |
| 64 | }() |
| 65 | n := 0 |
| 66 | for len(joined) < concurrent { |
| 67 | c, err := barrier.Accept() |
| 68 | if err != nil { |
| 69 | held <- -1 |
| 70 | return |
| 71 | } |
| 72 | joined = append(joined, c) |
| 73 | c.SetReadDeadline(time.Now().Add(time.Minute)) |
| 74 | told, err := bufio.NewReader(c).ReadString('\n') |
| 75 | if err != nil { |
| 76 | held <- -1 |
| 77 | return |
| 78 | } |
| 79 | if told == "held\n" { |
| 80 | n++ |
| 81 | } |
| 82 | } |
| 83 | for _, c := range joined { |
| 84 | c.Write([]byte("go\n")) |
| 85 | } |
| 86 | held <- n |
| 87 | }() |
| 88 | dest := sshDest{host: "valley-host"} |
| 89 | type sourcesResult struct { |
| 90 | entries []jsonHostSource |
| 91 | err error |
| 92 | } |
| 93 | sourcesDone := make(chan sourcesResult, 1) |
| 94 | go func() { |
| 95 | entries, err := readHostSources(context.Background(), dest) |
| 96 | sourcesDone <- sourcesResult{entries, err} |
| 97 | }() |
| 98 | builds, _, _, why := readBuilds(context.Background(), dest) |
| 99 | sr := <-sourcesDone |
| 100 | barrier.Close() |
| 101 | if n := <-held; n != concurrent { |
| 102 | t.Errorf("%d of the %d concurrent bounded reads held a slot at once", n, concurrent) |
| 103 | } |
| 104 | if pages := costRecords / telemetry.MaxReadLimit; why != "" || len(builds) != pages { |
| 105 | t.Errorf("the history read %d of %d pages' builds: %q", len(builds), pages, why) |
| 106 | } |
| 107 | if sr.err != nil || len(sr.entries) != 1 || sr.entries[0].Source != "mirrors" { |
| 108 | t.Errorf("sources read = %+v, %v; want mirrors failed", sr.entries, sr.err) |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | // fakePooledSSH is a host whose collector admits telemetry.BoundedSlots |
| 113 | // reads at once, as it does for one principal, and refuses any more. The |
| 114 | // newest worker page answers at once. Each older page's read and the |
| 115 | // sources read join the test's barrier, try for a slot and tell the |
| 116 | // barrier whether they hold one; admitted, each answers once the barrier |
| 117 | // says go, and fails when the barrier closes without saying it. |
| 118 | func fakePooledSSH(dir string, args []string) int { |
| 119 | _, command, ok := sshDestCommand(args) |
| 120 | if !ok { |
| 121 | return 255 |
| 122 | } |
| 123 | req, err := telemetry.ParseCommand(command) |
| 124 | if err != nil || (req.Op != telemetry.OpRead && req.Op != telemetry.OpSources) { |
| 125 | return 1 |
| 126 | } |
| 127 | answer := func(seq, end int64) { |
| 128 | fmt.Printf(`{"kind":"record","stream":"worker","seq":%d,"type":"check.result","project":"app","tree":"t1","check":"c-%d","data":{"result":"passed","build_ms":1000}}`+"\n", seq, seq) |
| 129 | fmt.Printf(`{"kind":"end","cursor":"worker=0123456789abcdef:%d"}`+"\n", end) |
| 130 | } |
| 131 | if req.Op == telemetry.OpRead && req.Cursor == "" { |
| 132 | answer(costRecords, costRecords) |
| 133 | return 0 |
| 134 | } |
| 135 | barrier, err := net.Dial("unix", filepath.Join(dir, "barrier")) |
| 136 | if err != nil { |
| 137 | return 1 |
| 138 | } |
| 139 | defer barrier.Close() |
| 140 | var slot *os.File |
| 141 | for i := range telemetry.BoundedSlots { |
| 142 | f, err := os.OpenFile(filepath.Join(dir, fmt.Sprintf("slot.%d", i)), os.O_CREATE|os.O_RDWR, 0o600) |
| 143 | if err == nil && syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) == nil { |
| 144 | slot = f |
| 145 | break |
| 146 | } |
| 147 | f.Close() |
| 148 | } |
| 149 | if slot == nil { |
| 150 | barrier.Write([]byte("refused\n")) |
| 151 | fmt.Printf(`{"kind":"error","error":%q}`+"\n", telemetry.SlotRefusal("operator", telemetry.BoundedSlots, "bounded")) |
| 152 | return 0 |
| 153 | } |
| 154 | defer slot.Close() |
| 155 | if _, err := barrier.Write([]byte("held\n")); err != nil { |
| 156 | return 1 |
| 157 | } |
| 158 | if said, _ := bufio.NewReader(barrier).ReadString('\n'); said != "go\n" { |
| 159 | return 1 |
| 160 | } |
| 161 | if req.Op == telemetry.OpSources { |
| 162 | fmt.Println(`{"kind":"header","host":"valley-host","format":"valley-telemetry/v1"}`) |
| 163 | fmt.Println(`{"kind":"source","name":"mirrors","state":"failed","detail":"valley-publish@app.service: activating, result exit-code, status 1","unit_states":[{"Id":"valley-publish@app.service","ActiveState":"activating","Result":"exit-code","ExecMainStatus":"1"}]}`) |
| 164 | fmt.Println(`{"kind":"end","truncated":false}`) |
| 165 | return 0 |
| 166 | } |
| 167 | cursor, _ := telemetry.ParseCursor(req.Cursor) |
| 168 | after := cursor["worker"].Seq |
| 169 | answer(after+1, after+telemetry.MaxReadLimit) |
| 170 | return 0 |
| 171 | } |
| 172 | |
| 173 | // lastBytes keeps the last bytes written through it, however they come. |
| 174 | func TestLastBytes(t *testing.T) { |
| 175 | l := &lastBytes{max: 4} |
| 176 | for _, w := range []string{"ab", "cde", "f", "ghijklm", "n"} { |
| 177 | l.Write([]byte(w)) |
| 178 | } |
| 179 | if string(l.b) != "klmn" { |
| 180 | t.Errorf("kept %q, not the last four bytes", l.b) |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | // Closing the reads cancels one still running at once, even when a |
| 185 | // process its ssh started, as a ProxyCommand is, holds ssh's output open: |
| 186 | // close never waits for that output, which a wait for ssh would take up |
| 187 | // to sshWaitDelay to give up on. |
| 188 | func TestClosingAReadDoesNotWaitForOutputHeldOpen(t *testing.T) { |
| 189 | dir := t.TempDir() |
| 190 | toolsOnPath(t, dir, "git") |
| 191 | said := filepath.Join(dir, "ssh.pids") |
| 192 | if err := syscall.Mkfifo(said, 0o600); err != nil { |
| 193 | t.Fatal(err) |
| 194 | } |
| 195 | // ssh starts a process that holds its output, says both process IDs, |
| 196 | // and stalls. |
| 197 | ssh := fmt.Sprintf("#!/bin/sh\nsleep 86397 &\necho \"$! $$\" > '%s'\nexec sleep 86396\n", said) |
| 198 | if err := os.WriteFile(filepath.Join(dir, "bin", "ssh"), []byte(ssh), 0o755); err != nil { |
| 199 | t.Fatal(err) |
| 200 | } |
| 201 | repo := filepath.Join(dir, "repo") |
| 202 | for _, args := range [][]string{{"init", "--quiet", repo}, {"-C", repo, "config", "valley.telemetry.remote", "ssh://git@valley-host/app.git"}} { |
| 203 | if out, err := exec.Command("git", args...).CombinedOutput(); err != nil { |
| 204 | t.Fatalf("git %v: %v\n%s", args, err, out) |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | c := newCosts() |
| 209 | read := c.start(git{env: os.Environ(), dir: repo}) |
| 210 | pids := make(chan []string, 1) |
| 211 | go func() { |
| 212 | data, _ := os.ReadFile(said) |
| 213 | pids <- strings.Fields(string(data)) |
| 214 | }() |
| 215 | var held []string |
| 216 | select { |
| 217 | case held = <-pids: |
| 218 | case <-read.done: |
| 219 | unheard(said) |
| 220 | t.Fatalf("the read ended before ssh started: %s", read.why) |
| 221 | case <-time.After(time.Minute): |
| 222 | unheard(said) |
| 223 | t.Fatal("the read's ssh did not start in a minute") |
| 224 | } |
| 225 | for _, p := range held { |
| 226 | if n, err := strconv.Atoi(p); err == nil { |
| 227 | defer syscall.Kill(n, syscall.SIGKILL) |
| 228 | } |
| 229 | } |
| 230 | began := time.Now() |
| 231 | c.close() |
| 232 | if took := time.Since(began); took >= sshWaitDelay { |
| 233 | t.Errorf("closing the read took %s, waiting for the output a process its ssh started held open", took) |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | // A build has grown only when it is slower than its baseline by more than |
| 238 | // both 20% and 30 s. |
| 239 | func TestGrew(t *testing.T) { |
| 240 | for _, c := range []struct { |
| 241 | build, baseline int64 |
| 242 | grown bool |
| 243 | }{ |
| 244 | {100_000, 60_000, true}, // +40 s, +67% |
| 245 | {500_000, 400_000, true}, // +100 s, +25% |
| 246 | {431_000, 363_000, false}, // +68 s, but +18.7% |
| 247 | {80_000, 60_000, false}, // +20 s, +33% |
| 248 | {1_230_000, 1_200_000 - 1, false}, // +30 s, +2.5% |
| 249 | {400_000, 400_000, false}, |
| 250 | {10_000, 400_000, false}, // faster |
| 251 | } { |
| 252 | if got := grew(c.build, c.baseline); got != c.grown { |
| 253 | t.Errorf("grew(%d, %d) = %v, want %v", c.build, c.baseline, got, c.grown) |
| 254 | } |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | func TestMedian(t *testing.T) { |
| 259 | for _, c := range []struct { |
| 260 | ms []int64 |
| 261 | want int64 |
| 262 | }{ |
| 263 | {[]int64{5}, 5}, |
| 264 | {[]int64{9, 1, 5}, 5}, |
| 265 | {[]int64{4, 1, 3, 2}, 2}, |
| 266 | {[]int64{10, 20}, 15}, |
| 267 | } { |
| 268 | if got := median(c.ms); got != c.want { |
| 269 | t.Errorf("median(%v) = %d, want %d", c.ms, got, c.want) |
| 270 | } |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | // The baseline is the median of a check's newest 20 uncached, passing |
| 275 | // builds in the project, with every version of the change left out. |
| 276 | func TestAddCosts(t *testing.T) { |
| 277 | me := strings.Repeat("k", 32) |
| 278 | other := func(i int) string { return fmt.Sprintf("%s%02d", strings.Repeat("m", 30), i) } |
| 279 | var builds []checkBuild // newest first |
| 280 | add := func(b checkBuild) { |
| 281 | if b.project == "" { |
| 282 | b.project = "app" |
| 283 | } |
| 284 | if b.result == "" { |
| 285 | b.result = checkPassed |
| 286 | } |
| 287 | builds = append(builds, b) |
| 288 | } |
| 289 | // This version's own builds, in one run. |
| 290 | add(checkBuild{run: "r2", change: me, version: 2, tree: "t2", check: "slow", buildMS: 200_000, evalMS: 24_000}) |
| 291 | add(checkBuild{run: "r2", change: me, version: 2, tree: "t2", check: "fast", buildMS: 120, evalMS: 24_000, cached: true}) |
| 292 | add(checkBuild{run: "r2", change: me, version: 2, tree: "t2", check: "fresh", buildMS: 9_000, evalMS: 23_000}) |
| 293 | // The change's earlier version, never counted. |
| 294 | add(checkBuild{run: "r1", change: me, version: 1, tree: "t1", check: "slow", buildMS: 1}) |
| 295 | // Other changes: a cached build, a failed one and another project's |
| 296 | // are left out, then 25 builds of which the newest 20 count. |
| 297 | add(checkBuild{change: other(98), check: "slow", buildMS: 2, cached: true}) |
| 298 | add(checkBuild{change: other(99), check: "slow", buildMS: 3, result: "failed"}) |
| 299 | add(checkBuild{project: "site", change: other(97), check: "slow", buildMS: 4}) |
| 300 | for i := 0; i < 25; i++ { |
| 301 | ms := int64(100_000 + i*1_000) // the newest 20: 100 s to 119 s |
| 302 | if i >= 20 { |
| 303 | ms = 900_000 |
| 304 | } |
| 305 | add(checkBuild{change: other(i), check: "slow", buildMS: ms}) |
| 306 | add(checkBuild{change: other(i), check: "fast", buildMS: 5_000}) |
| 307 | } |
| 308 | out := &jsonVersionChecks{Tree: "t2", Required: []jsonCheckState{{Name: "slow"}, {Name: "fast"}, {Name: "fresh"}, {Name: "manual"}}} |
| 309 | required := []jsonRequired{{Name: "slow", Runner: "nix"}, {Name: "fast", Runner: "nix"}, {Name: "fresh", Runner: "nix"}, {Name: "manual", Runner: "command"}} |
| 310 | addCosts(out, required, "app", me, 2, builds) |
| 311 | |
| 312 | slow, fast, fresh, manual := out.Required[0], out.Required[1], out.Required[2], out.Required[3] |
| 313 | if slow.BuildMS == nil || *slow.BuildMS != 200_000 || *slow.Cached || slow.BaselineMS == nil || *slow.BaselineMS != 109_500 || !slow.Grown || slow.New { |
| 314 | t.Errorf("slow: %+v", slow) |
| 315 | } |
| 316 | if fast.BuildMS == nil || *fast.BuildMS != 120 || !*fast.Cached || *fast.BaselineMS != 5_000 || fast.Grown { |
| 317 | t.Errorf("fast: %+v", fast) |
| 318 | } |
| 319 | if fresh.BuildMS == nil || *fresh.BuildMS != 9_000 || fresh.BaselineMS != nil || !fresh.New || fresh.Grown { |
| 320 | t.Errorf("fresh: %+v", fresh) |
| 321 | } |
| 322 | if manual.BuildMS != nil || manual.New || manual.BaselineMS != nil { |
| 323 | t.Errorf("manual: %+v", manual) |
| 324 | } |
| 325 | if out.BuildMS == nil || *out.BuildMS != 209_120 || *out.EvalMS != 24_000 { |
| 326 | t.Errorf("totals: build %v, eval %v", out.BuildMS, out.EvalMS) |
| 327 | } |
| 328 | out.State = checkPassed |
| 329 | for i := range out.Required { |
| 330 | out.Required[i].State = checkPassed |
| 331 | } |
| 332 | want := "checks: 4 passed in 3m29s (eval 24s); slow 200s, +91s against its recent 110s" |
| 333 | if got := checksLine(out); got != want { |
| 334 | t.Errorf("checksLine:\n got %s\nwant %s", got, want) |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | // A build is compared only with builds on its own capacity. A check whose |
| 339 | // builds so far ran on another is new, and is not grown. |
| 340 | func TestAddCostsCapacity(t *testing.T) { |
| 341 | builds := []checkBuild{ // newest first |
| 342 | {run: "r", change: "me", version: 1, check: "same", buildMS: 200_000, capacity: "big"}, |
| 343 | {run: "r", change: "me", version: 1, check: "resized", buildMS: 200_000, capacity: "big"}, |
| 344 | {change: "o1", check: "same", buildMS: 100_000, capacity: "big"}, |
| 345 | {change: "o1", check: "resized", buildMS: 10_000, capacity: "small"}, |
| 346 | } |
| 347 | var states []jsonCheckState |
| 348 | var required []jsonRequired |
| 349 | for _, name := range []string{"same", "resized"} { |
| 350 | builds[len(states)].project, builds[len(states)+2].project = "app", "app" |
| 351 | builds[len(states)].result, builds[len(states)+2].result = checkPassed, checkPassed |
| 352 | states = append(states, jsonCheckState{Name: name, State: checkPassed}) |
| 353 | required = append(required, jsonRequired{Name: name, Runner: "nix"}) |
| 354 | } |
| 355 | out := &jsonVersionChecks{State: checkPassed, Required: states} |
| 356 | addCosts(out, required, "app", "me", 1, builds) |
| 357 | if same := out.Required[0]; !same.Grown || same.New || *same.BaselineMS != 100_000 { |
| 358 | t.Errorf("same: %+v", same) |
| 359 | } |
| 360 | if resized := out.Required[1]; !resized.New || !resized.OtherCapacity || resized.Grown || resized.BaselineMS != nil { |
| 361 | t.Errorf("resized: %+v", resized) |
| 362 | } |
| 363 | } |