operations.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. // Copyright 2021 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package node
  15. import (
  16. "fmt"
  17. "github.com/lf-edge/ekuiper/internal/xsql"
  18. "github.com/lf-edge/ekuiper/pkg/api"
  19. "sync"
  20. )
  21. // UnOperation interface represents unary operations (i.e. Map, Filter, etc)
  22. type UnOperation interface {
  23. Apply(ctx api.StreamContext, data interface{}, fv *xsql.FunctionValuer, afv *xsql.AggregateFunctionValuer) interface{}
  24. }
  25. // UnFunc implements UnOperation as type func (context.Context, interface{})
  26. type UnFunc func(api.StreamContext, interface{}) interface{}
  27. // Apply implements UnOperation.Apply method
  28. func (f UnFunc) Apply(ctx api.StreamContext, data interface{}) interface{} {
  29. return f(ctx, data)
  30. }
  31. type UnaryOperator struct {
  32. *defaultSinkNode
  33. op UnOperation
  34. funcRegisters []xsql.FunctionRegister
  35. mutex sync.RWMutex
  36. cancelled bool
  37. }
  38. // NewUnary creates *UnaryOperator value
  39. func New(name string, registers []xsql.FunctionRegister, options *api.RuleOption) *UnaryOperator {
  40. return &UnaryOperator{
  41. funcRegisters: registers,
  42. defaultSinkNode: &defaultSinkNode{
  43. input: make(chan interface{}, options.BufferLength),
  44. defaultNode: &defaultNode{
  45. name: name,
  46. outputs: make(map[string]chan<- interface{}),
  47. concurrency: 1,
  48. sendError: options.SendError,
  49. },
  50. },
  51. }
  52. }
  53. // SetOperation sets the executor operation
  54. func (o *UnaryOperator) SetOperation(op UnOperation) {
  55. o.op = op
  56. }
  57. // Exec is the entry point for the executor
  58. func (o *UnaryOperator) Exec(ctx api.StreamContext, errCh chan<- error) {
  59. o.ctx = ctx
  60. log := ctx.GetLogger()
  61. log.Debugf("Unary operator %s is started", o.name)
  62. if len(o.outputs) <= 0 {
  63. go func() { errCh <- fmt.Errorf("no output channel found") }()
  64. return
  65. }
  66. // validate p
  67. if o.concurrency < 1 {
  68. o.concurrency = 1
  69. }
  70. //reset status
  71. o.statManagers = nil
  72. for i := 0; i < o.concurrency; i++ { // workers
  73. instance := i
  74. go o.doOp(ctx.WithInstance(instance), errCh)
  75. }
  76. }
  77. func (o *UnaryOperator) doOp(ctx api.StreamContext, errCh chan<- error) {
  78. logger := ctx.GetLogger()
  79. if o.op == nil {
  80. logger.Infoln("Unary operator missing operation")
  81. return
  82. }
  83. exeCtx, cancel := ctx.WithCancel()
  84. defer func() {
  85. logger.Infof("unary operator %s instance %d done, cancelling future items", o.name, ctx.GetInstanceId())
  86. cancel()
  87. }()
  88. stats, err := NewStatManager("op", ctx)
  89. if err != nil {
  90. o.drainError(errCh, err, ctx)
  91. return
  92. }
  93. o.mutex.Lock()
  94. o.statManagers = append(o.statManagers, stats)
  95. o.mutex.Unlock()
  96. fv, afv := xsql.NewFunctionValuersForOp(exeCtx, o.funcRegisters)
  97. for {
  98. select {
  99. // process incoming item
  100. case item := <-o.input:
  101. processed := false
  102. if item, processed = o.preprocess(item); processed {
  103. break
  104. }
  105. stats.IncTotalRecordsIn()
  106. stats.ProcessTimeStart()
  107. result := o.op.Apply(exeCtx, item, fv, afv)
  108. switch val := result.(type) {
  109. case nil:
  110. continue
  111. case error:
  112. logger.Errorf("Operation %s error: %s", ctx.GetOpId(), val)
  113. o.Broadcast(val)
  114. stats.IncTotalExceptions()
  115. continue
  116. default:
  117. stats.ProcessTimeEnd()
  118. o.Broadcast(val)
  119. stats.IncTotalRecordsOut()
  120. stats.SetBufferLength(int64(len(o.input)))
  121. }
  122. // is cancelling
  123. case <-ctx.Done():
  124. logger.Infof("unary operator %s instance %d cancelling....", o.name, ctx.GetInstanceId())
  125. o.mutex.Lock()
  126. cancel()
  127. o.cancelled = true
  128. o.mutex.Unlock()
  129. return
  130. }
  131. }
  132. }
  133. func (o *UnaryOperator) drainError(errCh chan<- error, err error, ctx api.StreamContext) {
  134. go func() {
  135. select {
  136. case errCh <- err:
  137. ctx.GetLogger().Errorf("unary operator %s error %s", o.name, err)
  138. case <-ctx.Done():
  139. // stop waiting
  140. }
  141. }()
  142. }