mqtt_source.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. package extensions
  2. import (
  3. "crypto/tls"
  4. "encoding/json"
  5. "fmt"
  6. MQTT "github.com/eclipse/paho.mqtt.golang"
  7. "github.com/emqx/kuiper/common"
  8. "github.com/emqx/kuiper/xstream/api"
  9. "github.com/google/uuid"
  10. "strconv"
  11. "strings"
  12. )
  13. type MQTTSource struct {
  14. srv string
  15. tpc string
  16. clientid string
  17. pVersion uint
  18. uName string
  19. password string
  20. certPath string
  21. pkeyPath string
  22. schema map[string]interface{}
  23. conn MQTT.Client
  24. }
  25. type MQTTConfig struct {
  26. Qos int `json:"qos"`
  27. Sharedsubscription bool `json:"sharedSubscription"`
  28. Servers []string `json:"servers"`
  29. Clientid string `json:"clientid"`
  30. PVersion string `json:"protocolVersion"`
  31. Uname string `json:"username"`
  32. Password string `json:"password"`
  33. Certification string `json:"certificationPath"`
  34. PrivateKPath string `json:"privateKeyPath"`
  35. }
  36. func (ms *MQTTSource) WithSchema(schema string) *MQTTSource {
  37. return ms
  38. }
  39. func (ms *MQTTSource) Configure(topic string, props map[string]interface{}) error {
  40. cfg := &MQTTConfig{}
  41. err := common.MapToStruct(props, cfg)
  42. if err != nil {
  43. return fmt.Errorf("read properties %v fail with error: %v", props, err)
  44. }
  45. ms.tpc = topic
  46. if srvs := cfg.Servers; srvs != nil && len(srvs) > 0 {
  47. ms.srv = srvs[0]
  48. } else {
  49. return fmt.Errorf("missing server property")
  50. }
  51. ms.clientid = cfg.Clientid
  52. ms.pVersion = 3
  53. if cfg.PVersion == "3.1.1" {
  54. ms.pVersion = 4
  55. }
  56. ms.uName = cfg.Uname
  57. ms.password = strings.Trim(cfg.Password, " ")
  58. ms.certPath = cfg.Certification
  59. ms.pkeyPath = cfg.PrivateKPath
  60. return nil
  61. }
  62. func (ms *MQTTSource) Open(ctx api.StreamContext, consumer chan<- api.SourceTuple, errCh chan<- error) {
  63. log := ctx.GetLogger()
  64. opts := MQTT.NewClientOptions().AddBroker(ms.srv).SetProtocolVersion(ms.pVersion)
  65. if ms.clientid == "" {
  66. if uuid, err := uuid.NewUUID(); err != nil {
  67. errCh <- fmt.Errorf("failed to get uuid, the error is %s", err)
  68. } else {
  69. ms.clientid = uuid.String()
  70. opts.SetClientID(uuid.String())
  71. }
  72. } else {
  73. opts.SetClientID(ms.clientid)
  74. }
  75. if ms.certPath != "" || ms.pkeyPath != "" {
  76. log.Infof("Connect MQTT broker with certification and keys.")
  77. if cp, err := common.ProcessPath(ms.certPath); err == nil {
  78. log.Infof("The certification file is %s.", cp)
  79. if kp, err1 := common.ProcessPath(ms.pkeyPath); err1 == nil {
  80. log.Infof("The private key file is %s.", kp)
  81. if cer, err2 := tls.LoadX509KeyPair(cp, kp); err2 != nil {
  82. errCh <- err2
  83. } else {
  84. opts.SetTLSConfig(&tls.Config{Certificates: []tls.Certificate{cer}})
  85. }
  86. } else {
  87. errCh <- err1
  88. }
  89. } else {
  90. errCh <- err
  91. }
  92. } else {
  93. log.Infof("Connect MQTT broker with username and password.")
  94. if ms.uName != "" {
  95. opts = opts.SetUsername(ms.uName)
  96. } else {
  97. log.Infof("The username is empty.")
  98. }
  99. if ms.password != "" {
  100. opts = opts.SetPassword(ms.password)
  101. } else {
  102. log.Infof("The password is empty.")
  103. }
  104. }
  105. opts.SetAutoReconnect(true)
  106. var reconn = false
  107. opts.SetConnectionLostHandler(func(client MQTT.Client, e error) {
  108. log.Errorf("The connection %s is disconnected due to error %s, will try to re-connect later.", ms.srv+": "+ms.clientid, e)
  109. reconn = true
  110. subscribe(ms.tpc, client, ctx, consumer)
  111. })
  112. opts.SetOnConnectHandler(func(client MQTT.Client) {
  113. if reconn {
  114. log.Infof("The connection is %s re-established successfully.", ms.srv+": "+ms.clientid)
  115. }
  116. })
  117. c := MQTT.NewClient(opts)
  118. if token := c.Connect(); token.Wait() && token.Error() != nil {
  119. errCh <- fmt.Errorf("found error when connecting to %s: %s", ms.srv, token.Error())
  120. }
  121. log.Infof("The connection to server %s was established successfully", ms.srv)
  122. ms.conn = c
  123. subscribe(ms.tpc, c, ctx, consumer)
  124. log.Infof("Successfully subscribe to topic %s", ms.srv+": "+ms.clientid)
  125. }
  126. func subscribe(topic string, client MQTT.Client, ctx api.StreamContext, consumer chan<- api.SourceTuple) {
  127. log := ctx.GetLogger()
  128. h := func(client MQTT.Client, msg MQTT.Message) {
  129. log.Debugf("instance %d received %s", ctx.GetInstanceId(), msg.Payload())
  130. result := make(map[string]interface{})
  131. //The unmarshal type can only be bool, float64, string, []interface{}, map[string]interface{}, nil
  132. if e := json.Unmarshal(msg.Payload(), &result); e != nil {
  133. log.Errorf("Invalid data format, cannot convert %s into JSON with error %s", string(msg.Payload()), e)
  134. return
  135. }
  136. meta := make(map[string]interface{})
  137. meta["topic"] = msg.Topic()
  138. meta["messageid"] = strconv.Itoa(int(msg.MessageID()))
  139. select {
  140. case consumer <- api.NewDefaultSourceTuple(result, meta):
  141. log.Debugf("send data to source node")
  142. case <-ctx.Done():
  143. return
  144. }
  145. }
  146. if token := client.Subscribe(topic, 0, h); token.Wait() && token.Error() != nil {
  147. log.Errorf("Found error: %s", token.Error())
  148. } else {
  149. log.Infof("Successfully subscribe to topic %s", topic)
  150. }
  151. }
  152. func (ms *MQTTSource) Close(ctx api.StreamContext) error {
  153. ctx.GetLogger().Infof("Mqtt Source instance %d Done", ctx.GetInstanceId())
  154. if ms.conn != nil && ms.conn.IsConnected() {
  155. ms.conn.Disconnect(5000)
  156. }
  157. return nil
  158. }