operations.go 3.9 KB

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