-
Notifications
You must be signed in to change notification settings - Fork 468
/
mqtt.go
502 lines (428 loc) · 14.6 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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
/*
Copyright 2023 The Dapr 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 mqtt
import (
"context"
"errors"
"fmt"
"net/url"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
"golang.org/x/exp/maps"
"github.com/dapr/components-contrib/metadata"
"github.com/dapr/components-contrib/pubsub"
"github.com/dapr/kit/logger"
"github.com/dapr/kit/utils"
)
const (
// Keys for request metadata
unsubscribeOnCloseKey = "unsubscribeOnClose"
)
// mqttPubSub type allows sending and receiving data to/from MQTT broker.
type mqttPubSub struct {
conn mqtt.Client
metadata *mqttMetadata
logger logger.Logger
topics map[string]mqttPubSubSubscription
subscribingLock sync.RWMutex
reconnectCh chan struct{}
closeCh chan struct{}
closed atomic.Bool
wg sync.WaitGroup
}
type mqttPubSubSubscription struct {
handler pubsub.Handler
alias string
matcher func(topic string) bool
}
// NewMQTTPubSub returns a new mqttPubSub instance.
func NewMQTTPubSub(logger logger.Logger) pubsub.PubSub {
return &mqttPubSub{
logger: logger,
reconnectCh: make(chan struct{}),
closeCh: make(chan struct{}),
}
}
// Init parses metadata and creates a new Pub Sub client.
func (m *mqttPubSub) Init(ctx context.Context, metadata pubsub.Metadata) error {
mqttMeta, err := parseMQTTMetaData(metadata, m.logger)
if err != nil {
return err
}
m.metadata = mqttMeta
err = m.connect(ctx)
if err != nil {
return fmt.Errorf("failed to establish connection to broker: %w", err)
}
m.topics = make(map[string]mqttPubSubSubscription)
m.logger.Debug("mqtt message bus initialization complete")
return nil
}
// Publish the topic to mqtt pub sub.
func (m *mqttPubSub) Publish(ctx context.Context, req *pubsub.PublishRequest) (err error) {
if m.closed.Load() {
return errors.New("component is closed")
}
if req.Topic == "" {
return errors.New("topic name is empty")
}
// Note this can contain PII
// m.logger.Debugf("mqtt publishing topic %s with data: %v", req.Topic, req.Data)
m.logger.Debugf("mqtt publishing topic %s", req.Topic)
retain := m.metadata.Retain
if val, ok := req.Metadata[mqttRetain]; ok && val != "" {
retain, err = strconv.ParseBool(val)
if err != nil {
return fmt.Errorf("mqtt invalid retain %s, %s", val, err)
}
}
token := m.conn.Publish(req.Topic, m.metadata.Qos, retain, req.Data)
ctx, cancel := context.WithTimeout(ctx, defaultWait)
defer cancel()
select {
case <-token.Done():
err = token.Error()
case <-m.closeCh:
err = errors.New("mqtt client closed")
case <-ctx.Done():
// Context canceled
err = ctx.Err()
}
if err != nil {
return fmt.Errorf("failed to publish: %w", err)
}
return nil
}
// Subscribe to the topic on MQTT.
// Request metadata includes:
// - "unsubscribeOnClose": if true, when the subscription is stopped (context canceled), then an Unsubscribe message is sent to the MQTT broker, which will stop delivering messages to this consumer ID until the subscription is explicitly re-started with a new Subscribe call. Otherwise, messages continue to be delivered but are not handled and are NACK'd automatically. "unsubscribeOnClose" should be used with dynamic subscriptions.
func (m *mqttPubSub) Subscribe(ctx context.Context, req pubsub.SubscribeRequest, handler pubsub.Handler) error {
if m.closed.Load() {
return errors.New("component is closed")
}
topic := req.Topic
if topic == "" {
return errors.New("topic name is empty")
}
unsubscribeOnClose := utils.IsTruthy(req.Metadata[unsubscribeOnCloseKey])
m.subscribingLock.Lock()
defer m.subscribingLock.Unlock()
// Add the topic then start the subscription
m.addTopic(topic, handler)
token := m.conn.Subscribe(topic, m.metadata.Qos, m.onMessage(ctx))
var err error
select {
case <-token.Done():
// Subscription went through (sucecessfully or not)
err = token.Error()
case <-ctx.Done():
err = fmt.Errorf("error while waiting for subscription token: %w", ctx.Err())
case <-time.After(defaultWait):
err = errors.New("timeout waiting for subscription")
}
if err != nil {
// Return an error
delete(m.topics, topic)
return fmt.Errorf("mqtt error from subscribe: %v", err)
}
m.logger.Infof("MQTT is subscribed to topic %s (qos: %d)", topic, m.metadata.Qos)
// Listen for context cancelation to remove the subscription
m.wg.Add(1)
go func() {
defer m.wg.Done()
select {
case <-ctx.Done():
case <-m.closeCh:
// If Close has been called, nothing to do here as the entire connection
// will be closed.
return
}
// Delete the topic from the map first, which stops routing messages to handlers
m.subscribingLock.Lock()
defer m.subscribingLock.Unlock()
delete(m.topics, topic)
// We will call Unsubscribe only if cleanSession is true or if "unsubscribeOnClose" in the request metadata is true
// Otherwise, calling this will make the broker lose the position of our subscription, which is not what we want if we are going to reconnect later
if !m.metadata.CleanSession && !unsubscribeOnClose {
return
}
unsubscribeToken := m.conn.Unsubscribe(topic)
var unsubscribeErr error
select {
case <-unsubscribeToken.Done():
// Subscription went through (sucecessfully or not)
unsubscribeErr = token.Error()
case <-time.After(defaultWait):
unsubscribeErr = fmt.Errorf("timeout while unsubscribing from topic %s", topic)
}
if unsubscribeErr != nil {
m.logger.Warnf("Failed to ubsubscribe from topic %s: %v", topic, unsubscribeErr)
}
}()
return nil
}
// onMessage returns the callback to be invoked when there's a new message from a topic
func (m *mqttPubSub) onMessage(ctx context.Context) func(client mqtt.Client, mqttMsg mqtt.Message) {
return func(client mqtt.Client, mqttMsg mqtt.Message) {
msg := pubsub.NewMessage{
Topic: mqttMsg.Topic(),
Data: mqttMsg.Payload(),
Metadata: map[string]string{"retained": strconv.FormatBool(mqttMsg.Retained())},
}
topicHandler := m.handlerForTopic(msg.Topic)
if topicHandler == nil {
m.logger.Warnf("No handler defined for messages received on topic %s", msg.Topic)
return
}
m.logger.Debugf("Processing MQTT message %s#%d (retained=%v)", mqttMsg.Topic(), mqttMsg.MessageID(), mqttMsg.Retained())
err := topicHandler(ctx, &msg)
if err != nil {
m.logger.Errorf("Failed processing MQTT message %s#%d: %v", mqttMsg.Topic(), mqttMsg.MessageID(), err)
return
}
m.logger.Debugf("Done processing MQTT message %s#%d; sending ACK", mqttMsg.Topic(), mqttMsg.MessageID())
mqttMsg.Ack()
}
}
// Returns the handler for a message sent to a given topic, supporting wildcards and other special syntaxes.
func (m *mqttPubSub) handlerForTopic(topic string) pubsub.Handler {
m.subscribingLock.RLock()
defer m.subscribingLock.RUnlock()
// First, try to see if we have a handler for the exact topic (no wildcards etc)
topicHandler, ok := m.topics[topic]
if ok && topicHandler.handler != nil {
return topicHandler.handler
}
// Iterate through the topics and run the matchers
for _, obj := range m.topics {
if obj.alias == topic {
return obj.handler
}
if obj.matcher != nil && obj.matcher(topic) {
return obj.handler
}
}
return nil
}
func (m *mqttPubSub) doConnect(ctx context.Context, clientID string) (mqtt.Client, error) {
uri, err := url.Parse(m.metadata.URL)
if err != nil {
return nil, err
}
opts := m.createClientOptions(uri, clientID)
client := mqtt.NewClient(opts)
token := client.Connect()
select {
case <-token.Done():
err = token.Error()
case <-ctx.Done():
err = ctx.Err()
}
if err != nil {
return nil, err
}
return client, nil
}
// Create a connection
func (m *mqttPubSub) connect(ctx context.Context) error {
m.subscribingLock.Lock()
defer m.subscribingLock.Unlock()
ctx, cancel := context.WithTimeout(ctx, defaultWait)
defer cancel()
conn, err := m.doConnect(ctx, m.metadata.ConsumerID)
if err != nil {
return err
}
m.conn = conn
return nil
}
func (m *mqttPubSub) createClientOptions(uri *url.URL, clientID string) *mqtt.ClientOptions {
opts := mqtt.NewClientOptions().
SetClientID(clientID).
SetCleanSession(m.metadata.CleanSession).
// If OrderMatters is true (default), handlers must not block, which is not an option for us
SetOrderMatters(false).
// Disable automatic ACKs as we need to do it manually
SetAutoAckDisabled(true).
// Configure reconnections
SetResumeSubs(true).
SetAutoReconnect(true).
SetConnectRetry(true).
SetConnectRetryInterval(20 * time.Second)
opts.OnConnectionLost = func(c mqtt.Client, err error) {
m.logger.Errorf("Connection with broker lost; error: %v", err)
}
opts.OnReconnecting = func(c mqtt.Client, co *mqtt.ClientOptions) {
m.logger.Info("Attempting to reconnect to broker…")
}
// On (re-)connection, add all established topic subscriptions
opts.OnConnect = func(c mqtt.Client) {
m.subscribingLock.RLock()
defer m.subscribingLock.RUnlock()
// If there's nothing to subscribe to, just return
if len(m.topics) == 0 {
return
}
// Create the list of topics to subscribe to
subscribeTopics := make(map[string]byte, len(m.topics))
for k := range m.topics {
subscribeTopics[k] = m.metadata.Qos
}
// Note that this is a bit unusual for a pubsub component as we're using a background context for the handler.
// This is because we can't really use a different context for each handler in a single SubscribeMultiple call, and the alternative (multiple individual Subscribe calls) is not ideal
ctx, cancel := context.WithCancel(context.Background())
m.wg.Add(1)
go func() {
defer m.wg.Done()
defer cancel()
<-m.closeCh
}()
token := c.SubscribeMultiple(
subscribeTopics,
m.onMessage(ctx),
)
var err error
subscribeCtx, subscribeCancel := context.WithTimeout(ctx, defaultWait)
defer subscribeCancel()
select {
case <-token.Done():
// Subscription went through (sucecessfully or not)
err = token.Error()
case <-subscribeCtx.Done():
err = fmt.Errorf("error while waiting for subscription token: %w", subscribeCtx.Err())
}
// Nothing we can do in case of errors besides logging them
// If we get here, the connection is almost likely broken anyways, so the client will attempt a reconnection soon if it hasn't already
if err != nil {
m.logger.Errorf("Error starting subscriptions in the OnConnect handler: %v", err)
}
}
// URL scheme backwards-compatibility
scheme := uri.Scheme
switch scheme {
case "mqtt":
scheme = "tcp"
case "mqtts", "tcps", "tls":
scheme = "ssl"
}
opts.AddBroker(scheme + "://" + uri.Host)
opts.SetUsername(uri.User.Username())
password, _ := uri.User.Password()
if password != "" {
opts.SetPassword(password)
}
// TLS
tlsConfig, err := pubsub.ConvertTLSPropertiesToTLSConfig(m.metadata.TLSProperties)
if err != nil {
m.logger.Warnf("failed to load TLS config: %s", err)
} else {
opts.SetTLSConfig(tlsConfig)
}
return opts
}
// Close the connection. Blocks until all subscriptions are closed.
func (m *mqttPubSub) Close() error {
m.subscribingLock.Lock()
defer m.subscribingLock.Unlock()
m.logger.Debug("Closing component")
// Clear all topics from the map as a first thing, before stopping all subscriptions (we have the lock anyways)
maps.Clear(m.topics)
if m.closed.CompareAndSwap(false, true) {
close(m.closeCh)
}
// Disconnect
m.conn.Disconnect(100)
m.wg.Wait()
return nil
}
func (m *mqttPubSub) Features() []pubsub.Feature {
return []pubsub.Feature{pubsub.FeatureSubscribeWildcards}
}
var sharedSubscriptionMatch = regexp.MustCompile(`^\$share\/(.*?)\/.`)
// Adds a topic to the list of subscriptions.
func (m *mqttPubSub) addTopic(origTopicName string, handler pubsub.Handler) {
obj := mqttPubSubSubscription{
handler: handler,
}
// Shared subscriptions begin with "$share/GROUPID/" and we can remove that prefix
topicName := origTopicName
if found := sharedSubscriptionMatch.FindStringIndex(origTopicName); found != nil && found[0] == 0 {
topicName = topicName[(found[1] - 1):]
obj.alias = topicName
}
// If the topic name contains a wildcard, we need to add a matcher
regexStr := buildRegexForTopic(topicName)
if regexStr != "" {
// We built our own regex and this should never panic
match := regexp.MustCompile(regexStr)
obj.matcher = func(topic string) bool {
return match.MatchString(topic)
}
}
m.topics[origTopicName] = obj
}
// Returns a regular expression string that matches the topic, with support for wildcards.
func buildRegexForTopic(topicName string) string {
// This is a bit more lax than the specs, which for example require "#" to be at the end of the string only:
// in practice, seems that (at least some) brokers are more flexible and allow "#" in the middle of a string too
var (
regexStr string
lastPos int = -1
start int
okPos bool
)
if strings.ContainsAny(topicName, "#+") {
regexStr = "^"
// It's ok to iterate over bytes here (rather than codepoints) because all characters we're looking for are always single-byte
for i := 0; i < len(topicName); i++ {
// Wildcard chars must either be at the beginning of the string or must follow a /
okPos = (i == 0 || topicName[i-1] == '/')
if topicName[i] == '#' && okPos {
lastPos = i
if i > 0 && i == (len(topicName)-1) {
// Edge case: we're at the end of the string so we can allow omitting the preceding /
regexStr += regexp.QuoteMeta(topicName[start:(i-1)]) + "(.*)"
} else {
regexStr += regexp.QuoteMeta(topicName[start:i]) + "(.*)"
}
start = i + 1
} else if topicName[i] == '+' && okPos {
lastPos = i
if i > 0 && i == (len(topicName)-1) {
// Edge case: we're at the end of the string so we can allow omitting the preceding /
regexStr += regexp.QuoteMeta(topicName[start:(i-1)]) + `((\/|)[^\/]*)`
} else {
regexStr += regexp.QuoteMeta(topicName[start:i]) + `([^\/]*)`
}
start = i + 1
}
}
regexStr += regexp.QuoteMeta(topicName[(lastPos+1):]) + "$"
}
if lastPos == -1 {
return ""
}
return regexStr
}
// GetComponentMetadata returns the metadata of the component.
func (m *mqttPubSub) GetComponentMetadata() (metadataInfo metadata.MetadataMap) {
metadataStruct := mqttMetadata{}
metadata.GetMetadataInfoFromStructType(reflect.TypeOf(metadataStruct), &metadataInfo, metadata.PubSubType)
return
}