-
Notifications
You must be signed in to change notification settings - Fork 451
/
server.go
283 lines (252 loc) · 9.27 KB
/
server.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
// Copyright (c) 2016 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 rawtcp
import (
"bufio"
"fmt"
"io"
"math/rand"
"net"
"sync"
"time"
"github.com/m3db/m3/src/aggregator/aggregator"
"github.com/m3db/m3/src/aggregator/rate"
"github.com/m3db/m3/src/metrics/encoding"
"github.com/m3db/m3/src/metrics/encoding/migration"
"github.com/m3db/m3/src/metrics/encoding/msgpack"
"github.com/m3db/m3/src/metrics/encoding/protobuf"
"github.com/m3db/m3/src/metrics/metadata"
"github.com/m3db/m3/src/metrics/metric/aggregated"
"github.com/m3db/m3/src/metrics/metric/unaggregated"
xserver "github.com/m3db/m3/src/x/server"
"github.com/uber-go/tally"
"go.uber.org/zap"
)
const (
unknownRemoteHostAddress = "<unknown>"
)
// NewServer creates a new raw TCP server.
func NewServer(address string, aggregator aggregator.Aggregator, opts Options) xserver.Server {
iOpts := opts.InstrumentOptions()
handlerScope := iOpts.MetricsScope().Tagged(map[string]string{"handler": "rawtcp"})
handler := NewHandler(aggregator, opts.SetInstrumentOptions(iOpts.SetMetricsScope(handlerScope)))
return xserver.NewServer(address, handler, opts.ServerOptions())
}
type handlerMetrics struct {
unknownMessageTypeErrors tally.Counter
addUntimedErrors tally.Counter
addTimedErrors tally.Counter
addForwardedErrors tally.Counter
unknownErrorTypeErrors tally.Counter
decodeErrors tally.Counter
errLogRateLimited tally.Counter
}
func newHandlerMetrics(scope tally.Scope) handlerMetrics {
return handlerMetrics{
unknownMessageTypeErrors: scope.Counter("unknown-message-type-errors"),
addUntimedErrors: scope.Counter("add-untimed-errors"),
addTimedErrors: scope.Counter("add-timed-errors"),
addForwardedErrors: scope.Counter("add-forwarded-errors"),
unknownErrorTypeErrors: scope.Counter("unknown-error-type-errors"),
decodeErrors: scope.Counter("decode-errors"),
errLogRateLimited: scope.Counter("error-log-rate-limited"),
}
}
type handler struct {
sync.Mutex
aggregator aggregator.Aggregator
log *zap.Logger
readBufferSize int
msgpackItOpts msgpack.UnaggregatedIteratorOptions
protobufItOpts protobuf.UnaggregatedOptions
errLogRateLimiter *rate.Limiter
rand *rand.Rand
metrics handlerMetrics
}
// NewHandler creates a new raw TCP handler.
func NewHandler(aggregator aggregator.Aggregator, opts Options) xserver.Handler {
nowFn := opts.ClockOptions().NowFn()
iOpts := opts.InstrumentOptions()
var limiter *rate.Limiter
if rateLimit := opts.ErrorLogLimitPerSecond(); rateLimit != 0 {
limiter = rate.NewLimiter(rateLimit, nowFn)
}
return &handler{
aggregator: aggregator,
log: iOpts.Logger(),
readBufferSize: opts.ReadBufferSize(),
msgpackItOpts: opts.MsgpackUnaggregatedIteratorOptions(),
protobufItOpts: opts.ProtobufUnaggregatedIteratorOptions(),
errLogRateLimiter: limiter,
rand: rand.New(rand.NewSource(nowFn().UnixNano())),
metrics: newHandlerMetrics(iOpts.MetricsScope()),
}
}
func (s *handler) Handle(conn net.Conn) {
remoteAddress := unknownRemoteHostAddress
if remoteAddr := conn.RemoteAddr(); remoteAddr != nil {
remoteAddress = remoteAddr.String()
}
reader := bufio.NewReaderSize(conn, s.readBufferSize)
it := migration.NewUnaggregatedIterator(reader, s.msgpackItOpts, s.protobufItOpts)
defer it.Close()
// Iterate over the incoming metrics stream and queue up metrics.
var (
untimedMetric unaggregated.MetricUnion
stagedMetadatas metadata.StagedMetadatas
forwardedMetric aggregated.ForwardedMetric
forwardMetadata metadata.ForwardMetadata
timedMetric aggregated.Metric
timedMetadata metadata.TimedMetadata
err error
)
for it.Next() {
current := it.Current()
switch current.Type {
case encoding.CounterWithMetadatasType:
untimedMetric = current.CounterWithMetadatas.Counter.ToUnion()
stagedMetadatas = current.CounterWithMetadatas.StagedMetadatas
err = toAddUntimedError(s.aggregator.AddUntimed(untimedMetric, stagedMetadatas))
case encoding.BatchTimerWithMetadatasType:
untimedMetric = current.BatchTimerWithMetadatas.BatchTimer.ToUnion()
stagedMetadatas = current.BatchTimerWithMetadatas.StagedMetadatas
err = toAddUntimedError(s.aggregator.AddUntimed(untimedMetric, stagedMetadatas))
case encoding.GaugeWithMetadatasType:
untimedMetric = current.GaugeWithMetadatas.Gauge.ToUnion()
stagedMetadatas = current.GaugeWithMetadatas.StagedMetadatas
err = toAddUntimedError(s.aggregator.AddUntimed(untimedMetric, stagedMetadatas))
case encoding.ForwardedMetricWithMetadataType:
forwardedMetric = current.ForwardedMetricWithMetadata.ForwardedMetric
forwardMetadata = current.ForwardedMetricWithMetadata.ForwardMetadata
err = toAddForwardedError(s.aggregator.AddForwarded(forwardedMetric, forwardMetadata))
case encoding.TimedMetricWithMetadataType:
timedMetric = current.TimedMetricWithMetadata.Metric
timedMetadata = current.TimedMetricWithMetadata.TimedMetadata
err = toAddTimedError(s.aggregator.AddTimed(timedMetric, timedMetadata))
default:
err = newUnknownMessageTypeError(current.Type)
}
if err == nil {
continue
}
// We rate limit the error log here because the error rate may scale with
// the metrics incoming rate and consume lots of cpu cycles.
if s.errLogRateLimiter != nil && !s.errLogRateLimiter.IsAllowed(1) {
s.metrics.errLogRateLimited.Inc(1)
continue
}
switch err.(type) {
case unknownMessageTypeError:
s.metrics.unknownMessageTypeErrors.Inc(1)
s.log.Error("unexpected message type",
zap.String("remoteAddress", remoteAddress),
zap.Error(err),
)
case addUntimedError:
s.metrics.addUntimedErrors.Inc(1)
s.log.Error("error adding untimed metric",
zap.String("remoteAddress", remoteAddress),
zap.Stringer("type", untimedMetric.Type),
zap.Stringer("id", untimedMetric.ID),
zap.Any("metadatas", stagedMetadatas),
zap.Error(err),
)
case addForwardedError:
s.metrics.addForwardedErrors.Inc(1)
s.log.Error("error adding forwarded metric",
zap.String("remoteAddress", remoteAddress),
zap.Stringer("id", forwardedMetric.ID),
zap.Time("timestamp", time.Unix(0, forwardedMetric.TimeNanos)),
zap.Float64s("values", forwardedMetric.Values),
zap.Error(err),
)
case addTimedError:
s.metrics.addTimedErrors.Inc(1)
s.log.Error("error adding timed metric",
zap.String("remoteAddress", remoteAddress),
zap.Stringer("id", timedMetric.ID),
zap.Time("timestamp", time.Unix(0, timedMetric.TimeNanos)),
zap.Float64("value", timedMetric.Value),
zap.Error(err),
)
default:
s.metrics.unknownErrorTypeErrors.Inc(1)
s.log.Error("unknown error type",
zap.String("errorType", fmt.Sprintf("%T", err)),
zap.Error(err),
)
}
}
// If there is an error during decoding, it's likely due to a broken connection
// and therefore we ignore the EOF error.
if err := it.Err(); err != nil && err != io.EOF {
s.log.Error("decode error",
zap.String("remoteAddress", remoteAddress),
zap.Error(err),
)
s.metrics.decodeErrors.Inc(1)
}
}
func (s *handler) Close() {
// NB(cw) Do not close s.aggregator here because it's shared between
// the raw TCP server and the http server, and it will be closed on
// exit signal.
}
type unknownMessageTypeError struct {
msgType encoding.UnaggregatedMessageType
}
func newUnknownMessageTypeError(
msgType encoding.UnaggregatedMessageType,
) unknownMessageTypeError {
return unknownMessageTypeError{msgType: msgType}
}
func (e unknownMessageTypeError) Error() string {
return fmt.Sprintf("unknown message type %v", e.msgType)
}
type addUntimedError struct {
err error
}
func toAddUntimedError(err error) error {
if err == nil {
return nil
}
return addUntimedError{err: err}
}
func (e addUntimedError) Error() string { return e.err.Error() }
type addTimedError struct {
err error
}
func toAddTimedError(err error) error {
if err == nil {
return nil
}
return addTimedError{err: err}
}
func (e addTimedError) Error() string { return e.err.Error() }
type addForwardedError struct {
err error
}
func toAddForwardedError(err error) error {
if err == nil {
return nil
}
return addForwardedError{err: err}
}
func (e addForwardedError) Error() string { return e.err.Error() }