File: command.go

package info (click to toggle)
icingadb 1.5.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 59,960 kB
  • sloc: ansic: 170,157; asm: 7,097; sql: 4,098; sh: 1,614; cpp: 1,132; makefile: 438; xml: 160
file content (73 lines) | stat: -rw-r--r-- 2,063 bytes parent folder | download | duplicates (2)
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
package command

import (
	"github.com/icinga/icinga-go-library/config"
	"github.com/icinga/icinga-go-library/database"
	"github.com/icinga/icinga-go-library/logging"
	"github.com/icinga/icinga-go-library/redis"
	"github.com/icinga/icinga-go-library/utils"
	"github.com/icinga/icingadb/internal"
	icingadbconfig "github.com/icinga/icingadb/internal/config"
	"github.com/icinga/icingadb/pkg/icingaredis/telemetry"
	"github.com/pkg/errors"
	"os"
	"time"
)

// Command provides factories for creating Redis and Database connections from Config.
type Command struct {
	Flags  icingadbconfig.Flags
	Config icingadbconfig.Config
}

// New parses CLI flags and the YAML configuration and returns a new Command.
// New prints any error during parsing to [os.Stderr] and exits.
func New() *Command {
	var flags icingadbconfig.Flags
	if err := config.ParseFlags(&flags); err != nil {
		if errors.Is(err, config.ErrInvalidArgument) {
			panic(err)
		}

		utils.PrintErrorThenExit(err, 2)
	}

	if flags.Version {
		internal.Version.Print("Icinga DB")
		os.Exit(0)
	}

	var cfg icingadbconfig.Config
	if err := config.Load(&cfg, config.LoadOptions{
		Flags:      flags,
		EnvOptions: config.EnvOptions{Prefix: "ICINGADB_"},
	}); err != nil {
		if errors.Is(err, config.ErrInvalidArgument) {
			panic(err)
		}

		utils.PrintErrorThenExit(err, 1)
	}

	return &Command{
		Flags:  flags,
		Config: cfg,
	}
}

// Database creates and returns a new icingadb.DB connection from config.Config.
func (c Command) Database(l *logging.Logger) (*database.DB, error) {
	return database.NewDbFromConfig(&c.Config.Database, l, database.RetryConnectorCallbacks{
		OnRetryableError: func(_ time.Duration, _ uint64, err, _ error) {
			telemetry.UpdateCurrentDbConnErr(err)
		},
		OnSuccess: func(_ time.Duration, _ uint64, _ error) {
			telemetry.UpdateCurrentDbConnErr(nil)
		},
	})
}

// Redis creates and returns a new icingaredis.Client connection from config.Config.
func (c Command) Redis(l *logging.Logger) (*redis.Client, error) {
	return redis.NewClientFromConfig(&c.Config.Redis, l)
}