window_op.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. package operators
  2. import (
  3. "github.com/emqx/kuiper/common"
  4. "github.com/emqx/kuiper/xsql"
  5. "github.com/emqx/kuiper/xstream/api"
  6. "github.com/emqx/kuiper/xstream/nodes"
  7. "fmt"
  8. "math"
  9. "time"
  10. )
  11. type WindowConfig struct {
  12. Type xsql.WindowType
  13. Length int
  14. Interval int //If interval is not set, it is equals to Length
  15. }
  16. type WindowOperator struct {
  17. input chan interface{}
  18. outputs map[string]chan<- interface{}
  19. name string
  20. ticker common.Ticker //For processing time only
  21. window *WindowConfig
  22. interval int
  23. triggerTime int64
  24. isEventTime bool
  25. watermarkGenerator *WatermarkGenerator //For event time only
  26. }
  27. func NewWindowOp(name string, w *xsql.Window, isEventTime bool, lateTolerance int64, streams []string) (*WindowOperator, error) {
  28. o := new(WindowOperator)
  29. o.input = make(chan interface{}, 1024)
  30. o.outputs = make(map[string]chan<- interface{})
  31. o.name = name
  32. o.isEventTime = isEventTime
  33. if w != nil{
  34. o.window = &WindowConfig{
  35. Type: w.WindowType,
  36. Length: w.Length.Val,
  37. Interval: w.Interval.Val,
  38. }
  39. }else{
  40. o.window = &WindowConfig{
  41. Type: xsql.NOT_WINDOW,
  42. }
  43. }
  44. if isEventTime{
  45. //Create watermark generator
  46. if w, err := NewWatermarkGenerator(o.window, lateTolerance, streams, o.input); err != nil{
  47. return nil, err
  48. }else{
  49. o.watermarkGenerator = w
  50. }
  51. }else{
  52. switch o.window.Type{
  53. case xsql.NOT_WINDOW:
  54. case xsql.TUMBLING_WINDOW:
  55. o.ticker = common.GetTicker(o.window.Length)
  56. o.interval = o.window.Length
  57. case xsql.HOPPING_WINDOW:
  58. o.ticker = common.GetTicker(o.window.Interval)
  59. o.interval = o.window.Interval
  60. case xsql.SLIDING_WINDOW:
  61. o.interval = o.window.Length
  62. case xsql.SESSION_WINDOW:
  63. o.ticker = common.GetTicker(o.window.Length)
  64. o.interval = o.window.Interval
  65. default:
  66. return nil, fmt.Errorf("unsupported window type %d", o.window.Type)
  67. }
  68. }
  69. return o, nil
  70. }
  71. func (o *WindowOperator) GetName() string {
  72. return o.name
  73. }
  74. func (o *WindowOperator) AddOutput(output chan<- interface{}, name string) error {
  75. if _, ok := o.outputs[name]; !ok{
  76. o.outputs[name] = output
  77. }else{
  78. fmt.Errorf("fail to add output %s, operator %s already has an output of the same name", name, o.name)
  79. }
  80. return nil
  81. }
  82. func (o *WindowOperator) GetInput() (chan<- interface{}, string) {
  83. return o.input, o.name
  84. }
  85. // Exec is the entry point for the executor
  86. // input: *xsql.Tuple from preprocessor
  87. // output: xsql.WindowTuplesSet
  88. func (o *WindowOperator) Exec(ctx api.StreamContext, errCh chan<- error ){
  89. log := ctx.GetLogger()
  90. log.Infof("Window operator %s is started", o.name)
  91. if len(o.outputs) <= 0 {
  92. go func(){errCh <- fmt.Errorf("no output channel found")}()
  93. return
  94. }
  95. if o.isEventTime{
  96. go o.execEventWindow(ctx, errCh)
  97. }else{
  98. go o.execProcessingWindow(ctx, errCh)
  99. }
  100. }
  101. func (o *WindowOperator) execProcessingWindow(ctx api.StreamContext, errCh chan<- error) {
  102. log := ctx.GetLogger()
  103. var (
  104. inputs []*xsql.Tuple
  105. c <-chan time.Time
  106. timeoutTicker common.Timer
  107. timeout <-chan time.Time
  108. )
  109. if o.ticker != nil {
  110. c = o.ticker.GetC()
  111. }
  112. for {
  113. select {
  114. // process incoming item
  115. case item, opened := <-o.input:
  116. if !opened {
  117. break
  118. }
  119. if d, ok := item.(*xsql.Tuple); !ok {
  120. log.Errorf("Expect xsql.Tuple type")
  121. break
  122. }else{
  123. log.Debugf("Event window receive tuple %s", d.Message)
  124. inputs = append(inputs, d)
  125. switch o.window.Type{
  126. case xsql.NOT_WINDOW:
  127. inputs, _ = o.scan(inputs, d.Timestamp, ctx)
  128. case xsql.SLIDING_WINDOW:
  129. inputs, _ = o.scan(inputs, d.Timestamp, ctx)
  130. case xsql.SESSION_WINDOW:
  131. if timeoutTicker != nil {
  132. timeoutTicker.Stop()
  133. timeoutTicker.Reset(time.Duration(o.window.Interval) * time.Millisecond)
  134. } else {
  135. timeoutTicker = common.GetTimer(o.window.Interval)
  136. timeout = timeoutTicker.GetC()
  137. }
  138. }
  139. }
  140. case now := <-c:
  141. if len(inputs) > 0 {
  142. n := common.TimeToUnixMilli(now)
  143. //For session window, check if the last scan time is newer than the inputs
  144. if o.window.Type == xsql.SESSION_WINDOW{
  145. //scan time for session window will record all triggers of the ticker but not the timeout
  146. lastTriggerTime := o.triggerTime
  147. o.triggerTime = n
  148. //Check if the current window has exceeded the max duration, if not continue expand
  149. if lastTriggerTime < inputs[0].Timestamp{
  150. break
  151. }
  152. }
  153. log.Infof("triggered by ticker")
  154. inputs, _ = o.scan(inputs, n, ctx)
  155. }
  156. case now := <-timeout:
  157. if len(inputs) > 0 {
  158. log.Infof("triggered by timeout")
  159. inputs, _ = o.scan(inputs, common.TimeToUnixMilli(now), ctx)
  160. //expire all inputs, so that when timer scan there is no item
  161. inputs = make([]*xsql.Tuple, 0)
  162. }
  163. // is cancelling
  164. case <-ctx.Done():
  165. log.Infoln("Cancelling window....")
  166. if o.ticker != nil{
  167. o.ticker.Stop()
  168. }
  169. return
  170. }
  171. }
  172. }
  173. func (o *WindowOperator) scan(inputs []*xsql.Tuple, triggerTime int64, ctx api.StreamContext) ([]*xsql.Tuple, bool){
  174. log := ctx.GetLogger()
  175. log.Infof("window %s triggered at %s", o.name, time.Unix(triggerTime/1000, triggerTime%1000))
  176. var delta int64
  177. if o.window.Type == xsql.HOPPING_WINDOW || o.window.Type == xsql.SLIDING_WINDOW {
  178. delta = o.calDelta(triggerTime, delta, log)
  179. }
  180. var results xsql.WindowTuplesSet = make([]xsql.WindowTuples, 0)
  181. i := 0
  182. //Sync table
  183. for _, tuple := range inputs {
  184. if o.window.Type == xsql.HOPPING_WINDOW || o.window.Type == xsql.SLIDING_WINDOW {
  185. diff := o.triggerTime - tuple.Timestamp
  186. if diff > int64(o.window.Length)+delta {
  187. log.Infof("diff: %d, length: %d, delta: %d", diff, o.window.Length, delta)
  188. log.Infof("tuple %s emitted at %d expired", tuple, tuple.Timestamp)
  189. //Expired tuple, remove it by not adding back to inputs
  190. continue
  191. }
  192. //Added back all inputs for non expired events
  193. inputs[i] = tuple
  194. i++
  195. } else if tuple.Timestamp > triggerTime {
  196. //Only added back early arrived events
  197. inputs[i] = tuple
  198. i++
  199. }
  200. if tuple.Timestamp <= triggerTime{
  201. results = results.AddTuple(tuple)
  202. }
  203. }
  204. triggered := false
  205. if len(results) > 0 {
  206. log.Infof("window %s triggered for %d tuples", o.name, len(inputs))
  207. if o.isEventTime{
  208. results.Sort()
  209. }
  210. count := nodes.Broadcast(o.outputs, results, ctx)
  211. //TODO deal with partial fail
  212. if count > 0{
  213. triggered = true
  214. }
  215. }
  216. return inputs[:i], triggered
  217. }
  218. func (o *WindowOperator) calDelta(triggerTime int64, delta int64, log api.Logger) int64 {
  219. lastTriggerTime := o.triggerTime
  220. o.triggerTime = triggerTime
  221. if lastTriggerTime <= 0 {
  222. delta = math.MaxInt16 //max int, all events for the initial window
  223. } else {
  224. if !o.isEventTime && o.window.Interval > 0 {
  225. delta = o.triggerTime - lastTriggerTime - int64(o.window.Interval)
  226. if delta > 100 {
  227. log.Warnf("Possible long computation in window; Previous eviction time: %d, current eviction time: %d", lastTriggerTime, o.triggerTime)
  228. }
  229. } else {
  230. delta = 0
  231. }
  232. }
  233. return delta
  234. }