| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "bytes" |
| 6 | "encoding/json" |
| 7 | "fmt" |
| 8 | "os" |
| 9 | "os/exec" |
| 10 | "path/filepath" |
| 11 | "runtime" |
| 12 | "strings" |
| 13 | "testing" |
| 14 | "time" |
| 15 | |
| 16 | "the-valley/telemetry" |
| 17 | ) |
| 18 | |
| 19 | func testCollector(t *testing.T) (*collector, *bytes.Buffer, string) { |
| 20 | t.Helper() |
| 21 | dir := t.TempDir() |
| 22 | worker := filepath.Join(dir, "worker") |
| 23 | c := &collector{ |
| 24 | manifest: manifest{V: 1, Host: "valley-host", Reporters: []string{"alice"}, Sources: []source{ |
| 25 | {Name: "worker", Enabled: true, Location: "local", Units: []string{"valley-worker.service"}, Stream: worker}, |
| 26 | {Name: "bus", Enabled: false, Location: "local", Units: []string{"valley-bus.service"}}, |
| 27 | }}, |
| 28 | grants: map[string]map[string]bool{"operator": {"observe": true}, "alice": {"report": true}}, |
| 29 | state: filepath.Join(dir, "collector"), |
| 30 | now: time.Now, |
| 31 | systemctl: func(units []string) ([]unitState, error) { |
| 32 | var s []unitState |
| 33 | for _, u := range units { |
| 34 | s = append(s, unitState{"Id": u, "LoadState": "loaded", "ActiveState": "inactive", "Result": "success"}) |
| 35 | } |
| 36 | return s, nil |
| 37 | }, |
| 38 | journal: func([]string, int, bool) ([]journalEntry, error) { return nil, nil }, |
| 39 | horizon: func([]string) string { return "" }, |
| 40 | } |
| 41 | out := &bytes.Buffer{} |
| 42 | c.out = &output{w: out} |
| 43 | return c, out, worker |
| 44 | } |
| 45 | |
| 46 | func ask(c *collector, out *bytes.Buffer, req telemetry.Request, body string) (int, []map[string]any) { |
| 47 | out.Reset() |
| 48 | c.out = &output{w: out} |
| 49 | line, _ := json.Marshal(req) |
| 50 | status := c.handle(bufio.NewReader(strings.NewReader(string(line)+"\n"+body)), nil) |
| 51 | var lines []map[string]any |
| 52 | for _, l := range strings.Split(strings.TrimSpace(out.String()), "\n") { |
| 53 | var m map[string]any |
| 54 | json.Unmarshal([]byte(l), &m) |
| 55 | lines = append(lines, m) |
| 56 | } |
| 57 | return status, lines |
| 58 | } |
| 59 | |
| 60 | func kind(lines []map[string]any, k string) []map[string]any { |
| 61 | var out []map[string]any |
| 62 | for _, l := range lines { |
| 63 | if l["kind"] == k { |
| 64 | out = append(out, l) |
| 65 | } |
| 66 | } |
| 67 | return out |
| 68 | } |
| 69 | |
| 70 | func clientRecord(epoch string, seq int, typ string) string { |
| 71 | r := telemetry.Record{Type: typ, Time: telemetry.Stamp(time.Now()), Run: "r1", ClientID: fmt.Sprintf("%s:%d", epoch, seq)} |
| 72 | b, _ := json.Marshal(r) |
| 73 | return string(b) + "\n" |
| 74 | } |
| 75 | |
| 76 | // A report is stored under the principal that sent it, stamped when it |
| 77 | // arrived, and a retried record is not stored twice. |
| 78 | func TestAReportIsStampedAndARetryIsHarmless(t *testing.T) { |
| 79 | c, out, _ := testCollector(t) |
| 80 | epoch := "0123456789abcdef" |
| 81 | body := clientRecord(epoch, 1, "approve.start") + clientRecord(epoch, 2, "check.result") |
| 82 | report := telemetry.Request{V: 1, Principal: "alice", Op: telemetry.OpReport} |
| 83 | status, lines := ask(c, out, report, body) |
| 84 | ack := kind(lines, "ack") |
| 85 | if status != 0 || len(ack) != 1 || ack[0]["accepted"] != 2.0 { |
| 86 | t.Fatalf("first report: %d %v", status, lines) |
| 87 | } |
| 88 | _, lines = ask(c, out, report, body+clientRecord(epoch, 4, "approve.end")) |
| 89 | ack = kind(lines, "ack") |
| 90 | if ack[0]["accepted"] != 1.0 || ack[0]["duplicates"] != 2.0 { |
| 91 | t.Fatalf("retried report: %v", ack) |
| 92 | } |
| 93 | recs, _, _ := c.reportStream("alice").Read(0, 100, 0) |
| 94 | if len(recs) != 4 || recs[2].Type != "report.gap" || recs[0].Principal != "alice" || recs[0].Received == "" { |
| 95 | t.Fatalf("stored %+v", recs) |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | // What a reporter may not say is refused record by record: a field the |
| 100 | // format lacks, a principal or receipt of its own, a host producer's |
| 101 | // type, a record without its own ID. |
| 102 | func TestAReportCannotSpeakForAnother(t *testing.T) { |
| 103 | c, out, _ := testCollector(t) |
| 104 | now := telemetry.Stamp(time.Now()) |
| 105 | body := strings.Join([]string{ |
| 106 | `{"type":"approve.start","time":"` + now + `","client_id":"0123456789abcdef:1","principal":"operator"}`, |
| 107 | `{"type":"approve.start","time":"` + now + `","client_id":"0123456789abcdef:2","received":"` + now + `"}`, |
| 108 | `{"type":"pass.start","time":"` + now + `","client_id":"0123456789abcdef:3"}`, |
| 109 | `{"type":"approve.start","time":"` + now + `","client_id":"0123456789abcdef:4","command":"rm -rf /"}`, |
| 110 | `{"type":"approve.start","time":"` + now + `"}`, |
| 111 | `not json`, |
| 112 | }, "\n") + "\n" |
| 113 | _, lines := ask(c, out, telemetry.Request{V: 1, Principal: "alice", Op: telemetry.OpReport}, body) |
| 114 | ack := kind(lines, "ack") |
| 115 | if len(ack) != 1 || ack[0]["accepted"] != 0.0 || ack[0]["rejected"] != 6.0 { |
| 116 | t.Fatalf("ack %v", lines) |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | // A report larger than its bound is cut off there, and says so. |
| 121 | func TestAReportIsBounded(t *testing.T) { |
| 122 | c, out, _ := testCollector(t) |
| 123 | var body strings.Builder |
| 124 | for i := 1; i <= telemetry.MaxReportRecords+10; i++ { |
| 125 | body.WriteString(clientRecord("0123456789abcdef", i, "check.queued")) |
| 126 | } |
| 127 | _, lines := ask(c, out, telemetry.Request{V: 1, Principal: "alice", Op: telemetry.OpReport}, body.String()) |
| 128 | ack := kind(lines, "ack") |
| 129 | if ack[0]["accepted"] != float64(telemetry.MaxReportRecords) || ack[0]["rejected"] != 1.0 { |
| 130 | t.Fatalf("ack %v", ack) |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | // Reading needs observe, reporting needs report, and neither implies the |
| 135 | // other. |
| 136 | func TestEachOperationNeedsItsGrant(t *testing.T) { |
| 137 | c, out, _ := testCollector(t) |
| 138 | for _, req := range []telemetry.Request{ |
| 139 | {V: 1, Principal: "alice", Op: telemetry.OpSources}, |
| 140 | {V: 1, Principal: "operator", Op: telemetry.OpReport}, |
| 141 | {V: 1, Principal: "mallory", Op: telemetry.OpRead}, |
| 142 | } { |
| 143 | if status, lines := ask(c, out, req, ""); status == 0 || len(kind(lines, "error")) != 1 { |
| 144 | t.Errorf("%s %s: %d %v", req.Principal, req.Op, status, lines) |
| 145 | } |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | // A cursor older than what a stream keeps reads as a gap, a cursor of a |
| 150 | // stream made again reads as a reset, and both resume at what is there. |
| 151 | func TestACursorGapIsSaid(t *testing.T) { |
| 152 | c, out, worker := testCollector(t) |
| 153 | st := &telemetry.Stream{Dir: worker, SegmentBytes: 1024, Segments: 2} |
| 154 | for i := 0; i < 40; i++ { |
| 155 | st.Append(&telemetry.Record{Type: "check.queued", Time: telemetry.Stamp(time.Now()), Run: "r1", Check: fmt.Sprintf("c%d", i)}) |
| 156 | } |
| 157 | rng, _ := st.Range() |
| 158 | read := telemetry.Request{V: 1, Principal: "operator", Op: telemetry.OpRead, Source: "worker", Cursor: "worker=" + rng.Epoch + ":3"} |
| 159 | _, lines := ask(c, out, read, "") |
| 160 | gaps := kind(lines, "gap") |
| 161 | if len(gaps) != 1 || gaps[0]["reason"] != "retention" || gaps[0]["to"] != float64(rng.First-1) { |
| 162 | t.Fatalf("gap %v", lines) |
| 163 | } |
| 164 | end := kind(lines, "end") |
| 165 | if end[0]["cursor"] != fmt.Sprintf("worker=%s:%d", rng.Epoch, rng.Last) { |
| 166 | t.Fatalf("end %v", end) |
| 167 | } |
| 168 | read.Cursor = "worker=fedcba9876543210:3" |
| 169 | _, lines = ask(c, out, read, "") |
| 170 | if gaps := kind(lines, "gap"); len(gaps) != 1 || gaps[0]["reason"] != "reset" { |
| 171 | t.Fatalf("reset %v", lines) |
| 172 | } |
| 173 | read.Source = "bus" |
| 174 | if status, _ := ask(c, out, read, ""); status == 0 { |
| 175 | t.Fatal("a disabled source read") |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | // A run its stream holds open while no unit of the source runs was |
| 180 | // interrupted; the source says so rather than idle. |
| 181 | func TestAnOpenRunWithNoUnitRunningIsStale(t *testing.T) { |
| 182 | c, out, worker := testCollector(t) |
| 183 | st := &telemetry.Stream{Dir: worker} |
| 184 | st.Append(&telemetry.Record{Type: "pass.start", Time: telemetry.Stamp(time.Now()), Run: "r1"}) |
| 185 | _, lines := ask(c, out, telemetry.Request{V: 1, Principal: "operator", Op: telemetry.OpSnapshot}, "") |
| 186 | for _, s := range kind(lines, "source") { |
| 187 | switch s["name"] { |
| 188 | case "worker": |
| 189 | if s["state"] != "stale" { |
| 190 | t.Errorf("worker %v", s) |
| 191 | } |
| 192 | case "bus": |
| 193 | if s["state"] != "disabled" { |
| 194 | t.Errorf("bus %v", s) |
| 195 | } |
| 196 | case "report.alice": |
| 197 | if s["state"] != "idle" { |
| 198 | t.Errorf("reports %v", s) |
| 199 | } |
| 200 | } |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | // A follower sees build output as it is written, and ends with a cursor. |
| 205 | func TestFollowStreamsBuildOutputAsItIsWritten(t *testing.T) { |
| 206 | c, out, worker := testCollector(t) |
| 207 | pollEvery = 50 * time.Millisecond |
| 208 | st := &telemetry.Stream{Dir: worker} |
| 209 | st.Append(&telemetry.Record{Type: "run.start", Time: telemetry.Stamp(time.Now()), Run: "r1"}) |
| 210 | log := st.Log("r1", "slow", telemetry.MaxLogBytes) |
| 211 | log.Write([]byte("before\n")) |
| 212 | go func() { |
| 213 | time.Sleep(300 * time.Millisecond) |
| 214 | log.Write([]byte("during \x1b[31mred\n")) |
| 215 | st.Append(&telemetry.Record{Type: "check.result", Time: telemetry.Stamp(time.Now()), Run: "r1", Check: "fast"}) |
| 216 | }() |
| 217 | _, lines := ask(c, out, telemetry.Request{V: 1, Principal: "operator", Op: telemetry.OpFollow, Seconds: 1, Logs: true}, "") |
| 218 | var text string |
| 219 | for _, l := range kind(lines, "log") { |
| 220 | text += l["text"].(string) |
| 221 | if l["untrusted"] != true { |
| 222 | t.Errorf("log not marked untrusted: %v", l) |
| 223 | } |
| 224 | } |
| 225 | if !strings.Contains(text, "before") || !strings.Contains(text, `during \x1b[31mred`) { |
| 226 | t.Fatalf("followed %q", text) |
| 227 | } |
| 228 | recs := kind(lines, "record") |
| 229 | if len(recs) != 1 || recs[0]["check"] != "fast" { |
| 230 | t.Fatalf("records %v", recs) |
| 231 | } |
| 232 | if end := kind(lines, "end"); len(end) != 1 || !strings.HasPrefix(end[0]["cursor"].(string), "worker=") { |
| 233 | t.Fatalf("end %v", end) |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | // A principal's follows and its bounded requests draw from pools of |
| 238 | // their own: five bounded requests at once are admitted, as one valley |
| 239 | // pending reads four older history pages alongside sources |
| 240 | // (status/checkcost.go, status/hostsources.go); with every follow slot |
| 241 | // held, a sources, snapshot and read are answered and a fifth follow is |
| 242 | // refused, naming follows; with every bounded slot held, a read is |
| 243 | // refused, naming them, and a follow is admitted. |
| 244 | func TestFollowsAndBoundedRequestsTakeSeparateSlots(t *testing.T) { |
| 245 | c, out, _ := testCollector(t) |
| 246 | as := func(op string) telemetry.Request { return telemetry.Request{V: 1, Principal: "operator", Op: op} } |
| 247 | hold := func(op string, n int) []func() { |
| 248 | t.Helper() |
| 249 | var held []func() |
| 250 | for range n { |
| 251 | release, err := c.slot(as(op)) |
| 252 | if err != nil { |
| 253 | t.Fatalf("%s slot %d: %v", op, len(held), err) |
| 254 | } |
| 255 | held = append(held, release) |
| 256 | } |
| 257 | return held |
| 258 | } |
| 259 | refused := func(op, what string) { |
| 260 | t.Helper() |
| 261 | status, lines := ask(c, out, as(op), "") |
| 262 | errs := kind(lines, "error") |
| 263 | if status == 0 || len(errs) != 1 { |
| 264 | t.Fatalf("%s was not refused: %d %v", op, status, lines) |
| 265 | } |
| 266 | if e := errs[0]["error"].(string); !telemetry.IsSlotRefusal(e) || !strings.Contains(e, what) { |
| 267 | t.Errorf("%s was refused with %q", op, e) |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | for _, release := range hold(telemetry.OpRead, telemetry.BoundedSlots) { |
| 272 | release() |
| 273 | } |
| 274 | |
| 275 | follows := hold(telemetry.OpFollow, telemetry.FollowSlots) |
| 276 | for _, op := range []string{telemetry.OpSources, telemetry.OpSnapshot, telemetry.OpRead} { |
| 277 | if status, lines := ask(c, out, as(op), ""); status != 0 || len(kind(lines, "end")) != 1 { |
| 278 | t.Errorf("%s with every follow slot held: %d %v", op, status, lines) |
| 279 | } |
| 280 | } |
| 281 | refused(telemetry.OpFollow, "4 follow requests") |
| 282 | for _, release := range follows { |
| 283 | release() |
| 284 | } |
| 285 | |
| 286 | bounded := hold(telemetry.OpSnapshot, telemetry.BoundedSlots) |
| 287 | refused(telemetry.OpRead, "5 bounded requests") |
| 288 | hold(telemetry.OpFollow, 1)[0]() |
| 289 | for _, release := range bounded { |
| 290 | release() |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | // A slot's holder that dies releases it: a process holds every follow |
| 295 | // slot, a follow is refused, and once the process is killed a follow is |
| 296 | // admitted. |
| 297 | func TestADeadHolderReleasesItsSlots(t *testing.T) { |
| 298 | follow := telemetry.Request{V: 1, Principal: "operator", Op: telemetry.OpFollow} |
| 299 | if state := os.Getenv("VALLEY_TEST_SLOT_STATE"); state != "" { |
| 300 | c := &collector{state: state} |
| 301 | var held []func() |
| 302 | for range telemetry.FollowSlots { |
| 303 | release, err := c.slot(follow) |
| 304 | if err != nil { |
| 305 | fmt.Println(err) |
| 306 | os.Exit(1) |
| 307 | } |
| 308 | held = append(held, release) |
| 309 | } |
| 310 | fmt.Println("held") |
| 311 | time.Sleep(time.Hour) |
| 312 | // The lock files stay referenced, so no finalizer closes them |
| 313 | // before the kill. |
| 314 | runtime.KeepAlive(held) |
| 315 | os.Exit(1) |
| 316 | } |
| 317 | c, _, _ := testCollector(t) |
| 318 | holder := exec.Command(os.Args[0], "-test.run=^TestADeadHolderReleasesItsSlots$") |
| 319 | holder.Env = append(os.Environ(), "VALLEY_TEST_SLOT_STATE="+c.state) |
| 320 | stdout, err := holder.StdoutPipe() |
| 321 | if err != nil { |
| 322 | t.Fatal(err) |
| 323 | } |
| 324 | if err := holder.Start(); err != nil { |
| 325 | t.Fatal(err) |
| 326 | } |
| 327 | stopped := false |
| 328 | stop := func() { |
| 329 | if !stopped { |
| 330 | stopped = true |
| 331 | holder.Process.Kill() |
| 332 | holder.Wait() |
| 333 | } |
| 334 | } |
| 335 | defer stop() |
| 336 | if line, _ := bufio.NewReader(stdout).ReadString('\n'); line != "held\n" { |
| 337 | t.Fatalf("the holder said %q", line) |
| 338 | } |
| 339 | if _, err := c.slot(follow); err == nil { |
| 340 | t.Fatal("a follow was admitted while another process held every follow slot") |
| 341 | } |
| 342 | stop() |
| 343 | release, err := c.slot(follow) |
| 344 | if err != nil { |
| 345 | t.Fatalf("a dead holder's slot was not given: %v", err) |
| 346 | } |
| 347 | release() |
| 348 | } |
| 349 | |
| 350 | // One principal cannot take every slot. |
| 351 | func TestSlotsArePerPrincipal(t *testing.T) { |
| 352 | c, _, _ := testCollector(t) |
| 353 | req := telemetry.Request{V: 1, Principal: "alice", Op: telemetry.OpReport} |
| 354 | release, err := c.slot(req) |
| 355 | if err != nil { |
| 356 | t.Fatal(err) |
| 357 | } |
| 358 | if _, err := c.slot(req); err == nil { |
| 359 | t.Fatal("a second report slot was given") |
| 360 | } |
| 361 | other, err := c.slot(telemetry.Request{V: 1, Principal: "operator", Op: telemetry.OpRead}) |
| 362 | if err != nil { |
| 363 | t.Fatalf("another principal was refused: %v", err) |
| 364 | } |
| 365 | other() |
| 366 | release() |
| 367 | if _, err := c.slot(req); err != nil { |
| 368 | t.Fatalf("a released slot was not given again: %v", err) |
| 369 | } |
| 370 | os.RemoveAll(c.state) |
| 371 | } |