gunk-dev/the-valley

store.go

source734bfb035238main's published tip history
14.9 KiB
1package telemetry
2
3// A stream is a directory of records, numbered in the order they were
4// stored, and bounded: records go into segment files of SegmentBytes, and
5// only the newest Segments of them are kept. So a stream never holds more
6// than about SegmentBytes × Segments, and its oldest records are the ones
7// it loses.
8//
9// epoch random, made once: a stream made again is
10// a different stream
11// lock flock'd by every writer while it appends
12// seg-<first seq>.jsonl records, one JSON line each
13// logs/<run>/<check>.log build output, each file bounded
14//
15// Writers in more than one process share a stream: each append holds the
16// lock, reads the last number stored and stores the next one. A reader
17// takes no lock. It reads whole lines only, so a line being written is
18// read on the next pass.
19//
20// A stream a producer exports for the collector is group-readable
21// (Shared): its files are made 0640, and its directories inherit the
22// collector's group from the exported directory the host makes (mkdir).
23// Nothing else in the producer's state is.
24
25import (
26 "bufio"
27 "bytes"
28 "crypto/rand"
29 "encoding/hex"
30 "encoding/json"
31 "errors"
32 "fmt"
33 "io"
34 "io/fs"
35 "os"
36 "path/filepath"
37 "sort"
38 "strconv"
39 "strings"
40 "sync"
41 "syscall"
42 "time"
43)
44
45// Stream is one stream directory and its bounds.
46type Stream struct {
47 Dir string
48 SegmentBytes int64 // default 1 MiB
49 Segments int // default 8
50 Shared bool // group-readable, for the collector
51 LockWait time.Duration
52}
53
54func (s *Stream) segmentBytes() int64 {
55 if s.SegmentBytes > 0 {
56 return s.SegmentBytes
57 }
58 return 1 << 20
59}
60
61func (s *Stream) segments() int {
62 if s.Segments > 0 {
63 return s.Segments
64 }
65 return 8
66}
67
68func (s *Stream) dirMode() os.FileMode {
69 if s.Shared {
70 return 0o750
71 }
72 return 0o700
73}
74
75func (s *Stream) fileMode() os.FileMode {
76 if s.Shared {
77 return 0o640
78 }
79 return 0o600
80}
81
82// mkdir makes a directory of the stream. A private stream's is made
83// owner-only whatever the umask. A shared stream's takes its group, and the
84// setgid bit that passes the group on, from the exported directory above
85// it, and its mode from the producer's umask, which the host sets to keep
86// group read: a chmod by a producer outside that group would drop the
87// setgid bit, and every file made after it would be unreadable to the
88// collector.
89func (s *Stream) mkdir(dir string) error {
90 if err := os.MkdirAll(dir, s.dirMode()); err != nil {
91 return err
92 }
93 if s.Shared {
94 return nil
95 }
96 return os.Chmod(dir, s.dirMode())
97}
98
99// create opens a file of the stream for appending, made with its mode.
100func (s *Stream) create(path string) (*os.File, error) {
101 f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND|syscall.O_NOFOLLOW|syscall.O_NONBLOCK, s.fileMode())
102 if err != nil {
103 return nil, err
104 }
105 info, err := f.Stat()
106 if err != nil || !info.Mode().IsRegular() {
107 f.Close()
108 return nil, fmt.Errorf("%s is not a regular file", path)
109 }
110 if info.Mode().Perm() != s.fileMode() {
111 if err := f.Chmod(s.fileMode()); err != nil {
112 f.Close()
113 return nil, err
114 }
115 }
116 return f, nil
117}
118
119// Epoch is the stream's random name, made the first time it is asked for.
120func (s *Stream) Epoch() (string, error) {
121 path := filepath.Join(s.Dir, "epoch")
122 if data, err := readSmall(path); err == nil {
123 if e := strings.TrimSpace(string(data)); epochRE.MatchString(e) {
124 return e, nil
125 }
126 return "", fmt.Errorf("%s does not hold an epoch", path)
127 }
128 if err := s.mkdir(s.Dir); err != nil {
129 return "", err
130 }
131 var b [8]byte
132 if _, err := rand.Read(b[:]); err != nil {
133 return "", err
134 }
135 e := hex.EncodeToString(b[:])
136 // Written whole under another name and linked into place, so no
137 // reader sees an epoch file without its epoch, and of two writers
138 // making it at once one wins and the other reads its epoch.
139 tmp, err := os.CreateTemp(s.Dir, ".epoch-*")
140 if err != nil {
141 return "", err
142 }
143 defer os.Remove(tmp.Name())
144 _, err = tmp.WriteString(e + "\n")
145 if err == nil {
146 err = tmp.Chmod(s.fileMode())
147 }
148 if cerr := tmp.Close(); err == nil {
149 err = cerr
150 }
151 if err != nil {
152 return "", err
153 }
154 if err := os.Link(tmp.Name(), path); errors.Is(err, fs.ErrExist) {
155 return s.Epoch()
156 } else if err != nil {
157 return "", err
158 }
159 return e, nil
160}
161
162// lock takes the stream's lock, waiting at most LockWait for it.
163func (s *Stream) lock() (*os.File, error) {
164 f, err := s.create(filepath.Join(s.Dir, "lock"))
165 if err != nil {
166 return nil, err
167 }
168 wait := s.LockWait
169 if wait == 0 {
170 wait = 2 * time.Second
171 }
172 deadline := time.Now().Add(wait)
173 for {
174 err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
175 if err == nil {
176 return f, nil
177 }
178 if !errors.Is(err, syscall.EWOULDBLOCK) || time.Now().After(deadline) {
179 f.Close()
180 return nil, fmt.Errorf("the lock of %s: %w", s.Dir, err)
181 }
182 time.Sleep(10 * time.Millisecond)
183 }
184}
185
186type segment struct {
187 path string
188 first int64
189}
190
191// list is the stream's segments, oldest first.
192func (s *Stream) list() ([]segment, error) {
193 entries, err := os.ReadDir(s.Dir)
194 if err != nil {
195 return nil, err
196 }
197 var segs []segment
198 for _, e := range entries {
199 name := e.Name()
200 if !strings.HasPrefix(name, "seg-") || !strings.HasSuffix(name, ".jsonl") {
201 continue
202 }
203 n, err := strconv.ParseInt(strings.TrimSuffix(strings.TrimPrefix(name, "seg-"), ".jsonl"), 10, 64)
204 if err != nil || n < 1 {
205 continue
206 }
207 segs = append(segs, segment{filepath.Join(s.Dir, name), n})
208 }
209 sort.Slice(segs, func(i, j int) bool { return segs[i].first < segs[j].first })
210 return segs, nil
211}
212
213func segmentName(first int64) string { return fmt.Sprintf("seg-%016d.jsonl", first) }
214
215// lastSeq is the number of the last whole record in a segment, or one
216// before its first when it holds none.
217func lastSeq(seg segment) (int64, bool, error) {
218 f, err := os.OpenFile(seg.path, os.O_RDONLY|syscall.O_NOFOLLOW|syscall.O_NONBLOCK, 0)
219 if err != nil {
220 return 0, false, err
221 }
222 defer f.Close()
223 info, err := f.Stat()
224 if err != nil {
225 return 0, false, err
226 }
227 size := info.Size()
228 if size == 0 {
229 return seg.first - 1, true, nil
230 }
231 from := max(size-64<<10, 0)
232 buf := make([]byte, size-from)
233 if _, err := f.ReadAt(buf, from); err != nil && !errors.Is(err, io.EOF) {
234 return 0, false, err
235 }
236 whole := buf[len(buf)-1] == '\n'
237 lines := bytes.Split(bytes.TrimRight(buf, "\n"), []byte("\n"))
238 for i := len(lines) - 1; i >= 0; i-- {
239 var r struct {
240 Seq int64 `json:"seq"`
241 }
242 if json.Unmarshal(lines[i], &r) == nil && r.Seq >= seg.first {
243 return r.Seq, whole, nil
244 }
245 }
246 return seg.first - 1, whole, nil
247}
248
249// Append stores a record as the stream's next, and returns its number.
250// The record is checked first (Validate), and its Stream and Seq are the
251// stream's to set.
252func (s *Stream) Append(r *Record) (int64, error) {
253 if err := r.Validate(); err != nil {
254 return 0, err
255 }
256 if _, err := s.Epoch(); err != nil {
257 return 0, err
258 }
259 lock, err := s.lock()
260 if err != nil {
261 return 0, err
262 }
263 defer lock.Close()
264
265 segs, err := s.list()
266 if err != nil {
267 return 0, err
268 }
269 seq := int64(1)
270 var cur segment
271 whole := true
272 if len(segs) > 0 {
273 cur = segs[len(segs)-1]
274 last, w, err := lastSeq(cur)
275 if err != nil {
276 return 0, err
277 }
278 seq, whole = last+1, w
279 if info, err := os.Stat(cur.path); err != nil || info.Size() >= s.segmentBytes() {
280 cur = segment{}
281 }
282 }
283 total := len(segs)
284 if cur.path == "" {
285 cur = segment{filepath.Join(s.Dir, segmentName(seq)), seq}
286 whole = true
287 total++
288 }
289 r.Stream, r.Seq = "", seq
290 line, err := json.Marshal(r)
291 if err != nil {
292 return 0, err
293 }
294 if !whole {
295 // A writer that stopped half way through a line left it
296 // unterminated; the line is ended, and readers skip it.
297 line = append([]byte("\n"), line...)
298 }
299 f, err := s.create(cur.path)
300 if err != nil {
301 return 0, err
302 }
303 _, err = f.Write(append(line, '\n'))
304 if cerr := f.Close(); err == nil {
305 err = cerr
306 }
307 if err != nil {
308 return 0, err
309 }
310 for _, old := range segs[:max(total-s.segments(), 0)] {
311 os.Remove(old.path)
312 }
313 return seq, nil
314}
315
316// Range is what a stream holds: its epoch, and the numbers of its oldest
317// and newest records. An empty stream has First = Last + 1.
318type Range struct {
319 Epoch string `json:"epoch"`
320 First int64 `json:"first"`
321 Last int64 `json:"last"`
322}
323
324// Range reads the stream's range without reading its records.
325func (s *Stream) Range() (Range, error) {
326 data, err := readSmall(filepath.Join(s.Dir, "epoch"))
327 if err != nil {
328 return Range{}, err
329 }
330 rng := Range{Epoch: strings.TrimSpace(string(data)), First: 1}
331 segs, err := s.list()
332 if err != nil {
333 return rng, err
334 }
335 if len(segs) == 0 {
336 return rng, nil
337 }
338 rng.First = segs[0].first
339 rng.Last, _, err = lastSeq(segs[len(segs)-1])
340 return rng, err
341}
342
343// Read returns the stream's records numbered after after, oldest first, at
344// most limit of them and about maxBytes of them, and the stream's range.
345// A line that does not read as a record is skipped.
346func (s *Stream) Read(after int64, limit int, maxBytes int) ([]Record, Range, error) {
347 rng, err := s.Range()
348 if err != nil {
349 return nil, rng, err
350 }
351 segs, err := s.list()
352 if err != nil {
353 return nil, rng, err
354 }
355 var out []Record
356 size := 0
357 for i, seg := range segs {
358 if i+1 < len(segs) && segs[i+1].first <= after+1 {
359 continue
360 }
361 f, err := os.OpenFile(seg.path, os.O_RDONLY|syscall.O_NOFOLLOW|syscall.O_NONBLOCK, 0)
362 if errors.Is(err, fs.ErrNotExist) {
363 continue // pruned since it was listed
364 }
365 if err != nil {
366 return out, rng, err
367 }
368 sc := bufio.NewScanner(f)
369 sc.Buffer(make([]byte, 64<<10), MaxRecordBytes*4)
370 for sc.Scan() {
371 var r Record
372 if json.Unmarshal(sc.Bytes(), &r) != nil || r.Seq <= after {
373 continue
374 }
375 if len(out) >= limit || (maxBytes > 0 && size+len(sc.Bytes()) > maxBytes) {
376 f.Close()
377 return out, rng, nil
378 }
379 size += len(sc.Bytes())
380 out = append(out, r)
381 }
382 f.Close()
383 }
384 return out, rng, nil
385}
386
387// Logs: build output a producer keeps beside its records. Each check's
388// output in a run is one file, cut off at a bound; logs/ keeps the newest
389// keptRuns runs.
390const keptRuns = 16
391
392// LogFile is one check's output as it is written. It keeps at most max
393// bytes, and says whether it dropped any. Nothing it does can hold up the
394// build whose output it keeps: the file is made and written by a goroutine
395// of its own, through a bounded queue, and output that finds the queue
396// full, because the disk under the stream has stalled, is dropped and
397// counted as cut off.
398type LogFile struct {
399 mu sync.Mutex
400 path string // "" when the run or check is no name a log can have
401 max int64
402 written int64
403 truncated bool
404 queue chan []byte
405 done chan struct{}
406 failed chan struct{} // closed once the file cannot be made or written
407 closed bool
408}
409
410// logQueue is how many writes a log holds while its file is written, and
411// logCloseWait how long Close waits for them.
412const (
413 logQueue = 256
414 logCloseWait = time.Second
415)
416
417// Log opens the log of check in run, for writing as the check runs.
418func (s *Stream) Log(run, check string, max int64) *LogFile {
419 l := &LogFile{max: max, queue: make(chan []byte, logQueue), done: make(chan struct{}), failed: make(chan struct{})}
420 if runRE.MatchString(run) && nameRE.MatchString(check) && !strings.Contains(check, "/") {
421 l.path = filepath.Join(s.Dir, "logs", run, check+".log")
422 }
423 go l.drain(s)
424 return l
425}
426
427// drain makes the log's file and writes what the queue brings. A log
428// whose file cannot be made or written drops the rest.
429func (l *LogFile) drain(s *Stream) {
430 defer close(l.done)
431 var f *os.File
432 if l.path != "" {
433 logs, dir := filepath.Dir(filepath.Dir(l.path)), filepath.Dir(l.path)
434 _, statErr := os.Stat(dir)
435 fresh := errors.Is(statErr, fs.ErrNotExist)
436 if err := s.mkdir(logs); err == nil {
437 if err := s.mkdir(dir); err == nil {
438 if fresh {
439 s.pruneLogs(logs)
440 }
441 f, _ = s.create(l.path)
442 }
443 }
444 }
445 if f == nil {
446 close(l.failed)
447 }
448 for p := range l.queue {
449 if f == nil {
450 continue
451 }
452 if _, err := f.Write(p); err != nil {
453 f.Close()
454 f = nil
455 close(l.failed)
456 }
457 }
458 if f != nil {
459 f.Close()
460 }
461}
462
463// pruneLogs removes all but the newest keptRuns run directories.
464func (s *Stream) pruneLogs(logs string) {
465 entries, err := os.ReadDir(logs)
466 if err != nil || len(entries) <= keptRuns {
467 return
468 }
469 type run struct {
470 path string
471 mod time.Time
472 }
473 var runs []run
474 for _, e := range entries {
475 if info, err := e.Info(); err == nil && e.IsDir() {
476 runs = append(runs, run{filepath.Join(logs, e.Name()), info.ModTime()})
477 }
478 }
479 sort.Slice(runs, func(i, j int) bool { return runs[i].mod.After(runs[j].mod) })
480 for _, r := range runs[min(keptRuns, len(runs)):] {
481 os.RemoveAll(r.path)
482 }
483}
484
485// Write keeps what fits under the bound and drops the rest. It never
486// fails and never waits, so a full or stalled disk or a dropped log never
487// fails or holds up the build it records.
488func (l *LogFile) Write(p []byte) (int, error) {
489 if l == nil {
490 return len(p), nil
491 }
492 l.mu.Lock()
493 defer l.mu.Unlock()
494 keep := p
495 if room := l.max - l.written; int64(len(keep)) > room {
496 keep = keep[:max(room, 0)]
497 l.truncated = true
498 }
499 l.written += int64(len(p))
500 if len(keep) == 0 || l.closed {
501 return len(p), nil
502 }
503 select {
504 case l.queue <- bytes.Clone(keep):
505 default:
506 l.truncated = true
507 }
508 return len(p), nil
509}
510
511// Close ends the log, waits at most logCloseWait for its writes, and says
512// how many bytes it was given and whether it kept fewer.
513func (l *LogFile) Close() (written int64, truncated bool) {
514 if l == nil {
515 return 0, false
516 }
517 l.mu.Lock()
518 if !l.closed {
519 l.closed = true
520 close(l.queue)
521 }
522 l.mu.Unlock()
523 timer := time.NewTimer(logCloseWait)
524 defer timer.Stop()
525 select {
526 case <-l.done:
527 case <-timer.C:
528 l.mu.Lock()
529 l.truncated = true
530 l.mu.Unlock()
531 }
532 l.mu.Lock()
533 defer l.mu.Unlock()
534 select {
535 case <-l.failed:
536 if l.written > 0 {
537 l.truncated = true
538 }
539 default:
540 }
541 return l.written, l.truncated
542}
543
544// LogEntry is one log file a stream holds.
545type LogEntry struct {
546 Run, Check, Path string
547 Size int64
548 Mod time.Time
549}
550
551// Logs lists the stream's log files, newest run first.
552func (s *Stream) Logs() []LogEntry {
553 logs := filepath.Join(s.Dir, "logs")
554 runs, _ := os.ReadDir(logs)
555 var out []LogEntry
556 for _, r := range runs {
557 if !r.IsDir() || !runRE.MatchString(r.Name()) {
558 continue
559 }
560 files, _ := os.ReadDir(filepath.Join(logs, r.Name()))
561 for _, f := range files {
562 info, err := f.Info()
563 if err != nil || !info.Mode().IsRegular() || !strings.HasSuffix(f.Name(), ".log") {
564 continue
565 }
566 out = append(out, LogEntry{r.Name(), strings.TrimSuffix(f.Name(), ".log"), filepath.Join(logs, r.Name(), f.Name()), info.Size(), info.ModTime()})
567 }
568 }
569 sort.SliceStable(out, func(i, j int) bool { return out[i].Mod.After(out[j].Mod) })
570 return out
571}
572
573// readSmall reads a small file of the stream, never through a link.
574func readSmall(path string) ([]byte, error) {
575 f, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NOFOLLOW|syscall.O_NONBLOCK, 0)
576 if err != nil {
577 return nil, err
578 }
579 defer f.Close()
580 return io.ReadAll(io.LimitReader(f, 4096))
581}