summaryrefslogtreecommitdiffstats
path: root/cmd/icingadb/main.go
blob: 29b7c4440ff2ce6119b6cf4a1f149db3740bc6c4 (plain)
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
package main

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"github.com/icinga/icingadb/internal/command"
	"github.com/icinga/icingadb/pkg/common"
	"github.com/icinga/icingadb/pkg/icingadb"
	"github.com/icinga/icingadb/pkg/icingadb/history"
	"github.com/icinga/icingadb/pkg/icingadb/overdue"
	v1 "github.com/icinga/icingadb/pkg/icingadb/v1"
	"github.com/icinga/icingadb/pkg/icingaredis"
	"github.com/icinga/icingadb/pkg/icingaredis/telemetry"
	"github.com/icinga/icingadb/pkg/logging"
	"github.com/icinga/icingadb/pkg/utils"
	"github.com/okzk/sdnotify"
	"github.com/pkg/errors"
	"go.uber.org/zap"
	"golang.org/x/sync/errgroup"
	"net"
	"os"
	"os/signal"
	"sync"
	"sync/atomic"
	"syscall"
	"time"
)

const (
	ExitSuccess                = 0
	ExitFailure                = 1
	expectedRedisSchemaVersion = "5"
)

func main() {
	os.Exit(run())
}

