forked from google/cloudprober
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cloudprober.go
345 lines (296 loc) · 9.38 KB
/
cloudprober.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
// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*
Package cloudprober provides a prober for running a set of probes.
Cloudprober takes in a config proto which dictates what probes should be created
with what configuration, and manages the asynchronous fan-in/fan-out of the
metrics data from these probes.
*/
package cloudprober
import (
"context"
"fmt"
"math/rand"
"net"
"net/http"
"os"
"strconv"
"sync"
"time"
"github.com/gogo/protobuf/proto"
"github.com/yext/cloudprober/config"
configpb "github.com/yext/cloudprober/config/proto"
"github.com/yext/cloudprober/logger"
"github.com/yext/cloudprober/metrics"
"github.com/yext/cloudprober/probes"
"github.com/yext/cloudprober/servers"
"github.com/yext/cloudprober/surfacers"
"github.com/yext/cloudprober/sysvars"
"github.com/yext/cloudprober/targets/lameduck"
rdsserver "github.com/yext/cloudprober/targets/rds/server"
"github.com/yext/cloudprober/targets/rtc/rtcreporter"
"github.com/yext/glog"
)
const (
sysvarsModuleName = "sysvars"
)
// Constants defining the default server host and port.
const (
DefaultServerHost = ""
DefaultServerPort = 9313
ServerHostEnvVar = "CLOUDPROBER_HOST"
ServerPortEnvVar = "CLOUDPROBER_PORT"
)
var prober *Prober
var proberMu sync.Mutex
// Prober represents a collection of probes where each probe implements the Probe interface.
type Prober struct {
Probes map[string]*probes.ProbeInfo
Servers []*servers.ServerInfo
c *configpb.ProberConfig
l *logger.Logger
rdsServer *rdsserver.Server
rtcReporter *rtcreporter.Reporter
surfacers []*surfacers.SurfacerInfo
serverListener net.Listener
// Used by GetConfig for /config handler.
textConfig string
}
func (pr *Prober) initDefaultServer() error {
serverHost := pr.c.GetHost()
if serverHost == "" {
serverHost = DefaultServerHost
// If ServerHostEnvVar is defined, it will override the default
// server host.
if host := os.Getenv(ServerHostEnvVar); host != "" {
serverHost = host
}
}
serverPort := int(pr.c.GetPort())
if serverPort == 0 {
serverPort = DefaultServerPort
// If ServerPortEnvVar is defined, it will override the default
// server port.
if portStr := os.Getenv(ServerPortEnvVar); portStr != "" {
port, err := strconv.ParseInt(portStr, 10, 32)
if err != nil {
return fmt.Errorf("failed to parse default port from the env var: %s=%s", ServerPortEnvVar, portStr)
}
serverPort = int(port)
}
}
ln, err := net.Listen("tcp", fmt.Sprintf("%s:%d", serverHost, serverPort))
if err != nil {
return fmt.Errorf("error while creating listener for default HTTP server. Err: %v", err)
}
pr.serverListener = ln
return nil
}
// InitFromConfig initializes Cloudprober using the provided config.
func InitFromConfig(configFile string) error {
// Return immediately if prober is already initialized.
proberMu.Lock()
defer proberMu.Unlock()
if prober != nil {
return nil
}
pr := &Prober{}
l := logger.NewStdoutCloudproberLog()
sysvars.Init(l, nil)
var err error
if pr.textConfig, err = config.ParseTemplate(configFile, sysvars.Vars()); err != nil {
return err
}
if err := pr.init(); err != nil {
return err
}
prober = pr
return nil
}
func (pr *Prober) init() error {
cfg := &configpb.ProberConfig{}
if err := proto.UnmarshalText(pr.textConfig, cfg); err != nil {
return err
}
pr.c = cfg
// Create a global logger. Each component gets its own logger on successful
// creation. For everything else, we use a global logger.
var err error
pr.l, err = logger.NewCloudproberLog("global")
if err != nil {
return fmt.Errorf("error in initializing global logger: %v", err)
}
// Initialize lameduck lister
globalTargetsOpts := pr.c.GetGlobalTargetsOptions()
if globalTargetsOpts.GetLameDuckOptions() != nil {
ldLogger, err := logger.NewCloudproberLog("lame-duck")
if err != nil {
return fmt.Errorf("error in initializing lame-duck logger: %v", err)
}
if err := lameduck.InitDefaultLister(globalTargetsOpts.GetLameDuckOptions(), nil, ldLogger); err != nil {
return err
}
}
// Initiliaze probes
pr.Probes, err = probes.Init(pr.c.GetProbe(), globalTargetsOpts, pr.l, sysvars.Vars())
if err != nil {
return err
}
// Start default HTTP server. It's used for profile handlers and
// prometheus exporter.
if err := pr.initDefaultServer(); err != nil {
return err
}
// Initialize servers
// TODO(manugarg): Plumb init context from cmd/cloudprober.
initCtx, cancelFunc := context.WithCancel(context.TODO())
pr.Servers, err = servers.Init(initCtx, pr.c.GetServer())
if err != nil {
cancelFunc()
goto cleanupInit
}
pr.surfacers, err = surfacers.Init(pr.c.GetSurfacer())
if err != nil {
goto cleanupInit
}
// Initialize RDS server, if configured.
if c := pr.c.GetRdsServer(); c != nil {
l, err := logger.NewCloudproberLog("rds-server")
if err != nil {
goto cleanupInit
}
if pr.rdsServer, err = rdsserver.New(initCtx, c, nil, l); err != nil {
goto cleanupInit
}
}
// Initialize RTC reporter, if configured.
if opts := pr.c.GetRtcReportOptions(); opts != nil {
l, err := logger.NewCloudproberLog("rtc-reporter")
if err != nil {
goto cleanupInit
}
if pr.rtcReporter, err = rtcreporter.New(opts, sysvars.Vars(), l); err != nil {
goto cleanupInit
}
}
return nil
cleanupInit:
if pr.serverListener != nil {
pr.serverListener.Close()
}
return err
}
// start starts a previously initialized Cloudprober.
func (pr *Prober) start(ctx context.Context) {
// Start the default server
srv := &http.Server{}
go func() {
<-ctx.Done()
srv.Close()
}()
go func() {
srv.Serve(pr.serverListener)
os.Exit(1)
}()
dataChan := make(chan *metrics.EventMetrics, 1000)
go func() {
var em *metrics.EventMetrics
for {
em = <-dataChan
var s = em.String()
if len(s) > logger.MaxLogEntrySize {
glog.Warningf("Metric entry for timestamp %v dropped due to large size: %d", em.Timestamp, len(s))
continue
}
// Replicate the surfacer message to every surfacer we have
// registered. Note that s.Write() is expected to be
// non-blocking to avoid blocking of EventMetrics message
// processing.
for _, surfacer := range pr.surfacers {
surfacer.Write(context.Background(), em)
}
}
}()
// Start a goroutine to export system variables
go sysvars.Start(ctx, dataChan, time.Millisecond*time.Duration(pr.c.GetSysvarsIntervalMsec()), pr.c.GetSysvarsEnvVar())
// Start servers, each in its own goroutine
for _, s := range pr.Servers {
go s.Start(ctx, dataChan)
}
// Start RDS server if configured.
if pr.rdsServer != nil {
go pr.rdsServer.Start(ctx, dataChan)
}
// Start RTC reporter if configured.
if pr.rtcReporter != nil {
go pr.rtcReporter.Start(ctx)
}
if pr.c.GetDisableJitter() {
for _, p := range pr.Probes {
go p.Start(ctx, dataChan)
}
return
}
pr.startProbesWithJitter(ctx, dataChan)
}
// startProbesWithJitter try to space out probes over time, as much as possible,
// without making it too complicated. We arrange probes into interval buckets -
// all probes with the same interval will be part of the same bucket, and we
// then spread out probes within that interval by introducing a delay of
// interval / len(probes) between probes. We also introduce a random jitter
// between different interval buckets.
func (pr *Prober) startProbesWithJitter(ctx context.Context, dataChan chan *metrics.EventMetrics) {
// Seed random number generator.
rand.Seed(time.Now().UnixNano())
// Make interval -> [probe1, probe2, probe3..] map
intervalBuckets := make(map[time.Duration][]*probes.ProbeInfo)
for _, p := range pr.Probes {
intervalBuckets[p.Options.Interval] = append(intervalBuckets[p.Options.Interval], p)
}
for interval, probeInfos := range intervalBuckets {
go func(interval time.Duration, probeInfos []*probes.ProbeInfo) {
// Introduce a random jitter between interval buckets.
randomDelayMsec := rand.Int63n(int64(interval.Seconds() * 1000))
time.Sleep(time.Duration(randomDelayMsec) * time.Millisecond)
interProbeDelay := interval / time.Duration(len(probeInfos))
// Spread out probes evenly with an interval bucket.
for _, p := range probeInfos {
pr.l.Info("Starting probe: ", p.Name)
go p.Start(ctx, dataChan)
time.Sleep(interProbeDelay)
}
}(interval, probeInfos)
}
}
// Start starts a previously initialized Cloudprober.
func Start(ctx context.Context) {
proberMu.Lock()
defer proberMu.Unlock()
if prober == nil {
panic("Prober is not initialized. Did you call cloudprober.InitFromConfig first?")
}
prober.start(ctx)
}
// GetConfig returns the prober config.
func GetConfig() string {
proberMu.Lock()
defer proberMu.Unlock()
return prober.textConfig
}
// GetInfo returns information on all the probes, servers and surfacers.
func GetInfo() (map[string]*probes.ProbeInfo, []*surfacers.SurfacerInfo, []*servers.ServerInfo) {
proberMu.Lock()
defer proberMu.Unlock()
return prober.Probes, prober.surfacers, prober.Servers
}