gunk-dev/the-valley

collector_test.go

source68d12192bbd3main's published tip history
12.5 KiB
1package main
2
3import (
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
19func 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
46func 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
60func 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
70func 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.
78func 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.
102func 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.
121func 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.
136func 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.
151func 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.
181func 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.
205func 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: four bounded requests at once are admitted, as one valley
239// pending's history reads four pages together (status/checkcost.go); with
240// every follow slot held, a sources, snapshot and read are answered and a
241// fifth follow is refused, naming follows; with every bounded slot held,
242// a read is refused, naming them, and a follow is admitted.
243func TestFollowsAndBoundedRequestsTakeSeparateSlots(t *testing.T) {
244 c, out, _ := testCollector(t)
245 as := func(op string) telemetry.Request { return telemetry.Request{V: 1, Principal: "operator", Op: op} }
246 hold := func(op string, n int) []func() {
247 t.Helper()
248 var held []func()
249 for range n {
250 release, err := c.slot(as(op))
251 if err != nil {
252 t.Fatalf("%s slot %d: %v", op, len(held), err)
253 }
254 held = append(held, release)
255 }
256 return held
257 }
258 refused := func(op, what string) {
259 t.Helper()
260 status, lines := ask(c, out, as(op), "")
261 errs := kind(lines, "error")
262 if status == 0 || len(errs) != 1 {
263 t.Fatalf("%s was not refused: %d %v", op, status, lines)
264 }
265 if e := errs[0]["error"].(string); !telemetry.IsSlotRefusal(e) || !strings.Contains(e, what) {
266 t.Errorf("%s was refused with %q", op, e)
267 }
268 }
269
270 for _, release := range hold(telemetry.OpRead, 4) {
271 release()
272 }
273
274 follows := hold(telemetry.OpFollow, telemetry.FollowSlots)
275 for _, op := range []string{telemetry.OpSources, telemetry.OpSnapshot, telemetry.OpRead} {
276 if status, lines := ask(c, out, as(op), ""); status != 0 || len(kind(lines, "end")) != 1 {
277 t.Errorf("%s with every follow slot held: %d %v", op, status, lines)
278 }
279 }
280 refused(telemetry.OpFollow, "4 follow requests")
281 for _, release := range follows {
282 release()
283 }
284
285 bounded := hold(telemetry.OpSnapshot, telemetry.BoundedSlots)
286 refused(telemetry.OpRead, "4 bounded requests")
287 hold(telemetry.OpFollow, 1)[0]()
288 for _, release := range bounded {
289 release()
290 }
291}
292
293// A slot's holder that dies releases it: a process holds every follow
294// slot, a follow is refused, and once the process is killed a follow is
295// admitted.
296func TestADeadHolderReleasesItsSlots(t *testing.T) {
297 follow := telemetry.Request{V: 1, Principal: "operator", Op: telemetry.OpFollow}
298 if state := os.Getenv("VALLEY_TEST_SLOT_STATE"); state != "" {
299 c := &collector{state: state}
300 var held []func()
301 for range telemetry.FollowSlots {
302 release, err := c.slot(follow)
303 if err != nil {
304 fmt.Println(err)
305 os.Exit(1)
306 }
307 held = append(held, release)
308 }
309 fmt.Println("held")
310 time.Sleep(time.Hour)
311 // The lock files stay referenced, so no finalizer closes them
312 // before the kill.
313 runtime.KeepAlive(held)
314 os.Exit(1)
315 }
316 c, _, _ := testCollector(t)
317 holder := exec.Command(os.Args[0], "-test.run=^TestADeadHolderReleasesItsSlots$")
318 holder.Env = append(os.Environ(), "VALLEY_TEST_SLOT_STATE="+c.state)
319 stdout, err := holder.StdoutPipe()
320 if err != nil {
321 t.Fatal(err)
322 }
323 if err := holder.Start(); err != nil {
324 t.Fatal(err)
325 }
326 stopped := false
327 stop := func() {
328 if !stopped {
329 stopped = true
330 holder.Process.Kill()
331 holder.Wait()
332 }
333 }
334 defer stop()
335 if line, _ := bufio.NewReader(stdout).ReadString('\n'); line != "held\n" {
336 t.Fatalf("the holder said %q", line)
337 }
338 if _, err := c.slot(follow); err == nil {
339 t.Fatal("a follow was admitted while another process held every follow slot")
340 }
341 stop()
342 release, err := c.slot(follow)
343 if err != nil {
344 t.Fatalf("a dead holder's slot was not given: %v", err)
345 }
346 release()
347}
348
349// One principal cannot take every slot.
350func TestSlotsArePerPrincipal(t *testing.T) {
351 c, _, _ := testCollector(t)
352 req := telemetry.Request{V: 1, Principal: "alice", Op: telemetry.OpReport}
353 release, err := c.slot(req)
354 if err != nil {
355 t.Fatal(err)
356 }
357 if _, err := c.slot(req); err == nil {
358 t.Fatal("a second report slot was given")
359 }
360 other, err := c.slot(telemetry.Request{V: 1, Principal: "operator", Op: telemetry.OpRead})
361 if err != nil {
362 t.Fatalf("another principal was refused: %v", err)
363 }
364 other()
365 release()
366 if _, err := c.slot(req); err != nil {
367 t.Fatalf("a released slot was not given again: %v", err)
368 }
369 os.RemoveAll(c.state)
370}