window_op.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. package operators
  2. import (
  3. "engine/common"
  4. "engine/xsql"
  5. "engine/xstream/api"
  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 api.StreamContext, errCh chan<- error ){
  90. log := ctx.GetLogger()
  91. log.Printf("Window operator %s is started", o.name)
  92. if len(o.outputs) <= 0 {
  93. go func(){errCh <- fmt.Errorf("no output channel found")}()
  94. return
  95. }
  96. if o.isEventTime{
  97. go o.execEventWindow(ctx, errCh)
  98. }else{
  99. go o.execProcessingWindow(ctx, errCh)
  100. }
  101. }
  102. func (o *WindowOperator) execProcessingWindow(ctx api.StreamContext, errCh chan<- error) {
  103. log := ctx.GetLogger()
  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 <-ctx.Done():
  166. log.Println("Cancelling window....")
  167. if o.ticker != nil{
  168. o.ticker.Stop()
  169. }
  170. return
  171. }
  172. }
  173. }
  174. func (o *WindowOperator) scan(inputs []*xsql.Tuple, triggerTime int64, ctx api.StreamContext) ([]*xsql.Tuple, bool){
  175. log := ctx.GetLogger()
  176. log.Printf("window %s triggered at %s", o.name, time.Unix(triggerTime/1000, triggerTime%1000))
  177. var delta int64
  178. if o.window.Type == xsql.HOPPING_WINDOW || o.window.Type == xsql.SLIDING_WINDOW {
  179. delta = o.calDelta(triggerTime, delta, log)
  180. }
  181. var results xsql.WindowTuplesSet = make([]xsql.WindowTuples, 0)
  182. i := 0
  183. //Sync table
  184. for _, tuple := range inputs {
  185. if o.window.Type == xsql.HOPPING_WINDOW || o.window.Type == xsql.SLIDING_WINDOW {
  186. diff := o.triggerTime - tuple.Timestamp
  187. if diff > int64(o.window.Length)+delta {
  188. log.Infof("diff: %d, length: %d, delta: %d", diff, o.window.Length, delta)
  189. log.Infof("tuple %s emitted at %d expired", tuple, tuple.Timestamp)
  190. //Expired tuple, remove it by not adding back to inputs
  191. continue
  192. }
  193. //Added back all inputs for non expired events
  194. inputs[i] = tuple
  195. i++
  196. } else if tuple.Timestamp > triggerTime {
  197. //Only added back early arrived events
  198. inputs[i] = tuple
  199. i++
  200. }
  201. if tuple.Timestamp <= triggerTime{
  202. results = results.AddTuple(tuple)
  203. }
  204. }
  205. triggered := false
  206. if len(results) > 0 {
  207. log.Printf("window %s triggered for %d tuples", o.name, len(inputs))
  208. if o.isEventTime{
  209. results.Sort()
  210. }
  211. count := nodes.Broadcast(o.outputs, results, ctx)
  212. //TODO deal with partial fail
  213. if count > 0{
  214. triggered = true
  215. }
  216. }
  217. return inputs[:i], triggered
  218. }
  219. func (o *WindowOperator) calDelta(triggerTime int64, delta int64, log *logrus.Entry) int64 {
  220. lastTriggerTime := o.triggerTime
  221. o.triggerTime = triggerTime
  222. if lastTriggerTime <= 0 {
  223. delta = math.MaxInt16 //max int, all events for the initial window
  224. } else {
  225. if !o.isEventTime && o.window.Interval > 0 {
  226. delta = o.triggerTime - lastTriggerTime - int64(o.window.Interval)
  227. if delta > 100 {
  228. log.Warnf("Possible long computation in window; Previous eviction time: %d, current eviction time: %d", lastTriggerTime, o.triggerTime)
  229. }
  230. } else {
  231. delta = 0
  232. }
  233. }
  234. return delta
  235. }