/
runtime_metrics.go
171 lines (156 loc) · 5.39 KB
/
runtime_metrics.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
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package metrics
import (
"runtime"
"sync"
"sync/atomic"
"time"
"github.com/uber-go/tally"
)
// _numGCThreshold comes from the PauseNs buffer size https://golang.org/pkg/runtime/#MemStats
var _numGCThreshold = uint32(256)
// StartCollectingRuntimeMetrics starts generating runtime metrics under given metrics scope with
// given frequency.
// Recommended usage:
// rmr := StartCollectingRuntimeMetrics(rootScope.Scope("runtime"), time.Second)
// ...
// rmr.Close()
func StartCollectingRuntimeMetrics(
scope tally.Scope, collectInterval time.Duration, config RuntimeConfig,
) *RuntimeCollector {
if config.Disabled {
return nil
}
runtimeCollector := NewRuntimeCollector(scope, collectInterval)
runtimeCollector.Start()
return runtimeCollector
}
type runtimeMetrics struct {
numGoRoutines tally.Gauge
goMaxProcs tally.Gauge
memoryAllocated tally.Gauge
memoryHeap tally.Gauge
memoryHeapIdle tally.Gauge
memoryHeapInuse tally.Gauge
memoryStack tally.Gauge
numGC tally.Counter
gcPauseMs tally.Timer
lastNumGC uint32
}
// RuntimeCollector is a struct containing the state of the runtimeMetrics.
type RuntimeCollector struct {
scope tally.Scope
collectInterval time.Duration
metrics runtimeMetrics
startedMutex sync.RWMutex
started bool // protected by startedMutex
quit chan struct{}
}
// RuntimeConfig contains configuration for initializing runtime metrics
type RuntimeConfig struct {
Disabled bool `yaml:"disabled"`
}
// NewRuntimeCollector creates a new RuntimeCollector.
func NewRuntimeCollector(
scope tally.Scope, collectInterval time.Duration,
) *RuntimeCollector {
var memstats runtime.MemStats
runtime.ReadMemStats(&memstats)
return &RuntimeCollector{
scope: scope,
collectInterval: collectInterval,
metrics: runtimeMetrics{
numGoRoutines: scope.Gauge("num-goroutines"),
goMaxProcs: scope.Gauge("gomaxprocs"),
memoryAllocated: scope.Gauge("memory.allocated"),
memoryHeap: scope.Gauge("memory.heap"),
memoryHeapIdle: scope.Gauge("memory.heapidle"),
memoryHeapInuse: scope.Gauge("memory.heapinuse"),
memoryStack: scope.Gauge("memory.stack"),
numGC: scope.Counter("memory.num-gc"),
gcPauseMs: scope.Timer("memory.gc-pause-ms"),
lastNumGC: memstats.NumGC,
},
started: false,
quit: make(chan struct{}),
}
}
// IsRunning returns true if the collector has been started and false if not.
func (r *RuntimeCollector) IsRunning() bool {
r.startedMutex.RLock()
defer r.startedMutex.RUnlock()
return r.started
}
// Start starts the collector thread that periodically emits metrics.
func (r *RuntimeCollector) Start() {
r.startedMutex.RLock()
if r.started {
r.startedMutex.RUnlock()
return
}
r.startedMutex.RUnlock()
go func() {
ticker := time.NewTicker(r.collectInterval)
for {
select {
case <-ticker.C:
r.generate()
case <-r.quit:
ticker.Stop()
return
}
}
}()
r.startedMutex.Lock()
r.started = true
r.startedMutex.Unlock()
}
// generate sends runtime metrics to the local metrics collector.
func (r *RuntimeCollector) generate() {
var memStats runtime.MemStats
runtime.ReadMemStats(&memStats)
r.metrics.numGoRoutines.Update(float64(runtime.NumGoroutine()))
r.metrics.goMaxProcs.Update(float64(runtime.GOMAXPROCS(0)))
r.metrics.memoryAllocated.Update(float64(memStats.Alloc))
r.metrics.memoryHeap.Update(float64(memStats.HeapAlloc))
r.metrics.memoryHeapIdle.Update(float64(memStats.HeapIdle))
r.metrics.memoryHeapInuse.Update(float64(memStats.HeapInuse))
r.metrics.memoryStack.Update(float64(memStats.StackInuse))
// memStats.NumGC is a perpetually incrementing counter (unless it wraps at 2^32)
num := memStats.NumGC
lastNum := atomic.SwapUint32(&r.metrics.lastNumGC, num) // reset for the next iteration
if delta := num - lastNum; delta > 0 {
r.metrics.numGC.Inc(int64(delta))
// Match the MemStats buffer and generate only the last _numGCThreshold
if delta >= _numGCThreshold {
lastNum = num - _numGCThreshold
}
for i := lastNum; i != num; i++ {
pause := memStats.PauseNs[i%256]
r.metrics.gcPauseMs.Record(time.Duration(pause))
}
}
}
// Close stops collecting runtime metrics. It cannot be started again after it's
// been stopped.
func (r *RuntimeCollector) Close() {
close(r.quit)
}