forked from stripe/veneur
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
1518 lines (1338 loc) · 43.8 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"
"runtime/debug"
"sort"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/DataDog/datadog-go/statsd"
"github.com/segmentio/fasthash/fnv1a"
"github.com/sirupsen/logrus"
"github.com/zenazn/goji/bind"
"github.com/zenazn/goji/graceful"
"google.golang.org/grpc"
"github.com/pkg/profile"
"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/ssfmetrics"
"github.com/stripe/veneur/v14/sources"
"github.com/stripe/veneur/v14/sources/proxy"
"github.com/stripe/veneur/v14/ssf"
"github.com/stripe/veneur/v14/tagging"
"github.com/stripe/veneur/v14/trace"
"github.com/stripe/veneur/v14/trace/metrics"
"github.com/stripe/veneur/v14/util/matcher"
)
// 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"
var profileStartOnce = sync.Once{}
var tracer = trace.GlobalTracer
const defaultTCPReadTimeout = 10 * time.Minute
const httpQuitEndpoint = "/quitquitquit"
type ParsedSourceConfig interface{}
type MetricSinkConfig interface{}
type SpanSinkConfig interface{}
type SourceTypes = map[string]struct {
// Creates a new source intsance.
Create func(
*Server, string, *logrus.Entry, ParsedSourceConfig,
) (sources.Source, error)
// Parses the config for the source into a format that is validated and safe
// to log.
ParseConfig func(string, interface{}) (ParsedSourceConfig, error)
}
type SpanSinkTypes = map[string]struct {
// Creates a new span sink intsance.
Create func(
*Server, string, *logrus.Entry, Config, SpanSinkConfig,
) (sinks.SpanSink, error)
// Parses the config for the sink into a format that is validated and safe to
// log.
ParseConfig func(string, interface{}) (SpanSinkConfig, error)
}
type MetricSinkTypes = map[string]struct {
// Creates a new metric sink instance.
Create func(
*Server, string, *logrus.Entry, Config, MetricSinkConfig,
) (sinks.MetricSink, error)
// Parses the config for the sink into a format that is validated and safe to
// log.
ParseConfig func(string, interface{}) (MetricSinkConfig, error)
}
// Config used to create a new server.
type ServerConfig struct {
Config Config
Logger *logrus.Logger
MetricSinkTypes MetricSinkTypes
SourceTypes SourceTypes
SpanSinkTypes SpanSinkTypes
}
type ProxyProtocol int64
const (
ProxyProtocolUnknown ProxyProtocol = iota
ProxyProtocolRest
ProxyProtocolGrpcSingle
ProxyProtocolGrpcStream
)
// A Server is the actual veneur instance that will be run.
type Server struct {
Config Config
logger *logrus.Entry
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
proxyProtocol ProxyProtocol
StatsdListenAddrs []net.Addr
SSFListenAddrs []net.Addr
GRPCListenAddrs []net.Addr
RcvbufBytes int
FlushOnShutdown bool
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
enableProfiling bool
HistogramAggregates samplers.HistogramAggregates
sources []internalSource
spanSinks []sinks.SpanSink
metricSinks []internalMetricSink
TraceClient *trace.Client
ssfInternalMetrics sync.Map
listeningPerProtocolMetrics *GlobalListeningPerProtocolMetrics
// gRPC server
grpcListenAddress string
grpcServer *proxy.Server
// gRPC forward clients
grpcForwardConn *grpc.ClientConn
stuckIntervals int
lastFlushUnix int64
parser samplers.Parser
}
type internalSource struct {
source sources.Source
tags []string
}
type internalMetricSink struct {
sink sinks.MetricSink
stripTags []matcher.TagMatcher
}
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
}
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
}
type ingest struct {
server *Server
tags []string
}
var _ sources.Ingest = &ingest{}
func (ingest *ingest) IngestMetric(metric *samplers.UDPMetric) {
metric.Tags = append(metric.Tags, ingest.tags...)
ingest.server.ingestMetric(metric)
}
func (server *Server) createSources(
logger *logrus.Logger, config *Config, sourceTypes SourceTypes,
) ([]internalSource, error) {
sources := []internalSource{}
for index, sourceConfig := range config.Sources {
sourceFactory, ok := sourceTypes[sourceConfig.Kind]
if !ok {
logger.Warnf("Unknown source kind %s; skipping.", sourceConfig.Kind)
}
parsedSourceConfig, err :=
sourceFactory.ParseConfig(sourceConfig.Name, sourceConfig.Config)
if err != nil {
return nil, err
}
// Overwrite the map config with the parsed config. This prevents senstive
// fields in the map from accidentally being logged.
config.Sources[index].Config = parsedSourceConfig
source, err := sourceFactory.Create(
server, sourceConfig.Name, logger.WithField("source", sourceConfig.Name),
parsedSourceConfig)
if err != nil {
return nil, err
}
sources = append(sources, internalSource{
source: source,
tags: sourceConfig.Tags,
})
}
return sources, nil
}
func (server *Server) createSpanSinks(
logger *logrus.Logger, config *Config, sinkTypes SpanSinkTypes,
) ([]sinks.SpanSink, error) {
sinks := []sinks.SpanSink{}
for index, sinkConfig := range config.SpanSinks {
sinkFactory, ok := sinkTypes[sinkConfig.Kind]
if !ok {
logger.Warnf("Unknown sink kind %s; skipping.", sinkConfig.Kind)
}
parsedSinkConfig, err := sinkFactory.ParseConfig(
sinkConfig.Name, sinkConfig.Config)
if err != nil {
return nil, err
}
// Overwrite the map config with the parsed config. This prevents senstive
// fields in the map from accidentally being logged.
config.SpanSinks[index].Config = parsedSinkConfig
sink, err := sinkFactory.Create(
server, sinkConfig.Name, logger.WithField("span_sink", sinkConfig.Name),
*config, parsedSinkConfig)
if err != nil {
return nil, err
}
sinks = append(sinks, sink)
}
return sinks, nil
}
func (server *Server) createMetricSinks(
logger *logrus.Logger, config *Config, sinkTypes MetricSinkTypes,
) ([]internalMetricSink, error) {
sinks := []internalMetricSink{}
for index, sinkConfig := range config.MetricSinks {
sinkFactory, ok := sinkTypes[sinkConfig.Kind]
if !ok {
logger.Warnf("Unknown sink kind %s; skipping.", sinkConfig.Kind)
continue
}
parsedSinkConfig, err := sinkFactory.ParseConfig(
sinkConfig.Name, sinkConfig.Config)
if err != nil {
return nil, err
}
// Overwrite the map config with the parsed config. This prevents senstive
// fields in the map from accidentally being logged.
config.MetricSinks[index].Config = parsedSinkConfig
sink, err := sinkFactory.Create(
server, sinkConfig.Name, logger.WithField("metric_sink", sinkConfig.Name),
*config, parsedSinkConfig)
if err != nil {
return nil, err
}
sinks = append(sinks, internalMetricSink{
sink: sink,
stripTags: sinkConfig.StripTags,
})
}
return sinks, nil
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}
// NewFromConfig creates a new veneur server from a configuration
// specification and sets up the passed logger according to the
// configuration.
func NewFromConfig(config ServerConfig) (*Server, error) {
logger := config.Logger
conf := config.Config
ret := &Server{
Config: conf,
// Control whether Veneur should emit metric
// "veneur.flush.unique_timeseries_total", which may come at a slight
// performance hit to workers.
CountUniqueTimeseries: conf.CountUniqueTimeseries,
// This must come before worker initialization. We need to initialize
// workers with state from *Server.IsWorker.
enableProfiling: conf.EnableProfiling,
ForwardAddr: conf.ForwardAddress,
grpcListenAddress: conf.GrpcAddress,
Hostname: conf.Hostname,
HistogramPercentiles: conf.Percentiles,
HTTPAddr: conf.HTTPAddress,
HTTPClient: &http.Client{
// make sure that POSTs to datadog do not overflow the flush interval
Timeout: conf.Interval * 9 / 10,
Transport: &http.Transport{
// If we're idle more than one interval something is up
IdleConnTimeout: conf.Interval * 2,
},
},
Interval: conf.Interval,
logger: logrus.NewEntry(config.Logger),
metricMaxLength: conf.MetricMaxLength,
numListeningHTTP: new(int32),
numReaders: conf.NumReaders,
parser: samplers.NewParser(conf.ExtendTags),
RcvbufBytes: conf.ReadBufferSizeBytes,
// closed in Shutdown; Same approach and http.Shutdown
shutdown: make(chan struct{}),
Tags: conf.Tags,
TagsAsMap: tagging.ParseTagSliceToMap(conf.Tags),
traceMaxLengthBytes: conf.TraceMaxLengthBytes,
SpanChan: make(chan *ssf.SSFSpan, conf.SpanChannelCapacity),
stuckIntervals: conf.FlushWatchdogMissedFlushes,
synchronizeInterval: conf.SynchronizeWithInterval,
// Allocate the slice, we'll fill it with workers later.
Workers: make([]*Worker, max(1, conf.NumWorkers)),
}
ret.HistogramAggregates.Value = 0
for _, agg := range conf.Aggregates {
ret.HistogramAggregates.Value += samplers.AggregatesLookup[agg]
}
ret.HistogramAggregates.Count = len(conf.Aggregates)
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.TraceClient, err = trace.NewChannelClient(ret.SpanChan,
trace.ReportStatistics(stats, 1*time.Second, []string{"ssf_format:internal"}),
normalizeSpans(conf),
)
if err != nil {
return ret, err
}
if conf.Debug {
logger.SetLevel(logrus.DebugLevel)
}
mpf := 0
if conf.MutexProfileFraction > 0 {
mpf = runtime.SetMutexProfileFraction(conf.MutexProfileFraction)
}
logger.WithFields(logrus.Fields{
"MutexProfileFraction": conf.MutexProfileFraction,
"previousMutexProfileFraction": mpf,
}).Info("Set mutex profile fraction")
if conf.BlockProfileRate > 0 {
runtime.SetBlockProfileRate(conf.BlockProfileRate)
}
logger.WithField("BlockProfileRate", conf.BlockProfileRate).Info("Set block profile rate (nanoseconds)")
ret.FlushOnShutdown = conf.FlushOnShutdown
// Use the pre-allocated Workers slice to know how many to start.
logger.WithField("number", len(ret.Workers)).Info("Preparing workers")
for i := range ret.Workers {
ret.Workers[i] = NewWorker(i+1, ret.IsLocal(), ret.CountUniqueTimeseries, ret.TraceClient, logger, 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, logger, &ret.parser)
if err != nil {
return ret, err
}
ret.spanSinks = append(ret.spanSinks, metricSink)
for _, addrStr := range conf.StatsdListenAddresses {
addr, err := protocol.ResolveAddr(addrStr.Value)
if err != nil {
return ret, err
}
ret.StatsdListenAddrs = append(ret.StatsdListenAddrs, addr)
}
for _, addrStr := range conf.SsfListenAddresses {
addr, err := protocol.ResolveAddr(addrStr.Value)
if err != nil {
return ret, err
}
ret.SSFListenAddrs = append(ret.SSFListenAddrs, addr)
}
for _, addrStr := range conf.GrpcListenAddresses {
addr, err := protocol.ResolveAddr(addrStr.Value)
if err != nil {
return ret, err
}
ret.GRPCListenAddrs = append(ret.GRPCListenAddrs, addr)
}
if conf.TLSKey.Value != "" {
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.Value))
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,
}
}
// Configure tracing sinks if we are listening for ssf
if len(conf.SsfListenAddresses) > 0 || len(conf.GrpcListenAddresses) > 0 {
trace.Enable()
// Set up as many span workers as we need:
if conf.NumSpanWorkers > 0 {
ret.SpanWorkerGoroutines = conf.NumSpanWorkers
} else {
ret.SpanWorkerGoroutines = 1
}
}
customMetricSinks, err :=
ret.createMetricSinks(logger, &conf, config.MetricSinkTypes)
if err != nil {
return nil, err
}
if conf.Features.MigrateMetricSinks {
ret.metricSinks = customMetricSinks
} else {
ret.metricSinks = append(ret.metricSinks, customMetricSinks...)
}
customSpanSinks, err :=
ret.createSpanSinks(logger, &conf, config.SpanSinkTypes)
if err != nil {
return nil, err
}
if conf.Features.MigrateSpanSinks {
ret.spanSinks = customSpanSinks
} else {
ret.spanSinks = append(ret.spanSinks, customSpanSinks...)
}
// After all sinks are initialized, set the list of tags to exclude
ret.setSinkExcludedTags(conf.TagsExclude, ret.metricSinks, ret.spanSinks)
if conf.HTTPQuit {
logger.WithField("endpoint", httpQuitEndpoint).Info("Enabling graceful shutdown endpoint (via HTTP POST request)")
ret.httpQuit = true
}
switch conf.Features.ProxyProtocol {
case "grpc-stream":
ret.proxyProtocol = ProxyProtocolGrpcStream
case "grpc-single":
ret.proxyProtocol = ProxyProtocolGrpcSingle
case "json":
ret.proxyProtocol = ProxyProtocolRest
default:
// TODO(arnavdugar): Remove conf.ForwardUseGrpc.
if conf.ForwardUseGrpc {
ret.proxyProtocol = ProxyProtocolGrpcSingle
} else {
ret.proxyProtocol = ProxyProtocolRest
}
}
ret.sources, err = ret.createSources(logger, &conf, config.SourceTypes)
if err != nil {
return nil, err
}
// Setup the grpc server if it was configured
if ret.grpcListenAddress != "" {
// convert all the workers to the proper interface
ingesters := make([]proxy.MetricIngester, len(ret.Workers))
for i, worker := range ret.Workers {
ingesters[i] = worker
}
ret.grpcServer = proxy.New(ret.grpcListenAddress, ingesters,
config.Logger.WithField("source", "proxy"),
proxy.WithTraceClient(ret.TraceClient))
ret.sources = append(ret.sources, internalSource{
source: ret.grpcServer,
tags: []string{},
})
}
// 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,
}
logger.Info("Tracking listening per protocol metrics on global instance")
}
logger.WithField("config", conf).Debug("Initialized server")
return ret, nil
}
// Start spins up the Server to do actual work, firing off goroutines for
// various workers and utilities.
func (s *Server) Start() {
s.logger.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, s.logger)
go func() {
s.logger.Info("Starting Event worker")
defer func() {
ConsumePanic(s.TraceClient, s.Hostname, recover())
}()
s.EventWorker.Work()
}()
s.logger.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.sink.Name()).Info("Starting metric sink")
if err := sink.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))
statsdSource := UdpMetricsSource{
logger: s.logger,
}
for _, addr := range s.StatsdListenAddrs {
concreteAddrs = append(
concreteAddrs, statsdSource.StartStatsd(s, addr, statsdPool))
}
s.StatsdListenAddrs = concreteAddrs
// Read Traces Forever!
ssfSource := SsfMetricsSource{
logger: s.logger,
}
if len(s.SSFListenAddrs) > 0 {
concreteAddrs := make([]net.Addr, 0, len(s.StatsdListenAddrs))
for _, addr := range s.SSFListenAddrs {
concreteAddrs = append(
concreteAddrs, ssfSource.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))
grpcSource := GrpcMetricsSource{
logger: s.logger,
}
for _, addr := range s.GRPCListenAddrs {
concreteAddrs = append(concreteAddrs, grpcSource.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.proxyProtocol == ProxyProtocolGrpcSingle ||
s.proxyProtocol == ProxyProtocolGrpcStream {
var err error
s.grpcForwardConn, err = grpc.Dial(s.ForwardAddr, grpc.WithInsecure())
if err != nil {
s.logger.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
cancel()
}()
if s.synchronizeInterval {
// We want to align our ticker to a multiple of its duration for
// convenience of bucketing.
<-time.After(CalculateTickDelay(s.Interval, time.Now()))
}
// We aligned the ticker to our interval above. It's worth noting that just
// because we aligned once we're not guaranteed to be perfect on each
// subsequent tick. This code is small, however, and should service the
// incoming tick signal fast enough that the amount we are "off" is
// negligible.
ticker := time.NewTicker(s.Interval)
for {
select {
case <-s.shutdown:
// stop flushing on graceful shutdown
ticker.Stop()
return
case triggered := <-ticker.C:
ctx, cancel := context.WithDeadline(ctx, triggered.Add(s.Interval))
s.Flush(ctx)
cancel()
}
}
}()
}
// FlushWatchdog periodically checks that at most
// `flush_watchdog_missed_flushes` were skipped in a Server. If more
// than that number was skipped, it panics (assuming that flushing is
// stuck) with a full level of detail on that panic's backtraces.
//
// It never terminates, so is ideally run from a goroutine in a
// program's main function.
func (s *Server) FlushWatchdog() {
defer func() {
ConsumePanic(s.TraceClient, s.Hostname, recover())
}()
if s.stuckIntervals == 0 {
// No watchdog needed:
return
}
atomic.StoreInt64(&s.lastFlushUnix, time.Now().UnixNano())
ticker := time.NewTicker(s.Interval)
for {
select {
case <-s.shutdown:
ticker.Stop()
return
case <-ticker.C:
last := time.Unix(0, atomic.LoadInt64(&s.lastFlushUnix))
since := time.Since(last)
// If no flush was kicked off in the last N
// times, we're stuck - panic because that's a
// bug.
if since > time.Duration(s.stuckIntervals)*s.Interval {
debug.SetTraceback("all")
s.logger.WithFields(logrus.Fields{
"last_flush": last,
"missed_intervals": s.stuckIntervals,
"time_since": since,
}).
Panic("Flushing seems to be stuck. Terminating.")
}
}
}
}
// Increment internal metrics keeping track of protocols received when listening
func incrementListeningProtocol(s *Server, protocol ProtocolType) {
metricsStruct := s.listeningPerProtocolMetrics
if metricsStruct != nil {
switch protocol {
case DOGSTATSD_TCP:
atomic.AddInt64(&metricsStruct.dogstatsdTcpReceivedTotal, 1)
case DOGSTATSD_UDP:
atomic.AddInt64(&metricsStruct.dogstatsdUdpReceivedTotal, 1)
case DOGSTATSD_UNIX:
atomic.AddInt64(&metricsStruct.dogstatsdUnixReceivedTotal, 1)
case DOGSTATSD_GRPC:
atomic.AddInt64(&metricsStruct.dogstatsdGrpcReceivedTotal, 1)
case SSF_UDP:
atomic.AddInt64(&metricsStruct.ssfUdpReceivedTotal, 1)
case SSF_UNIX:
atomic.AddInt64(&metricsStruct.ssfUnixReceivedTotal, 1)
case SSF_GRPC:
atomic.AddInt64(&metricsStruct.ssfGrpcReceivedTotal, 1)
default: //If it is an unrecognized protocol then don't increment anything
logrus.WithField("protocol", protocol).
Warning("Attempted to increment metrics for unrecognized protocol")
}
}
}
// HandleMetricPacket processes each packet that is sent to the server, and sends to an
// appropriate worker (EventWorker or Worker).
func (s *Server) HandleMetricPacket(packet []byte, protocolType ProtocolType) error {
// This is a very performance-sensitive function
// and packets may be dropped if it gets slowed down.
// Keep that in mind when modifying!
if len(packet) == 0 {
// a lot of clients send packets that accidentally have a trailing
// newline, it's easier to just let them be
return nil
}
samples := &ssf.Samples{}
defer metrics.Report(s.TraceClient, samples)
if !s.IsLocal() {
incrementListeningProtocol(s, protocolType)
}
if bytes.HasPrefix(packet, []byte{'_', 'e', '{'}) {
event, err := s.parser.ParseEvent(packet)
if err != nil {
s.logger.WithFields(logrus.Fields{
logrus.ErrorKey: err,
"packet": string(packet),
}).Debug("Could not parse packet")
samples.Add(ssf.Count("packet.error_total", 1, map[string]string{"packet_type": "event", "reason": "parse"}))
return err
}
s.EventWorker.sampleChan <- *event
} else if bytes.HasPrefix(packet, []byte{'_', 's', 'c'}) {
svcheck, err := s.parser.ParseServiceCheck(packet)
if err != nil {
s.logger.WithFields(logrus.Fields{
logrus.ErrorKey: err,
"packet": string(packet),
}).Debug("Could not parse packet")
samples.Add(ssf.Count("packet.error_total", 1, map[string]string{"packet_type": "service_check", "reason": "parse"}))
return err
}
s.ingestMetric(svcheck)
} else {
err := s.parser.ParseMetric(packet, s.ingestMetric)
if err != nil {
s.logger.WithFields(logrus.Fields{