edgex_wrapper.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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. //go:build edgex
  15. // +build edgex
  16. package edgex
  17. import (
  18. "fmt"
  19. "github.com/edgexfoundry/go-mod-messaging/v2/pkg/types"
  20. "github.com/lf-edge/ekuiper/internal/conf"
  21. "github.com/lf-edge/ekuiper/internal/topo/connection/clients"
  22. "github.com/lf-edge/ekuiper/pkg/api"
  23. "strings"
  24. "sync"
  25. )
  26. type messageHandler func(stopChan chan struct{}, msgChan chan types.MessageEnvelope)
  27. type edgexSubscriptionInfo struct {
  28. topic string
  29. handler messageHandler
  30. stop chan struct{}
  31. topicConsumers []*clients.ConsumerInfo
  32. }
  33. type edgexClientWrapper struct {
  34. cli *EdgexClient
  35. subLock sync.RWMutex
  36. //topic: subscriber
  37. //multiple go routine can sub same topic
  38. topicSubscriptions map[string]*edgexSubscriptionInfo
  39. //consumerId: SubscribedTopics
  40. subscribers map[string]clients.SubscribedTopics
  41. conSelector string
  42. refLock sync.RWMutex
  43. refCnt uint64
  44. }
  45. func NewEdgeClientWrapper(props map[string]interface{}) (clients.ClientWrapper, error) {
  46. if props == nil {
  47. conf.Log.Warnf("props is nill for mqtt client wrapper")
  48. }
  49. client := &EdgexClient{}
  50. err := client.CfgValidate(props)
  51. if err != nil {
  52. return nil, err
  53. }
  54. cliWpr := &edgexClientWrapper{
  55. cli: client,
  56. subLock: sync.RWMutex{},
  57. topicSubscriptions: make(map[string]*edgexSubscriptionInfo),
  58. subscribers: make(map[string]clients.SubscribedTopics),
  59. refCnt: 1,
  60. }
  61. err = client.Connect()
  62. if err != nil {
  63. return nil, err
  64. }
  65. return cliWpr, nil
  66. }
  67. func (mc *edgexClientWrapper) Publish(c api.StreamContext, topic string, message []byte, params map[string]interface{}) error {
  68. env := types.NewMessageEnvelope(message, c)
  69. env.ContentType = "application/json"
  70. if pk, ok := params["contentType"]; ok {
  71. if v, ok := pk.(string); ok {
  72. env.ContentType = v
  73. }
  74. }
  75. err := mc.cli.Publish(env, topic)
  76. if err != nil {
  77. return err
  78. }
  79. return nil
  80. }
  81. func (mc *edgexClientWrapper) messageHandler(topic string, sub *edgexSubscriptionInfo, messageErrors chan error) func(stopChan chan struct{}, msgChan chan types.MessageEnvelope) {
  82. return func(stopChan chan struct{}, msgChan chan types.MessageEnvelope) {
  83. for {
  84. select {
  85. case <-stopChan:
  86. conf.Log.Infof("message handler for topic %s stopped", topic)
  87. return
  88. case msgErr := <-messageErrors:
  89. //broadcast to all topic subscribers
  90. if sub != nil {
  91. for _, consumer := range sub.topicConsumers {
  92. select {
  93. case consumer.SubErrors <- msgErr:
  94. break
  95. default:
  96. conf.Log.Warnf("consumer SubErrors channel full for request id %s", consumer.ConsumerId)
  97. }
  98. }
  99. }
  100. case msg, ok := <-msgChan:
  101. if !ok {
  102. for _, consumer := range sub.topicConsumers {
  103. close(consumer.ConsumerChan)
  104. }
  105. conf.Log.Errorf("message handler for topic %s stopped", topic)
  106. return
  107. }
  108. //broadcast to all topic subscribers
  109. if sub != nil {
  110. for _, consumer := range sub.topicConsumers {
  111. select {
  112. case consumer.ConsumerChan <- &msg:
  113. break
  114. default:
  115. conf.Log.Warnf("consumer chan full for request id %s", consumer.ConsumerId)
  116. }
  117. }
  118. }
  119. }
  120. }
  121. }
  122. }
  123. func (mc *edgexClientWrapper) Subscribe(c api.StreamContext, subChan []api.TopicChannel, messageErrors chan error, _ map[string]interface{}) error {
  124. log := c.GetLogger()
  125. mc.subLock.Lock()
  126. defer mc.subLock.Unlock()
  127. subId := fmt.Sprintf("%s_%s_%d", c.GetRuleId(), c.GetOpId(), c.GetInstanceId())
  128. if _, ok := mc.subscribers[subId]; ok {
  129. return fmt.Errorf("already have subscription %s", subId)
  130. }
  131. subTopics := clients.SubscribedTopics{
  132. Topics: make([]string, 0),
  133. }
  134. for _, tpChan := range subChan {
  135. tpc := tpChan.Topic
  136. subTopics.Topics = append(subTopics.Topics, tpc)
  137. sub, found := mc.topicSubscriptions[tpc]
  138. if found {
  139. sub.topicConsumers = append(sub.topicConsumers, &clients.ConsumerInfo{
  140. ConsumerId: subId,
  141. ConsumerChan: tpChan.Messages,
  142. SubErrors: messageErrors,
  143. })
  144. log.Infof("subscription for topic %s already exists, reqId is %s, total subs %d", tpc, subId, len(sub.topicConsumers))
  145. } else {
  146. sub := &edgexSubscriptionInfo{
  147. topic: tpc,
  148. stop: make(chan struct{}, 1),
  149. topicConsumers: []*clients.ConsumerInfo{
  150. {
  151. ConsumerId: subId,
  152. ConsumerChan: tpChan.Messages,
  153. SubErrors: messageErrors,
  154. },
  155. },
  156. }
  157. log.Infof("new subscription for topic %s, reqId is %s", tpc, subId)
  158. message := make(chan types.MessageEnvelope)
  159. errChan := make(chan error)
  160. if err := mc.cli.Subscribe(message, tpc, errChan); err != nil {
  161. return err
  162. }
  163. sub.handler = mc.messageHandler(tpc, sub, errChan)
  164. go sub.handler(sub.stop, message)
  165. mc.topicSubscriptions[tpc] = sub
  166. }
  167. }
  168. mc.subscribers[subId] = subTopics
  169. return nil
  170. }
  171. func (mc *edgexClientWrapper) unsubscribe(c api.StreamContext) {
  172. log := c.GetLogger()
  173. mc.subLock.Lock()
  174. defer mc.subLock.Unlock()
  175. subId := fmt.Sprintf("%s_%s_%d", c.GetRuleId(), c.GetOpId(), c.GetInstanceId())
  176. subTopics, found := mc.subscribers[subId]
  177. if !found {
  178. log.Errorf("not found subscription id %s", subId)
  179. return
  180. }
  181. // just clean the consumers, do not clean the topic subscription
  182. for _, tpc := range subTopics.Topics {
  183. if sub, found := mc.topicSubscriptions[tpc]; found {
  184. for index, consumer := range sub.topicConsumers {
  185. if strings.EqualFold(subId, consumer.ConsumerId) {
  186. sub.topicConsumers = append(sub.topicConsumers[:index], sub.topicConsumers[index+1:]...)
  187. log.Infof("unsubscription topic %s for reqId %s, total subs %d", tpc, subId, len(sub.topicConsumers))
  188. }
  189. }
  190. }
  191. }
  192. delete(mc.subscribers, subId)
  193. }
  194. func (mc *edgexClientWrapper) SetConnectionSelector(conSelector string) {
  195. mc.conSelector = conSelector
  196. }
  197. func (mc *edgexClientWrapper) Release(c api.StreamContext) {
  198. mc.unsubscribe(c)
  199. clients.ClientRegistry.Lock.Lock()
  200. mc.DeRef(c)
  201. clients.ClientRegistry.Lock.Unlock()
  202. }
  203. func (mc *edgexClientWrapper) AddRef() {
  204. mc.refLock.Lock()
  205. defer mc.refLock.Unlock()
  206. mc.refCnt = mc.refCnt + 1
  207. conf.Log.Infof("edgex client wrapper add refence for connection selector %s total refcount %d", mc.conSelector, mc.refCnt)
  208. }
  209. func (mc *edgexClientWrapper) DeRef(c api.StreamContext) {
  210. log := c.GetLogger()
  211. mc.refLock.Lock()
  212. defer mc.refLock.Unlock()
  213. mc.refCnt = mc.refCnt - 1
  214. if mc.refCnt != 0 {
  215. conf.Log.Infof("edgex client wrapper derefence for connection selector %s total refcount %d", mc.conSelector, mc.refCnt)
  216. }
  217. if mc.refCnt == 0 {
  218. log.Infof("mqtt client wrapper reference count 0")
  219. if mc.conSelector != "" {
  220. conf.Log.Infof("remove mqtt client wrapper for connection selector %s", mc.conSelector)
  221. delete(clients.ClientRegistry.ShareClientStore, mc.conSelector)
  222. }
  223. // clean the go routine that waiting on the messages
  224. for _, sub := range mc.topicSubscriptions {
  225. sub.stop <- struct{}{}
  226. }
  227. _ = mc.cli.Disconnect()
  228. }
  229. }