window_op.go 6.7 KB

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