Repository navigation
Expand file tree
/
Copy pathconfig.go
More file actions
303 lines (272 loc) · 8.37 KB
/
Copy pathconfig.go
File metadata and controls
303 lines (272 loc) · 8.37 KB
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
// Copyright 2022 The Prometheus Authors
// 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 config
import (
"crypto/tls"
"crypto/x509"
"fmt"
"log/slog"
"maps"
"net"
"os"
"slices"
"strconv"
"strings"
"sync"
"github.com/go-sql-driver/mysql"
"github.com/prometheus/client_golang/prometheus"
"gopkg.in/ini.v1"
)
var (
configReloadSuccess = prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: "mysqld_exporter",
Name: "config_last_reload_successful",
Help: "Mysqld exporter config loaded successfully.",
})
configReloadSeconds = prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: "mysqld_exporter",
Name: "config_last_reload_success_timestamp_seconds",
Help: "Timestamp of the last successful configuration reload.",
})
opts = ini.LoadOptions{
// Do not error on nonexistent file to allow empty string as filename input
Loose: true,
// MySQL ini file can have boolean keys.
AllowBooleanKeys: true,
// Ignore the # character in the line to avoid password parsing failure when the MySQL password contains the # symbol
IgnoreInlineComment: true,
// Remove the first and last quotation marks
UnescapeValueDoubleQuotes: true,
}
err error
// Use the same pattern of TLS version strings as the mysql client binary.
tlsVersions = map[string]uint16{
"TLSv1.0": tls.VersionTLS10,
"TLSv1.1": tls.VersionTLS11,
"TLSv1.2": tls.VersionTLS12,
"TLSv1.3": tls.VersionTLS13,
}
)
type Config struct {
Sections map[string]MySqlConfig
}
type MySqlConfig struct {
User string `ini:"user"`
Password string `ini:"password"`
Host string `ini:"host"`
Port int `ini:"port"`
Socket string `ini:"socket"`
EnableCleartextPlugin bool `ini:"enable-cleartext-plugin"`
SslCa string `ini:"ssl-ca"`
SslCert string `ini:"ssl-cert"`
SslKey string `ini:"ssl-key"`
TlsInsecureSkipVerify bool `ini:"ssl-skip-verfication"` //nolint:misspell
Tls string `ini:"tls"`
TlsMinVersion string `ini:"tls-min-version"`
TlsMaxVersion string `ini:"tls-max-version"`
TlsServerName string `ini:"tls-server-name"`
}
type MySqlConfigHandler struct {
sync.RWMutex
TlsInsecureSkipVerify bool
Config *Config
}
func (ch *MySqlConfigHandler) GetConfig() *Config {
ch.RLock()
defer ch.RUnlock()
return ch.Config
}
func (ch *MySqlConfigHandler) ReloadConfig(filename string, mysqldAddress string, mysqldUser string, tlsInsecureSkipVerify bool, logger *slog.Logger) error {
var host, port string
defer func() {
if err != nil {
configReloadSuccess.Set(0)
} else {
configReloadSuccess.Set(1)
configReloadSeconds.SetToCurrentTime()
}
}()
cfg, err := ini.LoadSources(
opts,
[]byte("[client]\npassword = ${MYSQLD_EXPORTER_PASSWORD}\n"),
filename,
)
if err != nil {
return fmt.Errorf("failed to load config from %s: %w", filename, err)
}
if clientSection := cfg.Section("client"); clientSection != nil {
// Check if mysqldAddress is a unix socket
if prefix := "unix://"; strings.HasPrefix(mysqldAddress, prefix) {
socketPath := mysqldAddress[len(prefix):]
if cfgSocket := clientSection.Key("socket"); cfgSocket.String() == "" {
cfgSocket.SetValue(socketPath)
}
} else {
// Parse as TCP address (host:port)
if host, port, err = net.SplitHostPort(mysqldAddress); err != nil {
return fmt.Errorf("failed to parse address: %w", err)
}
if cfgHost := clientSection.Key("host"); cfgHost.String() == "" {
cfgHost.SetValue(host)
}
if cfgPort := clientSection.Key("port"); cfgPort.String() == "" {
cfgPort.SetValue(port)
}
}
if cfgUser := clientSection.Key("user"); cfgUser.String() == "" {
cfgUser.SetValue(mysqldUser)
}
}
cfg.ValueMapper = func(val string) string {
return os.Expand(val, func(name string) string {
if name == "$" {
return "$"
}
return os.Getenv(name)
})
}
config := &Config{}
m := make(map[string]MySqlConfig)
for _, sec := range cfg.Sections() {
sectionName := sec.Name()
if sectionName == "DEFAULT" {
continue
}
mysqlcfg := &MySqlConfig{
TlsInsecureSkipVerify: tlsInsecureSkipVerify,
}
err = sec.StrictMapTo(mysqlcfg)
if err != nil {
logger.Error("failed to parse config", "section", sectionName, "err", err)
continue
}
if err := mysqlcfg.validateConfig(); err != nil {
logger.Error("failed to validate config", "section", sectionName, "err", err)
continue
}
m[sectionName] = *mysqlcfg
}
config.Sections = m
if len(config.Sections) == 0 {
return fmt.Errorf("no configuration found")
}
ch.Lock()
ch.Config = config
ch.Unlock()
return nil
}
func (m MySqlConfig) validateConfig() error {
if m.User == "" {
return fmt.Errorf("no user specified in section or parent")
}
allowedTLSVersions := strings.Join(slices.Sorted(maps.Keys(tlsVersions)), ", ")
if _, ok := tlsVersions[m.TlsMinVersion]; !ok && m.TlsMinVersion != "" {
return fmt.Errorf("tls-min-version=%s is not allowed, use one of: %s", m.TlsMinVersion, allowedTLSVersions)
}
if _, ok := tlsVersions[m.TlsMaxVersion]; !ok && m.TlsMaxVersion != "" {
return fmt.Errorf("tls-max-version=%s is not allowed, use one of: %s", m.TlsMaxVersion, allowedTLSVersions)
}
if m.TlsMinVersion != "" && m.TlsMaxVersion != "" {
if tlsVersions[m.TlsMinVersion] > tlsVersions[m.TlsMaxVersion] {
return fmt.Errorf("tls-min-version must not be higher than tls-max-version: %s > %s", m.TlsMinVersion, m.TlsMaxVersion)
}
}
return nil
}
func (m MySqlConfig) FormDSN(target string, configSectionName string) (string, error) {
config := mysql.NewConfig()
config.User = m.User
config.Passwd = m.Password
config.Net = "tcp"
if target == "" {
if m.Socket == "" {
host := "127.0.0.1"
if m.Host != "" {
host = m.Host
}
port := "3306"
if m.Port != 0 {
port = strconv.Itoa(m.Port)
}
config.Addr = net.JoinHostPort(host, port)
} else {
config.Net = "unix"
config.Addr = m.Socket
}
} else if prefix := "unix://"; strings.HasPrefix(target, prefix) {
config.Net = "unix"
config.Addr = target[len(prefix):]
} else {
if _, _, err = net.SplitHostPort(target); err != nil {
return "", fmt.Errorf("failed to parse target: %s", err)
}
config.Addr = target
}
if m.TlsInsecureSkipVerify {
config.TLSConfig = "skip-verify"
} else {
config.TLSConfig = m.Tls
hasCustomTLS := m.SslCa != "" ||
m.TlsMinVersion != "" ||
m.TlsMaxVersion != "" ||
m.TlsServerName != ""
if hasCustomTLS {
if err := m.CustomizeTLS(configSectionName); err != nil {
err = fmt.Errorf("failed to register a custom TLS configuration for mysql dsn: %w", err)
return "", err
}
config.TLSConfig = configSectionName
}
}
if m.EnableCleartextPlugin {
config.AllowCleartextPasswords = true
}
return config.FormatDSN(), nil
}
func (m MySqlConfig) CustomizeTLS(configSectionName string) error {
var tlsCfg tls.Config
if m.SslCa != "" {
caBundle := x509.NewCertPool()
pemCA, err := os.ReadFile(m.SslCa)
if err != nil {
return err
}
if ok := caBundle.AppendCertsFromPEM(pemCA); ok {
tlsCfg.RootCAs = caBundle
} else {
return fmt.Errorf("failed parse pem-encoded CA certificates from %s", m.SslCa)
}
if m.SslCert != "" && m.SslKey != "" {
certPairs := make([]tls.Certificate, 0, 1)
keypair, err := tls.LoadX509KeyPair(m.SslCert, m.SslKey)
if err != nil {
return fmt.Errorf("failed to parse pem-encoded SSL cert %s or SSL key %s: %w",
m.SslCert, m.SslKey, err)
}
certPairs = append(certPairs, keypair)
tlsCfg.Certificates = certPairs
}
}
if m.TlsMinVersion != "" {
tlsCfg.MinVersion = tlsVersions[m.TlsMinVersion]
}
if m.TlsMaxVersion != "" {
tlsCfg.MaxVersion = tlsVersions[m.TlsMaxVersion]
}
if m.TlsServerName != "" {
tlsCfg.ServerName = m.TlsServerName
}
tlsCfg.InsecureSkipVerify = m.TlsInsecureSkipVerify
mysql.RegisterTLSConfig(configSectionName, &tlsCfg)
return nil
}