sink_node.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. // Copyright 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 node
  15. import (
  16. "fmt"
  17. "github.com/lf-edge/ekuiper/internal/binder/io"
  18. "github.com/lf-edge/ekuiper/internal/conf"
  19. "github.com/lf-edge/ekuiper/internal/topo/context"
  20. "github.com/lf-edge/ekuiper/internal/topo/node/cache"
  21. "github.com/lf-edge/ekuiper/internal/topo/node/metric"
  22. "github.com/lf-edge/ekuiper/internal/topo/transform"
  23. "github.com/lf-edge/ekuiper/internal/xsql"
  24. "github.com/lf-edge/ekuiper/pkg/api"
  25. "github.com/lf-edge/ekuiper/pkg/cast"
  26. "github.com/lf-edge/ekuiper/pkg/errorx"
  27. "github.com/lf-edge/ekuiper/pkg/infra"
  28. "github.com/lf-edge/ekuiper/pkg/message"
  29. "strings"
  30. "sync"
  31. )
  32. type SinkConf struct {
  33. Concurrency int `json:"concurrency"`
  34. RunAsync bool `json:"runAsync"`
  35. Omitempty bool `json:"omitIfEmpty"`
  36. SendSingle bool `json:"sendSingle"`
  37. DataTemplate string `json:"dataTemplate"`
  38. Format string `json:"format"`
  39. SchemaId string `json:"schemaId"`
  40. BufferLength int `json:"bufferLength"`
  41. conf.SinkConf
  42. }
  43. type SinkNode struct {
  44. *defaultSinkNode
  45. //static
  46. sinkType string
  47. mutex sync.RWMutex
  48. //configs (also static for sinks)
  49. options map[string]interface{}
  50. isMock bool
  51. //states varies after restart
  52. sinks []api.Sink
  53. }
  54. func NewSinkNode(name string, sinkType string, props map[string]interface{}) *SinkNode {
  55. bufferLength := 1024
  56. if c, ok := props["bufferLength"]; ok {
  57. if t, err := cast.ToInt(c, cast.STRICT); err != nil || t <= 0 {
  58. //invalid property bufferLength
  59. } else {
  60. bufferLength = t
  61. }
  62. }
  63. return &SinkNode{
  64. defaultSinkNode: &defaultSinkNode{
  65. input: make(chan interface{}, bufferLength),
  66. defaultNode: &defaultNode{
  67. name: name,
  68. concurrency: 1,
  69. ctx: nil,
  70. },
  71. },
  72. sinkType: sinkType,
  73. options: props,
  74. }
  75. }
  76. // NewSinkNodeWithSink Only for mock source, do not use it in production
  77. func NewSinkNodeWithSink(name string, sink api.Sink, props map[string]interface{}) *SinkNode {
  78. return &SinkNode{
  79. defaultSinkNode: &defaultSinkNode{
  80. input: make(chan interface{}, 1024),
  81. defaultNode: &defaultNode{
  82. name: name,
  83. concurrency: 1,
  84. ctx: nil,
  85. },
  86. },
  87. sinks: []api.Sink{sink},
  88. options: props,
  89. isMock: true,
  90. }
  91. }
  92. func (m *SinkNode) Open(ctx api.StreamContext, result chan<- error) {
  93. m.ctx = ctx
  94. logger := ctx.GetLogger()
  95. logger.Debugf("open sink node %s", m.name)
  96. go func() {
  97. err := infra.SafeRun(func() error {
  98. sconf, err := m.parseConf(logger)
  99. if err != nil {
  100. return err
  101. }
  102. tf, err := transform.GenTransform(sconf.DataTemplate, sconf.Format, sconf.SchemaId)
  103. if err != nil {
  104. msg := fmt.Sprintf("property dataTemplate %v is invalid: %v", sconf.DataTemplate, err)
  105. logger.Warnf(msg)
  106. return fmt.Errorf(msg)
  107. }
  108. ctx = context.WithValue(ctx.(*context.DefaultContext), context.TransKey, tf)
  109. m.reset()
  110. logger.Infof("open sink node %d instances", m.concurrency)
  111. for i := 0; i < m.concurrency; i++ { // workers
  112. go func(instance int) {
  113. panicOrError := infra.SafeRun(func() error {
  114. var (
  115. sink api.Sink
  116. err error
  117. )
  118. if !m.isMock {
  119. logger.Debugf("Trying to get sink for rule %s with options %v\n", ctx.GetRuleId(), m.options)
  120. sink, err = getSink(m.sinkType, m.options)
  121. if err != nil {
  122. return err
  123. }
  124. logger.Debugf("Successfully get the sink %s", m.sinkType)
  125. m.mutex.Lock()
  126. m.sinks = append(m.sinks, sink)
  127. m.mutex.Unlock()
  128. logger.Debugf("Now is to open sink for rule %s.\n", ctx.GetRuleId())
  129. if err := sink.Open(ctx); err != nil {
  130. return err
  131. }
  132. logger.Debugf("Successfully open sink for rule %s.\n", ctx.GetRuleId())
  133. } else {
  134. sink = m.sinks[instance]
  135. }
  136. stats, err := metric.NewStatManager(ctx, "sink")
  137. if err != nil {
  138. return err
  139. }
  140. m.mutex.Lock()
  141. m.statManagers = append(m.statManagers, stats)
  142. m.mutex.Unlock()
  143. if !sconf.EnableCache {
  144. for {
  145. select {
  146. case data := <-m.input:
  147. if temp, processed := m.preprocess(data); processed {
  148. break
  149. } else {
  150. data = temp
  151. }
  152. stats.SetBufferLength(int64(len(m.input)))
  153. stats.IncTotalRecordsIn()
  154. if sconf.RunAsync {
  155. go func() {
  156. p := infra.SafeRun(func() error {
  157. _ = doCollect(ctx, sink, data, stats, sconf)
  158. return nil
  159. })
  160. if p != nil {
  161. infra.DrainError(ctx, p, result)
  162. }
  163. }()
  164. } else {
  165. _ = doCollect(ctx, sink, data, stats, sconf)
  166. }
  167. case <-ctx.Done():
  168. logger.Infof("sink node %s instance %d done", m.name, instance)
  169. if err := sink.Close(ctx); err != nil {
  170. logger.Warnf("close sink node %s instance %d fails: %v", m.name, instance, err)
  171. }
  172. return nil
  173. }
  174. }
  175. } else {
  176. logger.Infof("Creating sink cache")
  177. if sconf.RunAsync { // async mode, the ack must have an id
  178. // is not supported and validated in the configure, should not go here
  179. return fmt.Errorf("async mode is not supported for cache sink")
  180. } else { // sync mode, the ack is already in order
  181. dataCh := make(chan []map[string]interface{}, sconf.BufferLength)
  182. c := cache.NewSyncCache(ctx, dataCh, result, stats, &sconf.SinkConf, sconf.BufferLength)
  183. for {
  184. select {
  185. case data := <-m.input:
  186. if temp, processed := m.preprocess(data); processed {
  187. break
  188. } else {
  189. data = temp
  190. }
  191. stats.IncTotalRecordsIn()
  192. outs := itemToMap(data)
  193. if sconf.Omitempty && (data == nil || len(outs) == 0) {
  194. ctx.GetLogger().Debugf("receive empty in sink")
  195. return nil
  196. }
  197. select {
  198. case dataCh <- outs:
  199. case <-ctx.Done():
  200. }
  201. case data := <-c.Out:
  202. stats.ProcessTimeStart()
  203. ack := true
  204. err := doCollectMaps(ctx, sink, sconf, data, stats)
  205. // Only recoverable error should be cached
  206. if err != nil {
  207. if strings.HasPrefix(err.Error(), errorx.IOErr) { // do not log to prevent a lot of logs!
  208. ack = false
  209. } else {
  210. ctx.GetLogger().Warnf("sink node %s instance %d publish %s error: %v", ctx.GetOpId(), ctx.GetInstanceId(), data, err)
  211. }
  212. } else {
  213. ctx.GetLogger().Debugf("sent data to MQTT: %v", data)
  214. }
  215. select {
  216. case c.Ack <- ack:
  217. case <-ctx.Done():
  218. }
  219. stats.ProcessTimeEnd()
  220. case <-ctx.Done():
  221. logger.Infof("sink node %s instance %d done", m.name, instance)
  222. if err := sink.Close(ctx); err != nil {
  223. logger.Warnf("close sink node %s instance %d fails: %v", m.name, instance, err)
  224. }
  225. return nil
  226. }
  227. }
  228. }
  229. }
  230. })
  231. if panicOrError != nil {
  232. infra.DrainError(ctx, panicOrError, result)
  233. }
  234. }(i)
  235. }
  236. return nil
  237. })
  238. if err != nil {
  239. infra.DrainError(ctx, err, result)
  240. }
  241. }()
  242. }
  243. func (m *SinkNode) parseConf(logger api.Logger) (*SinkConf, error) {
  244. sconf := &SinkConf{
  245. Concurrency: 1,
  246. RunAsync: false,
  247. Omitempty: false,
  248. SendSingle: false,
  249. DataTemplate: "",
  250. SinkConf: *conf.Config.Sink,
  251. BufferLength: 1024,
  252. }
  253. err := cast.MapToStruct(m.options, sconf)
  254. if err != nil {
  255. return nil, fmt.Errorf("read properties %v fail with error: %v", m.options, err)
  256. }
  257. if sconf.Concurrency <= 0 {
  258. logger.Warnf("invalid type for concurrency property, should be positive integer but found %t", sconf.Concurrency)
  259. sconf.Concurrency = 1
  260. }
  261. m.concurrency = sconf.Concurrency
  262. if sconf.Format == "" {
  263. sconf.Format = "json"
  264. } else if sconf.Format != message.FormatJson && sconf.Format != message.FormatProtobuf {
  265. logger.Warnf("invalid type for format property, should be json or protobuf but found %s", sconf.Format)
  266. sconf.Format = "json"
  267. }
  268. err = cast.MapToStruct(m.options, &sconf.SinkConf)
  269. if err != nil {
  270. return nil, fmt.Errorf("read properties %v to cache conf fail with error: %v", m.options, err)
  271. }
  272. if sconf.SinkConf.EnableCache && sconf.RunAsync {
  273. return nil, fmt.Errorf("cache is not supported for async sink, do not use enableCache and runAsync properties together")
  274. }
  275. err = sconf.SinkConf.Validate()
  276. if err != nil {
  277. return nil, fmt.Errorf("invalid cache properties: %v", err)
  278. }
  279. return sconf, err
  280. }
  281. func (m *SinkNode) reset() {
  282. if !m.isMock {
  283. m.sinks = nil
  284. }
  285. m.statManagers = nil
  286. }
  287. func doCollect(ctx api.StreamContext, sink api.Sink, item interface{}, stats metric.StatManager, sconf *SinkConf) error {
  288. stats.ProcessTimeStart()
  289. defer stats.ProcessTimeEnd()
  290. outs := itemToMap(item)
  291. if sconf.Omitempty && (item == nil || len(outs) == 0) {
  292. ctx.GetLogger().Debugf("receive empty in sink")
  293. return nil
  294. }
  295. return doCollectMaps(ctx, sink, sconf, outs, stats)
  296. }
  297. func doCollectMaps(ctx api.StreamContext, sink api.Sink, sconf *SinkConf, outs []map[string]interface{}, stats metric.StatManager) error {
  298. if !sconf.SendSingle {
  299. return doCollectData(ctx, sink, outs, stats)
  300. } else {
  301. var err error
  302. for _, d := range outs {
  303. if sconf.Omitempty && (d == nil || len(d) == 0) {
  304. ctx.GetLogger().Debugf("receive empty in sink")
  305. continue
  306. }
  307. newErr := doCollectData(ctx, sink, d, stats)
  308. if newErr != nil {
  309. err = newErr
  310. }
  311. }
  312. return err
  313. }
  314. }
  315. func itemToMap(item interface{}) []map[string]interface{} {
  316. var outs []map[string]interface{}
  317. switch val := item.(type) {
  318. case error:
  319. outs = []map[string]interface{}{
  320. {"error": val.Error()},
  321. }
  322. break
  323. case xsql.Collection: // The order is important here, because some element is both a collection and a row, such as WindowTuples, JoinTuples, etc.
  324. outs = val.ToMaps()
  325. break
  326. case xsql.Row:
  327. outs = []map[string]interface{}{
  328. val.ToMap(),
  329. }
  330. break
  331. case []map[string]interface{}: // for test only
  332. outs = val
  333. break
  334. default:
  335. outs = []map[string]interface{}{
  336. {"error": fmt.Sprintf("result is not a map slice but found %#v", val)},
  337. }
  338. }
  339. return outs
  340. }
  341. // doCollectData outData must be map or []map
  342. func doCollectData(ctx api.StreamContext, sink api.Sink, outData interface{}, stats metric.StatManager) error {
  343. select {
  344. case <-ctx.Done():
  345. ctx.GetLogger().Infof("sink node %s instance %d stops data resending", ctx.GetOpId(), ctx.GetInstanceId())
  346. return nil
  347. default:
  348. if err := sink.Collect(ctx, outData); err != nil {
  349. stats.IncTotalExceptions()
  350. return err
  351. } else {
  352. ctx.GetLogger().Debugf("success")
  353. stats.IncTotalRecordsOut()
  354. return nil
  355. }
  356. }
  357. }
  358. func getSink(name string, action map[string]interface{}) (api.Sink, error) {
  359. var (
  360. s api.Sink
  361. err error
  362. )
  363. s, err = io.Sink(name)
  364. if s != nil {
  365. err = s.Configure(action)
  366. if err != nil {
  367. return nil, err
  368. }
  369. return s, nil
  370. } else {
  371. if err != nil {
  372. return nil, err
  373. } else {
  374. return nil, fmt.Errorf("sink %s not found", name)
  375. }
  376. }
  377. }
  378. // AddOutput Override defaultNode
  379. func (m *SinkNode) AddOutput(_ chan<- interface{}, name string) error {
  380. return fmt.Errorf("fail to add output %s, sink %s cannot add output", name, m.name)
  381. }
  382. // Broadcast Override defaultNode
  383. func (m *SinkNode) Broadcast(_ interface{}) error {
  384. return fmt.Errorf("sink %s cannot add broadcast", m.name)
  385. }