source_node.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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/conf"
  18. "github.com/lf-edge/ekuiper/internal/converter"
  19. "github.com/lf-edge/ekuiper/internal/topo/context"
  20. nodeConf "github.com/lf-edge/ekuiper/internal/topo/node/conf"
  21. "github.com/lf-edge/ekuiper/internal/topo/node/metric"
  22. "github.com/lf-edge/ekuiper/internal/xsql"
  23. "github.com/lf-edge/ekuiper/pkg/api"
  24. "github.com/lf-edge/ekuiper/pkg/ast"
  25. "github.com/lf-edge/ekuiper/pkg/cast"
  26. "github.com/lf-edge/ekuiper/pkg/infra"
  27. "sync"
  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. si, err = getSourceInstance(m, instance)
  110. if err != nil {
  111. return err
  112. }
  113. m.mutex.Lock()
  114. m.sources = append(m.sources, si.source)
  115. m.mutex.Unlock()
  116. buffer = si.dataCh
  117. defer func() {
  118. logger.Infof("source %s done", m.name)
  119. m.close()
  120. buffer.Close()
  121. }()
  122. stats, err := metric.NewStatManager(ctx, "source")
  123. if err != nil {
  124. return err
  125. }
  126. m.mutex.Lock()
  127. m.statManagers = append(m.statManagers, stats)
  128. m.mutex.Unlock()
  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. stats.ProcessTimeStart()
  144. tuple := &xsql.Tuple{Emitter: m.name, Message: data.Message(), Timestamp: conf.GetNowInMilli(), Metadata: data.Meta()}
  145. var processedData interface{}
  146. if m.preprocessOp != nil {
  147. processedData = m.preprocessOp.Apply(ctx, tuple, nil, nil)
  148. } else {
  149. processedData = tuple
  150. }
  151. stats.ProcessTimeEnd()
  152. //blocking
  153. switch val := processedData.(type) {
  154. case nil:
  155. continue
  156. case error:
  157. logger.Errorf("Source %s preprocess error: %s", ctx.GetOpId(), val)
  158. m.Broadcast(val)
  159. stats.IncTotalExceptions(val.Error())
  160. default:
  161. m.Broadcast(val)
  162. }
  163. stats.IncTotalRecordsOut()
  164. stats.SetBufferLength(int64(buffer.GetLength()))
  165. if rw, ok := si.source.(api.Rewindable); ok {
  166. if offset, err := rw.GetOffset(); err != nil {
  167. infra.DrainError(ctx, err, errCh)
  168. } else {
  169. err = ctx.PutState(OffsetKey, offset)
  170. if err != nil {
  171. return err
  172. }
  173. logger.Debugf("Source save offset %v", offset)
  174. }
  175. }
  176. }
  177. }
  178. })
  179. if poe != nil {
  180. infra.DrainError(ctx, poe, errCh)
  181. }
  182. }(i)
  183. }
  184. return nil
  185. })
  186. if panicOrError != nil {
  187. infra.DrainError(ctx, panicOrError, errCh)
  188. }
  189. }()
  190. }
  191. func (m *SourceNode) reset() {
  192. m.statManagers = nil
  193. }
  194. func (m *SourceNode) close() {
  195. if m.options.SHARED {
  196. removeSourceInstance(m)
  197. }
  198. }