func run() int {
	cmd := command.New()
	logs, err := logging.NewLogging(
		utils.AppName(),
		cmd.Config.Logging.Level,
		cmd.Config.Logging.Output,
		cmd.Config.Logging.Options,
		cmd.Config.Logging.Interval,
	)
	if err != nil {
		utils.Fatal(errors.Wrap(err, "can't configure logging"))
	}
	// When started by systemd, NOTIFY_SOCKET is set by systemd for Type=notify supervised services, which is the
	// default setting for the Icinga DB service. So we notify that Icinga DB finished starting up.
	_ = sdnotify.Ready()

	logger := logs.GetLogger()
	defer logger.Sync()

	logger.Info("Starting Icinga DB")

	db, err := cmd.Database(logs.GetChildLogger("database"))
	if err != nil {
		logger.Fatalf("%+v", errors.Wrap(err, "can't create database connection pool from config"))
	}
	defer db.Close()
	{
		logger.Infof("Connecting to database at '%s'", net.JoinHostPort(cmd.Config.Database.Host, fmt.Sprint(cmd.Config.Database.Port)))
		err := db.Ping()
		if err != nil {
			logger.Fatalf("%+v", errors.Wrap(err, "can't connect to database"))
		}
	}

	if err := db.CheckSchema(context.Background()); err != nil {
		logger.Fatalf("%+v", err)
	}

	rc, err := cmd.Redis(logs.GetChildLogger("redis"))
	if err != nil {
		logger.Fatalf("%+v", errors.Wrap(err, "can't create Redis client from config"))
	}
	{
		logger.Infof("Connecting to Redis at '%s'", net.JoinHostPort(cmd.Config.Redis.Host, fmt.Sprint(cmd.Config.Redis.Port)))
		_, err := rc.Ping(context.Background()).Result()
		if err != nil {
			logger.Fatalf("%+v", errors.Wrap(err, "can't connect to Redis"))
		}
	}

	{
		pos, err := checkRedisSchema(logger, rc, "0-0")
		if err != nil {
			logger.Fatalf("%+v", err)
		}

		go monitorRedisSchema(logger, rc, pos)
	}

	ctx, cancelCtx := context.WithCancel(context.Background())
	defer cancelCtx()

	// Use dedicated connections for heartbeat and HA to ensure that heartbeats are always processed and
	// the instance table is updated. Otherwise, the connections can be too busy due to the synchronization of
	// configuration, status, history, etc., which can lead to handover / takeover loops because
	// the heartbeat is not read while HA gets stuck when updating the instance table.
	var heartbeat *icingaredis.Heartbeat
	var ha *icingadb.HA
	{
		rc, err := cmd.Redis(logs.GetChildLogger("redis"))
		if err != nil {
			logger.Fatalf("%+v", errors.Wrap(err, "can't create Redis client from config"))
		}
		heartbeat = icingaredis.NewHeartbeat(ctx, rc, logs.GetChildLogger("heartbeat"))

		db, err := cmd.Database(logs.GetChildLogger("database"))
		if err != nil {
			logger.Fatalf("%+v", errors.Wrap(err, "can't create database connection pool from config"))
		}
		defer db.Close()
		ha = icingadb.NewHA(ctx, db, heartbeat, logs.GetChildLogger("high-availability"))

		telemetryLogger := logs.GetChildLogger("telemetry")
		telemetry.StartHeartbeat(ctx, rc, telemetryLogger, ha, heartbeat)
		telemetry.WriteStats(ctx, rc, telemetryLogger)
	}
	// Closing ha on exit ensures that this instance retracts its heartbeat
	// from the database so that another instance can take over immediately.
	defer func() {
		// Give up after 3s, not 5m (default) not to hang for 5m if DB is down.
		ctx, cancelCtx := context.WithTimeout(context.Background(), 3*time.Second)

		ha.Close(ctx)
		cancelCtx()
	}()
	s := icingadb.NewSync(db, rc, logs.GetChildLogger("config-sync"))
	hs := history.NewSync(db, rc, logs.GetChildLogger("history-sync"))
	rt := icingadb.NewRuntimeUpdates(db, rc, logs.GetChildLogger("runtime-updates"))
	ods := overdue.NewSync(db, rc, logs.GetChildLogger("overdue-sync"))
	ret := history.NewRetention(
		db,
		cmd.Config.Retention.HistoryDays,
		cmd.Config.Retention.SlaDays,
		cmd.Config.Retention.Interval,
		cmd.Config.Retention.Count,
		cmd.Config.Retention.Options,
		logs.GetChildLogger("retention"),
	)

	sig := make(chan os.Signal, 1)
	signal.Notify(sig, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)

	go func() {
		logger.Info("Starting history sync")

		if err := hs.Sync(ctx); err != nil && !utils.IsContextCanceled(err) {
			logger.Fatalf("%+v", err)
		}
	}()

	// Main loop
	for {
		hactx, cancelHactx := context.WithCancel(ctx)
		for hactx.Err() == nil {
			select {
			case <-ha.Takeover():
				logger.Info("Taking over")

				go func() {
					for hactx.Err() == nil {
						synctx, cancelSynctx := context.WithCancel(ha.Environment().NewContext(hactx))
						g, synctx := errgroup.WithContext(synctx)
						// WaitGroups for initial synchronization.
						// Runtime updates must wait for initial synchronization to complete.
						configInitSync := sync.WaitGroup{}
						stateInitSync := &sync.WaitGroup{}

						// Clear the runtime update streams before starting anything else (rather than after the sync),
						// otherwise updates may be lost.
						runtimeConfigUpdateStreams, runtimeStateUpdateStreams, err := rt.ClearStreams(synctx)
						if err != nil {
							logger.Fatalf("%+v", err)
						}

						dump := icingadb.NewDumpSignals(rc, logs.GetChildLogger("dump-signals"))
						g.Go(func() error {
							logger.Debug("Staring config dump signal handling")

							return dump.Listen(synctx)
						})

						g.Go(func() error {
							select {
							case <-dump.InProgress():
								logger.Info("Icinga 2 started a new config dump, waiting for it to complete")
								cancelSynctx()

								return nil
							case <-synctx.Done():
								return synctx.Err()
							}
						})

						g.Go(func() error {
							logger.Info("Starting overdue sync")

							return ods.Sync(synctx)
						})

						syncStart := time.Now()
						atomic.StoreInt64(&telemetry.OngoingSyncStartMilli, syncStart.UnixMilli())

						logger.Info("Starting config sync")
						for _, factory := range v1.ConfigFactories {
							factory := factory

							configInitSync.Add(1)
							g.Go(func() error {
								defer configInitSync.Done()

								return s.SyncAfterDump(synctx, common.NewSyncSubject(factory), dump)
							})
						}
						logger.Info("Starting initial state sync")
						for _, factory := range v1.StateFactories {
							factory := factory

							stateInitSync.Add(1)
							g.Go(func() error {
								defer stateInitSync.Done()

								return s.SyncAfterDump(synctx, common.NewSyncSubject(factory), dump)
							})
						}

						configInitSync.Add(1)
						g.Go(func() error {
							defer configInitSync.Done()

							select {
							case <-dump.Done("icinga:customvar"):
							case <-synctx.Done():
								return synctx.Err()
							}

							return s.SyncCustomvars(synctx)
						})

						g.Go(func() error {
							configInitSync.Wait()
							atomic.StoreInt64(&telemetry.OngoingSyncStartMilli, 0)

							syncEnd := time.Now()
							elapsed := syncEnd.Sub(syncStart)
							logger := logs.GetChildLogger("config-sync")

							if synctx.Err() == nil {
								telemetry.LastSuccessfulSync.Store(telemetry.SuccessfulSync{
									FinishMilli:   syncEnd.UnixMilli(),
									DurationMilli: elapsed.Milliseconds(),
								})

								logger.Infof("Finished config sync in %s", elapsed)
							} else {
								logger.Warnf("Aborted config sync after %s", elapsed)
							}

							return nil
						})

						g.Go(func() error {
							stateInitSync.Wait()

							elapsed := time.Since(syncStart)
							logger := logs.GetChildLogger("config-sync")
							if synctx.Err() == nil {
								logger.Infof("Finished initial state sync in %s", elapsed)
							} else {
								logger.Warnf("Aborted initial state sync after %s", elapsed)
							}

							return nil
						})

						g.Go(func() error {
							configInitSync.Wait()

							if err := synctx.Err(); err != nil {
								return err
							}

							logger.Info("Starting config runtime updates sync")

							return rt.Sync(synctx, v1.ConfigFactories, runtimeConfigUpdateStreams, false)
						})

						g.Go(func() error {
							stateInitSync.Wait()

							if err := synctx.Err(); err != nil {
								return err
							}

							logger.Info("Starting state runtime updates sync")

							return rt.Sync(synctx, v1.StateFactories, runtimeStateUpdateStreams, true)
						})

						g.Go(func() error {
							// Wait for config and state sync to avoid putting additional pressure on the database.
							configInitSync.Wait()
							stateInitSync.Wait()

							if err := synctx.Err(); err != nil {
								return err
							}

							logger.Info("Starting history retention")

							return ret.Start(synctx)
						})

						if err := g.Wait(); err != nil && !utils.IsContextCanceled(err) {
							logger.Fatalf("%+v", err)
						}
					}
				}()
			case <-ha.Handover():
				logger.Warn("Handing over")

				cancelHactx()
			case <-hactx.Done():
				// Nothing to do here, surrounding loop will terminate now.
			case <-ha.Done():
				if err := ha.Err(); err != nil {
					logger.Fatalf("%+v", errors.Wrap(err, "HA exited with an error"))
				} else if ctx.Err() == nil {
					// ha is created as a single instance once. It should only exit if the main context is cancelled,
					// otherwise there is no way to get Icinga DB back into a working state.
					logger.Fatalf("%+v", errors.New("HA exited without an error but main context isn't cancelled"))
				}
				cancelHactx()

				return ExitFailure
			case <-ctx.Done():
				logger.Fatalf("%+v", errors.New("main context closed unexpectedly"))
			case s := <-sig:
				logger.Infow("Exiting due to signal", zap.String("signal", s.String()))
				cancelHactx()

				return ExitSuccess
			}
		}

		cancelHactx()
	}
}

