| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "bytes" |
| 6 | "encoding/json" |
| 7 | "fmt" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | "time" |
| 13 | |
| 14 | "the-valley/telemetry" |
| 15 | ) |
| 16 | |
| 17 | func testCollector(t *testing.T) (*collector, *bytes.Buffer, string) { |
| 18 | t.Helper() |
| 19 | dir := t.TempDir() |
| 20 | worker := filepath.Join(dir, "worker") |
| 21 | c := &collector{ |
| 22 | manifest: manifest{V: 1, Host: "valley-host", Reporters: []string{"alice"}, Sources: []source{ |
| 23 | {Name: "worker", Enabled: true, Location: "local", Units: []string{"valley-worker.service"}, Stream: worker}, |
| 24 | {Name: "bus", Enabled: false, Location: "local", Units: []string{"valley-bus.service"}}, |
| 25 | }}, |
| 26 | grants: map[string]map[string]bool{"operator": {"observe": true}, "alice": {"report": true}}, |
| 27 | state: filepath.Join(dir, "collector"), |
| 28 | now: time.Now, |
| 29 | systemctl: func(units []string) ([]unitState, error) { |
| 30 | var s []unitState |
| 31 | for _, u := range units { |
| 32 | s = append(s, unitState{"Id": u, "LoadState": "loaded", "ActiveState": "inactive", "Result": "success"}) |
| 33 | } |
| 34 | return s, nil |
| 35 | }, |
| 36 | journal: func([]string, int, bool) ([]journalEntry, error) { return nil, nil }, |
| 37 | horizon: func([]string) string { return "" }, |
| 38 | } |
| 39 | out := &bytes.Buffer{} |
| 40 | c.out = &output{w: out} |
| 41 | return c, out, worker |
| 42 | } |
| 43 | |
| 44 | func ask(c *collector, out *bytes.Buffer, req telemetry.Request, body string) (int, []map[string]any) { |
| 45 | out.Reset() |
| 46 | c.out = &output{w: out} |
| 47 | line, _ := json.Marshal(req) |
| 48 | status := c.handle(bufio.NewReader(strings.NewReader(string(line)+"\n"+body)), nil) |
| 49 | var lines []map[string]any |
| 50 | for _, l := range strings.Split(strings.TrimSpace(out.String()), "\n") { |
| 51 | var m map[string]any |
| 52 | json.Unmarshal([]byte(l), &m) |
| 53 | lines = append(lines, m) |
| 54 | } |
| 55 | return status, lines |
| 56 | } |
| 57 | |
| 58 | func kind(lines []map[string]any, k string) []map[string]any { |
| 59 | var out []map[string]any |
| 60 | for _, l := range lines { |
| 61 | if l["kind"] == k { |
| 62 | out = append(out, l) |
| 63 | } |
| 64 | } |
| 65 | return out |
| 66 | } |
| 67 | |
| 68 | func clientRecord(epoch string, seq int, typ string) string { |
| 69 | r := telemetry.Record{Type: typ, Time: telemetry.Stamp(time.Now()), Run: "r1", ClientID: fmt.Sprintf("%s:%d", epoch, seq)} |
| 70 | b, _ := json.Marshal(r) |
| 71 | return string(b) + "\n" |
| 72 | } |
| 73 | |
| 74 | // A report is stored under the principal that sent it, stamped when it |
| 75 | // arrived, and a retried record is not stored twice. |
| 76 | func TestAReportIsStampedAndARetryIsHarmless(t *testing.T) { |
| 77 | c, out, _ := testCollector(t) |
| 78 | epoch := "0123456789abcdef" |
| 79 | body := clientRecord(epoch, 1, "approve.start") + clientRecord(epoch, 2, "check.result") |
| 80 | report := telemetry.Request{V: 1, Principal: "alice", Op: telemetry.OpReport} |
| 81 | status, lines := ask(c, out, report, body) |
| 82 | ack := kind(lines, "ack") |
| 83 | if status != 0 || len(ack) != 1 || ack[0]["accepted"] != 2.0 { |
| 84 | t.Fatalf("first report: %d %v", status, lines) |
| 85 | } |
| 86 | _, lines = ask(c, out, report, body+clientRecord(epoch, 4, "approve.end")) |
| 87 | ack = kind(lines, "ack") |
| 88 | if ack[0]["accepted"] != 1.0 || ack[0]["duplicates"] != 2.0 { |
| 89 | t.Fatalf("retried report: %v", ack) |
| 90 | } |
| 91 | recs, _, _ := c.reportStream("alice").Read(0, 100, 0) |
| 92 | if len(recs) != 4 || recs[2].Type != "report.gap" || recs[0].Principal != "alice" || recs[0].Received == "" { |
| 93 | t.Fatalf("stored %+v", recs) |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | // What a reporter may not say is refused record by record: a field the |
| 98 | // format lacks, a principal or receipt of its own, a host producer's |
| 99 | // type, a record without its own ID. |
| 100 | func TestAReportCannotSpeakForAnother(t *testing.T) { |
| 101 | c, out, _ := testCollector(t) |
| 102 | now := telemetry.Stamp(time.Now()) |
| 103 | body := strings.Join([]string{ |
| 104 | `{"type":"approve.start","time":"` + now + `","client_id":"0123456789abcdef:1","principal":"operator"}`, |
| 105 | `{"type":"approve.start","time":"` + now + `","client_id":"0123456789abcdef:2","received":"` + now + `"}`, |
| 106 | `{"type":"pass.start","time":"` + now + `","client_id":"0123456789abcdef:3"}`, |
| 107 | `{"type":"approve.start","time":"` + now + `","client_id":"0123456789abcdef:4","command":"rm -rf /"}`, |
| 108 | `{"type":"approve.start","time":"` + now + `"}`, |
| 109 | `not json`, |
| 110 | }, "\n") + "\n" |
| 111 | _, lines := ask(c, out, telemetry.Request{V: 1, Principal: "alice", Op: telemetry.OpReport}, body) |
| 112 | ack := kind(lines, "ack") |
| 113 | if len(ack) != 1 || ack[0]["accepted"] != 0.0 || ack[0]["rejected"] != 6.0 { |
| 114 | t.Fatalf("ack %v", lines) |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | // A report larger than its bound is cut off there, and says so. |
| 119 | func TestAReportIsBounded(t *testing.T) { |
| 120 | c, out, _ := testCollector(t) |
| 121 | var body strings.Builder |
| 122 | for i := 1; i <= telemetry.MaxReportRecords+10; i++ { |
| 123 | body.WriteString(clientRecord("0123456789abcdef", i, "check.queued")) |
| 124 | } |
| 125 | _, lines := ask(c, out, telemetry.Request{V: 1, Principal: "alice", Op: telemetry.OpReport}, body.String()) |
| 126 | ack := kind(lines, "ack") |
| 127 | if ack[0]["accepted"] != float64(telemetry.MaxReportRecords) || ack[0]["rejected"] != 1.0 { |
| 128 | t.Fatalf("ack %v", ack) |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | // Reading needs observe, reporting needs report, and neither implies the |
| 133 | // other. |
| 134 | func TestEachOperationNeedsItsGrant(t *testing.T) { |
| 135 | c, out, _ := testCollector(t) |
| 136 | for _, req := range []telemetry.Request{ |
| 137 | {V: 1, Principal: "alice", Op: telemetry.OpSources}, |
| 138 | {V: 1, Principal: "operator", Op: telemetry.OpReport}, |
| 139 | {V: 1, Principal: "mallory", Op: telemetry.OpRead}, |
| 140 | } { |
| 141 | if status, lines := ask(c, out, req, ""); status == 0 || len(kind(lines, "error")) != 1 { |
| 142 | t.Errorf("%s %s: %d %v", req.Principal, req.Op, status, lines) |
| 143 | } |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | // A cursor older than what a stream keeps reads as a gap, a cursor of a |
| 148 | // stream made again reads as a reset, and both resume at what is there. |
| 149 | func TestACursorGapIsSaid(t *testing.T) { |
| 150 | c, out, worker := testCollector(t) |
| 151 | st := &telemetry.Stream{Dir: worker, SegmentBytes: 1024, Segments: 2} |
| 152 | for i := 0; i < 40; i++ { |
| 153 | st.Append(&telemetry.Record{Type: "check.queued", Time: telemetry.Stamp(time.Now()), Run: "r1", Check: fmt.Sprintf("c%d", i)}) |
| 154 | } |
| 155 | rng, _ := st.Range() |
| 156 | read := telemetry.Request{V: 1, Principal: "operator", Op: telemetry.OpRead, Source: "worker", Cursor: "worker=" + rng.Epoch + ":3"} |
| 157 | _, lines := ask(c, out, read, "") |
| 158 | gaps := kind(lines, "gap") |
| 159 | if len(gaps) != 1 || gaps[0]["reason"] != "retention" || gaps[0]["to"] != float64(rng.First-1) { |
| 160 | t.Fatalf("gap %v", lines) |
| 161 | } |
| 162 | end := kind(lines, "end") |
| 163 | if end[0]["cursor"] != fmt.Sprintf("worker=%s:%d", rng.Epoch, rng.Last) { |
| 164 | t.Fatalf("end %v", end) |
| 165 | } |
| 166 | read.Cursor = "worker=fedcba9876543210:3" |
| 167 | _, lines = ask(c, out, read, "") |
| 168 | if gaps := kind(lines, "gap"); len(gaps) != 1 || gaps[0]["reason"] != "reset" { |
| 169 | t.Fatalf("reset %v", lines) |
| 170 | } |
| 171 | read.Source = "bus" |
| 172 | if status, _ := ask(c, out, read, ""); status == 0 { |
| 173 | t.Fatal("a disabled source read") |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | // A run its stream holds open while no unit of the source runs was |
| 178 | // interrupted; the source says so rather than idle. |
| 179 | func TestAnOpenRunWithNoUnitRunningIsStale(t *testing.T) { |
| 180 | c, out, worker := testCollector(t) |
| 181 | st := &telemetry.Stream{Dir: worker} |
| 182 | st.Append(&telemetry.Record{Type: "pass.start", Time: telemetry.Stamp(time.Now()), Run: "r1"}) |
| 183 | _, lines := ask(c, out, telemetry.Request{V: 1, Principal: "operator", Op: telemetry.OpSnapshot}, "") |
| 184 | for _, s := range kind(lines, "source") { |
| 185 | switch s["name"] { |
| 186 | case "worker": |
| 187 | if s["state"] != "stale" { |
| 188 | t.Errorf("worker %v", s) |
| 189 | } |
| 190 | case "bus": |
| 191 | if s["state"] != "disabled" { |
| 192 | t.Errorf("bus %v", s) |
| 193 | } |
| 194 | case "report.alice": |
| 195 | if s["state"] != "idle" { |
| 196 | t.Errorf("reports %v", s) |
| 197 | } |
| 198 | } |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | // A follower sees build output as it is written, and ends with a cursor. |
| 203 | func TestFollowStreamsBuildOutputAsItIsWritten(t *testing.T) { |
| 204 | c, out, worker := testCollector(t) |
| 205 | pollEvery = 50 * time.Millisecond |
| 206 | st := &telemetry.Stream{Dir: worker} |
| 207 | st.Append(&telemetry.Record{Type: "run.start", Time: telemetry.Stamp(time.Now()), Run: "r1"}) |
| 208 | log := st.Log("r1", "slow", telemetry.MaxLogBytes) |
| 209 | log.Write([]byte("before\n")) |
| 210 | go func() { |
| 211 | time.Sleep(300 * time.Millisecond) |
| 212 | log.Write([]byte("during \x1b[31mred\n")) |
| 213 | st.Append(&telemetry.Record{Type: "check.result", Time: telemetry.Stamp(time.Now()), Run: "r1", Check: "fast"}) |
| 214 | }() |
| 215 | _, lines := ask(c, out, telemetry.Request{V: 1, Principal: "operator", Op: telemetry.OpFollow, Seconds: 1, Logs: true}, "") |
| 216 | var text string |
| 217 | for _, l := range kind(lines, "log") { |
| 218 | text += l["text"].(string) |
| 219 | if l["untrusted"] != true { |
| 220 | t.Errorf("log not marked untrusted: %v", l) |
| 221 | } |
| 222 | } |
| 223 | if !strings.Contains(text, "before") || !strings.Contains(text, `during \x1b[31mred`) { |
| 224 | t.Fatalf("followed %q", text) |
| 225 | } |
| 226 | recs := kind(lines, "record") |
| 227 | if len(recs) != 1 || recs[0]["check"] != "fast" { |
| 228 | t.Fatalf("records %v", recs) |
| 229 | } |
| 230 | if end := kind(lines, "end"); len(end) != 1 || !strings.HasPrefix(end[0]["cursor"].(string), "worker=") { |
| 231 | t.Fatalf("end %v", end) |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | // One principal cannot take every slot. |
| 236 | func TestSlotsArePerPrincipal(t *testing.T) { |
| 237 | c, _, _ := testCollector(t) |
| 238 | req := telemetry.Request{V: 1, Principal: "alice", Op: telemetry.OpReport} |
| 239 | release, err := c.slot(req) |
| 240 | if err != nil { |
| 241 | t.Fatal(err) |
| 242 | } |
| 243 | if _, err := c.slot(req); err == nil { |
| 244 | t.Fatal("a second report slot was given") |
| 245 | } |
| 246 | other, err := c.slot(telemetry.Request{V: 1, Principal: "operator", Op: telemetry.OpRead}) |
| 247 | if err != nil { |
| 248 | t.Fatalf("another principal was refused: %v", err) |
| 249 | } |
| 250 | other() |
| 251 | release() |
| 252 | if _, err := c.slot(req); err != nil { |
| 253 | t.Fatalf("a released slot was not given again: %v", err) |
| 254 | } |
| 255 | os.RemoveAll(c.state) |
| 256 | } |