mqtt_source.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. package extensions
  2. import (
  3. "crypto/tls"
  4. "encoding/json"
  5. "engine/common"
  6. "engine/xsql"
  7. "engine/xstream/api"
  8. "fmt"
  9. MQTT "github.com/eclipse/paho.mqtt.golang"
  10. "github.com/go-yaml/yaml"
  11. "github.com/google/uuid"
  12. "strconv"
  13. "strings"
  14. "time"
  15. )
  16. type MQTTSource struct {
  17. srv string
  18. tpc string
  19. clientid string
  20. pVersion uint
  21. uName string
  22. password string
  23. certPath string
  24. pkeyPath string
  25. schema map[string]interface{}
  26. conn MQTT.Client
  27. }
  28. type MQTTConfig struct {
  29. Qos string `yaml:"qos"`
  30. Sharedsubscription string `yaml:"sharedSubscription"`
  31. Servers []string `yaml:"servers"`
  32. Clientid string `yaml:"clientid"`
  33. PVersion string `yaml:"protocolVersion"`
  34. Uname string `yaml:"username"`
  35. Password string `yaml:"password"`
  36. Certification string `yaml:"certificationPath"`
  37. PrivateKPath string `yaml:"privateKeyPath"`
  38. }
  39. const confName string = "mqtt_source.yaml"
  40. func NewMQTTSource(topic string, confKey string) (*MQTTSource, error) {
  41. b := common.LoadConf(confName)
  42. var cfg map[string]MQTTConfig
  43. if err := yaml.Unmarshal(b, &cfg); err != nil {
  44. return nil, err
  45. }
  46. ms := &MQTTSource{tpc: topic}
  47. if srvs := cfg[confKey].Servers; srvs != nil && len(srvs) > 1 {
  48. return nil, fmt.Errorf("It only support one server in %s section.", confKey)
  49. } else if srvs == nil {
  50. srvs = cfg["default"].Servers
  51. if srvs != nil && len(srvs) == 1 {
  52. ms.srv = srvs[0]
  53. } else {
  54. return nil, fmt.Errorf("Wrong configuration in default section!")
  55. }
  56. } else {
  57. ms.srv = srvs[0]
  58. }
  59. if cid := cfg[confKey].Clientid; cid != "" {
  60. ms.clientid = cid
  61. } else {
  62. ms.clientid = cfg["default"].Clientid
  63. }
  64. var pversion uint = 3
  65. if pv := cfg[confKey].PVersion; pv != "" {
  66. if pv == "3.1.1" {
  67. pversion = 4
  68. }
  69. } else {
  70. pv = cfg["default"].PVersion
  71. if pv == "3.1.1" {
  72. pversion = 4
  73. }
  74. }
  75. ms.pVersion = pversion
  76. if uname := cfg[confKey].Uname; uname != "" {
  77. ms.uName = strings.Trim(uname, " ")
  78. } else {
  79. ms.uName = cfg["default"].Uname
  80. }
  81. if password := cfg[confKey].Password; password != "" {
  82. ms.password = strings.Trim(password, " ")
  83. } else {
  84. ms.password = cfg["default"].Password
  85. }
  86. if cpath := cfg[confKey].Certification; cpath != "" {
  87. ms.certPath = cpath
  88. } else {
  89. ms.certPath = cfg["default"].Certification
  90. }
  91. if pkpath := cfg[confKey].PrivateKPath; pkpath != "" {
  92. ms.pkeyPath = pkpath
  93. } else {
  94. ms.pkeyPath = cfg["default"].PrivateKPath
  95. }
  96. return ms, nil
  97. }
  98. func (ms *MQTTSource) WithSchema(schema string) *MQTTSource {
  99. return ms
  100. }
  101. func (ms *MQTTSource) Open(ctx api.StreamContext, consume api.ConsumeFunc) error {
  102. log := ctx.GetLogger()
  103. opts := MQTT.NewClientOptions().AddBroker(ms.srv).SetProtocolVersion(ms.pVersion)
  104. if ms.clientid == "" {
  105. if uuid, err := uuid.NewUUID(); err != nil {
  106. return fmt.Errorf("failed to get uuid, the error is %s", err)
  107. } else {
  108. opts.SetClientID(uuid.String())
  109. }
  110. } else {
  111. opts.SetClientID(ms.clientid)
  112. }
  113. if ms.certPath != "" || ms.pkeyPath != "" {
  114. log.Printf("Connect MQTT broker with certification and keys.")
  115. if cp, err := common.ProcessPath(ms.certPath); err == nil {
  116. log.Printf("The certification file is %s.", cp)
  117. if kp, err1 := common.ProcessPath(ms.pkeyPath); err1 == nil {
  118. log.Printf("The private key file is %s.", kp)
  119. if cer, err2 := tls.LoadX509KeyPair(cp, kp); err2 != nil {
  120. return err2
  121. } else {
  122. opts.SetTLSConfig(&tls.Config{Certificates: []tls.Certificate{cer}})
  123. }
  124. } else {
  125. return err1
  126. }
  127. } else {
  128. return err
  129. }
  130. } else {
  131. log.Printf("Connect MQTT broker with username and password.")
  132. if ms.uName != "" {
  133. opts = opts.SetUsername(ms.uName)
  134. }
  135. if ms.password != "" {
  136. opts = opts.SetPassword(ms.password)
  137. }
  138. }
  139. h := func(client MQTT.Client, msg MQTT.Message) {
  140. log.Infof("received %s", msg.Payload())
  141. result := make(map[string]interface{})
  142. //The unmarshal type can only be bool, float64, string, []interface{}, map[string]interface{}, nil
  143. if e := json.Unmarshal(msg.Payload(), &result); e != nil {
  144. log.Errorf("Invalid data format, cannot convert %s into JSON with error %s", string(msg.Payload()), e)
  145. return
  146. }
  147. //Convert the keys to lowercase
  148. result = xsql.LowercaseKeyMap(result)
  149. meta := make(map[string]interface{})
  150. meta[xsql.INTERNAL_MQTT_TOPIC_KEY] = msg.Topic()
  151. meta[xsql.INTERNAL_MQTT_MSG_ID_KEY] = strconv.Itoa(int(msg.MessageID()))
  152. tuple := &xsql.Tuple{Emitter: ms.tpc, Message:result, Timestamp: common.TimeToUnixMilli(time.Now()), Metadata:meta}
  153. consume(tuple)
  154. }
  155. //TODO error listener?
  156. opts.SetDefaultPublishHandler(h)
  157. c := MQTT.NewClient(opts)
  158. if token := c.Connect(); token.Wait() && token.Error() != nil {
  159. return fmt.Errorf("found error when connecting to %s: %s", ms.srv, token.Error())
  160. }
  161. log.Printf("The connection to server %s was established successfully", ms.srv)
  162. ms.conn = c
  163. if token := c.Subscribe(ms.tpc, 0, nil); token.Wait() && token.Error() != nil {
  164. return fmt.Errorf("Found error: %s", token.Error())
  165. }
  166. log.Printf("Successfully subscribe to topic %s", ms.tpc)
  167. return nil
  168. }
  169. func (ms *MQTTSource) Close(ctx api.StreamContext) error{
  170. ctx.GetLogger().Println("Mqtt Source Done")
  171. if ms.conn != nil && ms.conn.IsConnected() {
  172. ms.conn.Disconnect(5000)
  173. }
  174. return nil
  175. }