operations.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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. mutex sync.RWMutex
  35. cancelled bool
  36. }
  37. // NewUnary creates *UnaryOperator value
  38. func New(name string, options *api.RuleOption) *UnaryOperator {
  39. return &UnaryOperator{
  40. defaultSinkNode: &defaultSinkNode{
  41. input: make(chan interface{}, options.BufferLength),
  42. defaultNode: &defaultNode{
  43. name: name,
  44. outputs: make(map[string]chan<- interface{}),
  45. concurrency: 1,
  46. sendError: options.SendError,
  47. },
  48. },
  49. }
  50. }
  51. // SetOperation sets the executor operation
  52. func (o *UnaryOperator) SetOperation(op UnOperation) {
  53. o.op = op
  54. }
  55. // Exec is the entry point for the executor
  56. func (o *UnaryOperator) Exec(ctx api.StreamContext, errCh chan<- error) {
  57. o.ctx = ctx
  58. log := ctx.GetLogger()
  59. log.Debugf("Unary operator %s is started", o.name)
  60. if len(o.outputs) <= 0 {
  61. go func() { errCh <- fmt.Errorf("no output channel found") }()
  62. return
  63. }
  64. // validate p
  65. if o.concurrency < 1 {
  66. o.concurrency = 1
  67. }
  68. //reset status
  69. o.statManagers = nil
  70. for i := 0; i < o.concurrency; i++ { // workers
  71. instance := i
  72. go o.doOp(ctx.WithInstance(instance), errCh)
  73. }
  74. }
  75. func (o *UnaryOperator) doOp(ctx api.StreamContext, errCh chan<- error) {
  76. logger := ctx.GetLogger()
  77. if o.op == nil {
  78. logger.Infoln("Unary operator missing operation")
  79. return
  80. }
  81. exeCtx, cancel := ctx.WithCancel()
  82. defer func() {
  83. logger.Infof("unary operator %s instance %d done, cancelling future items", o.name, ctx.GetInstanceId())
  84. cancel()
  85. }()
  86. stats, err := NewStatManager("op", ctx)
  87. if err != nil {
  88. o.drainError(errCh, err, ctx)
  89. return
  90. }
  91. o.mutex.Lock()
  92. o.statManagers = append(o.statManagers, stats)
  93. o.mutex.Unlock()
  94. fv, afv := xsql.NewFunctionValuersForOp(exeCtx)
  95. for {
  96. select {
  97. // process incoming item
  98. case item := <-o.input:
  99. processed := false
  100. if item, processed = o.preprocess(item); processed {
  101. break
  102. }
  103. stats.IncTotalRecordsIn()
  104. stats.ProcessTimeStart()
  105. result := o.op.Apply(exeCtx, item, fv, afv)
  106. switch val := result.(type) {
  107. case nil:
  108. continue
  109. case error:
  110. logger.Errorf("Operation %s error: %s", ctx.GetOpId(), val)
  111. o.Broadcast(val)
  112. stats.IncTotalExceptions()
  113. continue
  114. default:
  115. stats.ProcessTimeEnd()
  116. o.Broadcast(val)
  117. stats.IncTotalRecordsOut()
  118. stats.SetBufferLength(int64(len(o.input)))
  119. }
  120. // is cancelling
  121. case <-ctx.Done():
  122. logger.Infof("unary operator %s instance %d cancelling....", o.name, ctx.GetInstanceId())
  123. o.mutex.Lock()
  124. cancel()
  125. o.cancelled = true
  126. o.mutex.Unlock()
  127. return
  128. }
  129. }
  130. }
  131. func (o *UnaryOperator) drainError(errCh chan<- error, err error, ctx api.StreamContext) {
  132. go func() {
  133. select {
  134. case errCh <- err:
  135. ctx.GetLogger().Errorf("unary operator %s error %s", o.name, err)
  136. case <-ctx.Done():
  137. // stop waiting
  138. }
  139. }()
  140. }