mqtt_source.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. // Copyright 2021-2023 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. "path"
  18. "strconv"
  19. pahoMqtt "github.com/eclipse/paho.mqtt.golang"
  20. "github.com/lf-edge/ekuiper/internal/compressor"
  21. "github.com/lf-edge/ekuiper/internal/conf"
  22. "github.com/lf-edge/ekuiper/internal/topo/connection/clients"
  23. "github.com/lf-edge/ekuiper/internal/xsql"
  24. "github.com/lf-edge/ekuiper/pkg/api"
  25. "github.com/lf-edge/ekuiper/pkg/cast"
  26. "github.com/lf-edge/ekuiper/pkg/message"
  27. )
  28. type MQTTSource struct {
  29. qos int
  30. format string
  31. tpc string
  32. buflen int
  33. config map[string]interface{}
  34. model modelVersion
  35. cli api.MessageClient
  36. decompressor message.Decompressor
  37. }
  38. type MQTTConfig struct {
  39. Format string `json:"format"`
  40. Qos int `json:"qos"`
  41. BufferLen int `json:"bufferLength"`
  42. KubeedgeModelFile string `json:"kubeedgeModelFile"`
  43. KubeedgeVersion string `json:"kubeedgeVersion"`
  44. Decompression string `json:"decompression"`
  45. }
  46. func (ms *MQTTSource) WithSchema(_ string) *MQTTSource {
  47. return ms
  48. }
  49. func (ms *MQTTSource) Configure(topic string, props map[string]interface{}) error {
  50. cfg := &MQTTConfig{
  51. BufferLen: 1024,
  52. }
  53. err := cast.MapToStruct(props, cfg)
  54. if err != nil {
  55. return fmt.Errorf("read properties %v fail with error: %v", props, err)
  56. }
  57. if cfg.BufferLen <= 0 {
  58. cfg.BufferLen = 1024
  59. }
  60. ms.buflen = cfg.BufferLen
  61. ms.tpc = topic
  62. ms.format = cfg.Format
  63. ms.qos = cfg.Qos
  64. ms.config = props
  65. if cfg.Decompression != "" {
  66. dc, err := compressor.GetDecompressor(cfg.Decompression)
  67. if err != nil {
  68. return fmt.Errorf("get decompressor %s fail with error: %v", cfg.Decompression, err)
  69. }
  70. ms.decompressor = dc
  71. }
  72. if 0 != len(cfg.KubeedgeModelFile) {
  73. p := path.Join("sources", cfg.KubeedgeModelFile)
  74. ms.model = modelFactory(cfg.KubeedgeVersion)
  75. err = conf.LoadConfigFromPath(p, ms.model)
  76. if err != nil {
  77. return err
  78. }
  79. }
  80. cli, err := clients.GetClient("mqtt", ms.config)
  81. if err != nil {
  82. return err
  83. }
  84. ms.cli = cli
  85. return nil
  86. }
  87. func (ms *MQTTSource) Open(ctx api.StreamContext, consumer chan<- api.SourceTuple, errCh chan<- error) {
  88. err := subscribe(ms, ctx, consumer)
  89. if err != nil {
  90. errCh <- err
  91. }
  92. }
  93. // should only return fatal error
  94. func subscribe(ms *MQTTSource, ctx api.StreamContext, consumer chan<- api.SourceTuple) error {
  95. log := ctx.GetLogger()
  96. messages := make(chan interface{}, ms.buflen)
  97. topics := []api.TopicChannel{{Topic: ms.tpc, Messages: messages}}
  98. err := make(chan error, len(topics))
  99. para := map[string]interface{}{
  100. "qos": byte(ms.qos),
  101. }
  102. if e := ms.cli.Subscribe(ctx, topics, err, para); e != nil {
  103. log.Errorf("Failed to subscribe to mqtt topic %s, error %s\n", ms.tpc, e.Error())
  104. return e
  105. } else {
  106. log.Infof("Successfully subscribed to topic %s.", ms.tpc)
  107. var tuples []api.SourceTuple
  108. for {
  109. select {
  110. case <-ctx.Done():
  111. log.Infof("Exit subscription to mqtt messagebus topic %s.", ms.tpc)
  112. return nil
  113. case e1 := <-err:
  114. tuples = []api.SourceTuple{
  115. &xsql.ErrorSourceTuple{
  116. Error: fmt.Errorf("the subscription to mqtt topic %s have error %s.\n", ms.tpc, e1.Error()),
  117. },
  118. }
  119. case env, ok := <-messages:
  120. if !ok { // the source is closed
  121. log.Infof("Exit subscription to mqtt messagebus topic %s.", ms.tpc)
  122. return nil
  123. }
  124. tuples = getTuples(ctx, ms, env)
  125. }
  126. for _, t := range tuples {
  127. select {
  128. case consumer <- t:
  129. log.Debugf("send data to source node")
  130. case <-ctx.Done():
  131. return nil
  132. }
  133. }
  134. }
  135. }
  136. }
  137. func getTuples(ctx api.StreamContext, ms *MQTTSource, env interface{}) []api.SourceTuple {
  138. rcvTime := conf.GetNow()
  139. msg, ok := env.(pahoMqtt.Message)
  140. if !ok { // should never happen
  141. return []api.SourceTuple{
  142. &xsql.ErrorSourceTuple{
  143. Error: fmt.Errorf("can not convert interface data to mqtt message %v.", env),
  144. },
  145. }
  146. }
  147. payload := msg.Payload()
  148. var err error
  149. if ms.decompressor != nil {
  150. payload, err = ms.decompressor.Decompress(payload)
  151. if err != nil {
  152. return []api.SourceTuple{
  153. &xsql.ErrorSourceTuple{
  154. Error: fmt.Errorf("can not decompress mqtt message %v.", err),
  155. },
  156. }
  157. }
  158. }
  159. results, e := ctx.DecodeIntoList(payload)
  160. // The unmarshal type can only be bool, float64, string, []interface{}, map[string]interface{}, nil
  161. if e != nil {
  162. return []api.SourceTuple{
  163. &xsql.ErrorSourceTuple{
  164. Error: fmt.Errorf("Invalid data format, cannot decode %s with error %s", string(msg.Payload()), e),
  165. },
  166. }
  167. }
  168. meta := make(map[string]interface{})
  169. meta["topic"] = msg.Topic()
  170. meta["messageid"] = strconv.Itoa(int(msg.MessageID()))
  171. tuples := make([]api.SourceTuple, 0, len(results))
  172. for _, result := range results {
  173. if nil != ms.model {
  174. sliErr := ms.model.checkType(result, msg.Topic())
  175. for _, v := range sliErr {
  176. ctx.GetLogger().Errorf(v)
  177. }
  178. }
  179. tuples = append(tuples, api.NewDefaultSourceTupleWithTime(result, meta, rcvTime))
  180. }
  181. return tuples
  182. }
  183. func (ms *MQTTSource) Close(ctx api.StreamContext) error {
  184. ctx.GetLogger().Infof("Mqtt Source instance %d Done", ctx.GetInstanceId())
  185. if ms.cli != nil {
  186. clients.ReleaseClient(ctx, ms.cli)
  187. }
  188. return nil
  189. }