gunk-dev/the-valley

read.go

sourceca98fdc29fbfmain's published tip history
11.3 KiB
1package main
2
3import (
4 "bufio"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "io"
9 "os"
10 "path/filepath"
11 "regexp"
12 "sort"
13 "strconv"
14 "strings"
15 "syscall"
16 "time"
17
18 "the-valley/telemetry"
19)
20
21type recordLine struct {
22 Kind string `json:"kind"`
23 telemetry.Record
24}
25
26// selection is what a read names: every stream, or one source's stream
27// and units.
28func (c *collector) selection(name string) (map[string]*telemetry.Stream, []string, error) {
29 all := c.streams()
30 if name == "" {
31 return all, nil, nil
32 }
33 if st, ok := all[name]; ok && strings.HasPrefix(name, "report.") {
34 return map[string]*telemetry.Stream{name: st}, nil, nil
35 }
36 for _, s := range c.manifest.Sources {
37 if s.Name != name {
38 continue
39 }
40 if !s.Enabled {
41 return nil, nil, fmt.Errorf("%s is not enabled on this host", name)
42 }
43 picked := map[string]*telemetry.Stream{}
44 if sn := c.streamOf(s); sn != "" && all[sn] != nil {
45 picked[sn] = all[sn]
46 }
47 return picked, s.Units, nil
48 }
49 return nil, nil, fmt.Errorf("no source is named %s; valley telemetry sources lists them", name)
50}
51
52func sortedNames(m map[string]*telemetry.Stream) []string {
53 names := make([]string, 0, len(m))
54 for n := range m {
55 names = append(names, n)
56 }
57 sort.Strings(names)
58 return names
59}
60
61// read answers a read: the selected units' lifecycle from the journal
62// (and their own output, with logs), each selected stream's records after
63// the cursor, and with logs the tail of each stream's newest build logs.
64// A stream the cursor does not name is read from its newest records.
65func (c *collector) read(req telemetry.Request) (telemetry.Cursor, error) {
66 cur, err := telemetry.ParseCursor(req.Cursor)
67 if err != nil {
68 return nil, err
69 }
70 streams, units, err := c.selection(req.Source)
71 if err != nil {
72 return nil, err
73 }
74 if len(units) > 0 {
75 entries, err := c.journal(units, req.Limit, req.Logs)
76 if err != nil {
77 c.out.send(map[string]any{"kind": "unavailable", "what": "journal", "error": err.Error()})
78 }
79 for _, e := range entries {
80 if e.Lifecycle {
81 c.out.send(map[string]any{"kind": "lifecycle", "time": e.Time, "unit": e.Unit, "message": e.Message})
82 } else {
83 c.out.send(map[string]any{"kind": "log", "untrusted": true, "time": e.Time, "unit": e.Unit, "text": e.Message})
84 }
85 }
86 }
87 for _, name := range sortedNames(streams) {
88 c.readStream(name, streams[name], cur, req.Limit, false, req.Logs)
89 }
90 if req.Logs {
91 for _, name := range sortedNames(streams) {
92 for i, l := range streams[name].Logs() {
93 if i == 8 {
94 break
95 }
96 c.sendLog(name, l, max(l.Size-telemetry.LogTailBytes, 0), l.Size)
97 }
98 }
99 }
100 return cur, nil
101}
102
103// readStream sends a stream's records after the cursor's position, and
104// moves the cursor past them. A position in another epoch, or older than
105// the stream still holds, is a gap, and is said. With fromEnd, a stream
106// the cursor does not name starts after its newest record; otherwise
107// with its newest limit records. A record of a check's own output is
108// sent only with logs, made safe to show and marked untrusted.
109func (c *collector) readStream(name string, st *telemetry.Stream, cur telemetry.Cursor, limit int, fromEnd, logs bool) {
110 rng, err := st.Range()
111 if errors.Is(err, os.ErrNotExist) {
112 return
113 }
114 if err != nil {
115 c.out.send(map[string]any{"kind": "unavailable", "what": name, "error": err.Error()})
116 return
117 }
118 pos, known := cur[name]
119 after := pos.Seq
120 switch {
121 case !known && fromEnd:
122 after = rng.Last
123 case !known:
124 after = max(rng.Last-int64(limit), rng.First-1)
125 case pos.Epoch != rng.Epoch:
126 c.out.send(map[string]any{"kind": "gap", "stream": name, "reason": "reset",
127 "detail": "the stream was made again since the cursor was given; it is read from its start"})
128 after = rng.First - 1
129 case after+1 < rng.First:
130 c.out.send(map[string]any{"kind": "gap", "stream": name, "reason": "retention", "from": after + 1, "to": rng.First - 1,
131 "detail": "these records were removed to keep the stream within its bound"})
132 after = rng.First - 1
133 case after > rng.Last:
134 c.out.send(map[string]any{"kind": "gap", "stream": name, "reason": "ahead",
135 "detail": "the cursor is past the stream's newest record"})
136 after = rng.Last
137 }
138 recs, _, err := st.Read(after, limit, telemetry.MaxResponseBytes/2)
139 if err != nil {
140 c.out.send(map[string]any{"kind": "unavailable", "what": name, "error": err.Error()})
141 }
142 cur[name] = telemetry.Position{Epoch: rng.Epoch, Seq: after}
143 for _, r := range recs {
144 r.Stream = name
145 if r.Untrusted() && !logs {
146 cur[name] = telemetry.Position{Epoch: rng.Epoch, Seq: r.Seq}
147 continue
148 }
149 if r.Untrusted() {
150 r.Data["text"] = telemetry.Sanitize(fmt.Sprint(r.Data["text"]))
151 r.Data["untrusted"] = true
152 }
153 if !c.out.send(recordLine{"record", r}) {
154 return
155 }
156 cur[name] = telemetry.Position{Epoch: rng.Epoch, Seq: r.Seq}
157 }
158}
159
160// sendLog sends the bytes of a build log from one offset to another. It
161// is untrusted text: the check's own output.
162func (c *collector) sendLog(stream string, l telemetry.LogEntry, from, to int64) bool {
163 f, err := os.OpenFile(l.Path, os.O_RDONLY|syscall.O_NOFOLLOW|syscall.O_NONBLOCK, 0)
164 if err != nil {
165 return true
166 }
167 defer f.Close()
168 buf := make([]byte, min(to-from, telemetry.LogTailBytes))
169 n, _ := f.ReadAt(buf, from)
170 return c.out.send(map[string]any{"kind": "log", "untrusted": true, "stream": stream, "run": l.Run, "check": l.Check,
171 "from": from, "to": from + int64(n), "size": l.Size, "capped": l.Size >= telemetry.MaxLogBytes,
172 "text": telemetry.Sanitize(string(buf[:n]))})
173}
174
175// follow sends what the selected streams store from now on, and with
176// logs the build output written from now on, until the request's seconds
177// are up. A heartbeat every heartbeatEvery carries the cursor, so a
178// reader that loses the connection resumes from it.
179func (c *collector) follow(req telemetry.Request) telemetry.Cursor {
180 cur, err := telemetry.ParseCursor(req.Cursor)
181 if err != nil {
182 c.out.fail("%v", err)
183 return nil
184 }
185 streams, _, err := c.selection(req.Source)
186 if err != nil {
187 c.out.fail("%v", err)
188 return nil
189 }
190 deadline := c.now().Add(time.Duration(req.Seconds) * time.Second)
191 offsets := map[string]int64{}
192 if req.Logs {
193 for _, st := range streams {
194 for _, l := range st.Logs() {
195 // What a run still writing has written so far, up to the
196 // last 4 KiB of it, and nothing of the logs of runs that
197 // have long ended.
198 if c.now().Sub(l.Mod) < time.Minute {
199 offsets[l.Path] = max(l.Size-4096, 0)
200 } else {
201 offsets[l.Path] = l.Size
202 }
203 }
204 }
205 }
206 beat := c.now()
207 for {
208 for _, name := range sortedNames(streams) {
209 c.readStream(name, streams[name], cur, telemetry.DefaultReadLimit, true, req.Logs)
210 }
211 if req.Logs {
212 for _, name := range sortedNames(streams) {
213 for _, l := range streams[name].Logs() {
214 if from, seen := offsets[l.Path]; !seen || l.Size > from {
215 if c.sendLog(name, l, from, l.Size) {
216 offsets[l.Path] = min(l.Size, from+telemetry.LogTailBytes)
217 }
218 }
219 }
220 }
221 }
222 if c.out.err != nil || c.out.truncated || !c.now().Before(deadline) {
223 return cur
224 }
225 if c.now().Sub(beat) >= heartbeatEvery {
226 beat = c.now()
227 c.out.send(map[string]any{"kind": "heartbeat", "time": telemetry.Stamp(beat), "cursor": cur.String()})
228 }
229 time.Sleep(pollEvery)
230 }
231}
232
233var (
234 pollEvery = time.Second
235 heartbeatEvery = 10 * time.Second
236)
237
238var clientIDRE = regexp.MustCompile(`^([0-9a-f]{16}):([0-9]{1,18})$`)
239
240// watermark is the newest record of one sender's spool the collector has
241// stored. A record at or below it is a retry, and is not stored again.
242type watermark struct {
243 Seq int64 `json:"seq"`
244 Touched string `json:"touched"`
245}
246
247const maxWatermarks = 64
248
249// report stores the records a reporter sends: each checked against the
250// format and the types a client may send, stamped with the principal and
251// the time it was received, and stored in the principal's own bounded
252// stream. A record the sender already delivered is counted and dropped.
253// The answer is one ack line saying what happened to each.
254func (c *collector) report(principal string, in *bufio.Reader) error {
255 st := c.reportStream(principal)
256 if err := os.MkdirAll(st.Dir, 0o700); err != nil {
257 return err
258 }
259 wmPath := filepath.Join(c.state, "reports", principal+".watermarks.json")
260 wm := map[string]watermark{}
261 if data, err := os.ReadFile(wmPath); err == nil {
262 json.Unmarshal(data, &wm)
263 }
264 body := bufio.NewReader(io.LimitReader(in, telemetry.MaxReportBytes+1))
265 accepted, duplicates, rejected, n, size := 0, 0, 0, 0, 0
266 var problems []string
267 reject := func(err error) {
268 rejected++
269 if len(problems) < 8 {
270 problems = append(problems, fmt.Sprintf("record %d: %v", n, err))
271 }
272 }
273 now := telemetry.Stamp(c.now())
274 for {
275 line, err := readLine(body, telemetry.MaxRecordBytes)
276 if errors.Is(err, io.EOF) {
277 break
278 }
279 n++
280 if err != nil {
281 reject(err)
282 break
283 }
284 size += len(line) + 1
285 if size > telemetry.MaxReportBytes || n > telemetry.MaxReportRecords {
286 reject(fmt.Errorf("a report holds at most %d records and %d bytes; the rest is refused", telemetry.MaxReportRecords, telemetry.MaxReportBytes))
287 break
288 }
289 r, err := telemetry.DecodeRecord(line)
290 if err != nil {
291 reject(err)
292 continue
293 }
294 m := clientIDRE.FindStringSubmatch(r.ClientID)
295 switch {
296 case m == nil:
297 err = errors.New("no client_id of the form epoch:seq")
298 case r.Stream != "" || r.Seq != 0 || r.Principal != "" || r.Received != "":
299 err = errors.New("stream, seq, principal and received are the collector's to set")
300 case !telemetry.ClientType(r.Type):
301 err = fmt.Errorf("a client may not report %q", r.Type)
302 default:
303 err = r.Validate()
304 }
305 if err != nil {
306 reject(err)
307 continue
308 }
309 epoch := m[1]
310 seq, _ := strconv.ParseInt(m[2], 10, 64)
311 w, known := wm[epoch]
312 if seq <= w.Seq {
313 duplicates++
314 continue
315 }
316 if seq > w.Seq+1 {
317 gap := telemetry.Record{Type: "report.gap", Time: now, Principal: principal, Received: now,
318 Data: map[string]any{"epoch": epoch, "from": w.Seq + 1, "to": seq - 1, "known": known}}
319 st.Append(&gap)
320 }
321 r.Principal, r.Received = principal, now
322 if _, err := st.Append(&r); err != nil {
323 reject(err)
324 break
325 }
326 accepted++
327 wm[epoch] = watermark{seq, now}
328 }
329 if len(wm) > maxWatermarks {
330 type kv struct {
331 k string
332 w watermark
333 }
334 var all []kv
335 for k, w := range wm {
336 all = append(all, kv{k, w})
337 }
338 sort.Slice(all, func(i, j int) bool { return all[i].w.Touched > all[j].w.Touched })
339 for _, e := range all[maxWatermarks:] {
340 delete(wm, e.k)
341 }
342 }
343 if err := writeAtomic(wmPath, wm); err != nil {
344 return err
345 }
346 acked := map[string]int64{}
347 for k, w := range wm {
348 acked[k] = w.Seq
349 }
350 c.out.send(map[string]any{"kind": "ack", "accepted": accepted, "duplicates": duplicates,
351 "rejected": rejected, "problems": problems, "acked": acked, "received": now})
352 c.out.end(nil)
353 // What a refused report still had to send is read and dropped: a unix
354 // socket closed with unread data resets its peer, and the sender would
355 // lose the answer above.
356 io.Copy(io.Discard, io.LimitReader(in, telemetry.MaxReportBytes+1))
357 return nil
358}
359
360func writeAtomic(path string, v any) error {
361 data, err := json.Marshal(v)
362 if err != nil {
363 return err
364 }
365 tmp, err := os.CreateTemp(filepath.Dir(path), ".tmp-*")
366 if err != nil {
367 return err
368 }
369 _, err = tmp.Write(data)
370 if cerr := tmp.Close(); err == nil {
371 err = cerr
372 }
373 if err == nil {
374 err = os.Rename(tmp.Name(), path)
375 }
376 if err != nil {
377 os.Remove(tmp.Name())
378 }
379 return err
380}