source_node.go 5.9 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. "github.com/lf-edge/ekuiper/internal/topo/node/metric"
  21. "github.com/lf-edge/ekuiper/internal/xsql"
  22. "github.com/lf-edge/ekuiper/pkg/api"
  23. "github.com/lf-edge/ekuiper/pkg/ast"
  24. "github.com/lf-edge/ekuiper/pkg/cast"
  25. "github.com/lf-edge/ekuiper/pkg/infra"
  26. "strings"
  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 := getSourceConf(ctx, 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. // Set retain size for table type
  88. if m.options.RETAIN_SIZE > 0 && m.streamType == ast.TypeTable {
  89. props["$retainSize"] = m.options.RETAIN_SIZE
  90. }
  91. format := fmt.Sprintf("%v", props["format"])
  92. schemaFile := ""
  93. schemaId := m.options.SCHEMAID
  94. if schemaId != "" {
  95. r := strings.Split(schemaId, ".")
  96. if len(r) != 2 {
  97. return fmt.Errorf("invalid schemaId: %s", schemaId)
  98. }
  99. schemaFile = r[0]
  100. }
  101. converter, err := converter.GetOrCreateConverter(format, schemaFile, schemaId)
  102. if err != nil {
  103. msg := fmt.Sprintf("cannot get converter from format %s, schemaId %s: %v", format, schemaId, err)
  104. logger.Warnf(msg)
  105. return fmt.Errorf(msg)
  106. }
  107. ctx = context.WithValue(ctx.(*context.DefaultContext), context.DecodeKey, converter)
  108. m.reset()
  109. logger.Infof("open source node with props %v, concurrency: %d, bufferLength: %d", conf.Printable(m.props), m.concurrency, m.bufferLength)
  110. for i := 0; i < m.concurrency; i++ { // workers
  111. go func(instance int) {
  112. poe := infra.SafeRun(func() error {
  113. //Do open source instances
  114. var (
  115. si *sourceInstance
  116. buffer *DynamicChannelBuffer
  117. err error
  118. )
  119. si, err = getSourceInstance(m, instance)
  120. if err != nil {
  121. return err
  122. }
  123. m.mutex.Lock()
  124. m.sources = append(m.sources, si.source)
  125. m.mutex.Unlock()
  126. buffer = si.dataCh
  127. defer func() {
  128. logger.Infof("source %s done", m.name)
  129. m.close()
  130. buffer.Close()
  131. }()
  132. stats, err := metric.NewStatManager(ctx, "source")
  133. if err != nil {
  134. return err
  135. }
  136. m.mutex.Lock()
  137. m.statManagers = append(m.statManagers, stats)
  138. m.mutex.Unlock()
  139. logger.Infof("Start source %s instance %d successfully", m.name, instance)
  140. for {
  141. select {
  142. case <-ctx.Done():
  143. return nil
  144. case err := <-si.errorCh:
  145. return err
  146. case data := <-buffer.Out:
  147. stats.IncTotalRecordsIn()
  148. stats.ProcessTimeStart()
  149. tuple := &xsql.Tuple{Emitter: m.name, Message: data.Message(), Timestamp: conf.GetNowInMilli(), Metadata: data.Meta()}
  150. processedData := m.preprocessOp.Apply(ctx, tuple, nil, nil)
  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()
  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. }