sink_cache.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. "encoding/gob"
  17. "fmt"
  18. "github.com/lf-edge/ekuiper/internal/conf"
  19. "github.com/lf-edge/ekuiper/internal/pkg/store"
  20. "github.com/lf-edge/ekuiper/internal/topo/checkpoint"
  21. "github.com/lf-edge/ekuiper/pkg/api"
  22. "github.com/lf-edge/ekuiper/pkg/kv"
  23. "path"
  24. "sort"
  25. "strconv"
  26. )
  27. type CacheTuple struct {
  28. index int
  29. data interface{}
  30. }
  31. type LinkedQueue struct {
  32. Data map[int]interface{}
  33. Tail int
  34. }
  35. func (l *LinkedQueue) append(item interface{}) {
  36. l.Data[l.Tail] = item
  37. l.Tail++
  38. }
  39. func (l *LinkedQueue) delete(index int) {
  40. delete(l.Data, index)
  41. }
  42. func (l *LinkedQueue) reset() {
  43. l.Tail = 0
  44. }
  45. func (l *LinkedQueue) length() int {
  46. return len(l.Data)
  47. }
  48. func (l *LinkedQueue) clone() *LinkedQueue {
  49. result := &LinkedQueue{
  50. Data: make(map[int]interface{}),
  51. Tail: l.Tail,
  52. }
  53. for k, v := range l.Data {
  54. result.Data[k] = v
  55. }
  56. return result
  57. }
  58. func (l *LinkedQueue) String() string {
  59. return fmt.Sprintf("tail: %d, data: %v", l.Tail, l.Data)
  60. }
  61. type Cache struct {
  62. //Data and control channels
  63. in <-chan interface{}
  64. Out chan *CacheTuple
  65. Complete chan int
  66. errorCh chan<- error
  67. //states
  68. pending *LinkedQueue
  69. changed bool
  70. //serialize
  71. key string //the key for current cache
  72. store kv.KeyValue
  73. }
  74. func NewTimebasedCache(in <-chan interface{}, limit int, saveInterval int, errCh chan<- error, ctx api.StreamContext) *Cache {
  75. c := &Cache{
  76. in: in,
  77. Out: make(chan *CacheTuple, limit),
  78. Complete: make(chan int),
  79. errorCh: errCh,
  80. }
  81. go c.timebasedRun(ctx, saveInterval)
  82. return c
  83. }
  84. func (c *Cache) initStore(ctx api.StreamContext) {
  85. logger := ctx.GetLogger()
  86. c.pending = &LinkedQueue{
  87. Data: make(map[int]interface{}),
  88. Tail: 0,
  89. }
  90. var err error
  91. err, c.store = store.GetKV(path.Join("sink", ctx.GetRuleId()))
  92. if err != nil {
  93. c.drainError(err)
  94. }
  95. c.key = ctx.GetOpId() + strconv.Itoa(ctx.GetInstanceId())
  96. logger.Debugf("cache saved to key %s", c.key)
  97. //load cache
  98. if err := c.loadCache(); err != nil {
  99. go c.drainError(err)
  100. return
  101. }
  102. }
  103. func (c *Cache) timebasedRun(ctx api.StreamContext, saveInterval int) {
  104. logger := ctx.GetLogger()
  105. c.initStore(ctx)
  106. ticker := conf.GetTicker(saveInterval)
  107. defer ticker.Stop()
  108. var tcount = 0
  109. for {
  110. select {
  111. case item := <-c.in:
  112. index := c.pending.Tail
  113. c.pending.append(item)
  114. //non blocking until limit exceeded
  115. c.Out <- &CacheTuple{
  116. index: index,
  117. data: item,
  118. }
  119. c.changed = true
  120. case index := <-c.Complete:
  121. c.pending.delete(index)
  122. c.changed = true
  123. case <-ticker.C:
  124. tcount++
  125. l := c.pending.length()
  126. if l == 0 {
  127. c.pending.reset()
  128. }
  129. //If the data is still changing, only do a save when the cache has more than threshold to prevent too much file IO
  130. //If the data is not changing in the time slot and have not saved before, save it. This is to prevent the
  131. //data won't be saved as the cache never pass the threshold
  132. //logger.Infof("ticker %t, l=%d\n", c.changed, l)
  133. if (c.changed && l > conf.Config.Sink.CacheThreshold) || (tcount == conf.Config.Sink.CacheTriggerCount && c.changed) {
  134. logger.Infof("save cache for rule %s, %s", ctx.GetRuleId(), c.pending.String())
  135. clone := c.pending.clone()
  136. c.changed = false
  137. go func() {
  138. if err := c.saveCache(logger, clone); err != nil {
  139. logger.Debugf("%v", err)
  140. c.drainError(err)
  141. }
  142. }()
  143. }
  144. if tcount >= conf.Config.Sink.CacheThreshold {
  145. tcount = 0
  146. }
  147. case <-ctx.Done():
  148. err := c.saveCache(logger, c.pending)
  149. if err != nil {
  150. logger.Warnf("Error found during saving cache: %s \n ", err)
  151. }
  152. logger.Infof("sink node %s instance cache %d done", ctx.GetOpId(), ctx.GetInstanceId())
  153. return
  154. }
  155. }
  156. }
  157. func (c *Cache) loadCache() error {
  158. gob.Register(c.pending)
  159. mt := new(LinkedQueue)
  160. if f, err := c.store.Get(c.key, &mt); f {
  161. if nil != err {
  162. return fmt.Errorf("load malform cache, found %v(%v)", c.key, mt)
  163. }
  164. c.pending = mt
  165. c.changed = true
  166. // To store the keys in slice in sorted order
  167. var keys []int
  168. for k := range mt.Data {
  169. keys = append(keys, k)
  170. }
  171. sort.Ints(keys)
  172. for _, k := range keys {
  173. t := &CacheTuple{
  174. index: k,
  175. data: mt.Data[k],
  176. }
  177. c.Out <- t
  178. }
  179. return nil
  180. }
  181. return nil
  182. }
  183. func (c *Cache) saveCache(logger api.Logger, p *LinkedQueue) error {
  184. logger.Infof("clean the cache and reopen")
  185. c.store.Clean()
  186. return c.store.Set(c.key, p)
  187. }
  188. func (c *Cache) drainError(err error) {
  189. c.errorCh <- err
  190. }
  191. func (c *Cache) Length() int {
  192. return c.pending.length()
  193. }
  194. func NewCheckpointbasedCache(in <-chan interface{}, limit int, tch <-chan struct{}, errCh chan<- error, ctx api.StreamContext) *Cache {
  195. c := &Cache{
  196. in: in,
  197. Out: make(chan *CacheTuple, limit),
  198. Complete: make(chan int),
  199. errorCh: errCh,
  200. }
  201. go c.checkpointbasedRun(ctx, tch)
  202. return c
  203. }
  204. func (c *Cache) checkpointbasedRun(ctx api.StreamContext, tch <-chan struct{}) {
  205. logger := ctx.GetLogger()
  206. c.initStore(ctx)
  207. for {
  208. select {
  209. case item := <-c.in:
  210. // possibility of barrier, ignore if found
  211. if boe, ok := item.(*checkpoint.BufferOrEvent); ok {
  212. if _, ok := boe.Data.(*checkpoint.Barrier); ok {
  213. c.Out <- &CacheTuple{
  214. data: item,
  215. }
  216. logger.Debugf("sink cache send out barrier %v", boe.Data)
  217. break
  218. }
  219. }
  220. index := c.pending.Tail
  221. c.pending.append(item)
  222. //non blocking until limit exceeded
  223. c.Out <- &CacheTuple{
  224. index: index,
  225. data: item,
  226. }
  227. logger.Debugf("sink cache send out tuple %v", item)
  228. c.changed = true
  229. case index := <-c.Complete:
  230. c.pending.delete(index)
  231. c.changed = true
  232. case <-tch:
  233. logger.Infof("save cache for rule %s, %s", ctx.GetRuleId(), c.pending.String())
  234. clone := c.pending.clone()
  235. if c.changed {
  236. go func() {
  237. if err := c.saveCache(logger, clone); err != nil {
  238. logger.Debugf("%v", err)
  239. c.drainError(err)
  240. }
  241. }()
  242. }
  243. c.changed = false
  244. case <-ctx.Done():
  245. logger.Infof("sink node %s instance cache %d done", ctx.GetOpId(), ctx.GetInstanceId())
  246. return
  247. }
  248. }
  249. }