tdengine.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. // Copyright 2021 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. // +build plugins
  15. package main
  16. import (
  17. "database/sql"
  18. "encoding/json"
  19. "fmt"
  20. "github.com/lf-edge/ekuiper/internal/conf"
  21. "github.com/lf-edge/ekuiper/pkg/api"
  22. "github.com/lf-edge/ekuiper/pkg/cast"
  23. _ "github.com/taosdata/driver-go/v2/taosSql"
  24. "reflect"
  25. "strings"
  26. )
  27. type (
  28. taosConfig struct {
  29. ProvideTs bool `json:"provideTs"`
  30. Port int `json:"port"`
  31. Ip string `json:"ip"`
  32. User string `json:"user"`
  33. Password string `json:"password"`
  34. Database string `json:"database"`
  35. Table string `json:"table"`
  36. TsFieldName string `json:"tsFieldName"`
  37. Fields []string `json:"fields"`
  38. }
  39. taosSink struct {
  40. conf *taosConfig
  41. db *sql.DB
  42. }
  43. )
  44. func (this *taosConfig) delTsField() {
  45. var auxFields []string
  46. for _, v := range this.Fields {
  47. if v != this.TsFieldName {
  48. auxFields = append(auxFields, v)
  49. }
  50. }
  51. this.Fields = auxFields
  52. }
  53. func (this *taosConfig) buildSql(ctx api.StreamContext, mapData map[string]interface{}) (string, error) {
  54. if 0 == len(mapData) {
  55. return "", fmt.Errorf("data is empty.")
  56. }
  57. if 0 == len(this.TsFieldName) {
  58. return "", fmt.Errorf("tsFieldName is empty.")
  59. }
  60. logger := ctx.GetLogger()
  61. var keys, vals []string
  62. if this.ProvideTs {
  63. if v, ok := mapData[this.TsFieldName]; !ok {
  64. return "", fmt.Errorf("Timestamp field not found : %s.", this.TsFieldName)
  65. } else {
  66. keys = append(keys, this.TsFieldName)
  67. vals = append(vals, fmt.Sprintf(`"%v"`, v))
  68. delete(mapData, this.TsFieldName)
  69. this.delTsField()
  70. }
  71. } else {
  72. vals = append(vals, "now")
  73. keys = append(keys, this.TsFieldName)
  74. }
  75. for _, k := range this.Fields {
  76. if v, ok := mapData[k]; ok {
  77. keys = append(keys, k)
  78. if reflect.String == reflect.TypeOf(v).Kind() {
  79. vals = append(vals, fmt.Sprintf(`"%v"`, v))
  80. } else {
  81. vals = append(vals, fmt.Sprintf(`%v`, v))
  82. }
  83. } else {
  84. logger.Warnln("not found field:", k)
  85. }
  86. }
  87. if 0 != len(this.Fields) {
  88. if len(this.Fields) < len(mapData) {
  89. logger.Warnln("some of values will be ignored.")
  90. }
  91. return fmt.Sprintf(`INSERT INTO %s (%s)VALUES(%s);`, this.Table, strings.Join(keys, `,`), strings.Join(vals, `,`)), nil
  92. }
  93. for k, v := range mapData {
  94. keys = append(keys, k)
  95. if reflect.String == reflect.TypeOf(v).Kind() {
  96. vals = append(vals, fmt.Sprintf(`"%v"`, v))
  97. } else {
  98. vals = append(vals, fmt.Sprintf(`%v`, v))
  99. }
  100. }
  101. if 0 != len(keys) {
  102. return fmt.Sprintf(`INSERT INTO %s (%s)VALUES(%s);`, this.Table, strings.Join(keys, `,`), strings.Join(vals, `,`)), nil
  103. }
  104. return "", nil
  105. }
  106. func (m *taosSink) Configure(props map[string]interface{}) error {
  107. cfg := &taosConfig{}
  108. err := cast.MapToStruct(props, cfg)
  109. if err != nil {
  110. return fmt.Errorf("read properties %v fail with error: %v", props, err)
  111. }
  112. if cfg.Ip == "" {
  113. cfg.Ip = "127.0.0.1"
  114. conf.Log.Infof("Not find IP conf, will use default value '127.0.0.1'.")
  115. }
  116. if cfg.User == "" {
  117. cfg.User = "root"
  118. conf.Log.Infof("Not find user conf, will use default value 'root'.")
  119. }
  120. if cfg.Password == "" {
  121. cfg.Password = "taosdata"
  122. conf.Log.Infof("Not find password conf, will use default value 'taosdata'.")
  123. }
  124. if cfg.Database == "" {
  125. return fmt.Errorf("property database is required")
  126. }
  127. if cfg.Table == "" {
  128. return fmt.Errorf("property table is required")
  129. }
  130. if cfg.TsFieldName == "" {
  131. return fmt.Errorf("property TsFieldName is required")
  132. }
  133. m.conf = cfg
  134. return nil
  135. }
  136. func (m *taosSink) Open(ctx api.StreamContext) (err error) {
  137. logger := ctx.GetLogger()
  138. logger.Debug("Opening tdengine sink")
  139. url := fmt.Sprintf(`%s:%s@tcp(%s:%d)/%s`, m.conf.User, m.conf.Password, m.conf.Ip, m.conf.Port, m.conf.Database)
  140. m.db, err = sql.Open("taosSql", url)
  141. return err
  142. }
  143. func (m *taosSink) Collect(ctx api.StreamContext, item interface{}) error {
  144. logger := ctx.GetLogger()
  145. data, ok := item.([]byte)
  146. if !ok {
  147. logger.Debug("tdengine sink receive non string data")
  148. return nil
  149. }
  150. logger.Debugf("tdengine sink receive %s", item)
  151. var sliData []map[string]interface{}
  152. err := json.Unmarshal(data, &sliData)
  153. if nil != err {
  154. return err
  155. }
  156. for _, mapData := range sliData {
  157. sql, err := m.conf.buildSql(ctx, mapData)
  158. if nil != err {
  159. return err
  160. }
  161. logger.Debugf(sql)
  162. rows, err := m.db.Query(sql)
  163. if err != nil {
  164. return err
  165. }
  166. rows.Close()
  167. }
  168. return nil
  169. }
  170. func (m *taosSink) Close(ctx api.StreamContext) error {
  171. if m.db != nil {
  172. return m.db.Close()
  173. }
  174. return nil
  175. }
  176. func Tdengine() api.Sink {
  177. return &taosSink{}
  178. }