window_op.go 10 KB

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