sink_node.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. c := cache.NewSyncCache(ctx, m.input, result, stats, &sconf.SinkConf, sconf.BufferLength)
  182. for {
  183. select {
  184. case data := <-c.Out:
  185. if temp, processed := m.preprocess(data); processed {
  186. break
  187. } else {
  188. data = temp
  189. }
  190. ack := true
  191. err := doCollect(ctx, sink, data, stats, sconf)
  192. // Only recoverable error should be cached
  193. if err != nil {
  194. if strings.HasPrefix(err.Error(), errorx.IOErr) { // do not log to prevent a lot of logs!
  195. ack = false
  196. } else {
  197. ctx.GetLogger().Warnf("sink node %s instance %d publish %s error: %v", ctx.GetOpId(), ctx.GetInstanceId(), data, err)
  198. }
  199. } else {
  200. ctx.GetLogger().Debugf("sent data to MQTT: %v", data)
  201. }
  202. select {
  203. case c.Ack <- ack:
  204. case <-ctx.Done():
  205. }
  206. case <-ctx.Done():
  207. logger.Infof("sink node %s instance %d done", m.name, instance)
  208. if err := sink.Close(ctx); err != nil {
  209. logger.Warnf("close sink node %s instance %d fails: %v", m.name, instance, err)
  210. }
  211. return nil
  212. }
  213. }
  214. }
  215. }
  216. })
  217. if panicOrError != nil {
  218. infra.DrainError(ctx, panicOrError, result)
  219. }
  220. }(i)
  221. }
  222. return nil
  223. })
  224. if err != nil {
  225. infra.DrainError(ctx, err, result)
  226. }
  227. }()
  228. }
  229. func (m *SinkNode) parseConf(logger api.Logger) (*SinkConf, error) {
  230. sconf := &SinkConf{
  231. Concurrency: 1,
  232. RunAsync: false,
  233. Omitempty: false,
  234. SendSingle: false,
  235. DataTemplate: "",
  236. SinkConf: *conf.Config.Sink,
  237. BufferLength: 1024,
  238. }
  239. err := cast.MapToStruct(m.options, sconf)
  240. if err != nil {
  241. return nil, fmt.Errorf("read properties %v fail with error: %v", m.options, err)
  242. }
  243. if sconf.Concurrency <= 0 {
  244. logger.Warnf("invalid type for concurrency property, should be positive integer but found %t", sconf.Concurrency)
  245. sconf.Concurrency = 1
  246. }
  247. m.concurrency = sconf.Concurrency
  248. if sconf.Format == "" {
  249. sconf.Format = "json"
  250. } else if sconf.Format != message.FormatJson && sconf.Format != message.FormatProtobuf {
  251. logger.Warnf("invalid type for format property, should be json or protobuf but found %s", sconf.Format)
  252. sconf.Format = "json"
  253. }
  254. err = cast.MapToStruct(m.options, &sconf.SinkConf)
  255. if err != nil {
  256. return nil, fmt.Errorf("read properties %v to cache conf fail with error: %v", m.options, err)
  257. }
  258. if sconf.SinkConf.EnableCache && sconf.RunAsync {
  259. return nil, fmt.Errorf("cache is not supported for async sink, do not use enableCache and runAsync properties together")
  260. }
  261. err = sconf.SinkConf.Validate()
  262. if err != nil {
  263. return nil, fmt.Errorf("invalid cache properties: %v", err)
  264. }
  265. return sconf, err
  266. }
  267. func (m *SinkNode) reset() {
  268. if !m.isMock {
  269. m.sinks = nil
  270. }
  271. m.statManagers = nil
  272. }
  273. func doCollect(ctx api.StreamContext, sink api.Sink, item interface{}, stats metric.StatManager, sconf *SinkConf) error {
  274. stats.ProcessTimeStart()
  275. defer stats.ProcessTimeEnd()
  276. var outs []map[string]interface{}
  277. switch val := item.(type) {
  278. case error:
  279. outs = []map[string]interface{}{
  280. {"error": val.Error()},
  281. }
  282. break
  283. case xsql.Collection: // The order is important here, because some element is both a collection and a row, such as WindowTuples, JoinTuples, etc.
  284. outs = val.ToMaps()
  285. break
  286. case xsql.Row:
  287. outs = []map[string]interface{}{
  288. val.ToMap(),
  289. }
  290. break
  291. case []map[string]interface{}: // for test only
  292. outs = val
  293. break
  294. default:
  295. outs = []map[string]interface{}{
  296. {"error": fmt.Sprintf("result is not a map slice but found %#v", val)},
  297. }
  298. }
  299. if sconf.Omitempty && (item == nil || len(outs) == 0) {
  300. ctx.GetLogger().Debugf("receive empty in sink")
  301. return nil
  302. }
  303. if !sconf.SendSingle {
  304. return doCollectData(ctx, sink, outs, stats)
  305. } else {
  306. var err error
  307. for _, d := range outs {
  308. if sconf.Omitempty && (d == nil || len(d) == 0) {
  309. ctx.GetLogger().Debugf("receive empty in sink")
  310. continue
  311. }
  312. newErr := doCollectData(ctx, sink, d, stats)
  313. if newErr != nil {
  314. err = newErr
  315. }
  316. }
  317. return err
  318. }
  319. }
  320. // doCollectData outData must be map or []map
  321. func doCollectData(ctx api.StreamContext, sink api.Sink, outData interface{}, stats metric.StatManager) error {
  322. select {
  323. case <-ctx.Done():
  324. ctx.GetLogger().Infof("sink node %s instance %d stops data resending", ctx.GetOpId(), ctx.GetInstanceId())
  325. return nil
  326. default:
  327. if err := sink.Collect(ctx, outData); err != nil {
  328. stats.IncTotalExceptions()
  329. return err
  330. } else {
  331. ctx.GetLogger().Debugf("success")
  332. stats.IncTotalRecordsOut()
  333. return nil
  334. }
  335. }
  336. }
  337. func getSink(name string, action map[string]interface{}) (api.Sink, error) {
  338. var (
  339. s api.Sink
  340. err error
  341. )
  342. s, err = io.Sink(name)
  343. if s != nil {
  344. err = s.Configure(action)
  345. if err != nil {
  346. return nil, err
  347. }
  348. return s, nil
  349. } else {
  350. if err != nil {
  351. return nil, err
  352. } else {
  353. return nil, fmt.Errorf("sink %s not found", name)
  354. }
  355. }
  356. }
  357. // AddOutput Override defaultNode
  358. func (m *SinkNode) AddOutput(_ chan<- interface{}, name string) error {
  359. return fmt.Errorf("fail to add output %s, sink %s cannot add output", name, m.name)
  360. }
  361. // Broadcast Override defaultNode
  362. func (m *SinkNode) Broadcast(_ interface{}) error {
  363. return fmt.Errorf("sink %s cannot add broadcast", m.name)
  364. }