source_node.go 5.3 KB

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