source_node.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. // Copyright 2021-2023 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. "sync"
  18. "github.com/lf-edge/ekuiper/internal/conf"
  19. "github.com/lf-edge/ekuiper/internal/converter"
  20. "github.com/lf-edge/ekuiper/internal/topo/context"
  21. nodeConf "github.com/lf-edge/ekuiper/internal/topo/node/conf"
  22. "github.com/lf-edge/ekuiper/internal/topo/node/metric"
  23. "github.com/lf-edge/ekuiper/internal/xsql"
  24. "github.com/lf-edge/ekuiper/pkg/api"
  25. "github.com/lf-edge/ekuiper/pkg/ast"
  26. "github.com/lf-edge/ekuiper/pkg/cast"
  27. "github.com/lf-edge/ekuiper/pkg/infra"
  28. )
  29. type SourceNode struct {
  30. *defaultNode
  31. streamType ast.StreamType
  32. sourceType string
  33. options *ast.Options
  34. bufferLength int
  35. props map[string]interface{}
  36. mutex sync.RWMutex
  37. sources []api.Source
  38. preprocessOp UnOperation
  39. }
  40. func NewSourceNode(name string, st ast.StreamType, op UnOperation, options *ast.Options, sendError bool) *SourceNode {
  41. t := options.TYPE
  42. if t == "" {
  43. if st == ast.TypeStream {
  44. t = "mqtt"
  45. } else if st == ast.TypeTable {
  46. t = "file"
  47. }
  48. }
  49. return &SourceNode{
  50. streamType: st,
  51. sourceType: t,
  52. defaultNode: &defaultNode{
  53. name: name,
  54. outputs: make(map[string]chan<- interface{}),
  55. concurrency: 1,
  56. sendError: sendError,
  57. },
  58. preprocessOp: op,
  59. options: options,
  60. }
  61. }
  62. const OffsetKey = "$$offset"
  63. func (m *SourceNode) Open(ctx api.StreamContext, errCh chan<- error) {
  64. m.ctx = ctx
  65. logger := ctx.GetLogger()
  66. logger.Infof("open source node %s with option %v", m.name, m.options)
  67. go func() {
  68. panicOrError := infra.SafeRun(func() error {
  69. props := nodeConf.GetSourceConf(m.sourceType, m.options)
  70. m.props = props
  71. if c, ok := props["concurrency"]; ok {
  72. if t, err := cast.ToInt(c, cast.STRICT); err != nil || t <= 0 {
  73. logger.Warnf("invalid type for concurrency property, should be positive integer but found %t", c)
  74. } else {
  75. m.concurrency = t
  76. }
  77. }
  78. bl := 102400
  79. if c, ok := props["bufferLength"]; ok {
  80. if t, err := cast.ToInt(c, cast.STRICT); err != nil || t <= 0 {
  81. logger.Warnf("invalid type for bufferLength property, should be positive integer but found %t", c)
  82. } else {
  83. bl = t
  84. }
  85. }
  86. m.bufferLength = bl
  87. if m.streamType == ast.TypeTable {
  88. props["isTable"] = true
  89. }
  90. props["delimiter"] = m.options.DELIMITER
  91. converter, err := converter.GetOrCreateConverter(m.options)
  92. if err != nil {
  93. msg := fmt.Sprintf("cannot get converter from format %s, schemaId %s: %v", m.options.FORMAT, m.options.SCHEMAID, err)
  94. logger.Warnf(msg)
  95. return fmt.Errorf(msg)
  96. }
  97. ctx = context.WithValue(ctx.(*context.DefaultContext), context.DecodeKey, converter)
  98. m.reset()
  99. logger.Infof("open source node with props %v, concurrency: %d, bufferLength: %d", conf.Printable(m.props), m.concurrency, m.bufferLength)
  100. for i := 0; i < m.concurrency; i++ { // workers
  101. go func(instance int) {
  102. poe := infra.SafeRun(func() error {
  103. //Do open source instances
  104. var (
  105. si *sourceInstance
  106. buffer *DynamicChannelBuffer
  107. err error
  108. )
  109. stats, err := metric.NewStatManager(ctx, "source")
  110. if err != nil {
  111. return err
  112. }
  113. m.mutex.Lock()
  114. m.statManagers = append(m.statManagers, stats)
  115. m.mutex.Unlock()
  116. si, err = getSourceInstance(m, instance)
  117. if err != nil {
  118. return err
  119. }
  120. m.mutex.Lock()
  121. m.sources = append(m.sources, si.source)
  122. m.mutex.Unlock()
  123. buffer = si.dataCh
  124. defer func() {
  125. logger.Infof("source %s done", m.name)
  126. m.close()
  127. buffer.Close()
  128. }()
  129. logger.Infof("Start source %s instance %d successfully", m.name, instance)
  130. for {
  131. select {
  132. case <-ctx.Done():
  133. return nil
  134. case err := <-si.errorCh:
  135. return err
  136. case data := <-buffer.Out:
  137. if t, ok := data.(*xsql.ErrorSourceTuple); ok {
  138. logger.Errorf("Source %s error: %v", ctx.GetOpId(), t.Error)
  139. stats.IncTotalExceptions(t.Error.Error())
  140. continue
  141. }
  142. stats.IncTotalRecordsIn()
  143. rcvTime := conf.GetNow()
  144. if !data.Timestamp().IsZero() {
  145. rcvTime = data.Timestamp()
  146. }
  147. stats.SetProcessTimeStart(rcvTime)
  148. tuple := &xsql.Tuple{Emitter: m.name, Message: data.Message(), Timestamp: rcvTime.UnixMilli(), Metadata: data.Meta()}
  149. var processedData interface{}
  150. if m.preprocessOp != nil {
  151. processedData = m.preprocessOp.Apply(ctx, tuple, nil, nil)
  152. } else {
  153. processedData = tuple
  154. }
  155. stats.ProcessTimeEnd()
  156. //blocking
  157. switch val := processedData.(type) {
  158. case nil:
  159. continue
  160. case error:
  161. logger.Errorf("Source %s preprocess error: %s", ctx.GetOpId(), val)
  162. m.Broadcast(val)
  163. stats.IncTotalExceptions(val.Error())
  164. default:
  165. m.Broadcast(val)
  166. }
  167. stats.IncTotalRecordsOut()
  168. stats.SetBufferLength(int64(buffer.GetLength()))
  169. if rw, ok := si.source.(api.Rewindable); ok {
  170. if offset, err := rw.GetOffset(); err != nil {
  171. infra.DrainError(ctx, err, errCh)
  172. } else {
  173. err = ctx.PutState(OffsetKey, offset)
  174. if err != nil {
  175. return err
  176. }
  177. logger.Debugf("Source save offset %v", offset)
  178. }
  179. }
  180. }
  181. }
  182. })
  183. if poe != nil {
  184. infra.DrainError(ctx, poe, errCh)
  185. }
  186. }(i)
  187. }
  188. return nil
  189. })
  190. if panicOrError != nil {
  191. infra.DrainError(ctx, panicOrError, errCh)
  192. }
  193. }()
  194. }
  195. func (m *SourceNode) reset() {
  196. m.statManagers = nil
  197. }
  198. func (m *SourceNode) close() {
  199. if m.options.SHARED {
  200. removeSourceInstance(m)
  201. }
  202. }