sink_cache.go 6.5 KB

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