forked from gobench-io/gobench
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mqtt.go
447 lines (402 loc) · 10.2 KB
/
mqtt.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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
package mqtt
import (
"context"
"log"
"time"
paho "github.com/eclipse/paho.mqtt.golang"
"github.com/thoverik/gobench"
"github.com/thoverik/gobench/metrics"
)
const conTotal string = "mqtt.connection.current_total"
const conError string = "mqtt.connection.connect.errors"
const conReconnect string = "mqtt.connection.reconnects"
const conLatency string = "mqtt.connection.connack.latency"
const pubQos0Latency string = "mqtt.publisher.qos0.puback.latency"
const pubQos0Total string = "mqtt.publisher.qos0.puback.in.total"
const pubQos1Latency string = "mqtt.publisher.qos1.puback.latency"
const pubQos1Total string = "mqtt.publisher.qos1.puback.in.total"
const pubQos2Latency string = "mqtt.publisher.qos2.puback.latency"
const pubQos2Total string = "mqtt.publisher.qos2.puback.in.total"
const subLatency string = "mqtt.subscriber.suback.latency"
const subTotal string = "mqtt.subscriber.current_total"
const subError string = "mqtt.subscriber.suback.error"
const unsubLatency string = "mqtt.subscriber.unsuback.latency"
const unsubError string = "mqtt.subscriber.unsuback.error"
const msgPublishedTotal string = "mqtt.message.published.total"
const msgConsumedTotal string = "mqtt.message.consumed.total"
// ContextKey is the type for context
type ContextKey string
type ClientOptions struct {
*paho.ClientOptions
}
func NewClientOptions() *ClientOptions {
t := paho.NewClientOptions()
o := &ClientOptions{ClientOptions: t}
return o
}
type MqttClient struct {
client paho.Client
}
func groups() []metrics.Group {
conGroup := metrics.Group{
Name: "MQTT Connections",
Graphs: []metrics.Graph{
{
Title: "Total Connections",
Unit: "N",
Metrics: []metrics.Metric{
{
Title: conTotal,
Type: metrics.Counter,
},
},
},
{
Title: "Connection Errors",
Unit: "N",
Metrics: []metrics.Metric{
{
Title: conError,
Type: metrics.Counter,
},
},
},
{
Title: "Reconnects",
Unit: "N",
Metrics: []metrics.Metric{
{
Title: conReconnect,
Type: metrics.Counter,
},
},
},
{
Title: "Connack Latency",
Unit: "Microsecond",
Metrics: []metrics.Metric{
{
Title: conLatency,
Type: metrics.Histogram,
},
},
},
},
}
qos0PubGroup := metrics.Group{
Name: "MQTT Publishers QoS 0",
Graphs: []metrics.Graph{
{
Title: "QoS0 Publish to Puback Latency",
Unit: "Microsecond",
Metrics: []metrics.Metric{
{
Title: pubQos0Latency,
Type: metrics.Histogram,
},
},
},
{
Title: "QoS0 Pubacks Received Total",
Unit: "N",
Metrics: []metrics.Metric{
{
Title: pubQos0Total,
Type: metrics.Counter,
},
},
},
},
}
qos1PubGroup := metrics.Group{
Name: "MQTT Publishers QoS 1",
Graphs: []metrics.Graph{
{
Title: "QoS1 Publish to Puback Latency",
Unit: "Microsecond",
Metrics: []metrics.Metric{
{
Title: pubQos1Latency,
Type: metrics.Histogram,
},
},
},
{
Title: "QoS1 Pubacks Received Total",
Unit: "N",
Metrics: []metrics.Metric{
{
Title: pubQos1Total,
Type: metrics.Counter,
},
},
},
},
}
qos2PubGroup := metrics.Group{
Name: "MQTT Publishers QoS 2",
Graphs: []metrics.Graph{
{
Title: "QoS2 Publish to Puback Latency",
Unit: "Microsecond",
Metrics: []metrics.Metric{
{
Title: pubQos2Latency,
Type: metrics.Histogram,
},
},
},
{
Title: "QoS2 Pubacks Received Total",
Unit: "N",
Metrics: []metrics.Metric{
{
Title: pubQos2Total,
Type: metrics.Counter,
},
},
},
},
}
consumerGroup := metrics.Group{
Name: "MQTT Consumers",
Graphs: []metrics.Graph{
{
Title: "Suback Latency",
Unit: "Microsecond",
Metrics: []metrics.Metric{
{
Title: subLatency,
Type: metrics.Histogram,
},
},
},
{
Title: "Subscriber Total",
Unit: "N",
Metrics: []metrics.Metric{
{
Title: subTotal,
Type: metrics.Counter,
},
},
},
{
Title: "Subscriber Suback Errors",
Unit: "N",
Metrics: []metrics.Metric{
{
Title: subError,
Type: metrics.Counter,
},
},
},
{
Title: "Unsuback Latency",
Unit: "Microsecond",
Metrics: []metrics.Metric{
{
Title: unsubError,
Type: metrics.Histogram,
},
},
},
{
Title: "Subscriber Unsuback Errors",
Unit: "N",
Metrics: []metrics.Metric{
{
Title: unsubError,
Type: metrics.Counter,
},
},
},
},
}
msgGroup := metrics.Group{
Name: "MQTT Messages",
Graphs: []metrics.Graph{
{
Title: "Total Published Messages",
Unit: "N",
Metrics: []metrics.Metric{
{
Title: msgPublishedTotal,
Type: metrics.Counter,
},
},
},
{
Title: "Total Consumed Messages",
Unit: "N",
Metrics: []metrics.Metric{
{
Title: msgConsumedTotal,
Type: metrics.Counter,
},
},
},
},
}
return []metrics.Group{
conGroup,
qos0PubGroup,
qos1PubGroup,
qos2PubGroup,
consumerGroup,
msgGroup,
}
}
func NewMqttClient(ctx *context.Context, opts *ClientOptions) (MqttClient, error) {
mqttClient := MqttClient{}
gs := groups()
if err := gobench.Setup(gs); err != nil {
return mqttClient, err
}
clientID := opts.ClientID
// generate random clientID if not provided
if clientID == "" {
clientID = gobench.RandomString(32)
}
opts.ClientOptions.SetClientID(clientID)
// be called when the client is connected.
// Both at initial connection time and upon automatic reconnect.
OnConnect := opts.OnConnect
opts.SetOnConnectHandler(func(c paho.Client) {
gobench.Notify(conTotal, 1)
if OnConnect != nil {
OnConnect(c)
}
})
// be executed in the case where the client unexpectedly loses connection with the MQTT broker.
OnConnectionLost := opts.OnConnectionLost
opts.SetConnectionLostHandler(func(c paho.Client, e error) {
gobench.Notify(conTotal, -1)
if OnConnectionLost != nil {
OnConnectionLost(c, e)
}
})
// be executed prior to the client attempting a reconnect to the MQTT broker.
OnReconnecting := opts.OnReconnecting
opts.SetReconnectingHandler(func(c paho.Client, o *paho.ClientOptions) {
gobench.Notify(conReconnect, 1)
if OnReconnecting != nil {
OnReconnecting(c, o)
}
})
client := paho.NewClient(opts.ClientOptions)
mqttClient.client = client
return mqttClient, nil
}
func (c *MqttClient) toSelfTopic(prefix string) string {
or := c.client.OptionsReader()
return prefix + or.ClientID()
}
// Connect will create a connection to the message broker, by default
// it will attempt to connect at v3.1.1 and auto retry at v3.1 if that
// fails
func (c *MqttClient) Connect(ctx *context.Context) error {
begin := time.Now()
token := c.client.Connect()
for !token.WaitTimeout(3 * time.Second) {
}
if err := token.Error(); err != nil {
log.Printf("mqtt connect fail: %s\n", err.Error())
gobench.Notify(conError, 1)
return err
}
gobench.Notify(conLatency, time.Since(begin).Microseconds())
return nil
}
// Publish will publish a message with the specified QoS and content
// to the specified topic.
func (c *MqttClient) Publish(ctx *context.Context, topic string, qos byte, data []byte) error {
begin := time.Now()
token := c.client.Publish(topic, qos, false, data)
token.WaitTimeout(3 * time.Second)
if err := token.Error(); err != nil {
log.Printf("mqtt publish fail: %s\n", err.Error())
return err
}
switch qos {
case 0:
gobench.Notify(pubQos0Total, 1)
gobench.Notify(pubQos0Latency, time.Since(begin).Microseconds())
case 1:
gobench.Notify(pubQos1Total, 1)
gobench.Notify(pubQos1Latency, time.Since(begin).Microseconds())
case 2:
gobench.Notify(pubQos2Total, 1)
gobench.Notify(pubQos2Latency, time.Since(begin).Microseconds())
}
gobench.Notify(msgPublishedTotal, 1)
return nil
}
// PublishToSelf starts a new publish. Topic is the concat of prefix
// and clientID. Provide a prefix, qos, and data
func (c *MqttClient) PublishToSelf(ctx *context.Context, prefix string, qos byte, data []byte) error {
topic := c.toSelfTopic(prefix)
return c.Publish(ctx, topic, qos, data)
}
// Subscribe starts a new subscription. Provide a MessageHandler to be executed when
// a message is published on the topic provided.
// One different from the original paho is that when callback is nil the message will
// not be forwarded to the default handler.
func (c *MqttClient) Subscribe(
ctx *context.Context,
topic string,
qos byte,
callback paho.MessageHandler,
) error {
begin := time.Now()
token := c.client.Subscribe(topic, qos, func(c paho.Client, m paho.Message) {
gobench.Notify(msgConsumedTotal, 1)
if callback != nil {
callback(c, m)
}
})
token.WaitTimeout(3 * time.Second)
if err := token.Error(); err != nil {
log.Printf("mqtt subscribe fail: %s\n", err.Error())
gobench.Notify(subError, 1)
return err
}
gobench.Notify(subLatency, time.Since(begin).Microseconds())
gobench.Notify(subTotal, 1)
return nil
}
// SubscribeToSelf starts a new subscription. Topic is the concat of prefix
// and clientID. Provide a MessageHandler to be executed when a message is
// published on the topic provided. One different from the original paho is
// that when callback is nil the message will not be forwarded to the default
// handler.
func (c *MqttClient) SubscribeToSelf(
ctx *context.Context,
prefix string,
qos byte,
callback paho.MessageHandler,
) error {
topic := c.toSelfTopic(prefix)
return c.Subscribe(ctx, topic, qos, callback)
}
// Unsubscribe will end the subscription from each of the topics provided.
// Messages published to those topics from other clients will no longer be
// received.
func (c *MqttClient) Unsubscribe(ctx *context.Context, topics ...string) error {
begin := time.Now()
token := c.client.Unsubscribe(topics...)
token.WaitTimeout(3 * time.Second)
if err := token.Error(); err != nil {
log.Printf("mqtt unsubscribe fail: %s\n", err.Error())
gobench.Notify(unsubError, 1)
return err
}
gobench.Notify(unsubLatency, time.Since(begin).Microseconds())
return nil
}
// Disconnect will end the connection with the server
func (c *MqttClient) Disconnect(ctx *context.Context) error {
c.client.Disconnect(500)
gobench.Notify(conTotal, -1)
return nil
}