-
Notifications
You must be signed in to change notification settings - Fork 183
/
writer.go
373 lines (321 loc) · 10.4 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
// Package writer contains the SignalFx writer. The writer is responsible for
// sending datapoints and events to SignalFx ingest. Ideally all data would
// flow through here, but right now a lot of it is written to ingest by
// collectd.
//
// The writer provides a channel that all monitors can submit datapoints on.
// All monitors should include the "monitorType" key in the `Meta` map of the
// datapoint for use in filtering.
package writer
import (
"context"
"net"
"net/http"
"sync"
"sync/atomic"
"time"
"github.com/davecgh/go-spew/spew"
"github.com/signalfx/golib/datapoint"
"github.com/signalfx/golib/event"
"github.com/signalfx/golib/sfxclient"
"github.com/signalfx/golib/trace"
"github.com/signalfx/signalfx-agent/internal/core/common/dpmeta"
"github.com/signalfx/signalfx-agent/internal/core/config"
"github.com/signalfx/signalfx-agent/internal/core/writer/tracetracker"
"github.com/signalfx/signalfx-agent/internal/monitors/types"
"github.com/signalfx/signalfx-agent/internal/utils"
log "github.com/sirupsen/logrus"
)
const (
// There cannot be more than this many events queued to be sent at any
// given time. This should be big enough for any reasonable use case.
eventBufferCapacity = 1000
)
// SignalFxWriter is what sends events and datapoints to SignalFx ingest. It
// receives events/datapoints on two buffered channels and writes them to
// SignalFx on a regular interval.
type SignalFxWriter struct {
client *sfxclient.HTTPSink
dimPropClient *dimensionPropertyClient
// Monitors should send datapoints to this
dpChan chan *datapoint.Datapoint
// Monitors should send events to this
eventChan chan *event.Event
spanChan chan *trace.Span
propertyChan chan *types.DimProperties
ctx context.Context
cancel context.CancelFunc
conf *config.WriterConfig
// map that holds host-specific ids like AWSUniqueID
hostIDDims map[string]string
dpBufferPool *sync.Pool
spanBufferPool *sync.Pool
eventBuffer []*event.Event
// Keeps track of what service names have been seen in trace spans that are
// emitted by the agent
serviceTracker *tracetracker.ActiveServiceTracker
dpRequestsActive int64
dpsInFlight int64
dpsSent int64
traceSpanRequestsActive int64
traceSpansInFlight int64
traceSpansSent int64
eventsSent int64
startTime time.Time
}
// New creates a new un-configured writer
func New(conf *config.WriterConfig, dpChan chan *datapoint.Datapoint, eventChan chan *event.Event,
propertyChan chan *types.DimProperties, spanChan chan *trace.Span) (*SignalFxWriter, error) {
sw := &SignalFxWriter{
conf: conf,
client: sfxclient.NewHTTPSink(),
dimPropClient: newDimensionPropertyClient(conf),
hostIDDims: conf.HostIDDims,
dpChan: dpChan,
eventChan: eventChan,
spanChan: spanChan,
propertyChan: propertyChan,
startTime: time.Now(),
dpBufferPool: &sync.Pool{
New: func() interface{} {
return make([]*datapoint.Datapoint, 0, conf.DatapointMaxBatchSize)
},
},
spanBufferPool: &sync.Pool{
New: func() interface{} {
return make([]*trace.Span, 0, conf.TraceSpanMaxBatchSize)
},
},
}
sw.ctx, sw.cancel = context.WithCancel(context.Background())
sw.client.AuthToken = conf.SignalFxAccessToken
sw.client.Client.Transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 3 * time.Second,
KeepAlive: 90 * time.Second,
DualStack: true,
}).DialContext,
MaxIdleConns: 100,
MaxIdleConnsPerHost: conf.MaxRequests,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
}
dpEndpointURL, err := conf.IngestURL.Parse("v2/datapoint")
if err != nil {
log.WithFields(log.Fields{
"error": err,
"ingestURL": conf.IngestURL.String(),
}).Error("Could not construct datapoint ingest URL")
return nil, err
}
sw.client.DatapointEndpoint = dpEndpointURL.String()
eventEndpointURL, err := conf.IngestURL.Parse("v2/event")
if err != nil {
log.WithFields(log.Fields{
"error": err,
"ingestURL": conf.IngestURL.String(),
}).Error("Could not construct event ingest URL")
return nil, err
}
sw.client.EventEndpoint = eventEndpointURL.String()
traceEndpointURL := conf.TraceEndpointURL
if traceEndpointURL == nil {
var err error
traceEndpointURL, err = conf.IngestURL.Parse("v1/trace")
if err != nil {
log.WithFields(log.Fields{
"error": err,
"ingestURL": conf.IngestURL.String(),
}).Error("Could not construct trace ingest URL")
return nil, err
}
}
sw.client.TraceEndpoint = traceEndpointURL.String()
go sw.listenForDatapoints()
go sw.listenForEventsAndDimProps()
go sw.listenForTraceSpans()
return sw, nil
}
func (sw *SignalFxWriter) shouldSendDatapoint(dp *datapoint.Datapoint) bool {
return sw.conf.DatapointFilter == nil || !sw.conf.DatapointFilter.Matches(dp)
}
func (sw *SignalFxWriter) preprocessDatapoint(dp *datapoint.Datapoint) {
dp.Dimensions = sw.addGlobalDims(dp.Dimensions)
// Some metrics aren't really specific to the host they are running
// on and shouldn't have any host-specific dims
if b, ok := dp.Meta[dpmeta.NotHostSpecificMeta].(bool); !ok || !b {
dp.Dimensions = sw.addhostIDFields(dp.Dimensions)
}
if sw.conf.LogDatapoints {
log.Debugf("Sending datapoint:\n%s", utils.DatapointToString(dp))
}
}
func (sw *SignalFxWriter) sendDatapoints(dps []*datapoint.Datapoint) error {
// This sends synchonously
err := sw.client.AddDatapoints(context.Background(), dps)
if err != nil {
log.WithFields(log.Fields{
"error": err,
}).Error("Error shipping datapoints to SignalFx")
// If there is an error sending datapoints then just forget about them.
return err
}
atomic.AddInt64(&sw.dpsSent, int64(len(dps)))
log.Debugf("Sent %d datapoints to SignalFx", len(dps))
return nil
}
func (sw *SignalFxWriter) sendEvents(events []*event.Event) error {
for i := range events {
events[i].Dimensions = sw.addGlobalDims(events[i].Dimensions)
ps := events[i].Properties
var notHostSpecific bool
if ps != nil {
if b, ok := ps[dpmeta.NotHostSpecificMeta].(bool); ok {
notHostSpecific = b
// Clear this so it doesn't leak through to ingest
delete(ps, dpmeta.NotHostSpecificMeta)
}
}
// Only override host dimension for now and omit other host id dims.
if !notHostSpecific && sw.hostIDDims != nil && sw.hostIDDims["host"] != "" {
events[i].Dimensions["host"] = sw.hostIDDims["host"]
}
if sw.conf.LogEvents {
log.WithFields(log.Fields{
"event": spew.Sdump(events[i]),
}).Debug("Sending event")
}
}
err := sw.client.AddEvents(context.Background(), events)
if err != nil {
log.WithError(err).Error("Error shipping events to SignalFx")
return err
}
sw.eventsSent += int64(len(events))
log.Debugf("Sent %d events to SignalFx", len(events))
return nil
}
// Mutates datapoint dimensions in place to add global dimensions. Also
// returns dims in case they were nil to begin with, so the return value should
// be assigned back to the dp Dimensions field.
func (sw *SignalFxWriter) addGlobalDims(dims map[string]string) map[string]string {
if dims == nil {
dims = make(map[string]string)
}
for name, value := range sw.conf.GlobalDimensions {
// If the dimensions are already set, don't override
if _, ok := dims[name]; !ok {
dims[name] = value
}
}
return dims
}
// Adds the host ids to the given map (e.g. dimensions/span tags), forcibly
// overridding any existing fields of the same name.
func (sw *SignalFxWriter) addhostIDFields(fields map[string]string) map[string]string {
if fields == nil {
fields = make(map[string]string)
}
for k, v := range sw.hostIDDims {
fields[k] = v
}
return fields
}
// listenForDatapoints waits for datapoints to come in on the provided
// channels and forwards them to SignalFx.
func (sw *SignalFxWriter) listenForDatapoints() {
// This acts like a semaphore if a request goroutine pushes into it before
// making the request and pulling out of it when the request is done.
// Pushes will block if there are more than the max number of outstanding
// requests.
dpSema := make(chan struct{}, sw.conf.DatapointMaxRequests)
for {
select {
case <-sw.ctx.Done():
return
case dp := <-sw.dpChan:
if !sw.shouldSendDatapoint(dp) {
continue
}
buf := append(sw.dpBufferPool.Get().([]*datapoint.Datapoint), dp)
buf = sw.drainDpChan(buf)
for i := range buf {
sw.preprocessDatapoint(buf[i])
}
atomic.AddInt64(&sw.dpsInFlight, int64(len(buf)))
go func() {
// Wait if there are more than the max outstanding requests
dpSema <- struct{}{}
atomic.AddInt64(&sw.dpRequestsActive, 1)
sw.sendDatapoints(buf)
<-dpSema
atomic.AddInt64(&sw.dpRequestsActive, -1)
atomic.AddInt64(&sw.dpsInFlight, -int64(len(buf)))
sw.dpBufferPool.Put(buf[:0])
}()
}
}
}
func (sw *SignalFxWriter) drainDpChan(buf []*datapoint.Datapoint) []*datapoint.Datapoint {
for {
select {
case dp := <-sw.dpChan:
if !sw.shouldSendDatapoint(dp) {
continue
}
buf = append(buf, dp)
if len(buf) >= sw.conf.DatapointMaxBatchSize {
return buf
}
default:
return buf
}
}
}
func (sw *SignalFxWriter) listenForEventsAndDimProps() {
eventTicker := time.NewTicker(time.Duration(sw.conf.EventSendIntervalSeconds) * time.Second)
defer eventTicker.Stop()
initEventBuffer := func() {
sw.eventBuffer = make([]*event.Event, 0, eventBufferCapacity)
}
initEventBuffer()
for {
select {
case <-sw.ctx.Done():
return
case event := <-sw.eventChan:
if len(sw.eventBuffer) > eventBufferCapacity {
log.WithFields(log.Fields{
"eventType": event.EventType,
"eventBufferLength": len(sw.eventBuffer),
}).Error("Dropping event due to overfull buffer")
continue
}
sw.eventBuffer = append(sw.eventBuffer, event)
case <-eventTicker.C:
if len(sw.eventBuffer) > 0 {
go sw.sendEvents(sw.eventBuffer)
initEventBuffer()
}
case dimProps := <-sw.propertyChan:
// Run the sync async so we don't block other cases in this select
go func(innerProps *types.DimProperties) {
err := sw.dimPropClient.SetPropertiesOnDimension(innerProps)
if err != nil {
log.WithFields(log.Fields{
"error": err,
"dimProps": innerProps,
}).Error("Could not sync properties to dimension")
}
}(dimProps)
}
}
}
// Shutdown the writer and stop sending datapoints
func (sw *SignalFxWriter) Shutdown() {
if sw.cancel != nil {
sw.cancel()
}
log.Debug("Stopped datapoint writer")
}