window_op.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. package nodes
  2. import (
  3. "encoding/gob"
  4. "fmt"
  5. "github.com/benbjohnson/clock"
  6. "github.com/emqx/kuiper/common"
  7. "github.com/emqx/kuiper/xsql"
  8. "github.com/emqx/kuiper/xstream/api"
  9. "math"
  10. "time"
  11. )
  12. type WindowConfig struct {
  13. Type xsql.WindowType
  14. Length int
  15. Interval int //If interval is not set, it is equals to Length
  16. }
  17. type WindowOperator struct {
  18. *defaultSinkNode
  19. window *WindowConfig
  20. interval int
  21. isEventTime bool
  22. watermarkGenerator *WatermarkGenerator //For event time only
  23. statManager StatManager
  24. ticker *clock.Ticker //For processing time only
  25. // states
  26. triggerTime int64
  27. msgCount int
  28. }
  29. const WINDOW_INPUTS_KEY = "$$windowInputs"
  30. const TRIGGER_TIME_KEY = "$$triggerTime"
  31. const MSG_COUNT_KEY = "$$msgCount"
  32. func init() {
  33. gob.Register([]*xsql.Tuple{})
  34. }
  35. func NewWindowOp(name string, w WindowConfig, streams []string, options *api.RuleOption) (*WindowOperator, error) {
  36. o := new(WindowOperator)
  37. o.defaultSinkNode = &defaultSinkNode{
  38. input: make(chan interface{}, options.BufferLength),
  39. defaultNode: &defaultNode{
  40. outputs: make(map[string]chan<- interface{}),
  41. name: name,
  42. sendError: options.SendError,
  43. },
  44. }
  45. o.isEventTime = options.IsEventTime
  46. o.window = &w
  47. if o.window.Interval == 0 && o.window.Type == xsql.COUNT_WINDOW {
  48. //if no interval value is set and it's count window, then set interval to length value.
  49. o.window.Interval = o.window.Length
  50. }
  51. if options.IsEventTime {
  52. //Create watermark generator
  53. if w, err := NewWatermarkGenerator(o.window, options.LateTol, streams, o.input); err != nil {
  54. return nil, err
  55. } else {
  56. o.watermarkGenerator = w
  57. }
  58. }
  59. return o, nil
  60. }
  61. // Exec is the entry point for the executor
  62. // input: *xsql.Tuple from preprocessor
  63. // output: xsql.WindowTuplesSet
  64. func (o *WindowOperator) Exec(ctx api.StreamContext, errCh chan<- error) {
  65. o.ctx = ctx
  66. log := ctx.GetLogger()
  67. log.Debugf("Window operator %s is started", o.name)
  68. if len(o.outputs) <= 0 {
  69. go func() { errCh <- fmt.Errorf("no output channel found") }()
  70. return
  71. }
  72. stats, err := NewStatManager("op", ctx)
  73. if err != nil {
  74. go func() { errCh <- err }()
  75. return
  76. }
  77. o.statManager = stats
  78. var inputs []*xsql.Tuple
  79. if s, err := ctx.GetState(WINDOW_INPUTS_KEY); err == nil {
  80. switch st := s.(type) {
  81. case []*xsql.Tuple:
  82. inputs = st
  83. log.Infof("Restore window state %+v", inputs)
  84. case nil:
  85. log.Debugf("Restore window state, nothing")
  86. default:
  87. errCh <- fmt.Errorf("restore window state `inputs` %v error, invalid type", st)
  88. }
  89. } else {
  90. log.Warnf("Restore window state fails: %s", err)
  91. }
  92. o.triggerTime = 0
  93. if s, err := ctx.GetState(TRIGGER_TIME_KEY); err == nil && s != nil {
  94. if si, ok := s.(int64); ok {
  95. o.triggerTime = si
  96. } else {
  97. errCh <- fmt.Errorf("restore window state `triggerTime` %v error, invalid type", s)
  98. }
  99. }
  100. o.msgCount = 0
  101. if s, err := ctx.GetState(MSG_COUNT_KEY); err == nil && s != nil {
  102. if si, ok := s.(int); ok {
  103. o.msgCount = si
  104. } else {
  105. errCh <- fmt.Errorf("restore window state `msgCount` %v error, invalid type", s)
  106. }
  107. }
  108. log.Infof("Start with window state triggerTime: %d, msgCount: %d", o.triggerTime, o.msgCount)
  109. if o.isEventTime {
  110. go o.execEventWindow(ctx, inputs, errCh)
  111. } else {
  112. go o.execProcessingWindow(ctx, inputs, errCh)
  113. }
  114. }
  115. func (o *WindowOperator) execProcessingWindow(ctx api.StreamContext, inputs []*xsql.Tuple, errCh chan<- error) {
  116. log := ctx.GetLogger()
  117. var (
  118. c <-chan time.Time
  119. timeoutTicker *clock.Timer
  120. timeout <-chan time.Time
  121. )
  122. switch o.window.Type {
  123. case xsql.NOT_WINDOW:
  124. case xsql.TUMBLING_WINDOW:
  125. o.ticker = common.GetTicker(o.window.Length)
  126. o.interval = o.window.Length
  127. case xsql.HOPPING_WINDOW:
  128. o.ticker = common.GetTicker(o.window.Interval)
  129. o.interval = o.window.Interval
  130. case xsql.SLIDING_WINDOW:
  131. o.interval = o.window.Length
  132. case xsql.SESSION_WINDOW:
  133. o.ticker = common.GetTicker(o.window.Length)
  134. o.interval = o.window.Interval
  135. case xsql.COUNT_WINDOW:
  136. o.interval = o.window.Interval
  137. }
  138. if o.ticker != nil {
  139. c = o.ticker.C
  140. //resume previous window
  141. if len(inputs) > 0 && o.triggerTime > 0 {
  142. nextTick := common.GetNowInMilli() + int64(o.interval)
  143. next := o.triggerTime
  144. switch o.window.Type {
  145. case xsql.TUMBLING_WINDOW, xsql.HOPPING_WINDOW:
  146. for {
  147. next = next + int64(o.interval)
  148. if next > nextTick {
  149. break
  150. }
  151. log.Debugf("triggered by restore inputs")
  152. inputs, _ = o.scan(inputs, next, ctx)
  153. ctx.PutState(WINDOW_INPUTS_KEY, inputs)
  154. ctx.PutState(TRIGGER_TIME_KEY, o.triggerTime)
  155. }
  156. case xsql.SESSION_WINDOW:
  157. timeout, duration := int64(o.window.Interval), int64(o.window.Length)
  158. for {
  159. et := inputs[0].Timestamp
  160. tick := et + (duration - et%duration)
  161. if et%duration == 0 {
  162. tick = et
  163. }
  164. var p int64
  165. for _, tuple := range inputs {
  166. var r int64 = math.MaxInt64
  167. if p > 0 {
  168. if tuple.Timestamp-p > timeout {
  169. r = p + timeout
  170. }
  171. }
  172. if tuple.Timestamp > tick {
  173. if tick-duration > et && tick < r {
  174. r = tick
  175. }
  176. tick += duration
  177. }
  178. if r < math.MaxInt64 {
  179. next = r
  180. break
  181. }
  182. p = tuple.Timestamp
  183. }
  184. if next > nextTick {
  185. break
  186. }
  187. log.Debugf("triggered by restore inputs")
  188. inputs, _ = o.scan(inputs, next, ctx)
  189. ctx.PutState(WINDOW_INPUTS_KEY, inputs)
  190. ctx.PutState(TRIGGER_TIME_KEY, o.triggerTime)
  191. }
  192. }
  193. }
  194. }
  195. for {
  196. select {
  197. // process incoming item
  198. case item, opened := <-o.input:
  199. processed := false
  200. if item, processed = o.preprocess(item); processed {
  201. break
  202. }
  203. o.statManager.IncTotalRecordsIn()
  204. o.statManager.ProcessTimeStart()
  205. if !opened {
  206. o.statManager.IncTotalExceptions()
  207. break
  208. }
  209. switch d := item.(type) {
  210. case error:
  211. o.Broadcast(d)
  212. o.statManager.IncTotalExceptions()
  213. case *xsql.Tuple:
  214. log.Debugf("Event window receive tuple %s", d.Message)
  215. inputs = append(inputs, d)
  216. switch o.window.Type {
  217. case xsql.NOT_WINDOW:
  218. inputs, _ = o.scan(inputs, d.Timestamp, ctx)
  219. case xsql.SLIDING_WINDOW:
  220. inputs, _ = o.scan(inputs, d.Timestamp, ctx)
  221. case xsql.SESSION_WINDOW:
  222. if timeoutTicker != nil {
  223. timeoutTicker.Stop()
  224. timeoutTicker.Reset(time.Duration(o.window.Interval) * time.Millisecond)
  225. } else {
  226. timeoutTicker = common.GetTimer(o.window.Interval)
  227. timeout = timeoutTicker.C
  228. }
  229. case xsql.COUNT_WINDOW:
  230. o.msgCount++
  231. log.Debugf(fmt.Sprintf("msgCount: %d", o.msgCount))
  232. if o.msgCount%o.window.Interval != 0 {
  233. continue
  234. } else {
  235. o.msgCount = 0
  236. }
  237. if tl, er := NewTupleList(inputs, o.window.Length); er != nil {
  238. log.Error(fmt.Sprintf("Found error when trying to "))
  239. errCh <- er
  240. } else {
  241. log.Debugf(fmt.Sprintf("It has %d of count window.", tl.count()))
  242. for tl.hasMoreCountWindow() {
  243. tsets := tl.nextCountWindow()
  244. log.Debugf("Sent: %v", tsets)
  245. //blocking if one of the channel is full
  246. o.Broadcast(tsets)
  247. o.statManager.IncTotalRecordsOut()
  248. }
  249. inputs = tl.getRestTuples()
  250. }
  251. }
  252. o.statManager.ProcessTimeEnd()
  253. o.statManager.SetBufferLength(int64(len(o.input)))
  254. ctx.PutState(WINDOW_INPUTS_KEY, inputs)
  255. ctx.PutState(MSG_COUNT_KEY, o.msgCount)
  256. default:
  257. o.Broadcast(fmt.Errorf("run Window error: expect xsql.Tuple type but got %[1]T(%[1]v)", d))
  258. o.statManager.IncTotalExceptions()
  259. }
  260. case now := <-c:
  261. n := common.TimeToUnixMilli(now)
  262. if o.window.Type == xsql.SESSION_WINDOW {
  263. lastTriggerTime := o.triggerTime
  264. o.triggerTime = n
  265. log.Debugf("session window update trigger time %d with %d inputs", n, len(inputs))
  266. if len(inputs) == 0 || lastTriggerTime < inputs[0].Timestamp {
  267. if len(inputs) > 0 {
  268. log.Debugf("session window last trigger time %d < first tuple %d", lastTriggerTime, inputs[0].Timestamp)
  269. }
  270. break
  271. }
  272. }
  273. if len(inputs) > 0 {
  274. o.statManager.ProcessTimeStart()
  275. log.Debugf("triggered by ticker at %d", n)
  276. inputs, _ = o.scan(inputs, n, ctx)
  277. o.statManager.ProcessTimeEnd()
  278. ctx.PutState(WINDOW_INPUTS_KEY, inputs)
  279. ctx.PutState(TRIGGER_TIME_KEY, o.triggerTime)
  280. }
  281. case now := <-timeout:
  282. if len(inputs) > 0 {
  283. o.statManager.ProcessTimeStart()
  284. log.Debugf("triggered by timeout")
  285. inputs, _ = o.scan(inputs, common.TimeToUnixMilli(now), ctx)
  286. //expire all inputs, so that when timer scan there is no item
  287. inputs = make([]*xsql.Tuple, 0)
  288. o.statManager.ProcessTimeEnd()
  289. ctx.PutState(WINDOW_INPUTS_KEY, inputs)
  290. ctx.PutState(TRIGGER_TIME_KEY, o.triggerTime)
  291. }
  292. // is cancelling
  293. case <-ctx.Done():
  294. log.Infoln("Cancelling window....")
  295. if o.ticker != nil {
  296. o.ticker.Stop()
  297. }
  298. return
  299. }
  300. }
  301. }
  302. type TupleList struct {
  303. tuples []*xsql.Tuple
  304. index int //Current index
  305. size int //The size for count window
  306. }
  307. func NewTupleList(tuples []*xsql.Tuple, windowSize int) (TupleList, error) {
  308. if windowSize <= 0 {
  309. return TupleList{}, fmt.Errorf("Window size should not be less than zero.")
  310. } else if tuples == nil || len(tuples) == 0 {
  311. return TupleList{}, fmt.Errorf("The tuples should not be nil or empty.")
  312. }
  313. tl := TupleList{tuples: tuples, size: windowSize}
  314. return tl, nil
  315. }
  316. func (tl *TupleList) hasMoreCountWindow() bool {
  317. if len(tl.tuples) < tl.size {
  318. return false
  319. }
  320. return tl.index == 0
  321. }
  322. func (tl *TupleList) count() int {
  323. if len(tl.tuples) < tl.size {
  324. return 0
  325. } else {
  326. return 1
  327. }
  328. }
  329. func (tl *TupleList) nextCountWindow() xsql.WindowTuplesSet {
  330. var results xsql.WindowTuplesSet = make([]xsql.WindowTuples, 0)
  331. var subT []*xsql.Tuple
  332. subT = tl.tuples[len(tl.tuples)-tl.size : len(tl.tuples)]
  333. for _, tuple := range subT {
  334. results = results.AddTuple(tuple)
  335. }
  336. tl.index = tl.index + 1
  337. return results
  338. }
  339. func (tl *TupleList) getRestTuples() []*xsql.Tuple {
  340. if len(tl.tuples) < tl.size {
  341. return tl.tuples
  342. }
  343. return tl.tuples[len(tl.tuples)-tl.size+1:]
  344. }
  345. func (o *WindowOperator) scan(inputs []*xsql.Tuple, triggerTime int64, ctx api.StreamContext) ([]*xsql.Tuple, bool) {
  346. log := ctx.GetLogger()
  347. log.Debugf("window %s triggered at %s(%d)", o.name, time.Unix(triggerTime/1000, triggerTime%1000), triggerTime)
  348. var delta int64
  349. if o.window.Type == xsql.HOPPING_WINDOW || o.window.Type == xsql.SLIDING_WINDOW {
  350. delta = o.calDelta(triggerTime, delta, log)
  351. }
  352. var results xsql.WindowTuplesSet = make([]xsql.WindowTuples, 0)
  353. i := 0
  354. //Sync table
  355. for _, tuple := range inputs {
  356. if o.window.Type == xsql.HOPPING_WINDOW || o.window.Type == xsql.SLIDING_WINDOW {
  357. diff := o.triggerTime - tuple.Timestamp
  358. if diff > int64(o.window.Length)+delta {
  359. log.Debugf("diff: %d, length: %d, delta: %d", diff, o.window.Length, delta)
  360. log.Debugf("tuple %s emitted at %d expired", tuple, tuple.Timestamp)
  361. //Expired tuple, remove it by not adding back to inputs
  362. continue
  363. }
  364. //Added back all inputs for non expired events
  365. inputs[i] = tuple
  366. i++
  367. } else if tuple.Timestamp > triggerTime {
  368. //Only added back early arrived events
  369. inputs[i] = tuple
  370. i++
  371. }
  372. if tuple.Timestamp <= triggerTime {
  373. results = results.AddTuple(tuple)
  374. }
  375. }
  376. triggered := false
  377. if len(results) > 0 {
  378. log.Debugf("window %s triggered for %d tuples", o.name, len(inputs))
  379. if o.isEventTime {
  380. results.Sort()
  381. }
  382. log.Debugf("Sent: %v", results)
  383. //blocking if one of the channel is full
  384. o.Broadcast(results)
  385. triggered = true
  386. o.statManager.IncTotalRecordsOut()
  387. log.Debugf("done scan")
  388. }
  389. return inputs[:i], triggered
  390. }
  391. func (o *WindowOperator) calDelta(triggerTime int64, delta int64, log api.Logger) int64 {
  392. lastTriggerTime := o.triggerTime
  393. o.triggerTime = triggerTime
  394. if lastTriggerTime <= 0 {
  395. delta = math.MaxInt16 //max int, all events for the initial window
  396. } else {
  397. if !o.isEventTime && o.window.Interval > 0 {
  398. delta = o.triggerTime - lastTriggerTime - int64(o.window.Interval)
  399. if delta > 100 {
  400. log.Warnf("Possible long computation in window; Previous eviction time: %d, current eviction time: %d", lastTriggerTime, o.triggerTime)
  401. }
  402. } else {
  403. delta = 0
  404. }
  405. }
  406. return delta
  407. }
  408. func (o *WindowOperator) GetMetrics() [][]interface{} {
  409. if o.statManager != nil {
  410. return [][]interface{}{
  411. o.statManager.GetMetrics(),
  412. }
  413. } else {
  414. return nil
  415. }
  416. }