mqtt_wrapper.go 7.5 KB

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