operations.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. package operators
  2. import (
  3. "fmt"
  4. "github.com/emqx/kuiper/xstream/api"
  5. "github.com/emqx/kuiper/xstream/nodes"
  6. "sync"
  7. )
  8. // UnOperation interface represents unary operations (i.e. Map, Filter, etc)
  9. type UnOperation interface {
  10. Apply(ctx api.StreamContext, data interface{}) interface{}
  11. }
  12. // UnFunc implements UnOperation as type func (context.Context, interface{})
  13. type UnFunc func(api.StreamContext, interface{}) interface{}
  14. // Apply implements UnOperation.Apply method
  15. func (f UnFunc) Apply(ctx api.StreamContext, data interface{}) interface{} {
  16. return f(ctx, data)
  17. }
  18. type UnaryOperator struct {
  19. op UnOperation
  20. concurrency int
  21. input chan interface{}
  22. outputs map[string]chan<- interface{}
  23. mutex sync.RWMutex
  24. cancelled bool
  25. name string
  26. statManagers []*nodes.StatManager
  27. }
  28. // NewUnary creates *UnaryOperator value
  29. func New(name string, bufferLength int) *UnaryOperator {
  30. // extract logger
  31. o := new(UnaryOperator)
  32. o.concurrency = 1
  33. o.input = make(chan interface{}, bufferLength)
  34. o.outputs = make(map[string]chan<- interface{})
  35. o.name = name
  36. return o
  37. }
  38. func (o *UnaryOperator) GetName() string {
  39. return o.name
  40. }
  41. // SetOperation sets the executor operation
  42. func (o *UnaryOperator) SetOperation(op UnOperation) {
  43. o.op = op
  44. }
  45. // SetConcurrency sets the concurrency level for the operation
  46. func (o *UnaryOperator) SetConcurrency(concurr int) {
  47. o.concurrency = concurr
  48. if o.concurrency < 1 {
  49. o.concurrency = 1
  50. }
  51. }
  52. func (o *UnaryOperator) AddOutput(output chan<- interface{}, name string) error {
  53. if _, ok := o.outputs[name]; !ok {
  54. o.outputs[name] = output
  55. } else {
  56. return fmt.Errorf("fail to add output %s, operator %s already has an output of the same name", name, o.name)
  57. }
  58. return nil
  59. }
  60. func (o *UnaryOperator) GetInput() (chan<- interface{}, string) {
  61. return o.input, o.name
  62. }
  63. // Exec is the entry point for the executor
  64. func (o *UnaryOperator) Exec(ctx api.StreamContext, errCh chan<- error) {
  65. log := ctx.GetLogger()
  66. log.Debugf("Unary operator %s is started", o.name)
  67. if len(o.outputs) <= 0 {
  68. go func() { errCh <- fmt.Errorf("no output channel found") }()
  69. return
  70. }
  71. // validate p
  72. if o.concurrency < 1 {
  73. o.concurrency = 1
  74. }
  75. for i := 0; i < o.concurrency; i++ { // workers
  76. instance := i
  77. go o.doOp(ctx.WithInstance(instance), errCh)
  78. }
  79. }
  80. func (o *UnaryOperator) doOp(ctx api.StreamContext, errCh chan<- error) {
  81. logger := ctx.GetLogger()
  82. if o.op == nil {
  83. logger.Infoln("Unary operator missing operation")
  84. return
  85. }
  86. exeCtx, cancel := ctx.WithCancel()
  87. defer func() {
  88. logger.Infof("unary operator %s instance %d done, cancelling future items", o.name, ctx.GetInstanceId())
  89. cancel()
  90. }()
  91. stats, err := nodes.NewStatManager("op", ctx)
  92. if err != nil {
  93. select {
  94. case errCh <- err:
  95. case <-ctx.Done():
  96. logger.Infof("unary operator %s cancelling....", o.name)
  97. o.mutex.Lock()
  98. cancel()
  99. o.cancelled = true
  100. o.mutex.Unlock()
  101. }
  102. return
  103. }
  104. o.mutex.Lock()
  105. o.statManagers = append(o.statManagers, stats)
  106. o.mutex.Unlock()
  107. for {
  108. select {
  109. // process incoming item
  110. case item := <-o.input:
  111. stats.IncTotalRecordsIn()
  112. stats.ProcessTimeStart()
  113. result := o.op.Apply(exeCtx, item)
  114. switch val := result.(type) {
  115. case nil:
  116. continue
  117. case error: //TODO error handling
  118. logger.Infoln(val)
  119. logger.Infoln(val.Error())
  120. stats.IncTotalExceptions()
  121. continue
  122. default:
  123. stats.ProcessTimeEnd()
  124. nodes.Broadcast(o.outputs, val, ctx)
  125. stats.IncTotalRecordsOut()
  126. stats.SetBufferLength(int64(len(o.input)))
  127. }
  128. // is cancelling
  129. case <-ctx.Done():
  130. logger.Infof("unary operator %s instance %d cancelling....", o.name, ctx.GetInstanceId())
  131. o.mutex.Lock()
  132. cancel()
  133. o.cancelled = true
  134. o.mutex.Unlock()
  135. return
  136. }
  137. }
  138. }
  139. func (o *UnaryOperator) GetMetrics() map[string]interface{} {
  140. result := make(map[string]interface{})
  141. for _, stats := range o.statManagers{
  142. for k, v := range stats.GetMetrics(){
  143. result[k] = v
  144. }
  145. }
  146. return result
  147. }