window_op.go 6.7 KB

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