summaryrefslogtreecommitdiffstats
path: root/pkg/config/database.go
blob: 0895d26c96a935a5ce5d850443848191ae48577d (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
package config

import (
	"context"
	"database/sql"
	"database/sql/driver"
	"fmt"
	"github.com/go-sql-driver/mysql"
	"github.com/icinga/icingadb/pkg/icingadb"
	"github.com/icinga/icingadb/pkg/logging"
	"github.com/icinga/icingadb/pkg/utils"
	"github.com/jmoiron/sqlx"
	"github.com/jmoiron/sqlx/reflectx"
	"github.com/lib/pq"
	"github.com/pkg/errors"
	"net"
	"net/url"
	"strconv"
	"strings"
	"time"
)

// Database defines database client configuration.
type Database struct {
	Type       string           `yaml:"type" default:"mysql"`
	Host       string           `yaml:"host"`
	Port       int              `yaml:"port"`
	Database   string           `yaml:"database"`
	User       string           `yaml:"user"`
	Password   string           `yaml:"password"`
	TlsOptions TLS              `yaml:",inline"`
	Options    icingadb.Options `yaml:"options"`
}

// Open prepares the DSN string and driver configuration,
// calls sqlx.Open, but returns *icingadb.DB.
func (d *Database) Open(logger *logging.Logger) (*icingadb.DB, error) {
	var db *sqlx.DB
	switch d.Type {
	case "mysql":
		config := mysql.NewConfig()

		config.User = d.User
		config.Passwd = d.Password
		config.Logger = icingadb.MysqlFuncLogger(logger.Debug)

		if d.isUnixAddr() {
			config.Net = "unix"
			config.Addr = d.Host
		} else {
			config.Net = "tcp"
			port := d.Port
			if port == 0 {
				port = 3306
			}
			config.Addr = net.JoinHostPort(d.Host, fmt.Sprint(port))
		}

		config.DBName = d.Database
		config.Timeout = time.Minute
		config.Params = map[string]string{"sql_mode": "'TRADITIONAL,ANSI_QUOTES'"}

		tlsConfig, err := d.TlsOptions.MakeConfig(d.Host)
		if err != nil {
			return nil, err
		}

		if tlsConfig != nil {
			config.TLSConfig = "icingadb"
			if err := mysql.RegisterTLSConfig(config.TLSConfig, tlsConfig); err != nil {
				return nil, errors.Wrap(err, "can't register TLS config")
			}
		}

		c, err := mysql.NewConnector(config)
		if err != nil {
			return nil, errors.Wrap(err, "can't open mysql database")
		}

		wsrepSyncWait := int64(d.Options.WsrepSyncWait)
		setWsrepSyncWait := func(ctx context.Context, conn driver.Conn) error {
			return setGaleraOpts(ctx, conn, wsrepSyncWait)
		}

		db = sqlx.NewDb(sql.OpenDB(icingadb.NewConnector(c, logger, setWsrepSyncWait)), icingadb.MySQL)
	case "pgsql":
		uri := &url.URL{
			Scheme: "postgres",
			User:   url.UserPassword(d.User, d.Password),
			Path:   "/" + url.PathEscape(d.Database),
		}

		query := url.Values{
			"connect_timeout":   {"60"},
			"binary_parameters": {"yes"},

			// Host and port can alternatively be specified in the query string. lib/pq can't parse the connection URI
			// if a Unix domain socket path is specified in the host part of the URI, therefore always use the query
			// string. See also https://github.com/lib/pq/issues/796
			"host": {d.Host},
		}
		if d.Port != 0 {
			query["port"] = []string{strconv.FormatInt(int64(d.Port), 10)}
		}

		if _, err := d.TlsOptions.MakeConfig(d.Host); err != nil {
			return nil, err
		}

		if d.TlsOptions.Enable {
			if d.TlsOptions.Insecure {
				query["sslmode"] = []string{"require"}
			} else {
				query["sslmode"] = []string{"verify-full"}
			}

			if d.TlsOptions.Cert != "" {
				query["sslcert"] = []string{d.TlsOptions.Cert}
			}

			if d.TlsOptions.Key != "" {
				query["sslkey"] = []string{d.TlsOptions.Key}
			}

			if d.TlsOptions.Ca != "" {
				query["sslrootcert"] = []string{d.TlsOptions.Ca}
			}
		} else {
			query["sslmode"] = []string{"disable"}
		}

		uri.RawQuery = query.Encode()

		connector, err := pq.NewConnector(uri.String())
		if err != nil {
			return nil, errors.Wrap(err, "can't open pgsql database")
		}

		db = sqlx.NewDb(sql.OpenDB(icingadb.NewConnector(connector, logger, nil)), icingadb.PostgreSQL)
	default:
		return nil, unknownDbType(d.Type)
	}

	db.SetMaxIdleConns(d.Options.MaxConnections / 3)
	db.SetMaxOpenConns(d.Options.MaxConnections)

	db.Mapper = reflectx.NewMapperFunc("db", func(s string) string {
		return utils.Key(s, '_')
	})

	return icingadb.NewDb(db, logger, &d.Options), nil
}

// Validate checks constraints in the supplied database configuration and returns an error if they are violated.
func (d *Database) Validate() error {
	switch d.Type {
	case "mysql", "pgsql":
	default:
		return unknownDbType(d.Type)
	}

	if d.Host == "" {
		return errors.New("database host missing")
	}

	if d.User == "" {
		return errors.New("database user missing")
	}

	if d.Database == "" {
		return errors.New("database name missing")
	}

	return d.Options.Validate()
}

func (d *Database) isUnixAddr() bool {
	return strings.HasPrefix(d.Host, "/")
}

func unknownDbType(t string) error {
	return errors.Errorf(`unknown database type %q, must be one of: "mysql", "pgsql"`, t)
}

// setGaleraOpts sets the "wsrep_sync_wait" variable for each session ensures that causality checks are performed
// before execution and that each statement is executed on a fully synchronized node. Doing so prevents foreign key
// violation when inserting into dependent tables on different MariaDB/MySQL nodes. When using MySQL single nodes,
// the "SET SESSION" command will fail with "Unknown system variable (1193)" and will therefore be silently dropped.
//
// https://mariadb.com/kb/en/galera-cluster-system-variables/#wsrep_sync_wait
func setGaleraOpts(ctx context.Context, conn driver.Conn, wsrepSyncWait int64) error {
	const galeraOpts = "SET SESSION wsrep_sync_wait=?"

	stmt, err := conn.(driver.ConnPrepareContext).PrepareContext(ctx, galeraOpts)
	if err != nil {
		if errors.Is(err, &mysql.MySQLError{Number: 1193}) { // Unknown system variable
			return nil
		}

		return errors.Wrap(err, "cannot prepare "+galeraOpts)
	}
	// This is just for an unexpected exit and any returned error can safely be ignored and in case
	// of the normal function exit, the stmt is closed manually, and its error is handled gracefully.
	defer func() { _ = stmt.Close() }()

	_, err = stmt.(driver.StmtExecContext).ExecContext(ctx, []driver.NamedValue{{Value: wsrepSyncWait}})
	if err != nil {
		return errors.Wrap(err, "cannot execute "+galeraOpts)
	}

	if err = stmt.Close(); err != nil {
		return errors.Wrap(err, "cannot close prepared statement "+galeraOpts)
	}

	return nil
}