/
memorylimiter.go
222 lines (186 loc) · 6.83 KB
/
memorylimiter.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
// 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 memorylimiter
import (
"context"
"errors"
"runtime"
"sync/atomic"
"time"
"go.opencensus.io/stats"
"go.uber.org/zap"
"go.opentelemetry.io/collector/consumer/pdata"
"go.opentelemetry.io/collector/consumer/pdatautil"
"go.opentelemetry.io/collector/obsreport"
"go.opentelemetry.io/collector/processor"
)
var (
// errForcedDrop will be returned to callers of ConsumeTraceData to indicate
// that data is being dropped due to high memory usage.
errForcedDrop = errors.New("data dropped due to high memory usage")
// Construction errors
errCheckIntervalOutOfRange = errors.New(
"checkInterval must be greater than zero")
errMemAllocLimitOutOfRange = errors.New(
"memAllocLimit must be greater than zero")
errMemSpikeLimitOutOfRange = errors.New(
"memSpikeLimit must be smaller than memAllocLimit")
)
type memoryLimiter struct {
memAllocLimit uint64
memSpikeLimit uint64
memCheckWait time.Duration
ballastSize uint64
// forceDrop is used atomically to indicate when data should be dropped.
forceDrop int64
ticker *time.Ticker
// The function to read the mem values is set as a reference to help with
// testing different values.
readMemStatsFn func(m *runtime.MemStats)
// Fields used for logging.
procName string
logger *zap.Logger
configMismatchedLogged bool
}
// newMemoryLimiter returns a new memorylimiter processor.
func newMemoryLimiter(logger *zap.Logger, cfg *Config) (*memoryLimiter, error) {
const mibBytes = 1024 * 1024
memAllocLimit := uint64(cfg.MemoryLimitMiB) * mibBytes
memSpikeLimit := uint64(cfg.MemorySpikeLimitMiB) * mibBytes
ballastSize := uint64(cfg.BallastSizeMiB) * mibBytes
if cfg.CheckInterval <= 0 {
return nil, errCheckIntervalOutOfRange
}
if memAllocLimit == 0 {
return nil, errMemAllocLimitOutOfRange
}
if memSpikeLimit >= memAllocLimit {
return nil, errMemSpikeLimitOutOfRange
}
ml := &memoryLimiter{
memAllocLimit: memAllocLimit,
memSpikeLimit: memSpikeLimit,
memCheckWait: cfg.CheckInterval,
ballastSize: ballastSize,
ticker: time.NewTicker(cfg.CheckInterval),
readMemStatsFn: runtime.ReadMemStats,
procName: cfg.Name(),
logger: logger,
}
ml.startMonitoring()
return ml, nil
}
func (ml *memoryLimiter) shutdown(context.Context) error {
ml.ticker.Stop()
return nil
}
// ProcessTraces implements the TProcessor interface
func (ml *memoryLimiter) ProcessTraces(ctx context.Context, td pdata.Traces) (pdata.Traces, error) {
numSpans := td.SpanCount()
if ml.forcingDrop() {
stats.Record(
ctx,
processor.StatDroppedSpanCount.M(int64(numSpans)),
processor.StatTraceBatchesDroppedCount.M(1))
// TODO: actually to be 100% sure that this is "refused" and not "dropped"
// it is necessary to check the pipeline to see if this is directly connected
// to a receiver (ie.: a receiver is on the call stack). For now it
// assumes that the pipeline is properly configured and a receiver is on the
// callstack.
obsreport.ProcessorTraceDataRefused(ctx, numSpans)
return td, errForcedDrop
}
// Even if the next consumer returns error record the data as accepted by
// this processor.
obsreport.ProcessorTraceDataAccepted(ctx, numSpans)
return td, nil
}
// ProcessMetrics implements the MProcessor interface
func (ml *memoryLimiter) ProcessMetrics(ctx context.Context, md pdata.Metrics) (pdata.Metrics, error) {
_, numDataPoints := pdatautil.MetricAndDataPointCount(md)
if ml.forcingDrop() {
// TODO: actually to be 100% sure that this is "refused" and not "dropped"
// it is necessary to check the pipeline to see if this is directly connected
// to a receiver (ie.: a receiver is on the call stack). For now it
// assumes that the pipeline is properly configured and a receiver is on the
// callstack.
obsreport.ProcessorMetricsDataRefused(ctx, numDataPoints)
return md, errForcedDrop
}
// Even if the next consumer returns error record the data as accepted by
// this processor.
obsreport.ProcessorMetricsDataAccepted(ctx, numDataPoints)
return md, nil
}
// ProcessLogs implements the LProcessor interface
func (ml *memoryLimiter) ProcessLogs(ctx context.Context, ld pdata.Logs) (pdata.Logs, error) {
numRecords := ld.LogRecordCount()
if ml.forcingDrop() {
// TODO: actually to be 100% sure that this is "refused" and not "dropped"
// it is necessary to check the pipeline to see if this is directly connected
// to a receiver (ie.: a receiver is on the call stack). For now it
// assumes that the pipeline is properly configured and a receiver is on the
// callstack.
obsreport.ProcessorLogRecordsRefused(ctx, numRecords)
return ld, errForcedDrop
}
// Even if the next consumer returns error record the data as accepted by
// this processor.
obsreport.ProcessorLogRecordsAccepted(ctx, numRecords)
return ld, nil
}
func (ml *memoryLimiter) readMemStats(ms *runtime.MemStats) {
ml.readMemStatsFn(ms)
// If proper configured ms.Alloc should be at least ml.ballastSize but since
// a misconfiguration is possible check for that here.
if ms.Alloc >= ml.ballastSize {
ms.Alloc -= ml.ballastSize
} else if !ml.configMismatchedLogged {
// This indicates misconfiguration. Log it once.
ml.configMismatchedLogged = true
ml.logger.Warn(typeStr + " is likely incorrectly configured. " + ballastSizeMibKey +
" must be set equal to --mem-ballast-size-mib command line option.")
}
}
// startMonitoring starts a ticker'd goroutine that will check memory usage
// every checkInterval period.
func (ml *memoryLimiter) startMonitoring() {
go func() {
for range ml.ticker.C {
ml.memCheck()
}
}()
}
// forcingDrop indicates when memory resources need to be released.
func (ml *memoryLimiter) forcingDrop() bool {
return atomic.LoadInt64(&ml.forceDrop) != 0
}
func (ml *memoryLimiter) memCheck() {
ms := &runtime.MemStats{}
ml.readMemStats(ms)
ml.memLimiting(ms)
}
func (ml *memoryLimiter) shouldForceDrop(ms *runtime.MemStats) bool {
return ml.memAllocLimit <= ms.Alloc || ml.memAllocLimit-ms.Alloc <= ml.memSpikeLimit
}
func (ml *memoryLimiter) memLimiting(ms *runtime.MemStats) {
if !ml.shouldForceDrop(ms) {
atomic.StoreInt64(&ml.forceDrop, 0)
} else {
atomic.StoreInt64(&ml.forceDrop, 1)
// Force a GC at this point and see if this is enough to get to
// the desired level.
runtime.GC()
}
}