tdengine.go 7.6 KB

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