-
Notifications
You must be signed in to change notification settings - Fork 0
/
backend.go
481 lines (418 loc) · 12.8 KB
/
backend.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
package backend
import (
"context"
"fmt"
"os"
"runtime/debug"
"sync"
"time"
"github.com/coreos/etcd/clientv3"
"github.com/coreos/etcd/pkg/transport"
"github.com/google/uuid"
corev2 "github.com/sensu/sensu-go/api/core/v2"
"github.com/sensu/sensu-go/asset"
"github.com/sensu/sensu-go/backend/agentd"
"github.com/sensu/sensu-go/backend/apid"
"github.com/sensu/sensu-go/backend/authentication"
"github.com/sensu/sensu-go/backend/authentication/providers/basic"
"github.com/sensu/sensu-go/backend/daemon"
"github.com/sensu/sensu-go/backend/dashboardd"
"github.com/sensu/sensu-go/backend/etcd"
"github.com/sensu/sensu-go/backend/eventd"
"github.com/sensu/sensu-go/backend/keepalived"
"github.com/sensu/sensu-go/backend/liveness"
"github.com/sensu/sensu-go/backend/messaging"
"github.com/sensu/sensu-go/backend/pipelined"
"github.com/sensu/sensu-go/backend/queue"
"github.com/sensu/sensu-go/backend/ringv2"
"github.com/sensu/sensu-go/backend/schedulerd"
"github.com/sensu/sensu-go/backend/seeds"
"github.com/sensu/sensu-go/backend/store"
etcdstore "github.com/sensu/sensu-go/backend/store/etcd"
"github.com/sensu/sensu-go/backend/tessend"
"github.com/sensu/sensu-go/rpc"
"github.com/sensu/sensu-go/system"
"github.com/sensu/sensu-go/types"
)
// Backend represents the backend server, which is used to hold the datastore
// and coordinating the daemons
type Backend struct {
Client *clientv3.Client
Daemons []daemon.Daemon
Etcd *etcd.Etcd
Store store.Store
EventStore EventStoreUpdater
done chan struct{}
ctx context.Context
cancel context.CancelFunc
}
// EventStoreUpdater offers a way to update an event store to a different
// implementation in-place.
type EventStoreUpdater interface {
UpdateEventStore(to store.EventStore)
}
func newClient(config *Config, backend *Backend) (*clientv3.Client, error) {
if config.NoEmbedEtcd {
tlsInfo := (transport.TLSInfo)(config.EtcdClientTLSInfo)
tlsConfig, err := tlsInfo.ClientConfig()
if err != nil {
return nil, err
}
// Don't start up an embedded etcd, return a client that connects to an
// external etcd instead.
return clientv3.New(clientv3.Config{
Endpoints: config.EtcdAdvertiseClientURLs,
DialTimeout: 5 * time.Second,
TLS: tlsConfig,
})
}
// Initialize and start etcd, because we'll need to provide an etcd client to
// the Wizard bus, which requires etcd to be started.
cfg := etcd.NewConfig()
cfg.DataDir = config.StateDir
cfg.ListenClientURLs = config.EtcdListenClientURLs
cfg.ListenPeerURLs = config.EtcdListenPeerURLs
cfg.InitialCluster = config.EtcdInitialCluster
cfg.InitialClusterState = config.EtcdInitialClusterState
cfg.InitialAdvertisePeerURLs = config.EtcdInitialAdvertisePeerURLs
cfg.AdvertiseClientURLs = config.EtcdAdvertiseClientURLs
cfg.Name = config.EtcdName
// Etcd TLS config
cfg.ClientTLSInfo = config.EtcdClientTLSInfo
cfg.PeerTLSInfo = config.EtcdPeerTLSInfo
cfg.CipherSuites = config.EtcdCipherSuites
if config.EtcdQuotaBackendBytes != 0 {
cfg.QuotaBackendBytes = config.EtcdQuotaBackendBytes
}
if config.EtcdMaxRequestBytes != 0 {
cfg.MaxRequestBytes = config.EtcdMaxRequestBytes
}
// Start etcd
e, err := etcd.NewEtcd(cfg)
if err != nil {
return nil, fmt.Errorf("error starting etcd: %s", err)
}
backend.Etcd = e
// Create an etcd client
return e.NewClient()
}
// Initialize instantiates a Backend struct with the provided config, by
// configuring etcd and establishing a list of daemons, which constitute our
// backend. The daemons will later be started according to their position in the
// b.Daemons list, and stopped in reverse order
func Initialize(config *Config) (*Backend, error) {
var err error
// Initialize a Backend struct
b := &Backend{}
b.done = make(chan struct{})
b.ctx, b.cancel = context.WithCancel(context.Background())
b.Client, err = newClient(config, b)
if err != nil {
return nil, err
}
// Initialize the store, which lives on top of etcd
logger.Debug("Initializing store...")
stor := etcdstore.NewStore(b.Client, config.EtcdName)
if err = seeds.SeedInitialData(stor); err != nil {
return nil, fmt.Errorf("error initializing the store: %s", err)
}
logger.Debug("Done initializing store")
b.Store = stor
_, err = stor.GetClusterID(b.ctx)
if err != nil {
switch err := err.(type) {
case *store.ErrNotFound:
if storeErr := stor.CreateClusterID(b.ctx, uuid.New().String()); storeErr != nil {
return nil, fmt.Errorf("error assigning a sensu cluster id: %s", err)
}
default:
return nil, fmt.Errorf("error retrieving sensu cluster id: %s", err)
}
}
eventStoreProxy := store.NewEventStoreProxy(stor)
b.EventStore = eventStoreProxy
logger.Debug("Registering backend...")
backendID := etcd.NewBackendIDGetter(b.ctx, b.Client)
logger.Debug("Done registering backend.")
// Initialize an etcd getter
queueGetter := queue.EtcdGetter{Client: b.Client, BackendIDGetter: backendID}
// Initialize the bus
bus, err := messaging.NewWizardBus(messaging.WizardBusConfig{})
if err != nil {
return nil, fmt.Errorf("error initializing %s: %s", bus.Name(), err)
}
b.Daemons = append(b.Daemons, bus)
// Initialize asset manager
backendEntity := b.getBackendEntity(config)
logger.WithField("entity", backendEntity).Info("backend entity information")
assetManager := asset.NewManager(config.CacheDir, backendEntity, &sync.WaitGroup{})
assetGetter, err := assetManager.StartAssetManager(b.ctx)
if err != nil {
return nil, fmt.Errorf("error initializing asset manager: %s", err)
}
// Initialize pipelined
pipeline, err := pipelined.New(pipelined.Config{
Store: stor,
Bus: bus,
ExtensionExecutorGetter: rpc.NewGRPCExtensionExecutor,
AssetGetter: assetGetter,
})
if err != nil {
return nil, fmt.Errorf("error initializing %s: %s", pipeline.Name(), err)
}
b.Daemons = append(b.Daemons, pipeline)
// Initialize eventd
event, err := eventd.New(eventd.Config{
Store: stor,
EventStore: eventStoreProxy,
Bus: bus,
LivenessFactory: liveness.EtcdFactory(b.ctx, b.Client),
})
if err != nil {
return nil, fmt.Errorf("error initializing %s: %s", event.Name(), err)
}
b.Daemons = append(b.Daemons, event)
ringPool := ringv2.NewPool(b.Client)
// Initialize schedulerd
scheduler, err := schedulerd.New(schedulerd.Config{
Store: stor,
Bus: bus,
QueueGetter: queueGetter,
RingPool: ringPool,
})
if err != nil {
return nil, fmt.Errorf("error initializing %s: %s", scheduler.Name(), err)
}
b.Daemons = append(b.Daemons, scheduler)
// Initialize agentd
agent, err := agentd.New(agentd.Config{
Host: config.AgentHost,
Port: config.AgentPort,
Bus: bus,
Store: stor,
TLS: config.TLS,
RingPool: ringPool,
})
if err != nil {
return nil, fmt.Errorf("error initializing %s: %s", agent.Name(), err)
}
b.Daemons = append(b.Daemons, agent)
// Initialize keepalived
keepalive, err := keepalived.New(keepalived.Config{
DeregistrationHandler: config.DeregistrationHandler,
Bus: bus,
Store: stor,
EventStore: stor,
LivenessFactory: liveness.EtcdFactory(b.ctx, b.Client),
RingPool: ringPool,
})
if err != nil {
return nil, fmt.Errorf("error initializing %s: %s", keepalive.Name(), err)
}
b.Daemons = append(b.Daemons, keepalive)
// Prepare the etcd client TLS config
etcdClientTLSInfo := (transport.TLSInfo)(config.EtcdClientTLSInfo)
etcdClientTLSConfig, err := etcdClientTLSInfo.ClientConfig()
if err != nil {
return nil, err
}
// Prepare the authentication providers
authenticator := &authentication.Authenticator{}
basic := &basic.Provider{
ObjectMeta: corev2.ObjectMeta{Name: basic.Type},
Store: stor,
}
authenticator.AddProvider(basic)
var clusterVersion string
// only retrieve the cluster version if etcd is embedded
if !config.NoEmbedEtcd {
clusterVersion = b.Etcd.GetClusterVersion()
}
// Initialize apid
api, err := apid.New(apid.Config{
ListenAddress: config.APIListenAddress,
URL: config.APIURL,
Bus: bus,
Store: stor,
EventStore: eventStoreProxy,
QueueGetter: queueGetter,
TLS: config.TLS,
Cluster: clientv3.NewCluster(b.Client),
EtcdClientTLSConfig: etcdClientTLSConfig,
Authenticator: authenticator,
ClusterVersion: clusterVersion,
})
if err != nil {
return nil, fmt.Errorf("error initializing %s: %s", api.Name(), err)
}
b.Daemons = append(b.Daemons, api)
// Initialize tessend
tessen, err := tessend.New(tessend.Config{
Store: stor,
RingPool: ringPool,
Client: b.Client,
Bus: bus,
})
if err != nil {
return nil, fmt.Errorf("error initializing %s: %s", tessen.Name(), err)
}
b.Daemons = append(b.Daemons, tessen)
// Initialize dashboardd TLS config
var dashboardTLSConfig *types.TLSOptions
// Always use dashboard tls options when they are specified
if config.DashboardTLSCertFile != "" && config.DashboardTLSKeyFile != "" {
dashboardTLSConfig = &types.TLSOptions{
CertFile: config.DashboardTLSCertFile,
KeyFile: config.DashboardTLSKeyFile,
}
} else if config.TLS != nil {
// use apid tls config if no dashboard tls options are specified
dashboardTLSConfig = &types.TLSOptions{
CertFile: config.TLS.GetCertFile(),
KeyFile: config.TLS.GetKeyFile(),
}
}
dashboard, err := dashboardd.New(dashboardd.Config{
APIURL: config.APIURL,
Host: config.DashboardHost,
Port: config.DashboardPort,
TLS: dashboardTLSConfig,
})
if err != nil {
return nil, fmt.Errorf("error initializing %s: %s", dashboard.Name(), err)
}
b.Daemons = append(b.Daemons, dashboard)
return b, nil
}
// Run starts all of the Backend server's daemons
func (b *Backend) Run() error {
eg := errGroup{
out: make(chan error),
}
sg := stopGroup{}
// Loop across the daemons in order to start them, then add them to our groups
for _, d := range b.Daemons {
if err := d.Start(); err != nil {
return fmt.Errorf("error starting %s: %s", d.Name(), err)
}
// Add the daemon to our errGroup
eg.errors = append(eg.errors, d)
// Add the daemon to our stopGroup
sg = append(sg, daemonStopper{
Name: d.Name(),
stopper: d,
})
}
// Reverse the order of our stopGroup so daemons are stopped in the proper
// order (last one started is first one stopped)
for i := len(sg)/2 - 1; i >= 0; i-- {
opp := len(sg) - 1 - i
sg[i], sg[opp] = sg[opp], sg[i]
}
if b.Etcd != nil {
// Add etcd to our errGroup, since it's not included in the daemon list
eg.errors = append(eg.errors, b.Etcd)
}
eg.Go()
select {
case err := <-eg.Err():
logger.WithError(err).Error("error in error group")
case <-b.ctx.Done():
logger.Info("backend shutting down")
}
var derr error
if err := sg.Stop(); err != nil {
if derr == nil {
derr = err
}
}
if b.Etcd != nil {
logger.Info("shutting down etcd")
defer func() {
if err := recover(); err != nil {
trace := string(debug.Stack())
logger.WithField("panic", trace).WithError(err.(error)).
Error("recovering from panic due to error, shutting down etcd")
}
err := b.Etcd.Shutdown()
if derr == nil {
derr = err
}
}()
}
// we allow inErrChan to leak to avoid panics from other
// goroutines writing errors to either after shutdown has been initiated.
close(b.done)
return derr
}
type stopper interface {
Stop() error
}
type daemonStopper struct {
stopper
Name string
}
type stopGroup []daemonStopper
func (s stopGroup) Stop() (err error) {
for _, stopper := range s {
logger.Info("shutting down ", stopper.Name)
e := stopper.Stop()
if err == nil {
err = e
}
}
return err
}
type errorer interface {
Err() <-chan error
}
type errGroup struct {
out chan error
errors []errorer
}
func (e errGroup) Go() {
for _, err := range e.errors {
err := err
go func() {
e.out <- <-err.Err()
}()
}
}
func (e errGroup) Err() <-chan error {
return e.out
}
// Stop the Backend cleanly.
func (b *Backend) Stop() {
b.cancel()
<-b.done
}
func (b *Backend) getBackendEntity(config *Config) *corev2.Entity {
entity := &corev2.Entity{
EntityClass: corev2.EntityBackendClass,
System: getSystemInfo(),
ObjectMeta: corev2.NewObjectMeta(getDefaultBackendID(), ""),
}
if config.DeregistrationHandler != "" {
entity.Deregistration = corev2.Deregistration{
Handler: config.DeregistrationHandler,
}
}
return entity
}
// getDefaultBackendID returns the default backend ID
func getDefaultBackendID() string {
defaultBackendID, err := os.Hostname()
if err != nil {
logger.WithError(err).Error("error getting hostname")
defaultBackendID = "unidentified-sensu-backend"
}
return defaultBackendID
}
// getSystemInfo returns the system info of the backend
func getSystemInfo() corev2.System {
info, err := system.Info()
if err != nil {
logger.WithError(err).Error("error getting system info")
}
return info
}