Debian Codegraph @

instrumentation/runtime/internal/deprecatedruntime/runtime.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package deprecatedruntime // import "go.opentelemetry.io/contrib/instrumentation/runtime/internal/deprecatedruntime"
5
6 import (
7 "context"
8 "math"
9 goruntime "runtime"
10 "sync"
11 "time"
12
13 "go.opentelemetry.io/otel/metric"
14 )
15
16 // Runtime reports the work-in-progress conventional runtime metrics specified by OpenTelemetry.
17 type runtime struct {
18 minimumReadMemStatsInterval time.Duration
19 meter metric.Meter
20 }
21
22 // Start initializes reporting of runtime metrics using the supplied config.
23 func Start(meter metric.Meter, minimumReadMemStatsInterval time.Duration) error {
24 r := &runtime{
25 meter: meter,
26 minimumReadMemStatsInterval: minimumReadMemStatsInterval,
27 }
28 return r.register()
29 }
30
31 func (r *runtime) register() error {
32 startTime := time.Now()
33 uptime, err := r.meter.Int64ObservableCounter(
34 "runtime.uptime",
35 metric.WithUnit("ms"),
36 metric.WithDescription("Milliseconds since application was initialized"),
37 )
38 if err != nil {
39 return err
40 }
41
42 goroutines, err := r.meter.Int64ObservableUpDownCounter(
43 "process.runtime.go.goroutines",
44 metric.WithDescription("Number of goroutines that currently exist"),
45 )
46 if err != nil {
47 return err
48 }
49
50 cgoCalls, err := r.meter.Int64ObservableUpDownCounter(
51 "process.runtime.go.cgo.calls",
52 metric.WithDescription("Number of cgo calls made by the current process"),
53 )
54 if err != nil {
55 return err
56 }
57
58 _, err = r.meter.RegisterCallback(
59 func(_ context.Context, o metric.Observer) error {
60 o.ObserveInt64(uptime, time.Since(startTime).Milliseconds())
61 o.ObserveInt64(goroutines, int64(goruntime.NumGoroutine()))
62 o.ObserveInt64(cgoCalls, goruntime.NumCgoCall())
63 return nil
64 },
65 uptime,
66 goroutines,
67 cgoCalls,
68 )
69 if err != nil {
70 return err
71 }
72
73 return r.registerMemStats()
74 }
75
76 func (r *runtime) registerMemStats() error {
77 var (
78 err error
79
80 heapAlloc metric.Int64ObservableUpDownCounter
81 heapIdle metric.Int64ObservableUpDownCounter
82 heapInuse metric.Int64ObservableUpDownCounter
83 heapObjects metric.Int64ObservableUpDownCounter
84 heapReleased metric.Int64ObservableUpDownCounter
85 heapSys metric.Int64ObservableUpDownCounter
86 liveObjects metric.Int64ObservableUpDownCounter
87
88 // TODO: is ptrLookups useful? I've not seen a value
89 // other than zero.
90 ptrLookups metric.Int64ObservableCounter
91
92 gcCount metric.Int64ObservableCounter
93 pauseTotalNs metric.Int64ObservableCounter
94 gcPauseNs metric.Int64Histogram
95
96 lastNumGC uint32
97 lastMemStats time.Time
98 memStats goruntime.MemStats
99
100 // lock prevents a race between batch observer and instrument registration.
101 lock sync.Mutex
102 )
103
104 lock.Lock()
105 defer lock.Unlock()
106
107 if heapAlloc, err = r.meter.Int64ObservableUpDownCounter(
108 "process.runtime.go.mem.heap_alloc",
109 metric.WithUnit("By"),
110 metric.WithDescription("Bytes of allocated heap objects"),
111 ); err != nil {
112 return err
113 }
114
115 if heapIdle, err = r.meter.Int64ObservableUpDownCounter(
116 "process.runtime.go.mem.heap_idle",
117 metric.WithUnit("By"),
118 metric.WithDescription("Bytes in idle (unused) spans"),
119 ); err != nil {
120 return err
121 }
122
123 if heapInuse, err = r.meter.Int64ObservableUpDownCounter(
124 "process.runtime.go.mem.heap_inuse",
125 metric.WithUnit("By"),
126 metric.WithDescription("Bytes in in-use spans"),
127 ); err != nil {
128 return err
129 }
130
131 if heapObjects, err = r.meter.Int64ObservableUpDownCounter(
132 "process.runtime.go.mem.heap_objects",
133 metric.WithDescription("Number of allocated heap objects"),
134 ); err != nil {
135 return err
136 }
137
138 // FYI see https://github.com/golang/go/issues/32284 to help
139 // understand the meaning of this value.
140 if heapReleased, err = r.meter.Int64ObservableUpDownCounter(
141 "process.runtime.go.mem.heap_released",
142 metric.WithUnit("By"),
143 metric.WithDescription("Bytes of idle spans whose physical memory has been returned to the OS"),
144 ); err != nil {
145 return err
146 }
147
148 if heapSys, err = r.meter.Int64ObservableUpDownCounter(
149 "process.runtime.go.mem.heap_sys",
150 metric.WithUnit("By"),
151 metric.WithDescription("Bytes of heap memory obtained from the OS"),
152 ); err != nil {
153 return err
154 }
155
156 if ptrLookups, err = r.meter.Int64ObservableCounter(
157 "process.runtime.go.mem.lookups",
158 metric.WithDescription("Number of pointer lookups performed by the runtime"),
159 ); err != nil {
160 return err
161 }
162
163 if liveObjects, err = r.meter.Int64ObservableUpDownCounter(
164 "process.runtime.go.mem.live_objects",
165 metric.WithDescription("Number of live objects is the number of cumulative Mallocs - Frees"),
166 ); err != nil {
167 return err
168 }
169
170 if gcCount, err = r.meter.Int64ObservableCounter(
171 "process.runtime.go.gc.count",
172 metric.WithDescription("Number of completed garbage collection cycles"),
173 ); err != nil {
174 return err
175 }
176
177 // Note that the following could be derived as a sum of
178 // individual pauses, but we may lose individual pauses if the
179 // observation interval is too slow.
180 if pauseTotalNs, err = r.meter.Int64ObservableCounter(
181 "process.runtime.go.gc.pause_total_ns",
182 metric.WithUnit("ns"),
183 metric.WithDescription("Cumulative nanoseconds in GC stop-the-world pauses since the program started"),
184 ); err != nil {
185 return err
186 }
187
188 if gcPauseNs, err = r.meter.Int64Histogram(
189 "process.runtime.go.gc.pause_ns",
190 metric.WithUnit("ns"),
191 metric.WithDescription("Amount of nanoseconds in GC stop-the-world pauses"),
192 ); err != nil {
193 return err
194 }
195
196 _, err = r.meter.RegisterCallback(
197 func(ctx context.Context, o metric.Observer) error {
198 lock.Lock()
199 defer lock.Unlock()
200
201 now := time.Now()
202 if now.Sub(lastMemStats) >= r.minimumReadMemStatsInterval {
203 goruntime.ReadMemStats(&memStats)
204 lastMemStats = now
205 }
206
207 o.ObserveInt64(heapAlloc, clampUint64(memStats.HeapAlloc))
208 o.ObserveInt64(heapIdle, clampUint64(memStats.HeapIdle))
209 o.ObserveInt64(heapInuse, clampUint64(memStats.HeapInuse))
210 o.ObserveInt64(heapObjects, clampUint64(memStats.HeapObjects))
211 o.ObserveInt64(heapReleased, clampUint64(memStats.HeapReleased))
212 o.ObserveInt64(heapSys, clampUint64(memStats.HeapSys))
213 o.ObserveInt64(liveObjects, clampUint64(memStats.Mallocs-memStats.Frees))
214 o.ObserveInt64(ptrLookups, clampUint64(memStats.Lookups))
215 o.ObserveInt64(gcCount, int64(memStats.NumGC))
216 o.ObserveInt64(pauseTotalNs, clampUint64(memStats.PauseTotalNs))
217
218 computeGCPauses(ctx, gcPauseNs, memStats.PauseNs[:], lastNumGC, memStats.NumGC)
219
220 lastNumGC = memStats.NumGC
221
222 return nil
223 },
224 heapAlloc,
225 heapIdle,
226 heapInuse,
227 heapObjects,
228 heapReleased,
229 heapSys,
230 liveObjects,
231
232 ptrLookups,
233
234 gcCount,
235 pauseTotalNs,
236 )
237 if err != nil {
238 return err
239 }
240 return nil
241 }
242
243 func clampUint64(v uint64) int64 {
244 if v > math.MaxInt64 {
245 return math.MaxInt64
246 }
247 return int64(v)
248 }
249
250 func computeGCPauses(
251 ctx context.Context,
252 recorder metric.Int64Histogram,
253 circular []uint64,
254 lastNumGC, currentNumGC uint32,
255 ) {
256 delta := int(int64(currentNumGC) - int64(lastNumGC))
257
258 if delta == 0 {
259 return
260 }
261
262 if delta >= len(circular) {
263 // There were > 256 collections, some may have been lost.
264 recordGCPauses(ctx, recorder, circular)
265 return
266 }
267
268 n := len(circular)
269 if n < 0 {
270 // Only the case in error situations.
271 return
272 }
273
274 length := uint64(n)
275
276 i := uint64(lastNumGC) % length
277 j := uint64(currentNumGC) % length
278
279 if j < i { // wrap around the circular buffer
280 recordGCPauses(ctx, recorder, circular[i:])
281 recordGCPauses(ctx, recorder, circular[:j])
282 return
283 }
284
285 recordGCPauses(ctx, recorder, circular[i:j])
286 }
287
288 func recordGCPauses(
289 ctx context.Context,
290 recorder metric.Int64Histogram,
291 pauses []uint64,
292 ) {
293 for _, pause := range pauses {
294 recorder.Record(ctx, clampUint64(pause))
295 }
296 }