-
Notifications
You must be signed in to change notification settings - Fork 35
/
ha_cluster_exporter.go
362 lines (319 loc) · 11.5 KB
/
ha_cluster_exporter.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
package main
import (
"fmt"
"net/http"
"os"
"strings"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/promlog"
// cannot use as setConfigDefault function will not work here
// log.level and log.format flags are set in vars/init
// "github.com/prometheus/common/promlog/flag"
"github.com/prometheus/common/version"
"github.com/prometheus/exporter-toolkit/web"
"github.com/spf13/viper"
// we could use this but want to define our own defaults
// webflag "github.com/prometheus/exporter-toolkit/web/kingpinflag"
"github.com/alecthomas/kingpin/v2"
"github.com/ClusterLabs/ha_cluster_exporter/collector"
"github.com/ClusterLabs/ha_cluster_exporter/collector/corosync"
"github.com/ClusterLabs/ha_cluster_exporter/collector/drbd"
"github.com/ClusterLabs/ha_cluster_exporter/collector/pacemaker"
"github.com/ClusterLabs/ha_cluster_exporter/collector/sbd"
)
const (
namespace = "ha_cluster_exporter"
)
var (
config *viper.Viper
// general flags
webListenAddress *string
webTelemetryPath *string
webConfig *string
logLevel *string
logFormat *string
// collector flags
haClusterCrmMonPath *string
haClusterCibadminPath *string
haClusterCorosyncCfgtoolpathPath *string
haClusterCorosyncQuorumtoolPath *string
haClusterSbdPath *string
haClusterSbdConfigPath *string
haClusterDrbdsetupPath *string
haClusterDrbdsplitbrainPath *string
// deprecated flags
enableTimestampsDeprecated *bool
portDeprecated *int
addressDeprecated *string
logLevelDeprecated *string
promlogConfig = &promlog.Config{
Level: &promlog.AllowedLevel{},
Format: &promlog.AllowedFormat{},
}
)
func init() {
config = viper.New()
config.SetConfigName("ha_cluster_exporter")
config.AddConfigPath("./")
config.AddConfigPath("$HOME/.config/")
config.AddConfigPath("/etc/")
config.AddConfigPath("/usr/etc/")
config.ReadInConfig()
// general flags
webListenAddress = kingpin.Flag(
"web.listen-address",
"Address to listen on for web interface and telemetry.",
).PlaceHolder(":9664").Default(setConfigDefault("web.listen-address", ":9664")).String()
webTelemetryPath = kingpin.Flag(
"web.telemetry-path",
"Path under which to expose metrics.",
).PlaceHolder("/metrics").Default(setConfigDefault("web.telemetry-path", "/metrics")).String()
// we could use this but want to define our own defaults
// webConfig = webflag.AddFlags(kingpin.CommandLine)
webConfig = kingpin.Flag(
"web.config.file",
"[EXPERIMENTAL] Path to configuration file that can enable TLS or authentication.",
).PlaceHolder("/etc/" + namespace + ".web.yaml").Default(setConfigDefault("web.config.file", "/etc/"+namespace+".web.yaml")).String()
// collector flags
haClusterCrmMonPath = kingpin.Flag(
"crm-mon-path",
"path to crm_mon executable",
).PlaceHolder("/usr/sbin/crm_mon").Default(setConfigDefault("crm-mon-path", "/usr/sbin/crm_mon")).String()
haClusterCibadminPath = kingpin.Flag(
"cibadmin-path",
"path to cibadmin executable",
).PlaceHolder("/usr/sbin/cibadmin").Default(setConfigDefault("cibadmin-path", "/usr/sbin/cibadmin")).String()
haClusterCorosyncCfgtoolpathPath = kingpin.Flag(
"corosync-cfgtoolpath-path",
"path to corosync-cfgtool executable",
).PlaceHolder("/usr/sbin/corosync-cfgtool").Default(setConfigDefault("corosync-cfgtoolpath-path", "/usr/sbin/corosync-cfgtool")).String()
haClusterCorosyncQuorumtoolPath = kingpin.Flag(
"corosync-quorumtool-path",
"path to corosync-quorumtool executable",
).PlaceHolder("/usr/sbin/corosync-quorumtool").Default(setConfigDefault("corosync-quorumtool-path", "/usr/sbin/corosync-quorumtool")).String()
haClusterSbdPath = kingpin.Flag(
"sbd-path",
"path to sbd executable",
).PlaceHolder("/usr/sbin/sbd").Default(setConfigDefault("sbd-path", "/usr/sbin/sbd")).String()
haClusterSbdConfigPath = kingpin.Flag(
"sbd-config-path",
"path to sbd configuration",
).PlaceHolder("/etc/sysconfig/sbd").Default(setConfigDefault("sbd-config-path", "/etc/sysconfig/sbd")).String()
haClusterDrbdsetupPath = kingpin.Flag(
"drbdsetup-path",
"path to drbdsetup executable",
).PlaceHolder("/sbin/drbdsetup").Default(setConfigDefault("drbdsetup-path", "/sbin/drbdsetup")).String()
haClusterDrbdsplitbrainPath = kingpin.Flag(
"drbdsplitbrain-path",
"path to drbd splitbrain hooks temporary files",
).PlaceHolder("/var/run/drbd/splitbrain").Default(setConfigDefault("drbdsplitbrain-path", "/var/run/drbd/splitbrain")).String()
enableTimestampsDeprecated = kingpin.Flag(
"enable-timestamps",
"[DEPRECATED] server-side metric timestamping is discouraged by Prometheus best-practices and should be avoided",
).PlaceHolder("false").Default(setConfigDefault("enable-timestamps", "false")).Bool()
addressDeprecated = kingpin.Flag(
"address",
"[DEPRECATED] please use --web.listen-address or --web.config.file to use Prometheus Exporter Toolkit",
).PlaceHolder("0.0.0.0").Default(setConfigDefault("address", "0.0.0.0")).String()
portDeprecated = kingpin.Flag(
"port",
"[DEPRECATED] please use --web.listen-address or --web.config.file to use Prometheus Exporter Toolkit",
).PlaceHolder("9664").Default(setConfigDefault("port", "9664")).Int()
logLevelDeprecated = kingpin.Flag(
"log-level",
"[DEPRECATED] please user log.level",
).PlaceHolder("info").Default(setConfigDefault("log-level", "info")).String()
// cannot use as setConfigDefault function will not work here
// log.level and log.format flags are set in vars/init
// flag.AddFlags(kingpin.CommandLine, promlogConfig)
logLevel = kingpin.Flag(
"log.level",
"Only log messages with the given severity or above. One of: [debug, info, warn, error]",
).PlaceHolder("info").Default(setConfigDefault("log.level", "info")).String()
logFormat = kingpin.Flag(
"log.format",
"Output format of log messages. One of: [logfmt, json]",
).PlaceHolder("logfmt").Default(setConfigDefault("log.format", "logfmt")).String()
// detect unit testing and skip kingpin.Parse() in init.
// see: https://github.com/alecthomas/kingpin/issues/187
testing := (strings.HasSuffix(os.Args[0], ".test") ||
strings.HasSuffix(os.Args[0], "__debug_bin"))
if testing {
return
}
kingpin.Version(version.Print(namespace))
kingpin.HelpFlag.Short('h')
var err error
kingpin.Parse()
// use deprecated log-level parameter if set
if *logLevelDeprecated != "info" {
*logLevel = *logLevelDeprecated
}
err = promlogConfig.Level.Set(*logLevel)
if err != nil {
fmt.Printf("%s: error: %s, try --help\n", namespace, err)
os.Exit(1)
}
err = promlogConfig.Format.Set(*logFormat)
if err != nil {
fmt.Printf("%s: error: %s, try --help\n", namespace, err)
os.Exit(1)
}
}
// looks up if a configName is define in viper config
// if it is not defined in the viper config, set the passed configDefault
func setConfigDefault(configName string, configDefault string) string {
var result string
if config.IsSet(configName) {
result = config.GetString(configName)
} else {
result = configDefault
}
return result
}
func registerCollectors(logger log.Logger) (collectors []prometheus.Collector, errors []error) {
pacemakerCollector, err := pacemaker.NewCollector(
*haClusterCrmMonPath,
*haClusterCibadminPath,
*enableTimestampsDeprecated,
logger,
)
if err != nil {
errors = append(errors, err)
} else {
collectors = append(collectors, pacemakerCollector)
}
corosyncCollector, err := corosync.NewCollector(
*haClusterCorosyncCfgtoolpathPath,
*haClusterCorosyncQuorumtoolPath,
*enableTimestampsDeprecated,
logger,
)
if err != nil {
errors = append(errors, err)
} else {
collectors = append(collectors, corosyncCollector)
}
sbdCollector, err := sbd.NewCollector(
*haClusterSbdPath,
*haClusterSbdConfigPath,
*enableTimestampsDeprecated,
logger,
)
if err != nil {
errors = append(errors, err)
} else {
collectors = append(collectors, sbdCollector)
}
drbdCollector, err := drbd.NewCollector(
*haClusterDrbdsetupPath,
*haClusterDrbdsplitbrainPath,
*enableTimestampsDeprecated,
logger,
)
if err != nil {
errors = append(errors, err)
} else {
collectors = append(collectors, drbdCollector)
}
for i, c := range collectors {
if c, ok := c.(collector.InstrumentableCollector); ok == true {
collectors[i] = collector.NewInstrumentedCollector(c, logger)
}
}
prometheus.MustRegister(collectors...)
return collectors, errors
}
func main() {
var err error
logger := promlog.New(promlogConfig)
level.Info(logger).Log("msg", fmt.Sprintf("Starting %s %s", namespace, version.Info()))
level.Info(logger).Log("msg", fmt.Sprintf("Build context %s", version.BuildContext()))
// re-read only to display Info/Warn
err = config.ReadInConfig()
if err != nil {
level.Warn(logger).Log("msg", "Reading config file failed", "err", err)
level.Info(logger).Log("msg", "Default config values will be used")
} else {
level.Info(logger).Log("msg", "Using config file: "+config.ConfigFileUsed())
}
// register collectors
collectors, errors := registerCollectors(logger)
for _, err = range errors {
level.Warn(logger).Log("msg", "Registration failure", "err", err)
}
if len(collectors) == 0 {
level.Error(logger).Log("msg", "No collector could be registered.", "err", err)
os.Exit(1)
}
for _, c := range collectors {
if c, ok := c.(collector.SubsystemCollector); ok == true {
level.Info(logger).Log("msg", c.GetSubsystem()+" collector registered.")
}
}
// if we're not in debug log level, we unregister the Go runtime metrics collector that gets registered by default
if *logLevel != "debug" {
prometheus.Unregister(prometheus.NewGoCollector())
}
var fullListenAddress string
// use deprecated parameters
if *addressDeprecated != "0.0.0.0" || *portDeprecated != 9664 {
fullListenAddress = fmt.Sprintf("%s:%d", *addressDeprecated, *portDeprecated)
// use new parameters
} else {
fullListenAddress = *webListenAddress
}
serveAddress := &http.Server{Addr: fullListenAddress}
servePath := *webTelemetryPath
var landingPage = []byte(`<html>
<head>
<title>ClusterLabs Linux HA Cluster Exporter</title>
</head>
<body>
<h1>ClusterLabs Linux HA Cluster Exporter</h1>
<h2>Prometheus exporter for Pacemaker based Linux HA clusters</h2>
<ul>
<li><a href="` + servePath + `">Metrics</a></li>
<li><a href="https://github.com/ClusterLabs/ha_cluster_exporter" target="_blank">GitHub</a></li>
</ul>
</body>
</html>
`)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write(landingPage)
})
http.Handle(servePath, promhttp.Handler())
level.Info(logger).Log("msg", "Serving metrics on "+fullListenAddress+servePath)
toolkitFlags := &web.FlagConfig{
WebListenAddresses: func() *[]string {
r := []string{*webListenAddress}
return &r
}(),
WebSystemdSocket: func() *bool {
r := false
return &r
}(),
WebConfigFile: func() *string {
r := ""
return &r
}(),
}
var listen error
_, err = os.Stat(*webConfig)
if err != nil {
level.Warn(logger).Log("msg", "Reading web config file failed", "err", err)
level.Info(logger).Log("msg", "Default web config or commandline values will be used")
listen = web.ListenAndServe(serveAddress, toolkitFlags, logger)
} else {
level.Info(logger).Log("msg", "Using web config file: "+*webConfig)
toolkitFlags.WebConfigFile = webConfig
listen = web.ListenAndServe(serveAddress, toolkitFlags, logger)
}
if err := listen; err != nil {
level.Error(logger).Log("msg", "Error starting HTTP server", "err", err)
os.Exit(1)
}
}