mqtt_wrapper.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. conf.Log.Warnf("The connection to mqtt broker %s client id %s disconnected with error: %s ", mc.cli.srv, mc.cli.clientid, err.Error())
  92. }
  93. func (mc *mqttClientWrapper) newMessageHandler(sub *mqttSubscriptionInfo) pahoMqtt.MessageHandler {
  94. return func(client pahoMqtt.Client, message pahoMqtt.Message) {
  95. if sub != nil {
  96. // broadcast to all consumers
  97. for _, consumer := range sub.topicConsumers {
  98. select {
  99. case consumer.ConsumerChan <- message:
  100. break
  101. default:
  102. conf.Log.Warnf("consumer chan full for request id %s", consumer.ConsumerId)
  103. }
  104. }
  105. }
  106. }
  107. }
  108. func (mc *mqttClientWrapper) Publish(_ api.StreamContext, topic string, message []byte, params map[string]interface{}) error {
  109. err := mc.checkConn()
  110. if err != nil {
  111. return err
  112. }
  113. var Qos byte = 0
  114. if pq, ok := params["qos"]; ok {
  115. if v, ok := pq.(byte); ok {
  116. Qos = v
  117. }
  118. }
  119. retained := false
  120. if pk, ok := params["retained"]; ok {
  121. if v, ok := pk.(bool); ok {
  122. retained = v
  123. }
  124. }
  125. err = mc.cli.Publish(topic, Qos, retained, message)
  126. if err != nil {
  127. return err
  128. }
  129. return nil
  130. }
  131. func (mc *mqttClientWrapper) checkConn() error {
  132. mc.subLock.RLock()
  133. defer mc.subLock.RUnlock()
  134. if !mc.connected {
  135. return fmt.Errorf("%s: %s", errorx.IOErr, "mqtt client is not connected")
  136. }
  137. return nil
  138. }
  139. func (mc *mqttClientWrapper) Subscribe(c api.StreamContext, subChan []api.TopicChannel, messageErrors chan error, params map[string]interface{}) error {
  140. log := c.GetLogger()
  141. mc.subLock.Lock()
  142. defer mc.subLock.Unlock()
  143. subId := fmt.Sprintf("%s_%s_%d", c.GetRuleId(), c.GetOpId(), c.GetInstanceId())
  144. if _, ok := mc.subscribers[subId]; ok {
  145. return fmt.Errorf("already have subscription %s", subId)
  146. }
  147. var Qos byte = 0
  148. if pq, ok := params["qos"]; ok {
  149. if v, ok := pq.(byte); ok {
  150. Qos = v
  151. }
  152. }
  153. subTopics := clients.SubscribedTopics{
  154. Topics: make([]string, 0),
  155. }
  156. for _, tpChan := range subChan {
  157. tpc := tpChan.Topic
  158. subTopics.Topics = append(subTopics.Topics, tpc)
  159. sub, found := mc.topicSubscriptions[tpc]
  160. if found {
  161. sub.topicConsumers = append(sub.topicConsumers, &clients.ConsumerInfo{
  162. ConsumerId: subId,
  163. ConsumerChan: tpChan.Messages,
  164. SubErrors: messageErrors,
  165. })
  166. log.Infof("subscription for topic %s already exists, reqId is %s, total subs %d", tpc, subId, len(sub.topicConsumers))
  167. } else {
  168. sub := &mqttSubscriptionInfo{
  169. topic: tpc,
  170. qos: Qos,
  171. topicConsumers: []*clients.ConsumerInfo{
  172. {
  173. ConsumerId: subId,
  174. ConsumerChan: tpChan.Messages,
  175. SubErrors: messageErrors,
  176. },
  177. },
  178. }
  179. sub.topicHandler = mc.newMessageHandler(sub)
  180. log.Infof("new subscription for topic %s, reqId is %s", tpc, subId)
  181. token := mc.cli.conn.Subscribe(tpc, Qos, sub.topicHandler)
  182. if token.Error() != nil {
  183. return token.Error()
  184. }
  185. mc.topicSubscriptions[tpc] = sub
  186. }
  187. }
  188. mc.subscribers[subId] = subTopics
  189. return nil
  190. }
  191. func (mc *mqttClientWrapper) unsubscribe(c api.StreamContext) {
  192. log := c.GetLogger()
  193. mc.subLock.Lock()
  194. defer mc.subLock.Unlock()
  195. subId := fmt.Sprintf("%s_%s_%d", c.GetRuleId(), c.GetOpId(), c.GetInstanceId())
  196. subTopics, found := mc.subscribers[subId]
  197. if !found {
  198. log.Errorf("not found subscription id %s", subId)
  199. return
  200. }
  201. for _, tpc := range subTopics.Topics {
  202. if sub, found := mc.topicSubscriptions[tpc]; found {
  203. for index, consumer := range sub.topicConsumers {
  204. if strings.EqualFold(subId, consumer.ConsumerId) {
  205. sub.topicConsumers = append(sub.topicConsumers[:index], sub.topicConsumers[index+1:]...)
  206. log.Infof("unsubscription topic %s for reqId %s, total subs %d", tpc, subId, len(sub.topicConsumers))
  207. }
  208. }
  209. if 0 == len(sub.topicConsumers) {
  210. delete(mc.topicSubscriptions, tpc)
  211. log.Infof("delete subscription for topic %s", tpc)
  212. mc.cli.conn.Unsubscribe(tpc)
  213. }
  214. }
  215. }
  216. delete(mc.subscribers, subId)
  217. }
  218. func (mc *mqttClientWrapper) Release(c api.StreamContext) {
  219. mc.unsubscribe(c)
  220. clients.ClientRegistry.Lock.Lock()
  221. mc.DeRef(c)
  222. clients.ClientRegistry.Lock.Unlock()
  223. }
  224. func (mc *mqttClientWrapper) SetConnectionSelector(conSelector string) {
  225. mc.conSelector = conSelector
  226. }
  227. func (mc *mqttClientWrapper) AddRef() {
  228. mc.refLock.Lock()
  229. defer mc.refLock.Unlock()
  230. mc.refCnt = mc.refCnt + 1
  231. conf.Log.Infof("mqtt client wrapper add refence for connection selector %s total refcount %d", mc.conSelector, mc.refCnt)
  232. }
  233. func (mc *mqttClientWrapper) DeRef(c api.StreamContext) {
  234. log := c.GetLogger()
  235. mc.refLock.Lock()
  236. defer mc.refLock.Unlock()
  237. mc.refCnt = mc.refCnt - 1
  238. if mc.refCnt == 0 {
  239. log.Infof("mqtt client wrapper reference count 0")
  240. if mc.conSelector != "" {
  241. conf.Log.Infof("remove mqtt client wrapper for connection selector %s", mc.conSelector)
  242. delete(clients.ClientRegistry.ShareClientStore, mc.conSelector)
  243. }
  244. _ = mc.cli.Disconnect()
  245. }
  246. }