sink_node.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. 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/transform"
  21. "github.com/lf-edge/ekuiper/pkg/api"
  22. "github.com/lf-edge/ekuiper/pkg/cast"
  23. "github.com/lf-edge/ekuiper/pkg/errorx"
  24. "strings"
  25. "sync"
  26. "time"
  27. )
  28. type SinkConf struct {
  29. Concurrency int `json:"concurrency"`
  30. RunAsync bool `json:"runAsync"`
  31. RetryInterval int `json:"retryInterval"`
  32. RetryCount int `json:"retryCount"`
  33. CacheLength int `json:"cacheLength"`
  34. CacheSaveInterval int `json:"cacheSaveInterval"`
  35. Omitempty bool `json:"omitIfEmpty"`
  36. SendSingle bool `json:"sendSingle"`
  37. DataTemplate string `json:"dataTemplate"`
  38. }
  39. type SinkNode struct {
  40. *defaultSinkNode
  41. //static
  42. sinkType string
  43. mutex sync.RWMutex
  44. //configs (also static for sinks)
  45. options map[string]interface{}
  46. isMock bool
  47. //states varies after restart
  48. sinks []api.Sink
  49. tch chan struct{} //channel to trigger cache saved, will be trigger by checkpoint only
  50. }
  51. func NewSinkNode(name string, sinkType string, props map[string]interface{}) *SinkNode {
  52. bufferLength := 1024
  53. if c, ok := props["bufferLength"]; ok {
  54. if t, err := cast.ToInt(c, cast.STRICT); err != nil || t <= 0 {
  55. //invalid property bufferLength
  56. } else {
  57. bufferLength = t
  58. }
  59. }
  60. return &SinkNode{
  61. defaultSinkNode: &defaultSinkNode{
  62. input: make(chan interface{}, bufferLength),
  63. defaultNode: &defaultNode{
  64. name: name,
  65. concurrency: 1,
  66. ctx: nil,
  67. },
  68. },
  69. sinkType: sinkType,
  70. options: props,
  71. }
  72. }
  73. // NewSinkNodeWithSink Only for mock source, do not use it in production
  74. func NewSinkNodeWithSink(name string, sink api.Sink, props map[string]interface{}) *SinkNode {
  75. return &SinkNode{
  76. defaultSinkNode: &defaultSinkNode{
  77. input: make(chan interface{}, 1024),
  78. defaultNode: &defaultNode{
  79. name: name,
  80. concurrency: 1,
  81. ctx: nil,
  82. },
  83. },
  84. sinks: []api.Sink{sink},
  85. options: props,
  86. isMock: true,
  87. }
  88. }
  89. func (m *SinkNode) Open(ctx api.StreamContext, result chan<- error) {
  90. m.ctx = ctx
  91. logger := ctx.GetLogger()
  92. logger.Debugf("open sink node %s", m.name)
  93. if m.qos >= api.AtLeastOnce {
  94. m.tch = make(chan struct{})
  95. }
  96. go func() {
  97. sconf := &SinkConf{
  98. Concurrency: 1,
  99. RunAsync: false,
  100. RetryInterval: 1000,
  101. RetryCount: 0,
  102. CacheLength: 1024,
  103. CacheSaveInterval: 1000,
  104. Omitempty: false,
  105. SendSingle: false,
  106. DataTemplate: "",
  107. }
  108. err := cast.MapToStruct(m.options, sconf)
  109. if err != nil {
  110. result <- fmt.Errorf("read properties %v fail with error: %v", m.options, err)
  111. return
  112. }
  113. if sconf.Concurrency <= 0 {
  114. logger.Warnf("invalid type for concurrency property, should be positive integer but found %t", sconf.Concurrency)
  115. sconf.Concurrency = 1
  116. }
  117. m.concurrency = sconf.Concurrency
  118. if sconf.RetryInterval <= 0 {
  119. logger.Warnf("invalid type for retryInterval property, should be positive integer but found %t", sconf.RetryInterval)
  120. sconf.RetryInterval = 1000
  121. }
  122. if sconf.RetryCount < 0 {
  123. logger.Warnf("invalid type for retryCount property, should be positive integer but found %t", sconf.RetryCount)
  124. sconf.RetryCount = 3
  125. }
  126. if sconf.CacheLength < 0 {
  127. logger.Warnf("invalid type for cacheLength property, should be positive integer but found %t", sconf.CacheLength)
  128. sconf.CacheLength = 1024
  129. }
  130. if sconf.CacheSaveInterval < 0 {
  131. logger.Warnf("invalid type for cacheSaveInterval property, should be positive integer but found %t", sconf.CacheSaveInterval)
  132. sconf.CacheSaveInterval = 1000
  133. }
  134. tf, err := transform.GenTransform(sconf.DataTemplate)
  135. if err != nil {
  136. msg := fmt.Sprintf("property dataTemplate %v is invalid: %v", sconf.DataTemplate, err)
  137. logger.Warnf(msg)
  138. result <- fmt.Errorf(msg)
  139. return
  140. }
  141. m.reset()
  142. logger.Infof("open sink node %d instances", m.concurrency)
  143. for i := 0; i < m.concurrency; i++ { // workers
  144. go func(instance int) {
  145. var sink api.Sink
  146. var err error
  147. if !m.isMock {
  148. logger.Debugf("Trying to get sink for rule %s with options %v\n", ctx.GetRuleId(), m.options)
  149. sink, err = getSink(m.sinkType, m.options)
  150. if err != nil {
  151. m.drainError(result, err, ctx, logger)
  152. return
  153. }
  154. logger.Debugf("Successfully get the sink %s", m.sinkType)
  155. m.mutex.Lock()
  156. m.sinks = append(m.sinks, sink)
  157. m.mutex.Unlock()
  158. logger.Debugf("Now is to open sink for rule %s.\n", ctx.GetRuleId())
  159. if err := sink.Open(ctx); err != nil {
  160. m.drainError(result, err, ctx, logger)
  161. return
  162. }
  163. logger.Debugf("Successfully open sink for rule %s.\n", ctx.GetRuleId())
  164. } else {
  165. sink = m.sinks[instance]
  166. }
  167. stats, err := NewStatManager("sink", ctx)
  168. if err != nil {
  169. m.drainError(result, err, ctx, logger)
  170. return
  171. }
  172. m.mutex.Lock()
  173. m.statManagers = append(m.statManagers, stats)
  174. m.mutex.Unlock()
  175. if conf.Config.Sink.DisableCache {
  176. for {
  177. select {
  178. case data := <-m.input:
  179. if temp, processed := m.preprocess(data); processed {
  180. break
  181. } else {
  182. data = temp
  183. }
  184. stats.SetBufferLength(int64(len(m.input)))
  185. if sconf.RunAsync {
  186. go doCollect(ctx, sink, data, stats, sconf, tf, nil)
  187. } else {
  188. doCollect(ctx, sink, data, stats, sconf, tf, nil)
  189. }
  190. case <-ctx.Done():
  191. logger.Infof("sink node %s instance %d done", m.name, instance)
  192. if err := sink.Close(ctx); err != nil {
  193. logger.Warnf("close sink node %s instance %d fails: %v", m.name, instance, err)
  194. }
  195. return
  196. case <-m.tch:
  197. logger.Debugf("rule %s sink receive checkpoint, do nothing", ctx.GetRuleId())
  198. }
  199. }
  200. } else {
  201. logger.Infof("Creating sink cache")
  202. var cache *Cache
  203. if m.qos >= api.AtLeastOnce {
  204. cache = NewCheckpointbasedCache(m.input, sconf.CacheLength, m.tch, result, ctx)
  205. } else {
  206. cache = NewTimebasedCache(m.input, sconf.CacheLength, sconf.CacheSaveInterval, result, ctx)
  207. }
  208. for {
  209. select {
  210. case data := <-cache.Out:
  211. if temp, processed := m.preprocess(data.data); processed {
  212. break
  213. } else {
  214. data.data = temp
  215. }
  216. stats.SetBufferLength(int64(len(m.input)))
  217. if sconf.RunAsync {
  218. go doCollect(ctx, sink, data, stats, sconf, tf, cache.Complete)
  219. } else {
  220. doCollect(ctx, sink, data, stats, sconf, tf, cache.Complete)
  221. }
  222. case <-ctx.Done():
  223. logger.Infof("sink node %s instance %d done", m.name, instance)
  224. if err := sink.Close(ctx); err != nil {
  225. logger.Warnf("close sink node %s instance %d fails: %v", m.name, instance, err)
  226. }
  227. return
  228. }
  229. }
  230. }
  231. }(i)
  232. }
  233. }()
  234. }
  235. func (m *SinkNode) reset() {
  236. if !m.isMock {
  237. m.sinks = nil
  238. }
  239. m.statManagers = nil
  240. }
  241. func doCollect(ctx api.StreamContext, sink api.Sink, item interface{}, stats StatManager, sconf *SinkConf, tp transform.TransFunc, signalCh chan<- int) {
  242. stats.IncTotalRecordsIn()
  243. stats.ProcessTimeStart()
  244. defer stats.ProcessTimeEnd()
  245. var outs []map[string]interface{}
  246. switch val := item.(type) {
  247. case error:
  248. outs = []map[string]interface{}{
  249. {"error": val.Error()},
  250. }
  251. case []map[string]interface{}:
  252. outs = val
  253. default:
  254. outs = []map[string]interface{}{
  255. {"error": fmt.Sprintf("result is not a string but found %#v", val)},
  256. }
  257. }
  258. if sconf.Omitempty && (item == nil || len(outs) == 0) {
  259. ctx.GetLogger().Debugf("receive empty in sink")
  260. return
  261. }
  262. if !sconf.SendSingle {
  263. doCollectData(ctx, sink, outs, stats, sconf, tp, signalCh)
  264. } else {
  265. for _, d := range outs {
  266. doCollectData(ctx, sink, d, stats, sconf, tp, signalCh)
  267. }
  268. }
  269. }
  270. // doCollectData outData must be map or []map
  271. func doCollectData(ctx api.StreamContext, sink api.Sink, outData interface{}, stats StatManager, sconf *SinkConf, tf transform.TransFunc, signalCh chan<- int) {
  272. vCtx := context.WithValue(ctx.(*context.DefaultContext), context.TransKey, &context.TransConfig{
  273. Data: outData,
  274. TFunc: tf,
  275. })
  276. retries := sconf.RetryCount
  277. for {
  278. select {
  279. case <-ctx.Done():
  280. ctx.GetLogger().Infof("sink node %s instance %d stops data resending", ctx.GetOpId(), ctx.GetInstanceId())
  281. return
  282. default:
  283. if err := sink.Collect(vCtx, outData); err != nil {
  284. stats.IncTotalExceptions()
  285. ctx.GetLogger().Warnf("sink node %s instance %d publish %s error: %v", ctx.GetOpId(), ctx.GetInstanceId(), outData, err)
  286. if sconf.RetryInterval > 0 && retries > 0 && strings.HasPrefix(err.Error(), errorx.IOErr) {
  287. retries--
  288. time.Sleep(time.Duration(sconf.RetryInterval) * time.Millisecond)
  289. ctx.GetLogger().Debugf("try again")
  290. } else {
  291. return
  292. }
  293. } else {
  294. ctx.GetLogger().Debugf("success")
  295. stats.IncTotalRecordsOut()
  296. if signalCh != nil {
  297. cacheTuple, ok := outData.(*CacheTuple)
  298. if !ok {
  299. ctx.GetLogger().Warnf("got none cache tuple %v, should not happen", outData)
  300. }
  301. select {
  302. case signalCh <- cacheTuple.index:
  303. default:
  304. ctx.GetLogger().Warnf("sink cache missing response for %d", cacheTuple.index)
  305. }
  306. }
  307. return
  308. }
  309. }
  310. }
  311. }
  312. func getSink(name string, action map[string]interface{}) (api.Sink, error) {
  313. var (
  314. s api.Sink
  315. err error
  316. )
  317. s, err = io.Sink(name)
  318. if s != nil {
  319. err = s.Configure(action)
  320. if err != nil {
  321. return nil, err
  322. }
  323. return s, nil
  324. } else {
  325. if err != nil {
  326. return nil, err
  327. } else {
  328. return nil, fmt.Errorf("sink %s not found", name)
  329. }
  330. }
  331. }
  332. // AddOutput Override defaultNode
  333. func (m *SinkNode) AddOutput(_ chan<- interface{}, name string) error {
  334. return fmt.Errorf("fail to add output %s, sink %s cannot add output", name, m.name)
  335. }
  336. // Broadcast Override defaultNode
  337. func (m *SinkNode) Broadcast(_ interface{}) error {
  338. return fmt.Errorf("sink %s cannot add broadcast", m.name)
  339. }
  340. func (m *SinkNode) drainError(errCh chan<- error, err error, ctx api.StreamContext, logger api.Logger) {
  341. go func() {
  342. select {
  343. case errCh <- err:
  344. ctx.GetLogger().Errorf("error in sink %s", err)
  345. case <-ctx.Done():
  346. m.close(ctx, logger)
  347. }
  348. }()
  349. }
  350. func (m *SinkNode) close(ctx api.StreamContext, logger api.Logger) {
  351. for _, s := range m.sinks {
  352. if err := s.Close(ctx); err != nil {
  353. logger.Warnf("close sink fails: %v", err)
  354. }
  355. }
  356. if m.tch != nil {
  357. close(m.tch)
  358. m.tch = nil
  359. }
  360. }
  361. // SaveCache Only called when checkpoint enabled
  362. func (m *SinkNode) SaveCache() {
  363. m.tch <- struct{}{}
  364. }