mqtt_wrapper.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. // Copyright 2022 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package mqtt
  15. import (
  16. "fmt"
  17. pahoMqtt "github.com/eclipse/paho.mqtt.golang"
  18. "github.com/lf-edge/ekuiper/internal/conf"
  19. "github.com/lf-edge/ekuiper/internal/topo/connection/clients"
  20. "github.com/lf-edge/ekuiper/pkg/api"
  21. "github.com/lf-edge/ekuiper/pkg/errorx"
  22. "strings"
  23. "sync"
  24. )
  25. type mqttSubscriptionInfo struct {
  26. topic string
  27. qos byte
  28. topicHandler pahoMqtt.MessageHandler
  29. topicConsumers []*clients.ConsumerInfo
  30. }
  31. type mqttClientWrapper struct {
  32. cli *MQTTClient
  33. subLock sync.RWMutex
  34. //topic: subscriber
  35. //multiple go routine can sub same topic
  36. topicSubscriptions map[string]*mqttSubscriptionInfo
  37. //consumerId: SubscribedTopics
  38. subscribers map[string]clients.SubscribedTopics
  39. conSelector string
  40. connected bool
  41. refLock sync.RWMutex
  42. refCnt uint64
  43. }
  44. func NewMqttClientWrapper(props map[string]interface{}) (clients.ClientWrapper, error) {
  45. if props == nil {
  46. conf.Log.Warnf("props is nill for mqtt client wrapper")
  47. }
  48. client := &MQTTClient{}
  49. err := client.CfgValidate(props)
  50. if err != nil {
  51. return nil, err
  52. }
  53. cliWpr := &mqttClientWrapper{
  54. cli: client,
  55. subLock: sync.RWMutex{},
  56. topicSubscriptions: make(map[string]*mqttSubscriptionInfo),
  57. subscribers: make(map[string]clients.SubscribedTopics),
  58. refCnt: 1,
  59. }
  60. err = client.Connect(cliWpr.onConnectHandler, cliWpr.onConnectLost)
  61. if err != nil {
  62. return nil, err
  63. }
  64. return cliWpr, nil
  65. }
  66. func (mc *mqttClientWrapper) onConnectHandler(_ pahoMqtt.Client) {
  67. // activeSubscriptions will be empty on the first connection.
  68. // On a re-connect is when the subscriptions must be re-created.
  69. conf.Log.Infof("The connection to mqtt broker %s client id %s established", mc.cli.srv, mc.cli.clientid)
  70. mc.subLock.Lock()
  71. defer mc.subLock.Unlock()
  72. mc.connected = true
  73. for topic, subscription := range mc.topicSubscriptions {
  74. token := mc.cli.conn.Subscribe(topic, subscription.qos, subscription.topicHandler)
  75. if token.Error() != nil {
  76. for _, con := range subscription.topicConsumers {
  77. select {
  78. case con.SubErrors <- token.Error():
  79. break
  80. default:
  81. conf.Log.Warnf("consumer SubErrors channel full for request id %s", con.ConsumerId)
  82. }
  83. }
  84. }
  85. }
  86. }
  87. func (mc *mqttClientWrapper) onConnectLost(_ pahoMqtt.Client, err error) {
  88. mc.subLock.Lock()
  89. defer mc.subLock.Unlock()
  90. mc.connected = false
  91. e := fmt.Errorf("The connection to mqtt broker %s client id %s disconnected with error: %s ", mc.cli.srv, mc.cli.clientid, err.Error())
  92. conf.Log.Warnf(e.Error())
  93. for _, sub := range mc.topicSubscriptions {
  94. if sub != nil {
  95. // broadcast errors to all consumers
  96. for _, consumer := range sub.topicConsumers {
  97. select {
  98. case consumer.SubErrors <- e:
  99. break
  100. default:
  101. conf.Log.Warnf("consumer chan full for request id %s", consumer.ConsumerId)
  102. }
  103. }
  104. }
  105. }
  106. }
  107. func (mc *mqttClientWrapper) newMessageHandler(sub *mqttSubscriptionInfo) pahoMqtt.MessageHandler {
  108. return func(client pahoMqtt.Client, message pahoMqtt.Message) {
  109. if sub != nil {
  110. // broadcast to all consumers
  111. for _, consumer := range sub.topicConsumers {
  112. select {
  113. case consumer.ConsumerChan <- message:
  114. break
  115. default:
  116. conf.Log.Warnf("consumer chan full for request id %s", consumer.ConsumerId)
  117. }
  118. }
  119. }
  120. }
  121. }
  122. func (mc *mqttClientWrapper) Publish(_ api.StreamContext, topic string, message []byte, params map[string]interface{}) error {
  123. err := mc.checkConn()
  124. if err != nil {
  125. return err
  126. }
  127. var Qos byte = 0
  128. if pq, ok := params["qos"]; ok {
  129. if v, ok := pq.(byte); ok {
  130. Qos = v
  131. }
  132. }
  133. retained := false
  134. if pk, ok := params["retained"]; ok {
  135. if v, ok := pk.(bool); ok {
  136. retained = v
  137. }
  138. }
  139. err = mc.cli.Publish(topic, Qos, retained, message)
  140. if err != nil {
  141. return err
  142. }
  143. return nil
  144. }
  145. func (mc *mqttClientWrapper) checkConn() error {
  146. mc.subLock.RLock()
  147. defer mc.subLock.RUnlock()
  148. if !mc.connected {
  149. return fmt.Errorf("%s: %s", errorx.IOErr, "mqtt client is not connected")
  150. }
  151. return nil
  152. }
  153. func (mc *mqttClientWrapper) Subscribe(c api.StreamContext, subChan []api.TopicChannel, messageErrors chan error, params map[string]interface{}) error {
  154. log := c.GetLogger()
  155. mc.subLock.Lock()
  156. defer mc.subLock.Unlock()
  157. subId := fmt.Sprintf("%s_%s_%d", c.GetRuleId(), c.GetOpId(), c.GetInstanceId())
  158. if _, ok := mc.subscribers[subId]; ok {
  159. return fmt.Errorf("already have subscription %s", subId)
  160. }
  161. var Qos byte = 0
  162. if pq, ok := params["qos"]; ok {
  163. if v, ok := pq.(byte); ok {
  164. Qos = v
  165. }
  166. }
  167. subTopics := clients.SubscribedTopics{
  168. Topics: make([]string, 0),
  169. }
  170. for _, tpChan := range subChan {
  171. tpc := tpChan.Topic
  172. subTopics.Topics = append(subTopics.Topics, tpc)
  173. sub, found := mc.topicSubscriptions[tpc]
  174. if found {
  175. sub.topicConsumers = append(sub.topicConsumers, &clients.ConsumerInfo{
  176. ConsumerId: subId,
  177. ConsumerChan: tpChan.Messages,
  178. SubErrors: messageErrors,
  179. })
  180. log.Infof("subscription for topic %s already exists, reqId is %s, total subs %d", tpc, subId, len(sub.topicConsumers))
  181. } else {
  182. sub := &mqttSubscriptionInfo{
  183. topic: tpc,
  184. qos: Qos,
  185. topicConsumers: []*clients.ConsumerInfo{
  186. {
  187. ConsumerId: subId,
  188. ConsumerChan: tpChan.Messages,
  189. SubErrors: messageErrors,
  190. },
  191. },
  192. }
  193. sub.topicHandler = mc.newMessageHandler(sub)
  194. log.Infof("new subscription for topic %s, reqId is %s", tpc, subId)
  195. token := mc.cli.conn.Subscribe(tpc, Qos, sub.topicHandler)
  196. if token.Error() != nil {
  197. return token.Error()
  198. }
  199. mc.topicSubscriptions[tpc] = sub
  200. }
  201. }
  202. mc.subscribers[subId] = subTopics
  203. return nil
  204. }
  205. func (mc *mqttClientWrapper) unsubscribe(c api.StreamContext) {
  206. log := c.GetLogger()
  207. mc.subLock.Lock()
  208. defer mc.subLock.Unlock()
  209. subId := fmt.Sprintf("%s_%s_%d", c.GetRuleId(), c.GetOpId(), c.GetInstanceId())
  210. subTopics, found := mc.subscribers[subId]
  211. if !found {
  212. log.Errorf("not found subscription id %s", subId)
  213. return
  214. }
  215. for _, tpc := range subTopics.Topics {
  216. if sub, found := mc.topicSubscriptions[tpc]; found {
  217. for index, consumer := range sub.topicConsumers {
  218. if strings.EqualFold(subId, consumer.ConsumerId) {
  219. sub.topicConsumers = append(sub.topicConsumers[:index], sub.topicConsumers[index+1:]...)
  220. log.Infof("unsubscription topic %s for reqId %s, total subs %d", tpc, subId, len(sub.topicConsumers))
  221. }
  222. }
  223. if 0 == len(sub.topicConsumers) {
  224. delete(mc.topicSubscriptions, tpc)
  225. log.Infof("delete subscription for topic %s", tpc)
  226. mc.cli.conn.Unsubscribe(tpc)
  227. }
  228. }
  229. }
  230. delete(mc.subscribers, subId)
  231. }
  232. func (mc *mqttClientWrapper) Release(c api.StreamContext) bool {
  233. mc.unsubscribe(c)
  234. return mc.deRef(c)
  235. }
  236. func (mc *mqttClientWrapper) SetConnectionSelector(conSelector string) {
  237. mc.conSelector = conSelector
  238. }
  239. func (mc *mqttClientWrapper) GetConnectionSelector() string {
  240. return mc.conSelector
  241. }
  242. func (mc *mqttClientWrapper) AddRef() {
  243. mc.refLock.Lock()
  244. defer mc.refLock.Unlock()
  245. mc.refCnt = mc.refCnt + 1
  246. conf.Log.Infof("mqtt client wrapper add refence for connection selector %s total refcount %d", mc.conSelector, mc.refCnt)
  247. }
  248. func (mc *mqttClientWrapper) deRef(c api.StreamContext) bool {
  249. log := c.GetLogger()
  250. mc.refLock.Lock()
  251. defer mc.refLock.Unlock()
  252. mc.refCnt = mc.refCnt - 1
  253. log.Infof("mqtt client wrapper reference count %d", mc.refCnt)
  254. if mc.refCnt == 0 {
  255. _ = mc.cli.Disconnect()
  256. return true
  257. } else {
  258. return false
  259. }
  260. }