// monitorRedisSchema monitors rc's icinga:schema version validity.
func monitorRedisSchema(logger *logging.Logger, rc *icingaredis.Client, pos string) {
	for {
		var err error
		pos, err = checkRedisSchema(logger, rc, pos)

		if err != nil {
			logger.Fatalf("%+v", err)
		}
	}
}

// checkRedisSchema verifies rc's icinga:schema version.
func checkRedisSchema(logger *logging.Logger, rc *icingaredis.Client, pos string) (newPos string, err error) {
	if pos == "0-0" {
		defer time.AfterFunc(3*time.Second, func() {
			logger.Info("Waiting for Icinga 2 to write into Redis, please make sure you have started Icinga 2 and the Icinga DB feature is enabled")
		}).Stop()
	} else {
		logger.Debug("Checking Icinga 2 and Icinga DB compatibility")
	}

	streams, err := rc.XReadUntilResult(context.Background(), &redis.XReadArgs{
		Streams: []string{"icinga:schema", pos},
	})
	if err != nil {
		return "", errors.Wrap(err, "can't read Redis schema version")
	}

	message := streams[0].Messages[0]
	if version := message.Values["version"]; version != expectedRedisSchemaVersion {
		// Since these error messages are trivial and mostly caused by users, we don't need
		// to print a stack trace here. However, since errors.Errorf() does this automatically,
		// we need to use fmt instead.
		return "", fmt.Errorf(
			"unexpected Redis schema version: %q (expected %q), please make sure you are running compatible"+
				" versions of Icinga 2 and Icinga DB", version, expectedRedisSchemaVersion,
		)
	}

	logger.Debug("Redis schema version is correct")
	return message.ID, nil
}