window_op.go 10 KB

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