-
Notifications
You must be signed in to change notification settings - Fork 451
/
writer.go
431 lines (376 loc) · 11.6 KB
/
writer.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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
// Copyright (c) 2018 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 client
import (
"errors"
"sync"
"github.com/m3db/m3/src/cluster/placement"
"github.com/m3db/m3/src/metrics/encoding"
"github.com/m3db/m3/src/metrics/encoding/protobuf"
"github.com/m3db/m3/src/metrics/metadata"
"github.com/m3db/m3/src/metrics/metric"
"github.com/m3db/m3/src/metrics/metric/aggregated"
"github.com/m3db/m3/src/metrics/metric/unaggregated"
"github.com/m3db/m3/src/metrics/policy"
xerrors "github.com/m3db/m3/src/x/errors"
"github.com/uber-go/tally"
"go.uber.org/atomic"
"go.uber.org/zap"
)
var (
errInstanceWriterClosed = errors.New("instance writer is closed")
errUnrecognizedMetricType = errors.New("unrecognized metric type")
errUnrecognizedPayloadType = errors.New("unrecognized payload type")
)
type instanceWriter interface {
// Write writes a metric payload for a given shard.
Write(shard uint32, payload payloadUnion) error
// Flush flushes any buffered metrics.
Flush() error
// QueueSize returns the size of the instance queue.
QueueSize() int
// Close closes the writer.
Close() error
}
type newLockedEncoderFn func(protobuf.UnaggregatedOptions) *lockedEncoder
type writer struct {
metrics writerMetrics
encoderOpts protobuf.UnaggregatedOptions
queue instanceQueue
log *zap.Logger
encodersByShard map[uint32]*lockedEncoder
newLockedEncoderFn newLockedEncoderFn
maxTimerBatchSize int
maxBatchSize int
sync.RWMutex
closed bool
}
func newInstanceWriter(instance placement.Instance, opts Options) instanceWriter {
var (
iOpts = opts.InstrumentOptions()
scope = iOpts.MetricsScope()
queueOpts = opts.SetInstrumentOptions(iOpts.SetMetricsScope(scope.SubScope("queue")))
)
w := &writer{
log: iOpts.Logger(),
metrics: newWriterMetrics(scope),
maxBatchSize: opts.MaxBatchSize(),
maxTimerBatchSize: opts.MaxTimerBatchSize(),
encoderOpts: opts.EncoderOptions(),
queue: newInstanceQueue(instance, queueOpts),
encodersByShard: make(map[uint32]*lockedEncoder),
}
w.newLockedEncoderFn = newLockedEncoder
return w
}
func (w *writer) Write(shard uint32, payload payloadUnion) error {
w.RLock()
if w.closed {
w.RUnlock()
return errInstanceWriterClosed
}
encoder, exists := w.encodersByShard[shard]
if exists {
err := w.encodeWithLock(encoder, payload)
w.RUnlock()
return err
}
w.RUnlock()
w.Lock()
if w.closed {
w.Unlock()
return errInstanceWriterClosed
}
encoder, exists = w.encodersByShard[shard]
if exists {
err := w.encodeWithLock(encoder, payload)
w.Unlock()
return err
}
encoder = w.newLockedEncoderFn(w.encoderOpts)
w.encodersByShard[shard] = encoder
err := w.encodeWithLock(encoder, payload)
w.Unlock()
return err
}
func (w *writer) Flush() error {
w.RLock()
if w.closed {
w.RUnlock()
return errInstanceWriterClosed
}
err := w.flushWithLock()
w.RUnlock()
if err != nil {
w.metrics.flushErrors.Inc(1)
return err
}
return nil
}
func (w *writer) Close() error {
w.Lock()
defer w.Unlock()
if w.closed {
return errInstanceWriterClosed
}
w.closed = true
if err := w.flushWithLock(); err != nil {
w.metrics.flushErrors.Inc(1)
}
return w.queue.Close()
}
func (w *writer) QueueSize() int {
return w.queue.Size()
}
func (w *writer) encodeWithLock(
encoder *lockedEncoder,
payload payloadUnion,
) error {
encoder.Lock()
var (
sizeBefore = encoder.Len()
err error
)
switch payload.payloadType {
case untimedType:
err = w.encodeUntimedWithLock(encoder, payload.untimed.metric, payload.untimed.metadatas)
case forwardedType:
err = w.encodeForwardedWithLock(encoder, payload.forwarded.metric, payload.forwarded.metadata)
case timedType:
err = w.encodeTimedWithLock(encoder, payload.timed.metric, payload.timed.metadata)
case timedWithStagedMetadatasType:
elem := payload.timedWithStagedMetadatas
err = w.encodeTimedWithStagedMetadatasWithLock(encoder, elem.metric, elem.metadatas)
case passthroughType:
err = w.encodePassthroughWithLock(encoder, payload.passthrough.metric, payload.passthrough.storagePolicy)
default:
err = errUnrecognizedPayloadType
}
if err != nil {
w.metrics.encodeErrors.Inc(1)
w.log.Error("encode untimed metric error",
zap.Any("payload", payload),
zap.Int("payloadType", int(payload.payloadType)),
zap.Error(err),
)
// Rewind buffer and clear out the encoder error.
encoder.Truncate(sizeBefore) //nolint:errcheck
encoder.Unlock()
return err
}
if encoder.Len() < w.maxBatchSize {
encoder.Unlock()
return nil
}
buffer := encoder.Relinquish()
encoder.Unlock()
return w.enqueueBuffer(buffer)
}
func (w *writer) encodeUntimedWithLock(
encoder *lockedEncoder,
metricUnion unaggregated.MetricUnion,
metadatas metadata.StagedMetadatas,
) error {
switch metricUnion.Type {
case metric.CounterType:
msg := encoding.UnaggregatedMessageUnion{
Type: encoding.CounterWithMetadatasType,
CounterWithMetadatas: unaggregated.CounterWithMetadatas{
Counter: metricUnion.Counter(),
StagedMetadatas: metadatas,
}}
return encoder.EncodeMessage(msg)
case metric.TimerType:
// If there is no limit on the timer batch size, write the full batch.
if w.maxTimerBatchSize == 0 {
msg := encoding.UnaggregatedMessageUnion{
Type: encoding.BatchTimerWithMetadatasType,
BatchTimerWithMetadatas: unaggregated.BatchTimerWithMetadatas{
BatchTimer: metricUnion.BatchTimer(),
StagedMetadatas: metadatas,
}}
return encoder.EncodeMessage(msg)
}
// Otherwise, honor maximum timer batch size.
var (
batchTimer = metricUnion.BatchTimer()
timerValues = batchTimer.Values
numTimerValues = len(timerValues)
start, end int
)
for start = 0; start < numTimerValues; start = end {
end = start + w.maxTimerBatchSize
if end > numTimerValues {
end = numTimerValues
}
singleBatchTimer := unaggregated.BatchTimer{
ID: batchTimer.ID,
Values: timerValues[start:end],
Annotation: metricUnion.Annotation,
}
msg := encoding.UnaggregatedMessageUnion{
Type: encoding.BatchTimerWithMetadatasType,
BatchTimerWithMetadatas: unaggregated.BatchTimerWithMetadatas{
BatchTimer: singleBatchTimer,
StagedMetadatas: metadatas,
}}
if err := encoder.EncodeMessage(msg); err != nil {
return err
}
// Unlock the encoder before we encode another metric to ensure other
// goroutines have an opportunity to encode metrics while larger timer
// batches are being encoded.
if end < numTimerValues {
encoder.Unlock()
encoder.Lock()
}
}
return nil
case metric.GaugeType:
msg := encoding.UnaggregatedMessageUnion{
Type: encoding.GaugeWithMetadatasType,
GaugeWithMetadatas: unaggregated.GaugeWithMetadatas{
Gauge: metricUnion.Gauge(),
StagedMetadatas: metadatas,
}}
return encoder.EncodeMessage(msg)
default:
}
return errUnrecognizedMetricType
}
func (w *writer) encodeForwardedWithLock(
encoder *lockedEncoder,
metric aggregated.ForwardedMetric,
metadata metadata.ForwardMetadata,
) error {
msg := encoding.UnaggregatedMessageUnion{
Type: encoding.ForwardedMetricWithMetadataType,
ForwardedMetricWithMetadata: aggregated.ForwardedMetricWithMetadata{
ForwardedMetric: metric,
ForwardMetadata: metadata,
}}
return encoder.EncodeMessage(msg)
}
func (w *writer) encodeTimedWithLock(
encoder *lockedEncoder,
metric aggregated.Metric,
metadata metadata.TimedMetadata,
) error {
msg := encoding.UnaggregatedMessageUnion{
Type: encoding.TimedMetricWithMetadataType,
TimedMetricWithMetadata: aggregated.TimedMetricWithMetadata{
Metric: metric,
TimedMetadata: metadata,
}}
return encoder.EncodeMessage(msg)
}
func (w *writer) encodeTimedWithStagedMetadatasWithLock(
encoder *lockedEncoder,
metric aggregated.Metric,
metadatas metadata.StagedMetadatas,
) error {
msg := encoding.UnaggregatedMessageUnion{
Type: encoding.TimedMetricWithMetadatasType,
TimedMetricWithMetadatas: aggregated.TimedMetricWithMetadatas{
Metric: metric,
StagedMetadatas: metadatas,
}}
return encoder.EncodeMessage(msg)
}
func (w *writer) encodePassthroughWithLock(
encoder *lockedEncoder,
metric aggregated.Metric,
storagePolicy policy.StoragePolicy,
) error {
msg := encoding.UnaggregatedMessageUnion{
Type: encoding.PassthroughMetricWithMetadataType,
PassthroughMetricWithMetadata: aggregated.PassthroughMetricWithMetadata{
Metric: metric,
StoragePolicy: storagePolicy,
}}
return encoder.EncodeMessage(msg)
}
func (w *writer) flushWithLock() error {
multiErr := xerrors.NewMultiError()
for _, encoder := range w.encodersByShard {
encoder.Lock()
if encoder.Len() == 0 {
encoder.Unlock()
continue
}
buffer := encoder.Relinquish()
encoder.Unlock()
if err := w.enqueueBuffer(buffer); err != nil {
multiErr = multiErr.Add(err)
}
}
w.queue.Flush()
return multiErr.FinalError()
}
func (w *writer) enqueueBuffer(buf protobuf.Buffer) error {
if err := w.queue.Enqueue(buf); err != nil {
w.metrics.enqueueErrors.Inc(1)
return err
}
w.metrics.buffersEnqueued.Inc(1)
return nil
}
const (
buffersMetric = "buffers"
actionTag = "action"
)
type writerMetrics struct {
buffersEnqueued tally.Counter
encodeErrors tally.Counter
enqueueErrors tally.Counter
flushErrors tally.Counter
}
func newWriterMetrics(s tally.Scope) writerMetrics {
return writerMetrics{
buffersEnqueued: s.Tagged(map[string]string{actionTag: "enqueued"}).Counter(buffersMetric),
encodeErrors: s.Tagged(map[string]string{actionTag: "encode-error"}).Counter(buffersMetric),
enqueueErrors: s.Tagged(map[string]string{actionTag: "enqueue-error"}).Counter(buffersMetric),
flushErrors: s.Tagged(map[string]string{actionTag: "flush-error"}).Counter(buffersMetric),
}
}
type lockedEncoder struct {
protobuf.UnaggregatedEncoder
sync.Mutex
}
func newLockedEncoder(encoderOpts protobuf.UnaggregatedOptions) *lockedEncoder {
encoder := protobuf.NewUnaggregatedEncoder(encoderOpts)
return &lockedEncoder{UnaggregatedEncoder: encoder}
}
type refCountedWriter struct {
instanceWriter
refCount
dirty atomic.Bool
}
func newRefCountedWriter(instance placement.Instance, opts Options) *refCountedWriter {
rcWriter := &refCountedWriter{instanceWriter: newInstanceWriter(instance, opts)}
rcWriter.refCount.SetDestructor(rcWriter.Close)
return rcWriter
}
func (rcWriter *refCountedWriter) Close() {
// NB: closing the writer needs to be done asynchronously because it may
// be called by writer manager while holding a lock that blocks any writes
// from proceeding.
go rcWriter.instanceWriter.Close() // nolint: errcheck
}