source_node.go 5.2 KB

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