-
Notifications
You must be signed in to change notification settings - Fork 24
/
main.go
319 lines (273 loc) · 9.84 KB
/
main.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
package main
import (
"crypto/tls"
"crypto/x509"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"gopkg.in/yaml.v2"
)
type config struct {
Probes []probeConfig `yaml:"probes"`
}
type probeConfig struct {
Name string `yaml:"name"`
Broker string `yaml:"broker_url"`
SubscribeTopic string `yaml:"subscribe_topic"`
Topic string `yaml:"topic"`
ClientPrefix string `yaml:"client_prefix"`
Username string `yaml:"username"`
Password string `yaml:"password"`
ClientCert string `yaml:"client_cert"`
ClientKey string `yaml:"client_key"`
CAChain string `yaml:"ca_chain"`
InsecureSkipVerify bool `yaml:"insecure_skip_verify"`
Messages int `yaml:"messages"`
TestInterval time.Duration `yaml:"interval"`
MessagePayload string `yaml:"message_payload"`
}
var build string
var (
messagesPublished = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "probe_mqtt_messages_published_total",
Help: "Number of published messages.",
}, []string{"name", "broker"})
messagesPublishTimeout = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "probe_mqtt_messages_publish_timeout_total",
Help: "Number of published messages.",
}, []string{"name", "broker"})
messagesReceived = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "probe_mqtt_messages_received_total",
Help: "Number of received messages.",
}, []string{"name", "broker"})
timedoutTests = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "probe_mqtt_timeouts_total",
Help: "Number of timed out tests.",
}, []string{"name", "broker"})
probeStarted = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "probe_mqtt_started_total",
Help: "Number of started probes.",
}, []string{"name", "broker"})
probeCompleted = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "probe_mqtt_completed_total",
Help: "Number of completed probes.",
}, []string{"name", "broker"})
errors = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "probe_mqtt_errors_total",
Help: "Number of errors occurred during test execution.",
}, []string{"name", "broker"})
probeDuration = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "probe_mqtt_duration_seconds",
Help: "Time taken to execute probe.",
}, []string{"name", "broker"})
logger = log.New(os.Stderr, "", log.Lmicroseconds|log.Ltime|log.Lshortfile)
configFile = flag.String("config.file", "config.yaml", "Exporter configuration file.")
listenAddress = flag.String("web.listen-address", ":9214", "The address to listen on for HTTP requests.")
enableTrace = flag.Bool("trace.enable", false, "set this flag to enable mqtt tracing")
)
func init() {
prometheus.MustRegister(probeStarted)
prometheus.MustRegister(probeDuration)
prometheus.MustRegister(probeCompleted)
prometheus.MustRegister(messagesPublished)
prometheus.MustRegister(messagesReceived)
prometheus.MustRegister(messagesPublishTimeout)
prometheus.MustRegister(timedoutTests)
prometheus.MustRegister(errors)
}
// newTLSConfig sets up a the go internal tls config from the given probe config.
func newTLSConfig(probeConfig *probeConfig) (*tls.Config, error) {
cfg := &tls.Config{
// RootCAs = certs used to verify server cert.
RootCAs: nil,
// ClientAuth = whether to request cert from server.
// Since the server is set up for SSL, this happens
// anyways.
ClientAuth: tls.NoClientCert,
// InsecureSkipVerify = verify that cert contents
// match server. IP matches what is in cert etc.
// If you set this to true, you basically trust any server
// presenting an SSL cert to you and rendering SSL useless.
InsecureSkipVerify: probeConfig.InsecureSkipVerify,
// Certificates = list of certs client sends to server.
Certificates: nil,
}
// Import trusted certificates from CAChain - purely for verification - not sent to TLS server
if probeConfig.CAChain != "" {
certpool := x509.NewCertPool()
pemCerts, err := ioutil.ReadFile(probeConfig.CAChain)
if err != nil {
return nil, fmt.Errorf("could not read ca_chain pem: %s", err.Error())
}
certpool.AppendCertsFromPEM(pemCerts)
cfg.RootCAs = certpool
}
if probeConfig.ClientCert != "" && probeConfig.ClientKey != "" {
// Import client certificate/key pair
// If you want the chain certs to be sent to the server, concatenate the leaf,
// intermediate and root into the ClientCert file
cert, err := tls.LoadX509KeyPair(probeConfig.ClientCert, probeConfig.ClientKey)
if err != nil {
return nil, fmt.Errorf("could not read client certificate an key: %s", err.Error())
}
cfg.Certificates = []tls.Certificate{cert}
}
if (probeConfig.ClientCert != "" && probeConfig.ClientKey == "") ||
(probeConfig.ClientCert == "" && probeConfig.ClientKey != "") {
return nil, fmt.Errorf("either ClientCert or ClientKey is set to empty string")
}
return cfg, nil
}
func connectClient(probeConfig *probeConfig, timeout time.Duration, opts *mqtt.ClientOptions) (mqtt.Client, error) {
tlsConfig, err := newTLSConfig(probeConfig)
if err != nil {
return nil, fmt.Errorf("could not setup TLS: %s", err.Error())
}
baseOptions := mqtt.NewClientOptions()
if opts != nil {
baseOptions = opts
}
baseOptions = baseOptions.SetAutoReconnect(false).
SetUsername(probeConfig.Username).
SetPassword(probeConfig.Password).
SetTLSConfig(tlsConfig).
AddBroker(probeConfig.Broker)
client := mqtt.NewClient(baseOptions)
token := client.Connect()
success := token.WaitTimeout(timeout)
if !success {
return nil, fmt.Errorf("reached connect timeout")
}
if token.Error() != nil {
return nil, fmt.Errorf("failed to connect client: %s", token.Error().Error())
}
return client, nil
}
func startProbe(probeConfig *probeConfig) {
num := probeConfig.Messages
setupTimeout := probeConfig.TestInterval / 3
probeTimeout := probeConfig.TestInterval / 3
setupDeadLine := time.Now().Add(setupTimeout)
qos := byte(0)
t0 := time.Now()
// Initialize optional metrics with initial values to have them present from the beginning
messagesPublished.WithLabelValues(probeConfig.Name, probeConfig.Broker).Add(0)
messagesReceived.WithLabelValues(probeConfig.Name, probeConfig.Broker).Add(0)
errors.WithLabelValues(probeConfig.Name, probeConfig.Broker).Add(0)
timedoutTests.WithLabelValues(probeConfig.Name, probeConfig.Broker).Add(0)
// Starting to fill metric vectors with meaningful values
probeStarted.WithLabelValues(probeConfig.Name, probeConfig.Broker).Inc()
defer func() {
probeCompleted.WithLabelValues(probeConfig.Name, probeConfig.Broker).Inc()
probeDuration.WithLabelValues(probeConfig.Name, probeConfig.Broker).Observe(time.Since(t0).Seconds())
}()
queue := make(chan [2]string)
reportError := func(error error) {
errors.WithLabelValues(probeConfig.Name, probeConfig.Broker).Inc()
logger.Printf("Probe %s: %s", probeConfig.Name, error.Error())
}
publisherOptions := mqtt.NewClientOptions().SetClientID(fmt.Sprintf("%s-p", probeConfig.ClientPrefix))
subscriberOptions := mqtt.NewClientOptions().SetClientID(fmt.Sprintf("%s-s", probeConfig.ClientPrefix)).
SetDefaultPublishHandler(func(client mqtt.Client, msg mqtt.Message) {
queue <- [2]string{msg.Topic(), string(msg.Payload())}
})
publisher, err := connectClient(probeConfig, time.Until(setupDeadLine), publisherOptions)
if err != nil {
reportError(err)
return
}
defer publisher.Disconnect(5)
subscriber, err := connectClient(probeConfig, time.Until(setupDeadLine), subscriberOptions)
if err != nil {
reportError(err)
return
}
defer subscriber.Disconnect(5)
if probeConfig.SubscribeTopic == "" {
probeConfig.SubscribeTopic = probeConfig.Topic
}
if token := subscriber.Subscribe(probeConfig.SubscribeTopic, qos, nil); token.WaitTimeout(time.Until(setupDeadLine)) && token.Error() != nil {
reportError(token.Error())
return
}
defer subscriber.Unsubscribe(probeConfig.SubscribeTopic)
probeDeadline := time.Now().Add(probeTimeout)
timeout := time.After(probeTimeout)
receiveCount := 0
// Support for custom message payload
msgPayload := "This is msg %d!"
if probeConfig.MessagePayload != "" {
msgPayload = probeConfig.MessagePayload
}
for i := 0; i < num; i++ {
text := fmt.Sprintf(msgPayload, i)
token := publisher.Publish(probeConfig.Topic, qos, false, text)
if !token.WaitTimeout(time.Until(probeDeadline)) {
messagesPublishTimeout.WithLabelValues(probeConfig.Name, probeConfig.Broker).Inc()
} else {
messagesPublished.WithLabelValues(probeConfig.Name, probeConfig.Broker).Inc()
}
}
for receiveCount < num {
select {
case <-queue:
receiveCount++
messagesReceived.WithLabelValues(probeConfig.Name, probeConfig.Broker).Inc()
case <-timeout:
timedoutTests.WithLabelValues(probeConfig.Name, probeConfig.Broker).Inc()
return
}
}
}
func main() {
flag.Parse()
yamlFile, err := ioutil.ReadFile(*configFile)
if err != nil {
logger.Fatalf("Error reading config file: %s", err)
}
mqtt.ERROR = logger
mqtt.CRITICAL = logger
if *enableTrace {
mqtt.WARN = logger
mqtt.DEBUG = logger
}
cfg := config{}
err = yaml.Unmarshal(yamlFile, &cfg)
if err != nil {
logger.Fatalf("Error parsing config file: %s", err)
}
logger.Printf("Starting mqtt_blackbox_exporter (build: %s)\n", build)
for _, probe := range cfg.Probes {
delay := probe.TestInterval
if delay == 0 {
delay = 60 * time.Second
}
go func(probeConfig probeConfig) {
for {
startProbe(&probeConfig)
time.Sleep(delay)
}
}(probe)
}
//nolint:staticcheck
http.Handle("/metrics", promhttp.Handler())
err = http.ListenAndServe(*listenAddress, nil)
if err != nil {
logger.Fatalf("Failed to serve metrics endpoint")
}
}