Debian Codegraph @

debian/go/src/golang.org/x/telemetry/internal/counter/counter.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 internal/counter implements the internals of the public counter package.
6 // In addition to the public API, this package also includes APIs to parse and
7 // manage the counter files, needed by the upload package.
8 package counter
9
10 import (
11 "fmt"
12 "os"
13 "runtime"
14 "strings"
15 "sync/atomic"
16 )
17
18 // Note: not using internal/godebug, so that internal/godebug can use internal/counter.
19 var debugCounter = strings.Contains(os.Getenv("GODEBUG"), "countertrace=1")
20
21 func debugPrintf(format string, args ...interface{}) {
22 if debugCounter {
23 if len(format) == 0 || format[len(format)-1] != '\n' {
24 format += "\n"
25 }
26 fmt.Fprintf(os.Stderr, "counter: "+format, args...)
27 }
28 }
29
30 // A Counter is a single named event counter.
31 // A Counter is safe for use by multiple goroutines simultaneously.
32 //
33 // Counters should typically be created using New
34 // and stored as global variables, like:
35 //
36 // package mypackage
37 // var errorCount = counter.New("mypackage/errors")
38 //
39 // (The initialization of errorCount in this example is handled
40 // entirely by the compiler and linker; this line executes no code
41 // at program startup.)
42 //
43 // Then code can call Add to increment the counter
44 // each time the corresponding event is observed.
45 //
46 // Although it is possible to use New to create
47 // a Counter each time a particular event needs to be recorded,
48 // that usage fails to amortize the construction cost over
49 // multiple calls to Add, so it is more expensive and not recommended.
50 type Counter struct {
51 name string
52 file *file
53
54 next atomic.Pointer[Counter]
55 state counterState
56 ptr counterPtr
57 }
58
59 func (c *Counter) Name() string {
60 return c.name
61 }
62
63 type counterPtr struct {
64 m *mappedFile
65 count *atomic.Uint64
66 }
67
68 type counterState struct {
69 bits atomic.Uint64
70 }
71
72 func (s *counterState) load() counterStateBits {
73 return counterStateBits(s.bits.Load())
74 }
75
76 func (s *counterState) update(old *counterStateBits, new counterStateBits) bool {
77 if s.bits.CompareAndSwap(uint64(*old), uint64(new)) {
78 *old = new
79 return true
80 }
81 return false
82 }
83
84 type counterStateBits uint64
85
86 const (
87 stateReaders counterStateBits = 1<<30 - 1
88 stateLocked counterStateBits = stateReaders
89 stateHavePtr counterStateBits = 1 << 30
90 stateExtraShift = 31
91 stateExtra counterStateBits = 1<<64 - 1<<stateExtraShift
92 )
93
94 func (b counterStateBits) readers() int { return int(b & stateReaders) }
95 func (b counterStateBits) locked() bool { return b&stateReaders == stateLocked }
96 func (b counterStateBits) havePtr() bool { return b&stateHavePtr != 0 }
97 func (b counterStateBits) extra() uint64 { return uint64(b&stateExtra) >> stateExtraShift }
98
99 func (b counterStateBits) incReader() counterStateBits { return b + 1 }
100 func (b counterStateBits) decReader() counterStateBits { return b - 1 }
101 func (b counterStateBits) setLocked() counterStateBits { return b | stateLocked }
102 func (b counterStateBits) clearLocked() counterStateBits { return b &^ stateLocked }
103 func (b counterStateBits) setHavePtr() counterStateBits { return b | stateHavePtr }
104 func (b counterStateBits) clearHavePtr() counterStateBits { return b &^ stateHavePtr }
105 func (b counterStateBits) clearExtra() counterStateBits { return b &^ stateExtra }
106 func (b counterStateBits) addExtra(n uint64) counterStateBits {
107 const maxExtra = uint64(stateExtra) >> stateExtraShift // 0x1ffffffff
108 x := b.extra()
109 if x+n < x || x+n > maxExtra {
110 x = maxExtra
111 } else {
112 x += n
113 }
114 return b.clearExtra() | counterStateBits(x)<<stateExtraShift
115 }
116
117 // New returns a counter with the given name.
118 // New can be called in global initializers and will be compiled down to
119 // linker-initialized data. That is, calling New to initialize a global
120 // has no cost at program startup.
121 func New(name string) *Counter {
122 // Note: not calling defaultFile.New in order to keep this
123 // function something the compiler can inline and convert
124 // into static data initializations, with no init-time footprint.
125 return &Counter{name: name, file: &defaultFile}
126 }
127
128 // Inc adds 1 to the counter.
129 func (c *Counter) Inc() {
130 c.Add(1)
131 }
132
133 // Add adds n to the counter. n cannot be negative, as counts cannot decrease.
134 func (c *Counter) Add(n int64) {
135 debugPrintf("Add %q += %d", c.name, n)
136
137 if n < 0 {
138 panic("Counter.Add negative")
139 }
140 if n == 0 {
141 return
142 }
143 c.file.register(c)
144
145 state := c.state.load()
146 for ; ; state = c.state.load() {
147 switch {
148 case !state.locked() && state.havePtr():
149 if !c.state.update(&state, state.incReader()) {
150 continue
151 }
152 // Counter unlocked or counter shared; has an initialized count pointer; acquired shared lock.
153 if c.ptr.count == nil {
154 for !c.state.update(&state, state.addExtra(uint64(n))) {
155 // keep trying - we already took the reader lock
156 state = c.state.load()
157 }
158 debugPrintf("Add %q += %d: nil extra=%d\n", c.name, n, state.extra())
159 } else {
160 sum := c.add(uint64(n))
161 debugPrintf("Add %q += %d: count=%d\n", c.name, n, sum)
162 }
163 c.releaseReader(state)
164 return
165
166 case state.locked():
167 if !c.state.update(&state, state.addExtra(uint64(n))) {
168 continue
169 }
170 debugPrintf("Add %q += %d: locked extra=%d\n", c.name, n, state.extra())
171 return
172
173 case !state.havePtr():
174 if !c.state.update(&state, state.addExtra(uint64(n)).setLocked()) {
175 continue
176 }
177 debugPrintf("Add %q += %d: noptr extra=%d\n", c.name, n, state.extra())
178 c.releaseLock(state)
179 return
180 }
181 }
182 }
183
184 func (c *Counter) releaseReader(state counterStateBits) {
185 for ; ; state = c.state.load() {
186 // If we are the last reader and havePtr was cleared
187 // while this batch of readers was using c.ptr,
188 // it's our job to update c.ptr by upgrading to a full lock
189 // and letting releaseLock do the work.
190 // Note: no new reader will attempt to add itself now that havePtr is clear,
191 // so we are only racing against possible additions to extra.
192 if state.readers() == 1 && !state.havePtr() {
193 if !c.state.update(&state, state.setLocked()) {
194 continue
195 }
196 debugPrintf("releaseReader %s: last reader, need ptr\n", c.name)
197 c.releaseLock(state)
198 return
199 }
200
201 // Release reader.
202 if !c.state.update(&state, state.decReader()) {
203 continue
204 }
205 debugPrintf("releaseReader %s: released (%d readers now)\n", c.name, state.readers())
206 return
207 }
208 }
209
210 func (c *Counter) releaseLock(state counterStateBits) {
211 for ; ; state = c.state.load() {
212 if !state.havePtr() {
213 // Set havePtr before updating ptr,
214 // to avoid race with the next clear of havePtr.
215 if !c.state.update(&state, state.setHavePtr()) {
216 continue
217 }
218 debugPrintf("releaseLock %s: reset havePtr (extra=%d)\n", c.name, state.extra())
219
220 // Optimization: only bother loading a new pointer
221 // if we have a value to add to it.
222 c.ptr = counterPtr{nil, nil}
223 if state.extra() != 0 {
224 c.ptr = c.file.lookup(c.name)
225 debugPrintf("releaseLock %s: ptr=%v\n", c.name, c.ptr)
226 }
227 }
228
229 if extra := state.extra(); extra != 0 && c.ptr.count != nil {
230 if !c.state.update(&state, state.clearExtra()) {
231 continue
232 }
233 sum := c.add(extra)
234 debugPrintf("releaseLock %s: flush extra=%d -> count=%d\n", c.name, extra, sum)
235 }
236
237 // Took care of refreshing ptr and flushing extra.
238 // Now we can release the lock, unless of course
239 // another goroutine cleared havePtr or added to extra,
240 // in which case we go around again.
241 if !c.state.update(&state, state.clearLocked()) {
242 continue
243 }
244 debugPrintf("releaseLock %s: unlocked\n", c.name)
245 return
246 }
247 }
248
249 func (c *Counter) add(n uint64) uint64 {
250 count := c.ptr.count
251 for {
252 old := count.Load()
253 sum := old + n
254 if sum < old {
255 sum = ^uint64(0)
256 }
257 if count.CompareAndSwap(old, sum) {
258 runtime.KeepAlive(c.ptr.m)
259 return sum
260 }
261 }
262 }
263
264 func (c *Counter) invalidate() {
265 for {
266 state := c.state.load()
267 if !state.havePtr() {
268 debugPrintf("invalidate %s: no ptr\n", c.name)
269 return
270 }
271 if c.state.update(&state, state.clearHavePtr()) {
272 debugPrintf("invalidate %s: cleared havePtr\n", c.name)
273 return
274 }
275 }
276 }
277
278 func (c *Counter) refresh() {
279 for {
280 state := c.state.load()
281 if state.havePtr() || state.readers() > 0 || state.extra() == 0 {
282 debugPrintf("refresh %s: havePtr=%v readers=%d extra=%d\n", c.name, state.havePtr(), state.readers(), state.extra())
283 return
284 }
285 if c.state.update(&state, state.setLocked()) {
286 debugPrintf("refresh %s: locked havePtr=%v readers=%d extra=%d\n", c.name, state.havePtr(), state.readers(), state.extra())
287 c.releaseLock(state)
288 return
289 }
290 }
291 }
292
293 // Read reads the given counter.
294 // This is the implementation of x/telemetry/counter/countertest.ReadCounter.
295 func Read(c *Counter) (uint64, error) {
296 if c.file.current.Load() == nil {
297 return c.state.load().extra(), nil
298 }
299 pf, err := readFile(c.file)
300 if err != nil {
301 return 0, err
302 }
303 v, ok := pf.Count[DecodeStack(c.Name())]
304 if !ok {
305 return v, fmt.Errorf("not found:%q", DecodeStack(c.Name()))
306 }
307 return v, nil
308 }
309
310 func readFile(f *file) (*File, error) {
311 if f == nil {
312 debugPrintf("No file")
313 return nil, fmt.Errorf("counter is not initialized - was Open called?")
314 }
315
316 // Note: don't call f.rotate here as this will enqueue a follow-up rotation.
317 f.rotate1()
318
319 if f.err != nil {
320 return nil, fmt.Errorf("failed to rotate mapped file - %v", f.err)
321 }
322 current := f.current.Load()
323 if current == nil {
324 return nil, fmt.Errorf("counter has no mapped file")
325 }
326 name := current.f.Name()
327 data, err := os.ReadFile(name)
328 if err != nil {
329 return nil, fmt.Errorf("failed to read from file: %v", err)
330 }
331 pf, err := Parse(name, data)
332 if err != nil {
333 return nil, fmt.Errorf("failed to parse: %v", err)
334 }
335 return pf, nil
336 }
337
338 // ReadFile reads the counters and stack counters from the given file.
339 // This is the implementation of x/telemetry/counter/countertest.Read
340 func ReadFile(name string) (counters, stackCounters map[string]uint64, _ error) {
341 // TODO: Document the format of the stackCounters names.
342
343 data, err := os.ReadFile(name)
344 if err != nil {
345 return nil, nil, fmt.Errorf("failed to read from file: %v", err)
346 }
347 pf, err := Parse(name, data)
348 if err != nil {
349 return nil, nil, fmt.Errorf("failed to parse: %v", err)
350 }
351 counters = make(map[string]uint64)
352 stackCounters = make(map[string]uint64)
353 for k, v := range pf.Count {
354 if IsStackCounter(k) {
355 stackCounters[DecodeStack(k)] = v
356 } else {
357 counters[k] = v
358 }
359 }
360 return counters, stackCounters, nil
361 }