source_node.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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/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. "sync"
  22. )
  23. type SourceNode struct {
  24. *defaultNode
  25. streamType ast.StreamType
  26. sourceType string
  27. options *ast.Options
  28. bufferLength int
  29. props map[string]interface{}
  30. mutex sync.RWMutex
  31. sources []api.Source
  32. }
  33. func NewSourceNode(name string, st ast.StreamType, options *ast.Options) *SourceNode {
  34. t := options.TYPE
  35. if t == "" {
  36. if st == ast.TypeStream {
  37. t = "mqtt"
  38. } else if st == ast.TypeTable {
  39. t = "file"
  40. }
  41. }
  42. return &SourceNode{
  43. streamType: st,
  44. sourceType: t,
  45. defaultNode: &defaultNode{
  46. name: name,
  47. outputs: make(map[string]chan<- interface{}),
  48. concurrency: 1,
  49. },
  50. options: options,
  51. }
  52. }
  53. const OffsetKey = "$$offset"
  54. func (m *SourceNode) Open(ctx api.StreamContext, errCh chan<- error) {
  55. m.ctx = ctx
  56. logger := ctx.GetLogger()
  57. logger.Infof("open source node %s with option %v", m.name, m.options)
  58. go func() {
  59. props := getSourceConf(ctx, m.sourceType, m.options)
  60. m.props = props
  61. if c, ok := props["concurrency"]; ok {
  62. if t, err := cast.ToInt(c, cast.STRICT); err != nil || t <= 0 {
  63. logger.Warnf("invalid type for concurrency property, should be positive integer but found %t", c)
  64. } else {
  65. m.concurrency = t
  66. }
  67. }
  68. bl := 102400
  69. if c, ok := props["bufferLength"]; ok {
  70. if t, err := cast.ToInt(c, cast.STRICT); err != nil || t <= 0 {
  71. logger.Warnf("invalid type for bufferLength property, should be positive integer but found %t", c)
  72. } else {
  73. bl = t
  74. }
  75. }
  76. m.bufferLength = bl
  77. // Set retain size for table type
  78. if m.options.RETAIN_SIZE > 0 && m.streamType == ast.TypeTable {
  79. props["$retainSize"] = m.options.RETAIN_SIZE
  80. }
  81. m.reset()
  82. logger.Infof("open source node %d instances", m.concurrency)
  83. for i := 0; i < m.concurrency; i++ { // workers
  84. go func(instance int) {
  85. //Do open source instances
  86. var (
  87. si *sourceInstance
  88. buffer *DynamicChannelBuffer
  89. err error
  90. )
  91. si, err = getSourceInstance(m, instance)
  92. if err != nil {
  93. m.drainError(errCh, err, ctx, logger)
  94. return
  95. }
  96. m.mutex.Lock()
  97. m.sources = append(m.sources, si.source)
  98. m.mutex.Unlock()
  99. buffer = si.dataCh
  100. defer func() {
  101. logger.Infof("source %s done", m.name)
  102. m.close(ctx, logger)
  103. buffer.Close()
  104. }()
  105. stats, err := NewStatManager("source", ctx)
  106. if err != nil {
  107. m.drainError(errCh, err, ctx, logger)
  108. return
  109. }
  110. m.mutex.Lock()
  111. m.statManagers = append(m.statManagers, stats)
  112. m.mutex.Unlock()
  113. logger.Infof("Start source %s instance %d successfully", m.name, instance)
  114. for {
  115. select {
  116. case <-ctx.Done():
  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 (m *SourceNode) drainError(errCh chan<- error, err error, ctx api.StreamContext, logger api.Logger) {
  153. select {
  154. case errCh <- err:
  155. logger.Debugf("sent error: %v", err)
  156. case <-ctx.Done():
  157. }
  158. return
  159. }
  160. func (m *SourceNode) close(ctx api.StreamContext, logger api.Logger) {
  161. if !m.options.SHARED {
  162. for _, s := range m.sources {
  163. if err := s.Close(ctx); err != nil {
  164. logger.Warnf("close source fails: %v", err)
  165. }
  166. }
  167. } else {
  168. removeSourceInstance(m)
  169. }
  170. }