Debian Codegraph @

debian/go/src/golang.org/x/telemetry/internal/counter/file.go

raw symbols SCIP
1 // Copyright 2023 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package counter
6
7 import (
8 "bytes"
9 "errors"
10 "fmt"
11 "math/rand"
12 "os"
13 "path"
14 "path/filepath"
15 "runtime"
16 "runtime/debug"
17 "sync"
18 "sync/atomic"
19 "time"
20 "unsafe"
21
22 "golang.org/x/telemetry/internal/mmap"
23 "golang.org/x/telemetry/internal/telemetry"
24 )
25
26 // A file is a counter file.
27 type file struct {
28 // Linked list of all known counters.
29 // (Linked list insertion is easy to make lock-free,
30 // and we don't want the initial counters incremented
31 // by a program to cause significant contention.)
32 counters atomic.Pointer[Counter] // head of list
33 end Counter // list ends at &end instead of nil
34
35 mu sync.Mutex
36 buildInfo *debug.BuildInfo
37 timeBegin, timeEnd time.Time
38 err error
39 current atomic.Pointer[mappedFile] // may be read without holding mu, but may be nil
40 }
41
42 var defaultFile file
43
44 // register ensures that the counter c is registered with the file.
45 func (f *file) register(c *Counter) {
46 debugPrintf("register %s %p\n", c.Name(), c)
47
48 // If counter is not registered with file, register it.
49 // Doing this lazily avoids init-time work
50 // as well as any execution cost at all for counters
51 // that are not used in a given program.
52 wroteNext := false
53 for wroteNext || c.next.Load() == nil {
54 head := f.counters.Load()
55 next := head
56 if next == nil {
57 next = &f.end
58 }
59 debugPrintf("register %s next %p\n", c.Name(), next)
60 if !wroteNext {
61 if !c.next.CompareAndSwap(nil, next) {
62 debugPrintf("register %s cas failed %p\n", c.Name(), c.next.Load())
63 continue
64 }
65 wroteNext = true
66 } else {
67 c.next.Store(next)
68 }
69 if f.counters.CompareAndSwap(head, c) {
70 debugPrintf("registered %s %p\n", c.Name(), f.counters.Load())
71 return
72 }
73 debugPrintf("register %s cas2 failed %p %p\n", c.Name(), f.counters.Load(), head)
74 }
75 }
76
77 // invalidateCounters marks as invalid all the pointers
78 // held by f's counters and then refreshes them.
79 //
80 // invalidateCounters cannot be called while holding f.mu,
81 // because a counter refresh may call f.lookup.
82 func (f *file) invalidateCounters() {
83 // Mark every counter as needing to refresh its count pointer.
84 if head := f.counters.Load(); head != nil {
85 for c := head; c != &f.end; c = c.next.Load() {
86 c.invalidate()
87 }
88 for c := head; c != &f.end; c = c.next.Load() {
89 c.refresh()
90 }
91 }
92 }
93
94 // lookup looks up the counter with the given name in the file,
95 // allocating it if needed, and returns a pointer to the atomic.Uint64
96 // containing the counter data.
97 // If the file has not been opened yet, lookup returns nil.
98 func (f *file) lookup(name string) counterPtr {
99 current := f.current.Load()
100 if current == nil {
101 debugPrintf("lookup %s - no mapped file\n", name)
102 return counterPtr{}
103 }
104 ptr := f.newCounter(name)
105 if ptr == nil {
106 return counterPtr{}
107 }
108 return counterPtr{current, ptr}
109 }
110
111 // ErrDisabled is the error returned when telemetry is disabled.
112 var ErrDisabled = errors.New("counter: disabled as Go telemetry is off")
113
114 var (
115 errNoBuildInfo = errors.New("counter: missing build info")
116 errCorrupt = errors.New("counter: corrupt counter file")
117 )
118
119 // weekEnd returns the day of the week on which uploads occur (and therefore
120 // counters expire).
121 //
122 // Reads the weekends file, creating one if none exists.
123 func weekEnd() (time.Weekday, error) {
124 // If there is no 'weekends' file create it and initialize it
125 // to a random day of the week. There is a short interval for
126 // a race.
127 weekends := filepath.Join(telemetry.Default.LocalDir(), "weekends")
128 day := fmt.Sprintf("%d\n", rand.Intn(7))
129 if _, err := os.ReadFile(weekends); err != nil {
130 if err := os.MkdirAll(telemetry.Default.LocalDir(), 0777); err != nil {
131 debugPrintf("%v: could not create telemetry.LocalDir %s", err, telemetry.Default.LocalDir())
132 return 0, err
133 }
134 if err = os.WriteFile(weekends, []byte(day), 0666); err != nil {
135 return 0, err
136 }
137 }
138
139 // race is over, read the file
140 buf, err := os.ReadFile(weekends)
141 // There is no reasonable way of recovering from errors
142 // so we just fail
143 if err != nil {
144 return 0, err
145 }
146 buf = bytes.TrimSpace(buf)
147 if len(buf) == 0 {
148 return 0, fmt.Errorf("empty weekends file")
149 }
150 weekend := time.Weekday(buf[0] - '0') // 0 is Sunday
151 // paranoia to make sure the value is legal
152 weekend %= 7
153 if weekend < 0 {
154 weekend += 7
155 }
156 return weekend, nil
157 }
158
159 // rotate checks to see whether the file f needs to be rotated,
160 // meaning to start a new counter file with a different date in the name.
161 // rotate is also used to open the file initially, meaning f.current can be nil.
162 // In general rotate should be called just once for each file.
163 // rotate will arrange a timer to call itself again when necessary.
164 func (f *file) rotate() {
165 expiry := f.rotate1()
166 if !expiry.IsZero() {
167 delay := time.Until(expiry)
168 // Some tests set CounterTime to a time in the past, causing delay to be
169 // negative. Avoid infinite loops by delaying at least a short interval.
170 //
171 // TODO(rfindley): instead, just also mock AfterFunc.
172 const minDelay = 1 * time.Minute
173 if delay < minDelay {
174 delay = minDelay
175 }
176 // TODO(rsc): Does this do the right thing for laptops closing?
177 time.AfterFunc(delay, f.rotate)
178 }
179 }
180
181 func nop() {}
182
183 // CounterTime returns the current UTC time.
184 // Mutable for testing.
185 var CounterTime = func() time.Time {
186 return time.Now().UTC()
187 }
188
189 // counterSpan returns the current time span for a counter file, as determined
190 // by [CounterTime] and the [weekEnd].
191 func counterSpan() (begin, end time.Time, _ error) {
192 year, month, day := CounterTime().Date()
193 begin = time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
194 // files always begin today, but expire on the next day of the week
195 // from the 'weekends' file.
196 weekend, err := weekEnd()
197 if err != nil {
198 return time.Time{}, time.Time{}, err
199 }
200 incr := int(weekend - begin.Weekday())
201 if incr <= 0 {
202 incr += 7 // ensure that end is later than begin
203 }
204 end = time.Date(year, month, day+incr, 0, 0, 0, 0, time.UTC)
205 return begin, end, nil
206 }
207
208 // rotate1 rotates the current counter file, returning its expiry, or the zero
209 // time if rotation failed.
210 func (f *file) rotate1() time.Time {
211 // Cleanup must be performed while unlocked, since invalidateCounters may
212 // involve calls to f.lookup.
213 var previous *mappedFile // read below while holding the f.mu.
214 defer func() {
215 // Counters must be invalidated whenever the mapped file changes.
216 if next := f.current.Load(); next != previous {
217 f.invalidateCounters()
218 // Ensure that the previous counter mapped file is closed.
219 if previous != nil {
220 previous.close() // safe to call multiple times
221 }
222 }
223 }()
224
225 f.mu.Lock()
226 defer f.mu.Unlock()
227
228 previous = f.current.Load()
229
230 if f.err != nil {
231 return time.Time{} // already in failed state; nothing to do
232 }
233
234 fail := func(err error) {
235 debugPrintf("rotate: %v", err)
236 f.err = err
237 f.current.Store(nil)
238 }
239
240 if mode, _ := telemetry.Default.Mode(); mode == "off" {
241 // TODO(rfindley): do we ever want to make ErrDisabled recoverable?
242 // Specifically, if f.err is ErrDisabled, should we check again during when
243 // rotating?
244 fail(ErrDisabled)
245 return time.Time{}
246 }
247
248 if f.buildInfo == nil {
249 bi, ok := debug.ReadBuildInfo()
250 if !ok {
251 fail(errNoBuildInfo)
252 return time.Time{}
253 }
254 f.buildInfo = bi
255 }
256
257 begin, end, err := counterSpan()
258 if err != nil {
259 fail(err)
260 return time.Time{}
261 }
262 if f.timeBegin.Equal(begin) && f.timeEnd.Equal(end) {
263 return f.timeEnd // nothing to do
264 }
265 f.timeBegin, f.timeEnd = begin, end
266
267 goVers, progPath, progVers := telemetry.ProgramInfo(f.buildInfo)
268 meta := fmt.Sprintf("TimeBegin: %s\nTimeEnd: %s\nProgram: %s\nVersion: %s\nGoVersion: %s\nGOOS: %s\nGOARCH: %s\n\n",
269 f.timeBegin.Format(time.RFC3339), f.timeEnd.Format(time.RFC3339),
270 progPath, progVers, goVers, runtime.GOOS, runtime.GOARCH)
271 if len(meta) > maxMetaLen { // should be impossible for our use
272 fail(fmt.Errorf("metadata too long"))
273 return time.Time{}
274 }
275
276 if progVers != "" {
277 progVers = "@" + progVers
278 }
279 baseName := fmt.Sprintf("%s%s-%s-%s-%s-%s.%s.count",
280 path.Base(progPath),
281 progVers,
282 goVers,
283 runtime.GOOS,
284 runtime.GOARCH,
285 f.timeBegin.Format("2006-01-02"),
286 FileVersion,
287 )
288 dir := telemetry.Default.LocalDir()
289 if err := os.MkdirAll(dir, 0777); err != nil {
290 fail(fmt.Errorf("making local dir: %v", err))
291 return time.Time{}
292 }
293 name := filepath.Join(dir, baseName)
294
295 m, err := openMapped(name, meta, nil)
296 if err != nil {
297 // Mapping failed:
298 // If there used to be a mapped file, after cleanup
299 // incrementing counters will only change their internal state.
300 // (before cleanup the existing mapped file would be updated)
301 fail(fmt.Errorf("openMapped: %v", err))
302 return time.Time{}
303 }
304
305 debugPrintf("using %v", m.f.Name())
306 f.current.Store(m)
307 return f.timeEnd
308 }
309
310 func (f *file) newCounter(name string) *atomic.Uint64 {
311 v, cleanup := f.newCounter1(name)
312 cleanup()
313 return v
314 }
315
316 func (f *file) newCounter1(name string) (v *atomic.Uint64, cleanup func()) {
317 f.mu.Lock()
318 defer f.mu.Unlock()
319
320 current := f.current.Load()
321 if current == nil {
322 return nil, nop
323 }
324 debugPrintf("newCounter %s in %s\n", name, current.f.Name())
325 if v, _, _, _ := current.lookup(name); v != nil {
326 return v, nop
327 }
328 v, newM, err := current.newCounter(name)
329 if err != nil {
330 debugPrintf("newCounter %s: %v\n", name, err)
331 return nil, nop
332 }
333
334 cleanup = nop
335 if newM != nil {
336 f.current.Store(newM)
337 // TODO(rfindley): shouldn't this close f.current?
338 cleanup = f.invalidateCounters
339 }
340 return v, cleanup
341 }
342
343 // Open associates counting with the defaultFile.
344 // The returned function is for testing only, and should
345 // be called after all Inc()s are finished, but before
346 // any reports are generated.
347 // (Otherwise expired count files will not be deleted on Windows.)
348 func Open() func() {
349 if telemetry.DisabledOnPlatform {
350 return func() {}
351 }
352 if mode, _ := telemetry.Default.Mode(); mode == "off" {
353 // Don't open the file when telemetry is off.
354 defaultFile.err = ErrDisabled
355 return func() {} // No need to clean up.
356 }
357 debugPrintf("Open")
358 defaultFile.rotate()
359 return func() {
360 // Once this has been called, the defaultFile is no longer usable.
361 mf := defaultFile.current.Load()
362 if mf == nil {
363 // telemetry might have been off
364 return
365 }
366 mf.close()
367 }
368 }
369
370 // A mappedFile is a counter file mmapped into memory.
371 type mappedFile struct {
372 meta string
373 hdrLen uint32
374 zero [4]byte
375 closeOnce sync.Once
376 f *os.File
377 mapping *mmap.Data
378 }
379
380 // existing should be nil the first time this is called for a file,
381 // and when remapping, should be the previous mappedFile.
382 func openMapped(name string, meta string, existing *mappedFile) (_ *mappedFile, err error) {
383 hdr, err := mappedHeader(meta)
384 if err != nil {
385 return nil, err
386 }
387
388 f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE, 0666)
389 if err != nil {
390 return nil, err
391 }
392 // Note: using local variable m here, not return value,
393 // so that return nil, err does not set m = nil and break the code in the defer.
394 m := &mappedFile{
395 f: f,
396 meta: meta,
397 }
398 // without this files cannot be cleanedup on Windows (affects tests)
399 runtime.SetFinalizer(m, (*mappedFile).close)
400 defer func() {
401 if err != nil {
402 m.close()
403 }
404 }()
405 info, err := f.Stat()
406 if err != nil {
407 return nil, err
408 }
409
410 // Establish file header and initial data area if not already present.
411 if info.Size() < minFileLen {
412 if _, err := f.WriteAt(hdr, 0); err != nil {
413 return nil, err
414 }
415 // Write zeros at the end of the file to extend it to minFileLen.
416 if _, err := f.WriteAt(m.zero[:], int64(minFileLen-len(m.zero))); err != nil {
417 return nil, err
418 }
419 info, err = f.Stat()
420 if err != nil {
421 return nil, err
422 }
423 if info.Size() < minFileLen {
424 return nil, fmt.Errorf("counter: writing file did not extend it")
425 }
426 }
427
428 // Map into memory.
429 var mapping mmap.Data
430 if existing != nil {
431 mapping, err = memmap(f, existing.mapping)
432 } else {
433 mapping, err = memmap(f, nil)
434 }
435 if err != nil {
436 return nil, err
437 }
438 m.mapping = &mapping
439 if !bytes.HasPrefix(m.mapping.Data, hdr) {
440 return nil, fmt.Errorf("counter: header mismatch")
441 }
442 m.hdrLen = uint32(len(hdr))
443
444 return m, nil
445 }
446
447 const (
448 FileVersion = "v1"
449 hdrPrefix = "# telemetry/counter file " + FileVersion + "\n"
450 recordUnit = 32
451 maxMetaLen = 512
452 numHash = 512 // 2kB for hash table
453 maxNameLen = 4 * 1024
454 limitOff = 0
455 hashOff = 4
456 pageSize = 16 * 1024
457 minFileLen = 16 * 1024
458 )
459
460 func mappedHeader(meta string) ([]byte, error) {
461 if len(meta) > maxMetaLen {
462 return nil, fmt.Errorf("counter: metadata too large")
463 }
464 np := round(len(hdrPrefix), 4)
465 n := round(np+4+len(meta), 32)
466 hdr := make([]byte, n)
467 copy(hdr, hdrPrefix)
468 *(*uint32)(unsafe.Pointer(&hdr[np])) = uint32(n)
469 copy(hdr[np+4:], meta)
470 return hdr, nil
471 }
472
473 func (m *mappedFile) place(limit uint32, name string) (start, end uint32) {
474 if limit == 0 {
475 // first record in file
476 limit = m.hdrLen + hashOff + 4*numHash
477 }
478 n := round(uint32(16+len(name)), recordUnit)
479 start = round(limit, recordUnit) // should already be rounded but just in case
480 if start/pageSize != (start+n)/pageSize {
481 // bump start to next page
482 start = round(limit, pageSize)
483 }
484 return start, start + n
485 }
486
487 var memmap = mmap.Mmap
488 var munmap = mmap.Munmap
489
490 func (m *mappedFile) close() {
491 m.closeOnce.Do(func() {
492 if m.mapping != nil {
493 munmap(m.mapping)
494 m.mapping = nil
495 }
496 if m.f != nil {
497 m.f.Close() // best effort
498 m.f = nil
499 }
500 })
501 }
502
503 // hash returns the hash code for name.
504 // The implementation is FNV-1a.
505 // This hash function is a fixed detail of the file format.
506 // It cannot be changed without also changing the file format version.
507 func hash(name string) uint32 {
508 const (
509 offset32 = 2166136261
510 prime32 = 16777619
511 )
512 h := uint32(offset32)
513 for i := 0; i < len(name); i++ {
514 c := name[i]
515 h = (h ^ uint32(c)) * prime32
516 }
517 return (h ^ (h >> 16)) % numHash
518 }
519
520 func (m *mappedFile) load32(off uint32) uint32 {
521 if int64(off) >= int64(len(m.mapping.Data)) {
522 return 0
523 }
524 return (*atomic.Uint32)(unsafe.Pointer(&m.mapping.Data[off])).Load()
525 }
526
527 func (m *mappedFile) cas32(off, old, new uint32) bool {
528 if int64(off) >= int64(len(m.mapping.Data)) {
529 panic("bad cas32") // return false would probably loop
530 }
531 return (*atomic.Uint32)(unsafe.Pointer(&m.mapping.Data[off])).CompareAndSwap(old, new)
532 }
533
534 func (m *mappedFile) entryAt(off uint32) (name []byte, next uint32, v *atomic.Uint64, ok bool) {
535 if off < m.hdrLen+hashOff || int64(off)+16 > int64(len(m.mapping.Data)) {
536 return nil, 0, nil, false
537 }
538 nameLen := m.load32(off+8) & 0x00ffffff
539 if nameLen == 0 || int64(off)+16+int64(nameLen) > int64(len(m.mapping.Data)) {
540 return nil, 0, nil, false
541 }
542 name = m.mapping.Data[off+16 : off+16+nameLen]
543 next = m.load32(off + 12)
544 v = (*atomic.Uint64)(unsafe.Pointer(&m.mapping.Data[off]))
545 return name, next, v, true
546 }
547
548 func (m *mappedFile) writeEntryAt(off uint32, name string) (next *atomic.Uint32, v *atomic.Uint64, ok bool) {
549 if off < m.hdrLen+hashOff || int64(off)+16+int64(len(name)) > int64(len(m.mapping.Data)) {
550 return nil, nil, false
551 }
552 copy(m.mapping.Data[off+16:], name)
553 atomic.StoreUint32((*uint32)(unsafe.Pointer(&m.mapping.Data[off+8])), uint32(len(name))|0xff000000)
554 next = (*atomic.Uint32)(unsafe.Pointer(&m.mapping.Data[off+12]))
555 v = (*atomic.Uint64)(unsafe.Pointer(&m.mapping.Data[off]))
556 return next, v, true
557 }
558
559 func (m *mappedFile) lookup(name string) (v *atomic.Uint64, headOff, head uint32, ok bool) {
560 h := hash(name)
561 headOff = m.hdrLen + hashOff + h*4
562 head = m.load32(headOff)
563 off := head
564 for off != 0 {
565 ename, next, v, ok := m.entryAt(off)
566 if !ok {
567 return nil, 0, 0, false
568 }
569 if string(ename) == name {
570 return v, headOff, head, true
571 }
572 off = next
573 }
574 return nil, headOff, head, true
575 }
576
577 func (m *mappedFile) newCounter(name string) (v *atomic.Uint64, m1 *mappedFile, err error) {
578 if len(name) > maxNameLen {
579 return nil, nil, fmt.Errorf("counter name too long")
580 }
581 orig := m
582 defer func() {
583 if m != orig {
584 if err != nil {
585 m.close()
586 } else {
587 m1 = m
588 }
589 }
590 }()
591
592 v, headOff, head, ok := m.lookup(name)
593 for !ok {
594 // Lookup found an invalid pointer,
595 // perhaps because the file has grown larger than the mapping.
596 limit := m.load32(m.hdrLen + limitOff)
597 if int64(limit) <= int64(len(m.mapping.Data)) {
598 // Mapping doesn't need to grow, so lookup found actual corruption.
599 debugPrintf("corrupt1\n")
600 return nil, nil, errCorrupt
601 }
602 newM, err := openMapped(m.f.Name(), m.meta, m)
603 if err != nil {
604 return nil, nil, err
605 }
606 if m != orig {
607 m.close()
608 }
609 m = newM
610 v, headOff, head, ok = m.lookup(name)
611 }
612 if v != nil {
613 return v, nil, nil
614 }
615
616 // Reserve space for new record.
617 // We are competing against other programs using the same file,
618 // so we use a compare-and-swap on the allocation limit in the header.
619 var start, end uint32
620 for {
621 // Determine where record should end, and grow file if needed.
622 limit := m.load32(m.hdrLen + limitOff)
623 start, end = m.place(limit, name)
624 debugPrintf("place %s at %#x-%#x\n", name, start, end)
625 if int64(end) > int64(len(m.mapping.Data)) {
626 newM, err := m.extend(end)
627 if err != nil {
628 return nil, nil, err
629 }
630 if m != orig {
631 m.close()
632 }
633 m = newM
634 continue
635 }
636
637 // Attempt to reserve that space for our record.
638 if m.cas32(m.hdrLen+limitOff, limit, end) {
639 break
640 }
641 }
642
643 // Write record.
644 next, v, ok := m.writeEntryAt(start, name)
645 if !ok {
646 debugPrintf("corrupt2 %#x+%d vs %#x\n", start, len(name), len(m.mapping.Data))
647 return nil, nil, errCorrupt // more likely our math is wrong
648 }
649
650 // Link record into hash chain, making sure not to introduce a duplicate.
651 // We know name does not appear in the chain starting at head.
652 for {
653 next.Store(head)
654 if m.cas32(headOff, head, start) {
655 return v, nil, nil
656 }
657
658 // Check new elements in chain for duplicates.
659 old := head
660 head = m.load32(headOff)
661 for off := head; off != old; {
662 ename, enext, v, ok := m.entryAt(off)
663 if !ok {
664 return nil, nil, errCorrupt
665 }
666 if string(ename) == name {
667 next.Store(^uint32(0)) // mark ours as dead
668 return v, nil, nil
669 }
670 off = enext
671 }
672 }
673 }
674
675 func (m *mappedFile) extend(end uint32) (*mappedFile, error) {
676 end = round(end, pageSize)
677 info, err := m.f.Stat()
678 if err != nil {
679 return nil, err
680 }
681 if info.Size() < int64(end) {
682 if _, err := m.f.WriteAt(m.zero[:], int64(end)-int64(len(m.zero))); err != nil {
683 return nil, err
684 }
685 }
686 newM, err := openMapped(m.f.Name(), m.meta, m)
687 m.f.Close()
688 return newM, err
689 }
690
691 // round returns x rounded up to the next multiple of unit,
692 // which must be a power of two.
693 func round[T int | uint32](x T, unit T) T {
694 return (x + unit - 1) &^ (unit - 1)
695 }