operations.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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/topo/node/metric"
  18. "github.com/lf-edge/ekuiper/internal/xsql"
  19. "github.com/lf-edge/ekuiper/pkg/api"
  20. "github.com/lf-edge/ekuiper/pkg/infra"
  21. "sync"
  22. )
  23. // UnOperation interface represents unary operations (i.e. Map, Filter, etc)
  24. type UnOperation interface {
  25. Apply(ctx api.StreamContext, data interface{}, fv *xsql.FunctionValuer, afv *xsql.AggregateFunctionValuer) interface{}
  26. }
  27. // UnFunc implements UnOperation as type func (context.Context, interface{})
  28. type UnFunc func(api.StreamContext, interface{}) interface{}
  29. // Apply implements UnOperation.Apply method
  30. func (f UnFunc) Apply(ctx api.StreamContext, data interface{}) interface{} {
  31. return f(ctx, data)
  32. }
  33. type UnaryOperator struct {
  34. *defaultSinkNode
  35. op UnOperation
  36. mutex sync.RWMutex
  37. cancelled bool
  38. }
  39. // NewUnary creates *UnaryOperator value
  40. func New(name string, options *api.RuleOption) *UnaryOperator {
  41. return &UnaryOperator{
  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. infra.DrainError(ctx, fmt.Errorf("no output channel found"), errCh)
  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 func() {
  75. err := infra.SafeRun(func() error {
  76. o.doOp(ctx.WithInstance(instance), errCh)
  77. return nil
  78. })
  79. if err != nil {
  80. infra.DrainError(ctx, err, errCh)
  81. }
  82. }()
  83. }
  84. }
  85. func (o *UnaryOperator) doOp(ctx api.StreamContext, errCh chan<- error) {
  86. logger := ctx.GetLogger()
  87. if o.op == nil {
  88. logger.Infoln("Unary operator missing operation")
  89. return
  90. }
  91. exeCtx, cancel := ctx.WithCancel()
  92. defer func() {
  93. logger.Infof("unary operator %s instance %d done, cancelling future items", o.name, ctx.GetInstanceId())
  94. cancel()
  95. }()
  96. stats, err := metric.NewStatManager(ctx, "op")
  97. if err != nil {
  98. infra.DrainError(ctx, err, errCh)
  99. return
  100. }
  101. o.mutex.Lock()
  102. o.statManagers = append(o.statManagers, stats)
  103. o.mutex.Unlock()
  104. fv, afv := xsql.NewFunctionValuersForOp(exeCtx)
  105. for {
  106. select {
  107. // process incoming item
  108. case item := <-o.input:
  109. processed := false
  110. if item, processed = o.preprocess(item); processed {
  111. break
  112. }
  113. stats.IncTotalRecordsIn()
  114. stats.ProcessTimeStart()
  115. result := o.op.Apply(exeCtx, item, fv, afv)
  116. switch val := result.(type) {
  117. case nil:
  118. continue
  119. case error:
  120. logger.Errorf("Operation %s error: %s", ctx.GetOpId(), val)
  121. o.Broadcast(val)
  122. stats.IncTotalExceptions()
  123. continue
  124. default:
  125. stats.ProcessTimeEnd()
  126. o.Broadcast(val)
  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. }