Debian Codegraph @

instrumentation/runtime/runtime.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package runtime // import "go.opentelemetry.io/contrib/instrumentation/runtime"
5
6 import (
7 "context"
8 "math"
9 "runtime/metrics"
10 "sync"
11 "time"
12
13 "go.opentelemetry.io/otel/attribute"
14 "go.opentelemetry.io/otel/metric"
15 "go.opentelemetry.io/otel/semconv/v1.40.0/goconv"
16
17 "go.opentelemetry.io/contrib/instrumentation/runtime/internal/deprecatedruntime"
18 "go.opentelemetry.io/contrib/instrumentation/runtime/internal/x"
19 )
20
21 // ScopeName is the instrumentation scope name.
22 const ScopeName = "go.opentelemetry.io/contrib/instrumentation/runtime"
23
24 const (
25 goTotalMemory = "/memory/classes/total:bytes"
26 goMemoryReleased = "/memory/classes/heap/released:bytes"
27 goHeapMemory = "/memory/classes/heap/stacks:bytes"
28 goMemoryLimit = "/gc/gomemlimit:bytes"
29 goMemoryAllocated = "/gc/heap/allocs:bytes"
30 goMemoryAllocations = "/gc/heap/allocs:objects"
31 goMemoryGoal = "/gc/heap/goal:bytes"
32 goGoroutines = "/sched/goroutines:goroutines"
33 goMaxProcs = "/sched/gomaxprocs:threads"
34 goConfigGC = "/gc/gogc:percent"
35 goSchedLatencies = "/sched/latencies:seconds"
36 )
37
38 // Start initializes reporting of runtime metrics using the supplied config.
39 // For goroutine scheduling metrics, additionally see [NewProducer].
40 //
41 // Metrics emitted by Start includes:
42 //
43 // go.memory.used By Memory used by the Go runtime.
44 // go.memory.limit By Go runtime memory limit configured by the user, if a limit exists.
45 // go.memory.allocated By Memory allocated to the heap by the application.
46 // go.memory.allocations {allocation} Count of allocations to the heap by the application.
47 // go.memory.gc.goal By Heap size target for the end of the GC cycle.
48 // go.goroutine.count {goroutine} Count of live goroutines.
49 // go.processor.limit {thread} The number of OS threads that can execute user-level Go code simultaneously.
50 // go.config.gogc % Heap size target percentage configured by the user, otherwise 100.
51 //
52 // When the OTEL_GO_X_DEPRECATED_RUNTIME_METRICS environment variable is set to
53 // true, the following deprecated metrics are produced:
54 //
55 // runtime.go.cgo.calls - Number of cgo calls made by the current process
56 // runtime.go.gc.count - Number of completed garbage collection cycles
57 // runtime.go.gc.pause_ns (ns) Amount of nanoseconds in GC stop-the-world pauses
58 // runtime.go.gc.pause_total_ns (ns) Cumulative nanoseconds in GC stop-the-world pauses since the program started
59 // runtime.go.goroutines - Number of goroutines that currently exist
60 // runtime.go.lookups - Number of pointer lookups performed by the runtime
61 // runtime.go.mem.heap_alloc (bytes) Bytes of allocated heap objects
62 // runtime.go.mem.heap_idle (bytes) Bytes in idle (unused) spans
63 // runtime.go.mem.heap_inuse (bytes) Bytes in in-use spans
64 // runtime.go.mem.heap_objects - Number of allocated heap objects
65 // runtime.go.mem.heap_released (bytes) Bytes of idle spans whose physical memory has been returned to the OS
66 // runtime.go.mem.heap_sys (bytes) Bytes of heap memory obtained from the OS
67 // runtime.go.mem.live_objects - Number of live objects is the number of cumulative Mallocs - Frees
68 // runtime.uptime (ms) Milliseconds since application was initialized
69 func Start(opts ...Option) error {
70 c := newConfig(opts...)
71 meter := c.MeterProvider.Meter(
72 ScopeName,
73 metric.WithInstrumentationVersion(Version),
74 )
75 if x.DeprecatedRuntimeMetrics.Enabled() {
76 if err := deprecatedruntime.Start(meter, c.MinimumReadMemStatsInterval); err != nil {
77 return err
78 }
79 }
80 memoryUsed, err := goconv.NewMemoryUsed(meter)
81 if err != nil {
82 return err
83 }
84 memoryLimit, err := goconv.NewMemoryLimit(meter)
85 if err != nil {
86 return err
87 }
88 memoryAllocated, err := goconv.NewMemoryAllocated(meter)
89 if err != nil {
90 return err
91 }
92 memoryAllocations, err := goconv.NewMemoryAllocations(meter)
93 if err != nil {
94 return err
95 }
96 memoryGCGoal, err := goconv.NewMemoryGCGoal(meter)
97 if err != nil {
98 return err
99 }
100 goroutineCount, err := goconv.NewGoroutineCount(meter)
101 if err != nil {
102 return err
103 }
104 processorLimit, err := goconv.NewProcessorLimit(meter)
105 if err != nil {
106 return err
107 }
108 configGogc, err := goconv.NewConfigGogc(meter)
109 if err != nil {
110 return err
111 }
112
113 otherMemoryOpt := metric.WithAttributeSet(
114 attribute.NewSet(memoryUsed.AttrMemoryType(goconv.MemoryTypeOther)),
115 )
116 stackMemoryOpt := metric.WithAttributeSet(
117 attribute.NewSet(memoryUsed.AttrMemoryType(goconv.MemoryTypeStack)),
118 )
119 collector := newCollector(c.MinimumReadMemStatsInterval, runtimeMetrics)
120 var lock sync.Mutex
121 _, err = meter.RegisterCallback(
122 func(_ context.Context, o metric.Observer) error {
123 lock.Lock()
124 defer lock.Unlock()
125 collector.refresh()
126 stackMemory := collector.getInt(goHeapMemory)
127 o.ObserveInt64(memoryUsed.Inst(), stackMemory, stackMemoryOpt)
128 totalMemory := collector.getInt(goTotalMemory) - collector.getInt(goMemoryReleased)
129 otherMemory := totalMemory - stackMemory
130 o.ObserveInt64(memoryUsed.Inst(), otherMemory, otherMemoryOpt)
131 // Only observe the limit metric if a limit exists
132 if limit := collector.getInt(goMemoryLimit); limit != math.MaxInt64 {
133 o.ObserveInt64(memoryLimit.Inst(), limit)
134 }
135 o.ObserveInt64(memoryAllocated.Inst(), collector.getInt(goMemoryAllocated))
136 o.ObserveInt64(memoryAllocations.Inst(), collector.getInt(goMemoryAllocations))
137 o.ObserveInt64(memoryGCGoal.Inst(), collector.getInt(goMemoryGoal))
138 o.ObserveInt64(goroutineCount.Inst(), collector.getInt(goGoroutines))
139 o.ObserveInt64(processorLimit.Inst(), collector.getInt(goMaxProcs))
140 o.ObserveInt64(configGogc.Inst(), collector.getInt(goConfigGC))
141 return nil
142 },
143 memoryUsed.Inst(),
144 memoryLimit.Inst(),
145 memoryAllocated.Inst(),
146 memoryAllocations.Inst(),
147 memoryGCGoal.Inst(),
148 goroutineCount.Inst(),
149 processorLimit.Inst(),
150 configGogc.Inst(),
151 )
152 if err != nil {
153 return err
154 }
155 return nil
156 }
157
158 // These are the metrics we actually fetch from the go runtime.
159 var runtimeMetrics = []string{
160 goTotalMemory,
161 goMemoryReleased,
162 goHeapMemory,
163 goMemoryLimit,
164 goMemoryAllocated,
165 goMemoryAllocations,
166 goMemoryGoal,
167 goGoroutines,
168 goMaxProcs,
169 goConfigGC,
170 }
171
172 type goCollector struct {
173 // now is used to replace the implementation of time.Now for testing
174 now func() time.Time
175 // lastCollect tracks the last time metrics were refreshed
176 lastCollect time.Time
177 // minimumInterval is the minimum amount of time between calls to metrics.Read
178 minimumInterval time.Duration
179 // sampleBuffer is populated by runtime/metrics
180 sampleBuffer []metrics.Sample
181 // sampleMap allows us to easily get the value of a single metric
182 sampleMap map[string]*metrics.Sample
183 }
184
185 func newCollector(minimumInterval time.Duration, metricNames []string) *goCollector {
186 g := &goCollector{
187 sampleBuffer: make([]metrics.Sample, 0, len(metricNames)),
188 sampleMap: make(map[string]*metrics.Sample, len(metricNames)),
189 minimumInterval: minimumInterval,
190 now: time.Now,
191 }
192 for _, metricName := range metricNames {
193 g.sampleBuffer = append(g.sampleBuffer, metrics.Sample{Name: metricName})
194 // sampleMap references a position in the sampleBuffer slice. If an
195 // element is appended to sampleBuffer, it must be added to sampleMap
196 // for the sample to be accessible in sampleMap.
197 g.sampleMap[metricName] = &g.sampleBuffer[len(g.sampleBuffer)-1]
198 }
199 return g
200 }
201
202 func (g *goCollector) refresh() {
203 now := g.now()
204 if now.Sub(g.lastCollect) < g.minimumInterval {
205 // refresh was invoked more frequently than allowed by the minimum
206 // interval. Do nothing.
207 return
208 }
209 metrics.Read(g.sampleBuffer)
210 g.lastCollect = now
211 }
212
213 func (g *goCollector) getInt(name string) int64 {
214 if s, ok := g.sampleMap[name]; ok && s.Value.Kind() == metrics.KindUint64 {
215 v := s.Value.Uint64()
216 if v > math.MaxInt64 {
217 return math.MaxInt64
218 }
219 return int64(v)
220 }
221 return 0
222 }
223
224 func (g *goCollector) getHistogram(name string) *metrics.Float64Histogram {
225 if s, ok := g.sampleMap[name]; ok && s.Value.Kind() == metrics.KindFloat64Histogram {
226 return s.Value.Float64Histogram()
227 }
228 return nil
229 }