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 namePrefix string
37 err error
38 meta string
39 current atomic.Pointer[mappedFile] // can 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 func (f *file) init(begin, end time.Time) {
120 info, ok := debug.ReadBuildInfo()
121 if !ok {
122 f.err = errNoBuildInfo
123 return
124 }
125 if mode, _ := telemetry.Default.Mode(); mode == "off" {
126 f.err = ErrDisabled
127 return
128 }
129 dir := telemetry.Default.LocalDir()
130
131 if err := os.MkdirAll(dir, 0777); err != nil {
132 f.err = err
133 return
134 }
135
136 goVers, progPath, progVers := telemetry.ProgramInfo(info)
137 f.meta = fmt.Sprintf("TimeBegin: %s\nTimeEnd: %s\nProgram: %s\nVersion: %s\nGoVersion: %s\nGOOS: %s\nGOARCH: %s\n\n",
138 begin.Format(time.RFC3339), end.Format(time.RFC3339),
139 progPath, progVers, goVers, runtime.GOOS, runtime.GOARCH)
140 if len(f.meta) > maxMetaLen { // should be impossible for our use
141 f.err = fmt.Errorf("metadata too long")
142 return
143 }
144 if progVers != "" {
145 progVers = "@" + progVers
146 }
147 prefix := fmt.Sprintf("%s%s-%s-%s-%s-", path.Base(progPath), progVers, goVers, runtime.GOOS, runtime.GOARCH)
148 f.namePrefix = filepath.Join(dir, prefix)
149 }
150
151 // filename returns the name of the file to use for f,
152 // given the current time now.
153 // It also returns the time when that name will no longer be valid
154 // and a new filename should be computed.
155 func (f *file) filename(now time.Time) (name string, expire time.Time, err error) {
156 now = now.UTC()
157 year, month, day := now.Date()
158 begin := time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
159 // files always begin today, but expire on the next day of the week
160 // from the 'weekends' file.
161 incr, err := fileValidity(now)
162 if err != nil {
163 return "", time.Time{}, err
164 }
165 end := time.Date(year, month, day+incr, 0, 0, 0, 0, time.UTC)
166 if f.namePrefix == "" && f.err == nil {
167 f.init(begin, end)
168 debugPrintf("init: %#q, %v", f.namePrefix, f.err)
169 }
170 // f.err != nil was set in f.init and means it is impossible to
171 // have a counter file
172 if f.err != nil {
173 return "", time.Time{}, f.err
174 }
175
176 name = f.namePrefix + now.Format("2006-01-02") + "." + FileVersion + ".count"
177 return name, end, nil
178 }
179
180 // fileValidity returns the number of days that a file is valid for.
181 // It is the number of days to the next day of the week from the 'weekends' file.
182 func fileValidity(now time.Time) (int, error) {
183 // If there is no 'weekends' file create it and initialize it
184 // to a random day of the week. There is a short interval for
185 // a race.
186 weekends := filepath.Join(telemetry.Default.LocalDir(), "weekends")
187 day := fmt.Sprintf("%d\n", rand.Intn(7))
188 if _, err := os.ReadFile(weekends); err != nil {
189 if err := os.MkdirAll(telemetry.Default.LocalDir(), 0777); err != nil {
190 debugPrintf("%v: could not create telemetry.LocalDir %s", err, telemetry.Default.LocalDir())
191 return 7, err
192 }
193 if err = os.WriteFile(weekends, []byte(day), 0666); err != nil {
194 return 7, err
195 }
196 }
197
198 // race is over, read the file
199 buf, err := os.ReadFile(weekends)
200 // There is no reasonable way of recovering from errors
201 // so we just fail
202 if err != nil {
203 return 7, err
204 }
205 buf = bytes.TrimSpace(buf)
206 if len(buf) == 0 {
207 return 7, err
208 }
209 dayofweek := time.Weekday(buf[0] - '0') // 0 is Sunday
210 // paranoia to make sure the value is legal
211 dayofweek %= 7
212 if dayofweek < 0 {
213 dayofweek += 7
214 }
215 today := now.Weekday()
216 incr := dayofweek - today
217 if incr <= 0 {
218 incr += 7
219 }
220 return int(incr), nil
221 }
222
223 // rotate checks to see whether the file f needs to be rotated,
224 // meaning to start a new counter file with a different date in the name.
225 // rotate is also used to open the file initially, meaning f.current can be nil.
226 // In general rotate should be called just once for each file.
227 // rotate will arrange a timer to call itself again when necessary.
228 func (f *file) rotate() {
229 expire, cleanup := f.rotate1()
230 cleanup()
231 if !expire.IsZero() {
232 // TODO(rsc): Does this do the right thing for laptops closing?
233 time.AfterFunc(time.Until(expire), f.rotate)
234 }
235 }
236
237 func nop() {}
238
239 // CounterTime returns the current UTC time.
240 // Mutable for testing.
241 var CounterTime = func() time.Time {
242 return time.Now().UTC()
243 }
244
245 func (f *file) rotate1() (expire time.Time, cleanup func()) {
246 f.mu.Lock()
247 defer f.mu.Unlock()
248
249 var previous *mappedFile
250 cleanup = func() {
251 // convert counters to new mapping (or nil)
252 // from old mapping (or nil)
253 f.invalidateCounters()
254 if previous == nil {
255 // no old mapping to worry about
256 return
257 }
258 // now it is safe to clean up the old mapping
259 // Quim Montel pointed out the previous coeanup was incomplete
260 previous.close()
261 }
262
263 name, expire, err := f.filename(CounterTime())
264 if err != nil {
265 // This could be mode == "off" (when rotate is called for the first time)
266 ret := nop
267 if previous = f.current.Load(); previous != nil {
268 // or it could be some strange error
269 f.current.Store(nil)
270 ret = cleanup
271 }
272 debugPrintf("rotate: %v\n", err)
273 return time.Time{}, ret
274 }
275
276 previous = f.current.Load()
277 if previous != nil && name == previous.f.Name() {
278 // the existing file is fine
279 return expire, nop
280 }
281
282 m, err := openMapped(name, f.meta, nil)
283 if err != nil {
284 // Mapping failed:
285 // If there used to be a mapped file, after cleanup
286 // incrementing counters will only change their internal state.
287 // (before cleanup the existing mapped file would be updated)
288 f.current.Store(nil) // invalidate the current mapping
289 debugPrintf("rotate: openMapped: %v\n", err)
290 return time.Time{}, cleanup
291 }
292
293 debugPrintf("using %v", m.f.Name())
294 f.current.Store(m)
295
296 return expire, cleanup
297 }
298
299 func (f *file) newCounter(name string) *atomic.Uint64 {
300 v, cleanup := f.newCounter1(name)
301 cleanup()
302 return v
303 }
304
305 func (f *file) newCounter1(name string) (v *atomic.Uint64, cleanup func()) {
306 f.mu.Lock()
307 defer f.mu.Unlock()
308
309 current := f.current.Load()
310 if current == nil {
311 return nil, nop
312 }
313 debugPrintf("newCounter %s in %s\n", name, current.f.Name())
314 if v, _, _, _ := current.lookup(name); v != nil {
315 return v, nop
316 }
317 v, newM, err := current.newCounter(name)
318 if err != nil {
319 debugPrintf("newCounter %s: %v\n", name, err)
320 return nil, nop
321 }
322
323 cleanup = nop
324 if newM != nil {
325 f.current.Store(newM)
326 cleanup = f.invalidateCounters
327 }
328 return v, cleanup
329 }
330
331 // Open associates counting with the defaultFile.
332 // The returned function is for testing only, and should
333 // be called after all Inc()s are finished, but before
334 // any reports are generated.
335 // (Otherwise expired count files will not be deleted on Windows.)
336 func Open() func() {
337 if telemetry.DisabledOnPlatform {
338 return func() {}
339 }
340 if mode, _ := telemetry.Default.Mode(); mode == "off" {
341 // Don't open the file when telemetry is off.
342 defaultFile.err = ErrDisabled
343 return func() {} // No need to clean up.
344 }
345 debugPrintf("Open")
346 defaultFile.rotate()
347 return func() {
348 // Once this has been called, the defaultFile is no longer usable.
349 mf := defaultFile.current.Load()
350 if mf == nil {
351 // telemetry might have been off
352 return
353 }
354 mf.close()
355 }
356 }
357
358 // A mappedFile is a counter file mmapped into memory.
359 type mappedFile struct {
360 meta string
361 hdrLen uint32
362 zero [4]byte
363 closeOnce sync.Once
364 f *os.File
365 mapping *mmap.Data
366 }
367
368 // existing should be nil the first time this is called for a file,
369 // and when remapping, should be the previous mappedFile.
370 func openMapped(name string, meta string, existing *mappedFile) (_ *mappedFile, err error) {
371 hdr, err := mappedHeader(meta)
372 if err != nil {
373 return nil, err
374 }
375
376 f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE, 0666)
377 if err != nil {
378 return nil, err
379 }
380 // Note: using local variable m here, not return value,
381 // so that return nil, err does not set m = nil and break the code in the defer.
382 m := &mappedFile{
383 f: f,
384 meta: meta,
385 }
386 // without this files cannot be cleanedup on Windows (affects tests)
387 runtime.SetFinalizer(m, (*mappedFile).close)
388 defer func() {
389 if err != nil {
390 m.close()
391 }
392 }()
393 info, err := f.Stat()
394 if err != nil {
395 return nil, err
396 }
397
398 // Establish file header and initial data area if not already present.
399 if info.Size() < minFileLen {
400 if _, err := f.WriteAt(hdr, 0); err != nil {
401 return nil, err
402 }
403 // Write zeros at the end of the file to extend it to minFileLen.
404 if _, err := f.WriteAt(m.zero[:], int64(minFileLen-len(m.zero))); err != nil {
405 return nil, err
406 }
407 info, err = f.Stat()
408 if err != nil {
409 return nil, err
410 }
411 if info.Size() < minFileLen {
412 return nil, fmt.Errorf("counter: writing file did not extend it")
413 }
414 }
415
416 // Map into memory.
417 var mapping mmap.Data
418 if existing != nil {
419 mapping, err = memmap(f, existing.mapping)
420 } else {
421 mapping, err = memmap(f, nil)
422 }
423 if err != nil {
424 return nil, err
425 }
426 m.mapping = &mapping
427 if !bytes.HasPrefix(m.mapping.Data, hdr) {
428 return nil, fmt.Errorf("counter: header mismatch")
429 }
430 m.hdrLen = uint32(len(hdr))
431
432 return m, nil
433 }
434
435 const (
436 FileVersion = "v1"
437 hdrPrefix = "# telemetry/counter file " + FileVersion + "\n"
438 recordUnit = 32
439 maxMetaLen = 512
440 numHash = 512 // 2kB for hash table
441 maxNameLen = 4 * 1024
442 limitOff = 0
443 hashOff = 4
444 pageSize = 16 * 1024
445 minFileLen = 16 * 1024
446 )
447
448 func mappedHeader(meta string) ([]byte, error) {
449 if len(meta) > maxMetaLen {
450 return nil, fmt.Errorf("counter: metadata too large")
451 }
452 np := round(len(hdrPrefix), 4)
453 n := round(np+4+len(meta), 32)
454 hdr := make([]byte, n)
455 copy(hdr, hdrPrefix)
456 *(*uint32)(unsafe.Pointer(&hdr[np])) = uint32(n)
457 copy(hdr[np+4:], meta)
458 return hdr, nil
459 }
460
461 func (m *mappedFile) place(limit uint32, name string) (start, end uint32) {
462 if limit == 0 {
463 // first record in file
464 limit = m.hdrLen + hashOff + 4*numHash
465 }
466 n := round(uint32(16+len(name)), recordUnit)
467 start = round(limit, recordUnit) // should already be rounded but just in case
468 if start/pageSize != (start+n)/pageSize {
469 // bump start to next page
470 start = round(limit, pageSize)
471 }
472 return start, start + n
473 }
474
475 var memmap = mmap.Mmap
476 var munmap = mmap.Munmap
477
478 func (m *mappedFile) close() {
479 m.closeOnce.Do(func() {
480 if m.mapping != nil {
481 munmap(m.mapping)
482 m.mapping = nil
483 }
484 if m.f != nil {
485 m.f.Close() // best effort
486 m.f = nil
487 }
488 })
489 }
490
491 // hash returns the hash code for name.
492 // The implementation is FNV-1a.
493 // This hash function is a fixed detail of the file format.
494 // It cannot be changed without also changing the file format version.
495 func hash(name string) uint32 {
496 const (
497 offset32 = 2166136261
498 prime32 = 16777619
499 )
500 h := uint32(offset32)
501 for i := 0; i < len(name); i++ {
502 c := name[i]
503 h = (h ^ uint32(c)) * prime32
504 }
505 return (h ^ (h >> 16)) % numHash
506 }
507
508 func (m *mappedFile) load32(off uint32) uint32 {
509 if int64(off) >= int64(len(m.mapping.Data)) {
510 return 0
511 }
512 return (*atomic.Uint32)(unsafe.Pointer(&m.mapping.Data[off])).Load()
513 }
514
515 func (m *mappedFile) cas32(off, old, new uint32) bool {
516 if int64(off) >= int64(len(m.mapping.Data)) {
517 panic("bad cas32") // return false would probably loop
518 }
519 return (*atomic.Uint32)(unsafe.Pointer(&m.mapping.Data[off])).CompareAndSwap(old, new)
520 }
521
522 func (m *mappedFile) entryAt(off uint32) (name []byte, next uint32, v *atomic.Uint64, ok bool) {
523 if off < m.hdrLen+hashOff || int64(off)+16 > int64(len(m.mapping.Data)) {
524 return nil, 0, nil, false
525 }
526 nameLen := m.load32(off+8) & 0x00ffffff
527 if nameLen == 0 || int64(off)+16+int64(nameLen) > int64(len(m.mapping.Data)) {
528 return nil, 0, nil, false
529 }
530 name = m.mapping.Data[off+16 : off+16+nameLen]
531 next = m.load32(off + 12)
532 v = (*atomic.Uint64)(unsafe.Pointer(&m.mapping.Data[off]))
533 return name, next, v, true
534 }
535
536 func (m *mappedFile) writeEntryAt(off uint32, name string) (next *atomic.Uint32, v *atomic.Uint64, ok bool) {
537 if off < m.hdrLen+hashOff || int64(off)+16+int64(len(name)) > int64(len(m.mapping.Data)) {
538 return nil, nil, false
539 }
540 copy(m.mapping.Data[off+16:], name)
541 atomic.StoreUint32((*uint32)(unsafe.Pointer(&m.mapping.Data[off+8])), uint32(len(name))|0xff000000)
542 next = (*atomic.Uint32)(unsafe.Pointer(&m.mapping.Data[off+12]))
543 v = (*atomic.Uint64)(unsafe.Pointer(&m.mapping.Data[off]))
544 return next, v, true
545 }
546
547 func (m *mappedFile) lookup(name string) (v *atomic.Uint64, headOff, head uint32, ok bool) {
548 h := hash(name)
549 headOff = m.hdrLen + hashOff + h*4
550 head = m.load32(headOff)
551 off := head
552 for off != 0 {
553 ename, next, v, ok := m.entryAt(off)
554 if !ok {
555 return nil, 0, 0, false
556 }
557 if string(ename) == name {
558 return v, headOff, head, true
559 }
560 off = next
561 }
562 return nil, headOff, head, true
563 }
564
565 func (m *mappedFile) newCounter(name string) (v *atomic.Uint64, m1 *mappedFile, err error) {
566 if len(name) > maxNameLen {
567 return nil, nil, fmt.Errorf("counter name too long")
568 }
569 orig := m
570 defer func() {
571 if m != orig {
572 if err != nil {
573 m.close()
574 } else {
575 m1 = m
576 }
577 }
578 }()
579
580 v, headOff, head, ok := m.lookup(name)
581 for !ok {
582 // Lookup found an invalid pointer,
583 // perhaps because the file has grown larger than the mapping.
584 limit := m.load32(m.hdrLen + limitOff)
585 if int64(limit) <= int64(len(m.mapping.Data)) {
586 // Mapping doesn't need to grow, so lookup found actual corruption.
587 debugPrintf("corrupt1\n")
588 return nil, nil, errCorrupt
589 }
590 newM, err := openMapped(m.f.Name(), m.meta, m)
591 if err != nil {
592 return nil, nil, err
593 }
594 if m != orig {
595 m.close()
596 }
597 m = newM
598 v, headOff, head, ok = m.lookup(name)
599 }
600 if v != nil {
601 return v, nil, nil
602 }
603
604 // Reserve space for new record.
605 // We are competing against other programs using the same file,
606 // so we use a compare-and-swap on the allocation limit in the header.
607 var start, end uint32
608 for {
609 // Determine where record should end, and grow file if needed.
610 limit := m.load32(m.hdrLen + limitOff)
611 start, end = m.place(limit, name)
612 debugPrintf("place %s at %#x-%#x\n", name, start, end)
613 if int64(end) > int64(len(m.mapping.Data)) {
614 newM, err := m.extend(end)
615 if err != nil {
616 return nil, nil, err
617 }
618 if m != orig {
619 m.close()
620 }
621 m = newM
622 continue
623 }
624
625 // Attempt to reserve that space for our record.
626 if m.cas32(m.hdrLen+limitOff, limit, end) {
627 break
628 }
629 }
630
631 // Write record.
632 next, v, ok := m.writeEntryAt(start, name)
633 if !ok {
634 debugPrintf("corrupt2 %#x+%d vs %#x\n", start, len(name), len(m.mapping.Data))
635 return nil, nil, errCorrupt // more likely our math is wrong
636 }
637
638 // Link record into hash chain, making sure not to introduce a duplicate.
639 // We know name does not appear in the chain starting at head.
640 for {
641 next.Store(head)
642 if m.cas32(headOff, head, start) {
643 return v, nil, nil
644 }
645
646 // Check new elements in chain for duplicates.
647 old := head
648 head = m.load32(headOff)
649 for off := head; off != old; {
650 ename, enext, v, ok := m.entryAt(off)
651 if !ok {
652 return nil, nil, errCorrupt
653 }
654 if string(ename) == name {
655 next.Store(^uint32(0)) // mark ours as dead
656 return v, nil, nil
657 }
658 off = enext
659 }
660 }
661 }
662
663 func (m *mappedFile) extend(end uint32) (*mappedFile, error) {
664 end = round(end, pageSize)
665 info, err := m.f.Stat()
666 if err != nil {
667 return nil, err
668 }
669 if info.Size() < int64(end) {
670 if _, err := m.f.WriteAt(m.zero[:], int64(end)-int64(len(m.zero))); err != nil {
671 return nil, err
672 }
673 }
674 newM, err := openMapped(m.f.Name(), m.meta, m)
675 m.f.Close()
676 return newM, err
677 }
678
679 // round returns x rounded up to the next multiple of unit,
680 // which must be a power of two.
681 func round[T int | uint32](x T, unit T) T {
682 return (x + unit - 1) &^ (unit - 1)
683 }