tdengine.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. // Copyright 2021-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. package main
  15. import (
  16. "database/sql"
  17. "encoding/json"
  18. "fmt"
  19. "github.com/lf-edge/ekuiper/internal/conf"
  20. "github.com/lf-edge/ekuiper/pkg/api"
  21. "github.com/lf-edge/ekuiper/pkg/cast"
  22. _ "github.com/taosdata/driver-go/v2/taosSql"
  23. "reflect"
  24. "strings"
  25. )
  26. type (
  27. taosConfig struct {
  28. ProvideTs bool `json:"provideTs"`
  29. Port int `json:"port"`
  30. Ip string `json:"ip"` // To be deprecated
  31. Host string `json:"host"`
  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. STable string `json:"sTable"`
  39. TagFields []string `json:"tagFields"`
  40. DataTemplate string `json:"dataTemplate"`
  41. TableDataField string `json:"tableDataField"`
  42. }
  43. taosSink struct {
  44. conf *taosConfig
  45. url string
  46. db *sql.DB
  47. }
  48. )
  49. func (t *taosConfig) delTsField() {
  50. var auxFields []string
  51. for _, v := range t.Fields {
  52. if v != t.TsFieldName {
  53. auxFields = append(auxFields, v)
  54. }
  55. }
  56. t.Fields = auxFields
  57. }
  58. func (t *taosConfig) buildSql(ctx api.StreamContext, mapData map[string]interface{}) (string, error) {
  59. if 0 == len(mapData) {
  60. return "", fmt.Errorf("data is empty.")
  61. }
  62. logger := ctx.GetLogger()
  63. var (
  64. table, sTable string
  65. keys, vals, tags []string
  66. err error
  67. )
  68. table, err = ctx.ParseTemplate(t.Table, mapData)
  69. if err != nil {
  70. logger.Errorf("parse template for table %s error: %v", t.Table, err)
  71. return "", err
  72. }
  73. sTable, err = ctx.ParseTemplate(t.STable, mapData)
  74. if err != nil {
  75. logger.Errorf("parse template for sTable %s error: %v", t.STable, err)
  76. return "", err
  77. }
  78. if t.ProvideTs {
  79. if v, ok := mapData[t.TsFieldName]; !ok {
  80. return "", fmt.Errorf("Timestamp field not found : %s.", t.TsFieldName)
  81. } else {
  82. keys = append(keys, t.TsFieldName)
  83. vals = append(vals, fmt.Sprintf(`"%v"`, v))
  84. }
  85. } else {
  86. vals = append(vals, "now")
  87. keys = append(keys, t.TsFieldName)
  88. }
  89. if len(t.Fields) != 0 {
  90. for _, k := range t.Fields {
  91. if k == t.TsFieldName {
  92. continue
  93. }
  94. if v, ok := mapData[k]; ok {
  95. keys = append(keys, k)
  96. if reflect.String == reflect.TypeOf(v).Kind() {
  97. vals = append(vals, fmt.Sprintf(`"%v"`, v))
  98. } else {
  99. vals = append(vals, fmt.Sprintf(`%v`, v))
  100. }
  101. } else {
  102. logger.Warnln("not found field:", k)
  103. }
  104. }
  105. } else {
  106. for k, v := range mapData {
  107. if k == t.TsFieldName {
  108. continue
  109. }
  110. keys = append(keys, k)
  111. if reflect.String == reflect.TypeOf(v).Kind() {
  112. vals = append(vals, fmt.Sprintf(`"%v"`, v))
  113. } else {
  114. vals = append(vals, fmt.Sprintf(`%v`, v))
  115. }
  116. }
  117. }
  118. if len(t.TagFields) > 0 {
  119. for _, v := range t.TagFields {
  120. switch mapData[v].(type) {
  121. case string:
  122. tags = append(tags, fmt.Sprintf(`"%s"`, mapData[v]))
  123. default:
  124. tags = append(tags, fmt.Sprintf(`%v`, mapData[v]))
  125. }
  126. }
  127. }
  128. sqlStr := fmt.Sprintf("%s (%s)", table, strings.Join(keys, ","))
  129. if sTable != "" {
  130. sqlStr += " using " + sTable
  131. }
  132. if len(tags) != 0 {
  133. sqlStr += " tags (" + strings.Join(tags, ",") + ")"
  134. }
  135. sqlStr += " values (" + strings.Join(vals, ",") + ")"
  136. return sqlStr, nil
  137. }
  138. func (m *taosSink) Configure(props map[string]interface{}) error {
  139. cfg := &taosConfig{
  140. User: "root",
  141. Password: "taosdata",
  142. }
  143. err := cast.MapToStruct(props, cfg)
  144. if err != nil {
  145. return fmt.Errorf("read properties %v fail with error: %v", props, err)
  146. }
  147. if cfg.Ip != "" {
  148. conf.Log.Warnf("Deprecated: Tdengine sink ip property is deprecated, use host instead.")
  149. if cfg.Host == "" {
  150. cfg.Host = cfg.Ip
  151. }
  152. }
  153. if cfg.Host == "" {
  154. cfg.Host = "localhost"
  155. }
  156. if cfg.User == "" {
  157. return fmt.Errorf("propert user is required.")
  158. }
  159. if cfg.Password == "" {
  160. return fmt.Errorf("propert password is required.")
  161. }
  162. if cfg.Database == "" {
  163. return fmt.Errorf("property database is required")
  164. }
  165. if cfg.Table == "" {
  166. return fmt.Errorf("property table is required")
  167. }
  168. if cfg.TsFieldName == "" {
  169. return fmt.Errorf("property TsFieldName is required")
  170. }
  171. if cfg.STable != "" && len(cfg.TagFields) == 0 {
  172. return fmt.Errorf("property tagFields is required when sTable is set")
  173. }
  174. m.url = fmt.Sprintf(`%s:%s@tcp(%s:%d)/%s`, cfg.User, cfg.Password, cfg.Host, cfg.Port, cfg.Database)
  175. m.conf = cfg
  176. return nil
  177. }
  178. func (m *taosSink) Open(ctx api.StreamContext) (err error) {
  179. ctx.GetLogger().Debug("Opening tdengine sink")
  180. m.db, err = sql.Open("taosSql", m.url)
  181. return err
  182. }
  183. func (m *taosSink) Collect(ctx api.StreamContext, item interface{}) error {
  184. ctx.GetLogger().Debugf("tdengine sink receive %s", item)
  185. if m.conf.DataTemplate != "" {
  186. jsonBytes, _, err := ctx.TransformOutput(item)
  187. if err != nil {
  188. return err
  189. }
  190. tm := make(map[string]interface{})
  191. err = json.Unmarshal(jsonBytes, &tm)
  192. if err != nil {
  193. return fmt.Errorf("fail to decode data %s after applying dataTemplate for error %v", string(jsonBytes), err)
  194. }
  195. item = tm
  196. }
  197. if m.conf.TableDataField != "" {
  198. mapData, ok := item.(map[string]interface{})
  199. if ok {
  200. item = mapData[m.conf.TableDataField]
  201. }
  202. }
  203. switch v := item.(type) {
  204. case []map[string]interface{}:
  205. strSli := make([]string, len(v))
  206. for _, mapData := range v {
  207. str, err := m.conf.buildSql(ctx, mapData)
  208. if err != nil {
  209. ctx.GetLogger().Errorf("tdengine sink build sql error %v for data", err, mapData)
  210. return err
  211. }
  212. strSli = append(strSli, str)
  213. }
  214. if len(strSli) > 0 {
  215. strBatch := strings.Join(strSli, " ")
  216. return m.writeToDB(ctx, &strBatch)
  217. }
  218. return nil
  219. case map[string]interface{}:
  220. strBatch, err := m.conf.buildSql(ctx, v)
  221. if err != nil {
  222. ctx.GetLogger().Errorf("tdengine sink build sql error %v for data", err, v)
  223. return err
  224. }
  225. return m.writeToDB(ctx, &strBatch)
  226. case []interface{}:
  227. strSli := make([]string, len(v))
  228. for _, data := range v {
  229. mapData, ok := data.(map[string]interface{})
  230. if !ok {
  231. ctx.GetLogger().Errorf("unsupported type: %T", data)
  232. return fmt.Errorf("unsupported type: %T", data)
  233. }
  234. str, err := m.conf.buildSql(ctx, mapData)
  235. if err != nil {
  236. ctx.GetLogger().Errorf("tdengine sink build sql error %v for data", err, mapData)
  237. return err
  238. }
  239. strSli = append(strSli, str)
  240. }
  241. if len(strSli) > 0 {
  242. strBatch := strings.Join(strSli, " ")
  243. return m.writeToDB(ctx, &strBatch)
  244. }
  245. return nil
  246. default: // never happen
  247. return fmt.Errorf("unsupported type: %T", item)
  248. }
  249. }
  250. func (m *taosSink) writeToDB(ctx api.StreamContext, SqlVal *string) error {
  251. finalSql := "INSERT INTO " + *SqlVal + ";"
  252. ctx.GetLogger().Debugf(finalSql)
  253. rows, err := m.db.Query(finalSql)
  254. if err != nil {
  255. return err
  256. }
  257. rows.Close()
  258. return nil
  259. }
  260. func (m *taosSink) Close(ctx api.StreamContext) error {
  261. if m.db != nil {
  262. return m.db.Close()
  263. }
  264. return nil
  265. }
  266. func Tdengine() api.Sink {
  267. return &taosSink{}
  268. }