source_node.go 6.2 KB

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