operations.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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. //reset status
  76. o.statManagers = nil
  77. for i := 0; i < o.concurrency; i++ { // workers
  78. instance := i
  79. go o.doOp(ctx.WithInstance(instance), errCh)
  80. }
  81. }
  82. func (o *UnaryOperator) doOp(ctx api.StreamContext, errCh chan<- error) {
  83. logger := ctx.GetLogger()
  84. if o.op == nil {
  85. logger.Infoln("Unary operator missing operation")
  86. return
  87. }
  88. exeCtx, cancel := ctx.WithCancel()
  89. defer func() {
  90. logger.Infof("unary operator %s instance %d done, cancelling future items", o.name, ctx.GetInstanceId())
  91. cancel()
  92. }()
  93. stats, err := nodes.NewStatManager("op", ctx)
  94. if err != nil {
  95. select {
  96. case errCh <- err:
  97. case <-ctx.Done():
  98. logger.Infof("unary operator %s cancelling....", o.name)
  99. o.mutex.Lock()
  100. cancel()
  101. o.cancelled = true
  102. o.mutex.Unlock()
  103. }
  104. return
  105. }
  106. o.mutex.Lock()
  107. o.statManagers = append(o.statManagers, stats)
  108. o.mutex.Unlock()
  109. for {
  110. select {
  111. // process incoming item
  112. case item := <-o.input:
  113. stats.IncTotalRecordsIn()
  114. stats.ProcessTimeStart()
  115. result := o.op.Apply(exeCtx, item)
  116. switch val := result.(type) {
  117. case nil:
  118. continue
  119. case error:
  120. logger.Errorf("Operation %s error: %s", ctx.GetOpId(), val)
  121. nodes.Broadcast(o.outputs, val, ctx)
  122. stats.IncTotalExceptions()
  123. continue
  124. default:
  125. stats.ProcessTimeEnd()
  126. nodes.Broadcast(o.outputs, val, ctx)
  127. stats.IncTotalRecordsOut()
  128. stats.SetBufferLength(int64(len(o.input)))
  129. }
  130. // is cancelling
  131. case <-ctx.Done():
  132. logger.Infof("unary operator %s instance %d cancelling....", o.name, ctx.GetInstanceId())
  133. o.mutex.Lock()
  134. cancel()
  135. o.cancelled = true
  136. o.mutex.Unlock()
  137. return
  138. }
  139. }
  140. }
  141. func (m *UnaryOperator) GetMetrics() (result [][]interface{}) {
  142. for _, stats := range m.statManagers {
  143. result = append(result, stats.GetMetrics())
  144. }
  145. return result
  146. }