-
Notifications
You must be signed in to change notification settings - Fork 566
/
runtime.go
352 lines (299 loc) · 9.9 KB
/
runtime.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package runtime // import "go.opentelemetry.io/contrib/instrumentation/runtime"
import (
"context"
goruntime "runtime"
"sync"
"time"
"go.opentelemetry.io/contrib"
"go.opentelemetry.io/otel/api/global"
"go.opentelemetry.io/otel/api/metric"
"go.opentelemetry.io/otel/api/unit"
)
// Runtime reports the work-in-progress conventional runtime metrics specified by OpenTelemetry
type runtime struct {
config config
meter metric.Meter
}
// config contains optional settings for reporting runtime metrics.
type config struct {
// MinimumReadMemStatsInterval sets the mininum interval
// between calls to runtime.ReadMemStats(). Negative values
// are ignored.
MinimumReadMemStatsInterval time.Duration
// MeterProvider sets the metric.Provider. If nil, the global
// Provider will be used.
MeterProvider metric.Provider
}
// Option supports configuring optional settings for runtime metrics.
type Option interface {
// ApplyRuntime updates *config.
ApplyRuntime(*config)
}
// DefaultMinimumReadMemStatsInterval is the default minimum interval
// between calls to runtime.ReadMemStats(). Use the
// WithMinimumReadMemStatsInterval() option to modify this setting in
// Start().
const DefaultMinimumReadMemStatsInterval time.Duration = 15 * time.Second
// WithMinimumReadMemStatsInterval sets a minimum interval between calls to
// runtime.ReadMemStats(), which is a relatively expensive call to make
// frequently. This setting is ignored when `d` is negative.
func WithMinimumReadMemStatsInterval(d time.Duration) Option {
return minimumReadMemStatsIntervalOption(d)
}
type minimumReadMemStatsIntervalOption time.Duration
// ApplyRuntime implements Option.
func (o minimumReadMemStatsIntervalOption) ApplyRuntime(c *config) {
if o >= 0 {
c.MinimumReadMemStatsInterval = time.Duration(o)
}
}
// WithMeterProvider sets the Metric implementation to use for
// reporting. If this option is not used, the global metric.Provider
// will be used. `provider` must be non-nil.
func WithMeterProvider(provider metric.Provider) Option {
return metricProviderOption{provider}
}
type metricProviderOption struct{ metric.Provider }
// ApplyRuntime implements Option.
func (o metricProviderOption) ApplyRuntime(c *config) {
c.MeterProvider = o.Provider
}
// configure computes a config from the supplied Options.
func configure(opts ...Option) config {
c := config{
MeterProvider: global.MeterProvider(),
MinimumReadMemStatsInterval: DefaultMinimumReadMemStatsInterval,
}
for _, opt := range opts {
opt.ApplyRuntime(&c)
}
return c
}
// Start initializes reporting of runtime metrics using the supplied config.
func Start(opts ...Option) error {
c := configure(opts...)
if c.MinimumReadMemStatsInterval < 0 {
c.MinimumReadMemStatsInterval = DefaultMinimumReadMemStatsInterval
}
if c.MeterProvider == nil {
c.MeterProvider = global.MeterProvider()
}
r := &runtime{
meter: c.MeterProvider.Meter(
"go.opentelemetry.io/contrib/instrumentation/runtime",
metric.WithInstrumentationVersion(contrib.SemVersion()),
),
config: c,
}
return r.register()
}
func (r *runtime) register() error {
startTime := time.Now()
if _, err := r.meter.NewInt64SumObserver(
"runtime.uptime",
func(_ context.Context, result metric.Int64ObserverResult) {
result.Observe(time.Since(startTime).Milliseconds())
},
metric.WithUnit(unit.Milliseconds),
metric.WithDescription("Milliseconds since application was initialized"),
); err != nil {
return err
}
if _, err := r.meter.NewInt64UpDownSumObserver(
"runtime.go.goroutines",
func(_ context.Context, result metric.Int64ObserverResult) {
result.Observe(int64(goruntime.NumGoroutine()))
},
metric.WithDescription("Number of goroutines that currently exist"),
); err != nil {
return err
}
if _, err := r.meter.NewInt64SumObserver(
"runtime.go.cgo.calls",
func(_ context.Context, result metric.Int64ObserverResult) {
result.Observe(goruntime.NumCgoCall())
},
metric.WithDescription("Number of cgo calls made by the current process"),
); err != nil {
return err
}
if err := r.registerMemStats(); err != nil {
return err
}
return nil
}
func (r *runtime) registerMemStats() error {
var (
err error
heapAlloc metric.Int64UpDownSumObserver
heapIdle metric.Int64UpDownSumObserver
heapInuse metric.Int64UpDownSumObserver
heapObjects metric.Int64UpDownSumObserver
heapReleased metric.Int64UpDownSumObserver
heapSys metric.Int64UpDownSumObserver
liveObjects metric.Int64UpDownSumObserver
// TODO: is ptrLookups useful? I've not seen a value
// other than zero.
ptrLookups metric.Int64SumObserver
gcCount metric.Int64SumObserver
pauseTotalNs metric.Int64SumObserver
gcPauseNs metric.Int64ValueRecorder
lastNumGC uint32
lastMemStats time.Time
memStats goruntime.MemStats
// lock prevents a race between batch observer and instrument registration.
lock sync.Mutex
)
lock.Lock()
defer lock.Unlock()
batchObserver := r.meter.NewBatchObserver(func(ctx context.Context, result metric.BatchObserverResult) {
lock.Lock()
defer lock.Unlock()
now := time.Now()
if now.Sub(lastMemStats) >= r.config.MinimumReadMemStatsInterval {
goruntime.ReadMemStats(&memStats)
lastMemStats = now
}
result.Observe(
nil,
heapAlloc.Observation(int64(memStats.HeapAlloc)),
heapIdle.Observation(int64(memStats.HeapIdle)),
heapInuse.Observation(int64(memStats.HeapInuse)),
heapObjects.Observation(int64(memStats.HeapObjects)),
heapReleased.Observation(int64(memStats.HeapReleased)),
heapSys.Observation(int64(memStats.HeapSys)),
liveObjects.Observation(int64(memStats.Mallocs-memStats.Frees)),
ptrLookups.Observation(int64(memStats.Lookups)),
gcCount.Observation(int64(memStats.NumGC)),
pauseTotalNs.Observation(int64(memStats.PauseTotalNs)),
)
computeGCPauses(ctx, &gcPauseNs, memStats.PauseNs[:], lastNumGC, memStats.NumGC)
lastNumGC = memStats.NumGC
})
if heapAlloc, err = batchObserver.NewInt64UpDownSumObserver(
"runtime.go.mem.heap_alloc",
metric.WithUnit(unit.Bytes),
metric.WithDescription("Bytes of allocated heap objects"),
); err != nil {
return err
}
if heapIdle, err = batchObserver.NewInt64UpDownSumObserver(
"runtime.go.mem.heap_idle",
metric.WithUnit(unit.Bytes),
metric.WithDescription("Bytes in idle (unused) spans"),
); err != nil {
return err
}
if heapInuse, err = batchObserver.NewInt64UpDownSumObserver(
"runtime.go.mem.heap_inuse",
metric.WithUnit(unit.Bytes),
metric.WithDescription("Bytes in in-use spans"),
); err != nil {
return err
}
if heapObjects, err = batchObserver.NewInt64UpDownSumObserver(
"runtime.go.mem.heap_objects",
metric.WithDescription("Number of allocated heap objects"),
); err != nil {
return err
}
// FYI see https://github.com/golang/go/issues/32284 to help
// understand the meaning of this value.
if heapReleased, err = batchObserver.NewInt64UpDownSumObserver(
"runtime.go.mem.heap_released",
metric.WithUnit(unit.Bytes),
metric.WithDescription("Bytes of idle spans whose physical memory has been returned to the OS"),
); err != nil {
return err
}
if heapSys, err = batchObserver.NewInt64UpDownSumObserver(
"runtime.go.mem.heap_sys",
metric.WithUnit(unit.Bytes),
metric.WithDescription("Bytes of heap memory obtained from the OS"),
); err != nil {
return err
}
if ptrLookups, err = batchObserver.NewInt64SumObserver(
"runtime.go.mem.lookups",
metric.WithDescription("Number of pointer lookups performed by the runtime"),
); err != nil {
return err
}
if liveObjects, err = batchObserver.NewInt64UpDownSumObserver(
"runtime.go.mem.live_objects",
metric.WithDescription("Number of live objects is the number of cumulative Mallocs - Frees"),
); err != nil {
return err
}
if gcCount, err = batchObserver.NewInt64SumObserver(
"runtime.go.gc.count",
metric.WithDescription("Number of completed garbage collection cycles"),
); err != nil {
return err
}
// Note that the following could be derived as a sum of
// individual pauses, but we may lose individual pauses if the
// observation interval is too slow.
if pauseTotalNs, err = batchObserver.NewInt64SumObserver(
"runtime.go.gc.pause_total_ns",
// TODO: nanoseconds units
metric.WithDescription("Cumulative nanoseconds in GC stop-the-world pauses since the program started"),
); err != nil {
return err
}
if gcPauseNs, err = r.meter.NewInt64ValueRecorder(
"runtime.go.gc.pause_ns",
// TODO: nanoseconds units
metric.WithDescription("Amount of nanoseconds in GC stop-the-world pauses"),
); err != nil {
return err
}
return nil
}
func computeGCPauses(
ctx context.Context,
recorder *metric.Int64ValueRecorder,
circular []uint64,
lastNumGC, currentNumGC uint32,
) {
delta := int(int64(currentNumGC) - int64(lastNumGC))
if delta == 0 {
return
}
if delta >= len(circular) {
// There were > 256 collections, some may have been lost.
recordGCPauses(ctx, recorder, circular)
return
}
length := uint32(len(circular))
i := lastNumGC % length
j := currentNumGC % length
if j < i { // wrap around the circular buffer
recordGCPauses(ctx, recorder, circular[i:])
recordGCPauses(ctx, recorder, circular[:j])
return
}
recordGCPauses(ctx, recorder, circular[i:j])
}
func recordGCPauses(
ctx context.Context,
recorder *metric.Int64ValueRecorder,
pauses []uint64,
) {
for _, pause := range pauses {
recorder.Record(ctx, int64(pause))
}
}