forked from stripe/veneur
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
1685 lines (1463 loc) · 49.3 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
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package veneur
import (
"bufio"
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"errors"
"fmt"
"io"
"net"
"net/http"
"reflect"
"runtime"
rtdebug "runtime/debug"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/DataDog/datadog-go/statsd"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3iface"
"github.com/getsentry/sentry-go"
"github.com/sirupsen/logrus"
"github.com/zenazn/goji/bind"
"github.com/zenazn/goji/graceful"
"google.golang.org/grpc"
"github.com/pkg/profile"
vhttp "github.com/stripe/veneur/v14/http"
"github.com/stripe/veneur/v14/importsrv"
"github.com/stripe/veneur/v14/plugins"
localfilep "github.com/stripe/veneur/v14/plugins/localfile"
s3p "github.com/stripe/veneur/v14/plugins/s3"
"github.com/stripe/veneur/v14/protocol"
"github.com/stripe/veneur/v14/samplers"
"github.com/stripe/veneur/v14/scopedstatsd"
"github.com/stripe/veneur/v14/sinks"
"github.com/stripe/veneur/v14/sinks/datadog"
"github.com/stripe/veneur/v14/sinks/debug"
"github.com/stripe/veneur/v14/sinks/falconer"
"github.com/stripe/veneur/v14/sinks/kafka"
"github.com/stripe/veneur/v14/sinks/lightstep"
"github.com/stripe/veneur/v14/sinks/newrelic"
"github.com/stripe/veneur/v14/sinks/prometheus"
"github.com/stripe/veneur/v14/sinks/signalfx"
"github.com/stripe/veneur/v14/sinks/splunk"
"github.com/stripe/veneur/v14/sinks/ssfmetrics"
"github.com/stripe/veneur/v14/sinks/xray"
"github.com/stripe/veneur/v14/ssf"
"github.com/stripe/veneur/v14/trace"
"github.com/stripe/veneur/v14/trace/metrics"
)
// VERSION stores the current veneur version.
// It must be a var so it can be set at link time.
var VERSION = defaultLinkValue
var BUILD_DATE = defaultLinkValue
const defaultLinkValue = "dirty"
// REDACTED is used to replace values that we don't want to leak into loglines (e.g., credentials)
const REDACTED = "REDACTED"
var profileStartOnce = sync.Once{}
var log = logrus.StandardLogger()
var tracer = trace.GlobalTracer
const defaultTCPReadTimeout = 10 * time.Minute
const httpQuitEndpoint = "/quitquitquit"
// A Server is the actual veneur instance that will be run.
type Server struct {
Workers []*Worker
EventWorker *EventWorker
SpanChan chan *ssf.SSFSpan
SpanWorker *SpanWorker
SpanWorkerGoroutines int
CountUniqueTimeseries bool
Statsd *scopedstatsd.ScopedClient
Hostname string
Tags []string
TagsAsMap map[string]string
HTTPClient *http.Client
HTTPAddr string
numListeningHTTP *int32 // An atomic boolean for whether or not the HTTP server is running
ForwardAddr string
forwardUseGRPC bool
StatsdListenAddrs []net.Addr
SSFListenAddrs []net.Addr
GRPCListenAddrs []net.Addr
RcvbufBytes int
interval time.Duration
synchronizeInterval bool
numReaders int
metricMaxLength int
traceMaxLengthBytes int
tlsConfig *tls.Config
tcpReadTimeout time.Duration
// closed when the server is shutting down gracefully
shutdown chan struct{}
httpQuit bool
HistogramPercentiles []float64
plugins []plugins.Plugin
pluginMtx sync.Mutex
enableProfiling bool
HistogramAggregates samplers.HistogramAggregates
spanSinks []sinks.SpanSink
metricSinks []sinks.MetricSink
TraceClient *trace.Client
ssfInternalMetrics sync.Map
listeningPerProtocolMetrics *GlobalListeningPerProtocolMetrics
// gRPC server
grpcListenAddress string
grpcServer *importsrv.Server
// gRPC forward clients
grpcForwardConn *grpc.ClientConn
stuckIntervals int
lastFlushUnix int64
}
type GlobalListeningPerProtocolMetrics struct {
dogstatsdTcpReceivedTotal int64
dogstatsdUdpReceivedTotal int64
dogstatsdUnixReceivedTotal int64
dogstatsdGrpcReceivedTotal int64
ssfUnixReceivedTotal int64
ssfUdpReceivedTotal int64
ssfGrpcReceivedTotal int64
}
type ProtocolType int
const (
DOGSTATSD_TCP ProtocolType = iota
DOGSTATSD_UDP
DOGSTATSD_UNIX
DOGSTATSD_GRPC
SSF_UNIX
SSF_UDP
SSF_GRPC
)
func (p ProtocolType) String() string {
return [...]string{
"dogstatsd-tcp",
"dogstatsd-udp",
"dogstatsd-unix",
"dogstatsd-grpc",
"ssf-unix",
"ssf-udp",
"ssf-grpc",
}[p]
}
// ssfServiceSpanMetrics refer to the span metrics that will
// be emitted for single (service,ssf_format) combination on each flush.
// It is expected the values on the struct will only be handled
// using atomic operations
type ssfServiceSpanMetrics struct {
ssfSpansReceivedTotal int64
ssfRootSpansReceivedTotal int64
}
// SetLogger sets the default logger in veneur to the passed value.
func SetLogger(logger *logrus.Logger) {
log = logger
}
func scopeFromName(name string) (ssf.SSFSample_Scope, error) {
switch name {
case "default":
fallthrough
case "":
return ssf.SSFSample_DEFAULT, nil
case "global":
return ssf.SSFSample_GLOBAL, nil
case "local":
return ssf.SSFSample_LOCAL, nil
default:
return 0, fmt.Errorf("unknown metric scope option %q", name)
}
}
func normalizeSpans(conf Config) trace.ClientParam {
return func(cl *trace.Client) error {
var err error
typeScopes := map[ssf.SSFSample_Metric]ssf.SSFSample_Scope{}
typeScopes[ssf.SSFSample_COUNTER], err = scopeFromName(conf.VeneurMetricsScopes.Counter)
if err != nil {
return err
}
typeScopes[ssf.SSFSample_GAUGE], err = scopeFromName(conf.VeneurMetricsScopes.Gauge)
if err != nil {
return err
}
typeScopes[ssf.SSFSample_HISTOGRAM], err = scopeFromName(conf.VeneurMetricsScopes.Histogram)
if err != nil {
return err
}
typeScopes[ssf.SSFSample_SET], err = scopeFromName(conf.VeneurMetricsScopes.Set)
if err != nil {
return err
}
typeScopes[ssf.SSFSample_STATUS], err = scopeFromName(conf.VeneurMetricsScopes.Status)
if err != nil {
return err
}
tags := map[string]string{}
for _, elem := range conf.VeneurMetricsAdditionalTags {
tag := strings.SplitN(elem, ":", 2)
switch len(tag) {
case 2:
tags[tag[0]] = tag[1]
case 1:
tags[tag[0]] = ""
}
}
normalizer := func(sample *ssf.SSFSample) {
// adjust tags:
if sample.Tags == nil {
sample.Tags = map[string]string{}
}
for k, v := range tags {
if _, ok := sample.Tags[k]; ok {
// do not overwrite existing tags:
continue
}
sample.Tags[k] = v
}
// adjust the scope:
toScope := typeScopes[sample.Metric]
if sample.Scope != ssf.SSFSample_DEFAULT || toScope == ssf.SSFSample_DEFAULT {
return
}
sample.Scope = toScope
}
option := trace.NormalizeSamples(normalizer)
return option(cl)
}
}
func scopesFromConfig(conf Config) (scopedstatsd.MetricScopes, error) {
var err error
var ms scopedstatsd.MetricScopes
ms.Gauge, err = scopeFromName(conf.VeneurMetricsScopes.Gauge)
if err != nil {
return ms, err
}
ms.Count, err = scopeFromName(conf.VeneurMetricsScopes.Counter)
if err != nil {
return ms, err
}
ms.Histogram, err = scopeFromName(conf.VeneurMetricsScopes.Histogram)
if err != nil {
return ms, err
}
return ms, nil
}
// NewFromConfig creates a new veneur server from a configuration
// specification and sets up the passed logger according to the
// configuration.
func NewFromConfig(logger *logrus.Logger, conf Config) (*Server, error) {
ret := &Server{}
ret.Hostname = conf.Hostname
ret.Tags = conf.Tags
mappedTags := samplers.ParseTagSliceToMap(ret.Tags)
ret.synchronizeInterval = conf.SynchronizeWithInterval
ret.TagsAsMap = mappedTags
ret.HistogramPercentiles = conf.Percentiles
ret.HistogramAggregates.Value = 0
for _, agg := range conf.Aggregates {
ret.HistogramAggregates.Value += samplers.AggregatesLookup[agg]
}
ret.HistogramAggregates.Count = len(conf.Aggregates)
var err error
ret.interval, err = conf.ParseInterval()
if err != nil {
return ret, err
}
ret.stuckIntervals = conf.FlushWatchdogMissedFlushes
transport := &http.Transport{
IdleConnTimeout: ret.interval * 2, // If we're idle more than one interval something is up
}
ret.HTTPClient = &http.Client{
// make sure that POSTs to datadog do not overflow the flush interval
Timeout: ret.interval * 9 / 10,
Transport: transport,
}
stats, err := statsd.New(conf.StatsAddress, statsd.WithoutTelemetry(), statsd.WithMaxMessagesPerPayload(4096))
if err != nil {
return ret, err
}
stats.Namespace = "veneur."
scopes, err := scopesFromConfig(conf)
if err != nil {
return ret, err
}
ret.Statsd = scopedstatsd.NewClient(stats, conf.VeneurMetricsAdditionalTags, scopes)
ret.SpanChan = make(chan *ssf.SSFSpan, conf.SpanChannelCapacity)
ret.TraceClient, err = trace.NewChannelClient(ret.SpanChan,
trace.ReportStatistics(stats, 1*time.Second, []string{"ssf_format:internal"}),
normalizeSpans(conf),
)
if err != nil {
return ret, err
}
// Initialize Sentry if a Dsn is provided, else we leave it uninitalized
// and no-op the methods.
if conf.SentryDsn != "" {
err = sentry.Init(sentry.ClientOptions{
Dsn: conf.SentryDsn,
})
if err != nil {
return ret, err
}
}
if conf.Debug {
logger.SetLevel(logrus.DebugLevel)
}
mpf := 0
if conf.MutexProfileFraction > 0 {
mpf = runtime.SetMutexProfileFraction(conf.MutexProfileFraction)
}
log.WithFields(logrus.Fields{
"MutexProfileFraction": conf.MutexProfileFraction,
"previousMutexProfileFraction": mpf,
}).Info("Set mutex profile fraction")
if conf.BlockProfileRate > 0 {
runtime.SetBlockProfileRate(conf.BlockProfileRate)
}
log.WithField("BlockProfileRate", conf.BlockProfileRate).Info("Set block profile rate (nanoseconds)")
if conf.EnableProfiling {
ret.enableProfiling = true
}
// This is a check to ensure that we don't repeatedly add a hook
// to the "global" log instance on repeated calls to `NewFromConfig`
// such as those made in testing. By skipping this we avoid a race
// condition in logrus discussed here:
// https://github.com/sirupsen/logrus/issues/295
if _, ok := logger.Hooks[logrus.FatalLevel]; !ok {
logger.AddHook(sentryHook{
hostname: ret.Hostname,
lv: []logrus.Level{
logrus.ErrorLevel,
logrus.FatalLevel,
logrus.PanicLevel,
},
})
}
// After log hooks are configured, if any further errors are
// found during setup we should use logger.Fatal or
// logger.Panic, because that will give us breakage monitoring
// through Sentry.
numWorkers := 1
if conf.NumWorkers > 1 {
numWorkers = conf.NumWorkers
}
logger.WithField("number", numWorkers).Info("Preparing workers")
// Allocate the slice, we'll fill it with workers later.
ret.Workers = make([]*Worker, numWorkers)
ret.numReaders = conf.NumReaders
// This must come before worker initialization. We need to
// initialize workers with state from *Server.IsWorker.
ret.ForwardAddr = conf.ForwardAddress
// Control whether Veneur should emit metric
// "veneur.flush.unique_timeseries_total", which may come at a
// slight performance hit to workers.
ret.CountUniqueTimeseries = conf.CountUniqueTimeseries
// Use the pre-allocated Workers slice to know how many to start.
for i := range ret.Workers {
ret.Workers[i] = NewWorker(i+1, ret.IsLocal(), ret.CountUniqueTimeseries, ret.TraceClient, log, ret.Statsd)
// do not close over loop index
go func(w *Worker) {
defer func() {
ConsumePanic(ret.TraceClient, ret.Hostname, recover())
}()
w.Work()
}(ret.Workers[i])
}
ret.EventWorker = NewEventWorker(ret.TraceClient, ret.Statsd)
// Set up a span sink that extracts metrics from SSF spans and
// reports them via the metric workers:
processors := make([]ssfmetrics.Processor, len(ret.Workers))
for i, w := range ret.Workers {
processors[i] = w
}
metricSink, err := ssfmetrics.NewMetricExtractionSink(processors, conf.IndicatorSpanTimerName, conf.ObjectiveSpanTimerName, ret.TraceClient, log)
if err != nil {
return ret, err
}
ret.spanSinks = append(ret.spanSinks, metricSink)
for _, addrStr := range conf.StatsdListenAddresses {
addr, err := protocol.ResolveAddr(addrStr)
if err != nil {
return ret, err
}
ret.StatsdListenAddrs = append(ret.StatsdListenAddrs, addr)
}
for _, addrStr := range conf.SsfListenAddresses {
addr, err := protocol.ResolveAddr(addrStr)
if err != nil {
return ret, err
}
ret.SSFListenAddrs = append(ret.SSFListenAddrs, addr)
}
for _, addrStr := range conf.GrpcListenAddresses {
addr, err := protocol.ResolveAddr(addrStr)
if err != nil {
return ret, err
}
ret.GRPCListenAddrs = append(ret.GRPCListenAddrs, addr)
}
ret.metricMaxLength = conf.MetricMaxLength
ret.traceMaxLengthBytes = conf.TraceMaxLengthBytes
ret.RcvbufBytes = conf.ReadBufferSizeBytes
ret.HTTPAddr = conf.HTTPAddress
ret.numListeningHTTP = new(int32)
if conf.TLSKey != "" {
if conf.TLSCertificate == "" {
err = errors.New("tls_key is set; must set tls_certificate")
logger.WithError(err).Error("Improper TLS configuration")
return ret, err
}
// load the TLS key and certificate
var cert tls.Certificate
cert, err = tls.X509KeyPair([]byte(conf.TLSCertificate), []byte(conf.TLSKey))
if err != nil {
logger.WithError(err).Error("Improper TLS configuration")
return ret, err
}
clientAuthMode := tls.NoClientCert
var clientCAs *x509.CertPool
if conf.TLSAuthorityCertificate != "" {
// load the authority; require clients to present certificated signed by this authority
clientAuthMode = tls.RequireAndVerifyClientCert
clientCAs = x509.NewCertPool()
ok := clientCAs.AppendCertsFromPEM([]byte(conf.TLSAuthorityCertificate))
if !ok {
err = errors.New("tls_authority_certificate: Could not load any certificates")
logger.WithError(err).Error("Improper TLS configuration")
return ret, err
}
}
ret.tlsConfig = &tls.Config{
Certificates: []tls.Certificate{cert},
ClientAuth: clientAuthMode,
ClientCAs: clientCAs,
}
}
if conf.SignalfxAPIKey != "" {
tracedHTTP := *ret.HTTPClient
tracedHTTP.Transport = vhttp.NewTraceRoundTripper(tracedHTTP.Transport, ret.TraceClient, "signalfx")
fallback := signalfx.NewClient(conf.SignalfxEndpointBase, conf.SignalfxAPIKey, &tracedHTTP)
byTagClients := map[string]signalfx.DPClient{}
for _, perTag := range conf.SignalfxPerTagAPIKeys {
byTagClients[perTag.Name] = signalfx.NewClient(conf.SignalfxEndpointBase, perTag.APIKey, &tracedHTTP)
}
if conf.SignalfxDynamicPerTagAPIKeysRefreshPeriod == "" {
conf.SignalfxDynamicPerTagAPIKeysRefreshPeriod = "10m"
}
dynamicKeyRefreshPeriod, err := time.ParseDuration(conf.SignalfxDynamicPerTagAPIKeysRefreshPeriod)
if err != nil {
return ret, err
}
log.WithField("endpoint_base", conf.SignalfxEndpointBase).Info("Creating SignalFx sink")
sfxSink, err := signalfx.NewSignalFxSink(conf.SignalfxHostnameTag, conf.Hostname, ret.TagsAsMap, log, fallback, conf.SignalfxVaryKeyBy, byTagClients, conf.SignalfxMetricNamePrefixDrops, conf.SignalfxMetricTagPrefixDrops, metricSink, conf.SignalfxFlushMaxPerBody, conf.SignalfxAPIKey, conf.SignalfxDynamicPerTagAPIKeysEnable, dynamicKeyRefreshPeriod, conf.SignalfxEndpointBase, conf.SignalfxEndpointAPI, &tracedHTTP)
if err != nil {
return ret, err
}
ret.metricSinks = append(ret.metricSinks, sfxSink)
}
if conf.NewrelicInsertKey != "" && conf.NewrelicAccountID > 0 {
nrSink, err := newrelic.NewNewRelicMetricSink(
conf.NewrelicInsertKey,
conf.NewrelicAccountID,
conf.NewrelicRegion,
conf.NewrelicEventType,
conf.NewrelicCommonTags,
log,
conf.NewrelicServiceCheckEventType,
)
if err != nil {
return ret, err
}
ret.metricSinks = append(ret.metricSinks, nrSink)
}
if conf.DatadogAPIKey != "" && conf.DatadogAPIHostname != "" {
excludeTagsPrefixByPrefixMetric := map[string][]string{}
for _, m := range conf.DatadogExcludeTagsPrefixByPrefixMetric {
excludeTagsPrefixByPrefixMetric[m.MetricPrefix] = m.Tags
}
ddSink, err := datadog.NewDatadogMetricSink(
ret.interval.Seconds(), conf.DatadogFlushMaxPerBody, conf.Hostname, ret.Tags,
conf.DatadogAPIHostname, conf.DatadogAPIKey, ret.HTTPClient, log, conf.DatadogMetricNamePrefixDrops,
excludeTagsPrefixByPrefixMetric,
)
if err != nil {
return ret, err
}
ret.metricSinks = append(ret.metricSinks, ddSink)
}
// Configure tracing sinks if we are listening for ssf
if len(conf.SsfListenAddresses) > 0 || len(conf.GrpcListenAddresses) > 0 {
trace.Enable()
// configure Datadog as a Span sink
if conf.DatadogAPIKey != "" && conf.DatadogTraceAPIAddress != "" {
ddSink, err := datadog.NewDatadogSpanSink(
conf.DatadogTraceAPIAddress, conf.DatadogSpanBufferSize,
ret.HTTPClient, log,
)
if err != nil {
return ret, err
}
ret.spanSinks = append(ret.spanSinks, ddSink)
logger.Info("Configured Datadog span sink")
}
if conf.XrayAddress != "" {
if conf.XraySamplePercentage == 0 {
log.Warn("XRay sample percentage is 0, no segments will be sent.")
} else {
annotationTags := make([]string, 0, len(conf.XrayAnnotationTags))
for _, tag := range conf.XrayAnnotationTags {
annotationTags = append(annotationTags, strings.Split(tag, ":")[0])
}
xraySink, err := xray.NewXRaySpanSink(conf.XrayAddress, conf.XraySamplePercentage, ret.TagsAsMap, annotationTags, log)
if err != nil {
return ret, err
}
ret.spanSinks = append(ret.spanSinks, xraySink)
logger.WithFields(logrus.Fields{
"sample_percentage": conf.XraySamplePercentage,
"num_annotation_tags": annotationTags,
}).Info("Configured X-Ray span sink")
}
}
if conf.NewrelicInsertKey != "" {
nrSpanSink, err := newrelic.NewNewRelicSpanSink(
conf.NewrelicInsertKey,
conf.NewrelicAccountID,
conf.NewrelicRegion,
conf.NewrelicCommonTags,
conf.NewrelicTraceObserverURL,
log,
)
if err != nil {
return ret, err
}
ret.spanSinks = append(ret.spanSinks, nrSpanSink)
logger.WithFields(logrus.Fields{
"span_url": conf.NewrelicTraceObserverURL,
"common_tags": conf.NewrelicCommonTags,
}).Info("Configured New Relic span sink")
}
// configure Lightstep as a Span Sink
if conf.LightstepAccessToken != "" {
var lsSink sinks.SpanSink
lsSink, err = lightstep.NewLightStepSpanSink(
conf.LightstepCollectorHost, conf.LightstepReconnectPeriod,
conf.LightstepMaximumSpans, conf.LightstepNumClients,
conf.LightstepAccessToken, log,
)
if err != nil {
return ret, err
}
ret.spanSinks = append(ret.spanSinks, lsSink)
logger.Info("Configured Lightstep span sink")
}
if (conf.SplunkHecToken != "" && conf.SplunkHecAddress == "") ||
(conf.SplunkHecToken == "" && conf.SplunkHecAddress != "") {
return ret, fmt.Errorf("both splunk_hec_address and splunk_hec_token need to be set!")
}
if conf.SplunkHecToken != "" && conf.SplunkHecAddress != "" {
var sendTimeout, ingestTimeout, connLifetime, connJitter time.Duration
if conf.SplunkHecSendTimeout != "" {
sendTimeout, err = time.ParseDuration(conf.SplunkHecSendTimeout)
if err != nil {
return ret, err
}
}
if conf.SplunkHecIngestTimeout != "" {
ingestTimeout, err = time.ParseDuration(conf.SplunkHecIngestTimeout)
if err != nil {
return ret, err
}
}
if conf.SplunkHecMaxConnectionLifetime != "" {
connLifetime, err = time.ParseDuration(conf.SplunkHecMaxConnectionLifetime)
if err != nil {
return ret, err
}
}
if conf.SplunkHecConnectionLifetimeJitter != "" {
connJitter, err = time.ParseDuration(conf.SplunkHecConnectionLifetimeJitter)
if err != nil {
return ret, err
}
}
sss, err := splunk.NewSplunkSpanSink(conf.SplunkHecAddress, conf.SplunkHecToken, conf.Hostname, conf.SplunkHecTLSValidateHostname, log, ingestTimeout, sendTimeout, conf.SplunkHecBatchSize, conf.SplunkHecSubmissionWorkers, conf.SplunkSpanSampleRate, connLifetime, connJitter)
if err != nil {
return ret, err
}
ret.spanSinks = append(ret.spanSinks, sss)
}
if conf.FalconerAddress != "" {
falsink, err := falconer.NewSpanSink(context.Background(), conf.FalconerAddress, log, grpc.WithInsecure())
if err != nil {
return ret, err
}
ret.spanSinks = append(ret.spanSinks, falsink)
logger.Info("Configured Falconer trace sink")
}
// Set up as many span workers as we need:
ret.SpanWorkerGoroutines = 1
if conf.NumSpanWorkers > 0 {
ret.SpanWorkerGoroutines = conf.NumSpanWorkers
}
}
if conf.KafkaBroker != "" {
if conf.KafkaMetricTopic != "" || conf.KafkaCheckTopic != "" || conf.KafkaEventTopic != "" {
kSink, err := kafka.NewKafkaMetricSink(
log, ret.TraceClient, conf.KafkaBroker, conf.KafkaCheckTopic, conf.KafkaEventTopic,
conf.KafkaMetricTopic, conf.KafkaMetricRequireAcks,
conf.KafkaPartitioner, conf.KafkaRetryMax,
conf.KafkaMetricBufferBytes, conf.KafkaMetricBufferMessages,
conf.KafkaMetricBufferFrequency,
)
if err != nil {
return ret, err
}
ret.metricSinks = append(ret.metricSinks, kSink)
logger.Info("Configured Kafka metric sink")
} else {
logger.Warn("Kafka metric sink skipped due to missing metric, check and event topic")
}
if conf.KafkaSpanTopic != "" {
sink, err := kafka.NewKafkaSpanSink(log, ret.TraceClient, conf.KafkaBroker, conf.KafkaSpanTopic,
conf.KafkaPartitioner, conf.KafkaMetricRequireAcks, conf.KafkaRetryMax,
conf.KafkaSpanBufferBytes, conf.KafkaSpanBufferMesages,
conf.KafkaSpanBufferFrequency, conf.KafkaSpanSerializationFormat,
conf.KafkaSpanSampleTag, conf.KafkaSpanSampleRatePercent,
)
if err != nil {
return ret, err
}
ret.spanSinks = append(ret.spanSinks, sink)
logger.Info("Configured Kafka span sink")
} else {
logger.Warn("Kafka span sink skipped due to missing span topic")
}
}
if conf.PrometheusRepeaterAddress != "" {
prometheusMetricSink, err := prometheus.NewStatsdRepeater(
conf.PrometheusRepeaterAddress,
conf.PrometheusNetworkType,
log,
)
if err != nil {
return ret, err
}
ret.metricSinks = append(ret.metricSinks, prometheusMetricSink)
logger.Info("Configured Prometheus metric sink.")
}
{
mtx := sync.Mutex{}
if conf.DebugFlushedMetrics {
ret.metricSinks = append(ret.metricSinks, debug.NewDebugMetricSink(&mtx, log))
}
if conf.DebugIngestedSpans {
blackhole := debug.NewDebugSpanSink(&mtx, log)
ret.spanSinks = append(ret.spanSinks, blackhole)
logger.WithField("name", blackhole.Name()).Info("Starting logger debug sink")
}
}
// After all sinks are initialized, set the list of tags to exclude
setSinkExcludedTags(conf.TagsExclude, ret.metricSinks, ret.spanSinks)
var svc s3iface.S3API
awsID := conf.AwsAccessKeyID
awsSecret := conf.AwsSecretAccessKey
if conf.AwsS3Bucket != "" {
var sess *session.Session
var err error
if len(awsID) > 0 && len(awsSecret) > 0 {
sess, err = session.NewSession(&aws.Config{
Region: aws.String(conf.AwsRegion),
Credentials: credentials.NewStaticCredentials(awsID, awsSecret, ""),
})
} else {
sess, err = session.NewSession(&aws.Config{
Region: aws.String(conf.AwsRegion),
})
}
if err != nil {
logger.Infof("error getting AWS session: %s", err)
svc = nil
} else {
logger.Info("Successfully created AWS session")
svc = s3.New(sess)
plugin := &s3p.S3Plugin{
Logger: log,
Svc: svc,
S3Bucket: conf.AwsS3Bucket,
Hostname: ret.Hostname,
}
ret.registerPlugin(plugin)
}
} else {
logger.Info("AWS S3 bucket not set. Skipping S3 Plugin initialization.")
}
if svc == nil {
logger.Info("S3 archives are disabled")
} else {
logger.Info("S3 archives are enabled")
}
if conf.FlushFile != "" {
localFilePlugin := &localfilep.Plugin{
FilePath: conf.FlushFile,
Logger: log,
}
ret.registerPlugin(localFilePlugin)
logger.Info(fmt.Sprintf("Local file logging to %s", conf.FlushFile))
}
// closed in Shutdown; Same approach and http.Shutdown
ret.shutdown = make(chan struct{})
if conf.HTTPQuit {
logger.WithField("endpoint", httpQuitEndpoint).Info("Enabling graceful shutdown endpoint (via HTTP POST request)")
ret.httpQuit = true
}
// Don't emit keys into logs now that we're done with them.
conf.AwsAccessKeyID = REDACTED
conf.AwsSecretAccessKey = REDACTED
conf.DatadogAPIKey = REDACTED
conf.LightstepAccessToken = REDACTED
conf.NewrelicInsertKey = REDACTED
conf.SentryDsn = REDACTED
conf.SignalfxAPIKey = REDACTED
conf.TLSKey = REDACTED
ret.forwardUseGRPC = conf.ForwardUseGrpc
// Setup the grpc server if it was configured
ret.grpcListenAddress = conf.GrpcAddress
if ret.grpcListenAddress != "" {
// convert all the workers to the proper interface
ingesters := make([]importsrv.MetricIngester, len(ret.Workers))
for i, worker := range ret.Workers {
ingesters[i] = worker
}
ret.grpcServer = importsrv.New(ingesters,
importsrv.WithTraceClient(ret.TraceClient))
}
// If this is a global veneur then initialize the listening per protocol metrics
if !ret.IsLocal() {
ret.listeningPerProtocolMetrics = &GlobalListeningPerProtocolMetrics{
dogstatsdTcpReceivedTotal: 0,
dogstatsdUdpReceivedTotal: 0,
dogstatsdUnixReceivedTotal: 0,
dogstatsdGrpcReceivedTotal: 0,
ssfUdpReceivedTotal: 0,
ssfUnixReceivedTotal: 0,
ssfGrpcReceivedTotal: 0,
}
log.Info("Tracking listening per protocol metrics on global instance")
}
logger.WithField("config", conf).Debug("Initialized server")
return ret, err
}
// Start spins up the Server to do actual work, firing off goroutines for
// various workers and utilities.
func (s *Server) Start() {
log.WithField("version", VERSION).Info("Starting server")
// Set up the processors for spans:
// Use the pre-allocated Workers slice to know how many to start.
s.SpanWorker = NewSpanWorker(s.spanSinks, s.TraceClient, s.Statsd, s.SpanChan, s.TagsAsMap)
go func() {
log.Info("Starting Event worker")
defer func() {
ConsumePanic(s.TraceClient, s.Hostname, recover())
}()
s.EventWorker.Work()
}()
log.WithField("n", s.SpanWorkerGoroutines).Info("Starting span workers")
for i := 0; i < s.SpanWorkerGoroutines; i++ {
go func() {
defer func() {
ConsumePanic(s.TraceClient, s.Hostname, recover())
}()
s.SpanWorker.Work()
}()
}
statsdPool := &sync.Pool{
// We +1 this so we an "detect" when someone sends us too long of a metric!
New: func() interface{} {
return make([]byte, s.metricMaxLength+1)
},
}
tracePool := &sync.Pool{
New: func() interface{} {
return make([]byte, s.traceMaxLengthBytes)
},
}
for _, sink := range s.spanSinks {
logrus.WithField("sink", sink.Name()).Info("Starting span sink")
if err := sink.Start(s.TraceClient); err != nil {
logrus.WithError(err).WithField("sink", sink).Panic("Error starting span sink")
}
}
for _, sink := range s.metricSinks {
logrus.WithField("sink", sink.Name()).Info("Starting metric sink")
if err := sink.Start(s.TraceClient); err != nil {
logrus.WithError(err).WithField("sink", sink).Fatal("Error starting metric sink")
}
}
// Read Metrics Forever!
concreteAddrs := make([]net.Addr, 0, len(s.StatsdListenAddrs))
for _, addr := range s.StatsdListenAddrs {
concreteAddrs = append(concreteAddrs, StartStatsd(s, addr, statsdPool))
}
s.StatsdListenAddrs = concreteAddrs
// Read Traces Forever!
if len(s.SSFListenAddrs) > 0 {
concreteAddrs := make([]net.Addr, 0, len(s.StatsdListenAddrs))
for _, addr := range s.SSFListenAddrs {
concreteAddrs = append(concreteAddrs, StartSSF(s, addr, tracePool))
}
s.SSFListenAddrs = concreteAddrs
} else {
logrus.Info("Tracing sockets are not configured - not reading trace socket")
}
// Read grpc traces forever!
if len(s.GRPCListenAddrs) > 0 {
concreteAddrs := make([]net.Addr, 0, len(s.GRPCListenAddrs))
for _, addr := range s.GRPCListenAddrs {
concreteAddrs = append(concreteAddrs, StartGRPC(s, addr))
}
//If there are already ssf listen addresses then append the grpc ones otherwise just use the grpc ones
if len(s.SSFListenAddrs) > 0 {
s.SSFListenAddrs = append(s.SSFListenAddrs, concreteAddrs...)
} else {
s.SSFListenAddrs = concreteAddrs
}
//If there are already statsd listen addresses then append the grpc ones otherwise just use the grpc ones
if len(s.StatsdListenAddrs) > 0 {
s.StatsdListenAddrs = append(s.StatsdListenAddrs, concreteAddrs...)
} else {
s.StatsdListenAddrs = concreteAddrs
}
} else {
logrus.Info("GRPC tracing sockets are not configured - not reading trace socket")
}
// Initialize a gRPC connection for forwarding
if s.forwardUseGRPC {
var err error
s.grpcForwardConn, err = grpc.Dial(s.ForwardAddr, grpc.WithInsecure())
if err != nil {
log.WithError(err).WithFields(logrus.Fields{
"forwardAddr": s.ForwardAddr,
}).Fatal("Failed to initialize a gRPC connection for forwarding")
}
}
// Flush every Interval forever!
go func() {
defer func() {
ConsumePanic(s.TraceClient, s.Hostname, recover())
}()
ctx, cancel := context.WithCancel(context.Background())
go func() {
// If the server is shutting down, cancel any in-flight flush:
<-s.shutdown