-
Notifications
You must be signed in to change notification settings - Fork 100
/
statsd.go
226 lines (200 loc) · 6.86 KB
/
statsd.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
package statsd
import (
"context"
"net"
"os"
"strconv"
"sync"
"time"
"github.com/atlassian/gostatsd"
"github.com/atlassian/gostatsd/pkg/statser"
log "github.com/Sirupsen/logrus"
"github.com/spf13/viper"
"golang.org/x/time/rate"
)
// Server encapsulates all of the parameters necessary for starting up
// the statsd server. These can either be set via command line or directly.
type Server struct {
Backends []gostatsd.Backend
CloudProvider gostatsd.CloudProvider
Limiter *rate.Limiter
InternalTags gostatsd.Tags
InternalNamespace string
DefaultTags gostatsd.Tags
ExpiryInterval time.Duration
FlushInterval time.Duration
IgnoreHost bool
MaxReaders int
MaxWorkers int
MaxQueueSize int
MaxConcurrentEvents int
MaxEventQueueSize int
MetricsAddr string
Namespace string
PercentThreshold []float64
CacheOptions
Viper *viper.Viper
}
// Run runs the server until context signals done.
func (s *Server) Run(ctx context.Context) error {
return s.RunWithCustomSocket(ctx, func() (net.PacketConn, error) {
return net.ListenPacket("udp", s.MetricsAddr)
})
}
// SocketFactory is an indirection layer over net.ListenPacket() to allow for different implementations.
type SocketFactory func() (net.PacketConn, error)
// RunWithCustomSocket runs the server until context signals done.
// Listening socket is created using sf.
func (s *Server) RunWithCustomSocket(ctx context.Context, sf SocketFactory) error {
// 0. Start runnable backends
var wgBackends sync.WaitGroup
defer wgBackends.Wait() // Wait for backends to shutdown
ctxBack, cancelBack := context.WithCancel(context.Background()) // Separate context!
defer cancelBack() // Tell backends to shutdown
for _, b := range s.Backends {
if b, ok := b.(gostatsd.RunnableBackend); ok {
wgBackends.Add(1)
go b.Run(ctxBack, wgBackends.Done)
}
}
// 1. Start the Dispatcher
factory := agrFactory{
percentThresholds: s.PercentThreshold,
expiryInterval: s.ExpiryInterval,
}
dispatcher := NewMetricDispatcher(s.MaxWorkers, s.MaxQueueSize, &factory)
var wgDispatcher sync.WaitGroup
defer wgDispatcher.Wait() // Wait for dispatcher to shutdown
ctxDisp, cancelDisp := context.WithCancel(context.Background()) // Separate context!
defer cancelDisp() // Tell the dispatcher to shutdown
wgDispatcher.Add(1)
go dispatcher.Run(ctxDisp, wgDispatcher.Done)
// 2. Start handlers
ip := gostatsd.UnknownIP
var handler Handler // nolint: gosimple, megacheck
handler = NewDispatchingHandler(dispatcher, s.Backends, s.DefaultTags, uint(s.MaxConcurrentEvents))
if s.CloudProvider != nil {
ch := NewCloudHandler(s.CloudProvider, handler, s.Limiter, &s.CacheOptions)
handler = ch
var wgCloudHandler sync.WaitGroup
defer wgCloudHandler.Wait() // Wait for handler to shutdown
ctxHandler, cancelHandler := context.WithCancel(context.Background()) // Separate context!
defer cancelHandler() // Tell the handler to shutdown
wgCloudHandler.Add(1)
go ch.Run(ctxHandler, wgCloudHandler.Done)
selfIP, err := s.CloudProvider.SelfIP()
if err != nil {
log.Warnf("Failed to get self ip: %v", err)
} else {
ip = selfIP
}
}
// 3. Attach the dispatchers metrics
hostname := getHost()
namespace := s.Namespace
if s.InternalNamespace != "" {
if namespace != "" {
namespace = namespace + "." + s.InternalNamespace
} else {
namespace = s.InternalNamespace
}
}
var wgStatser sync.WaitGroup
wgStatser.Add(1)
defer wgStatser.Wait()
ctxStatser, cancelStatser := context.WithCancel(context.Background())
defer cancelStatser()
bufferSize := 10 + 4*s.MaxWorkers // Estimate: 3 for the CSW on each (+ a bit), and a bit of overhead for things that tick in the background
statser := statser.NewInternalStatser(bufferSize, s.InternalTags, namespace, hostname, handler)
// TODO: Make internal metric dispatch configurable
// statser := NewLoggingStatser(s.InternalTags, log.NewEntry(log.New()))
go statser.Run(ctxStatser, wgStatser.Done)
dispatcher.runMetrics(ctxStatser, statser)
// 4. Start the Receiver
var wgReceiver sync.WaitGroup
defer wgReceiver.Wait() // Wait for all receivers to finish
// Open socket
c, err := sf()
if err != nil {
return err
}
defer func() {
// This makes receivers error out and stop
if e := c.Close(); e != nil {
log.Warnf("Error closing socket: %v", e)
}
}()
receiver := NewMetricReceiver(s.Namespace, s.IgnoreHost, handler, statser)
wgReceiver.Add(s.MaxReaders + 1)
go receiver.runMetrics(ctx, wgReceiver.Done)
for r := 0; r < s.MaxReaders; r++ {
go receiver.Receive(ctx, wgReceiver.Done, c)
}
// 5. Start the Flusher
flusher := NewMetricFlusher(s.FlushInterval, dispatcher, handler, s.Backends, ip, hostname, statser)
var wgFlusher sync.WaitGroup
defer wgFlusher.Wait() // Wait for the Flusher to finish
wgFlusher.Add(1)
go flusher.Run(ctx, wgFlusher.Done)
// 6. Send events on start and on stop
// TODO: Push these in to statser
defer sendStopEvent(handler, ip, hostname)
sendStartEvent(ctx, handler, ip, hostname)
// 7. Listen until done
<-ctx.Done()
return ctx.Err()
}
func sendStartEvent(ctx context.Context, handler Handler, selfIP gostatsd.IP, hostname string) {
err := handler.DispatchEvent(ctx, &gostatsd.Event{
Title: "Gostatsd started",
Text: "Gostatsd started",
DateHappened: time.Now().Unix(),
Hostname: hostname,
SourceIP: selfIP,
Priority: gostatsd.PriLow,
})
if unexpectedErr(err) {
log.Warnf("Failed to send start event: %v", err)
}
}
func sendStopEvent(handler Handler, selfIP gostatsd.IP, hostname string) {
ctx, cancelFunc := context.WithTimeout(context.Background(), 2*time.Second)
defer cancelFunc()
err := handler.DispatchEvent(ctx, &gostatsd.Event{
Title: "Gostatsd stopped",
Text: "Gostatsd stopped",
DateHappened: time.Now().Unix(),
Hostname: hostname,
SourceIP: selfIP,
Priority: gostatsd.PriLow,
})
if unexpectedErr(err) {
log.Warnf("Failed to send stop event: %v", err)
}
handler.WaitForEvents()
}
func getHost() string {
host, err := os.Hostname()
if err != nil {
log.Warnf("Cannot get hostname: %v", err)
return ""
}
return host
}
type agrFactory struct {
percentThresholds []float64
expiryInterval time.Duration
}
func (af *agrFactory) Create() Aggregator {
return NewMetricAggregator(af.percentThresholds, af.expiryInterval)
}
func toStringSlice(fs []float64) []string {
s := make([]string, len(fs))
for i, f := range fs {
s[i] = strconv.FormatFloat(f, 'f', -1, 64)
}
return s
}
func unexpectedErr(err error) bool {
return err != nil && err != context.Canceled && err != context.DeadlineExceeded
}