source_pool.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. "context"
  17. "fmt"
  18. "github.com/lf-edge/ekuiper/internal/conf"
  19. kctx "github.com/lf-edge/ekuiper/internal/topo/context"
  20. "github.com/lf-edge/ekuiper/pkg/api"
  21. "sync"
  22. )
  23. //// Package vars and funcs
  24. var (
  25. pool = &sourcePool{
  26. registry: make(map[string]*sourceSingleton),
  27. }
  28. )
  29. // node is readonly
  30. func getSourceInstance(node *SourceNode, index int) (*sourceInstance, error) {
  31. var si *sourceInstance
  32. if node.options.SHARED {
  33. rkey := fmt.Sprintf("%s.%s", node.sourceType, node.name)
  34. s, ok := pool.load(rkey)
  35. if !ok {
  36. ns, err := getSource(node.sourceType)
  37. if err != nil {
  38. return nil, err
  39. }
  40. s, err = pool.addInstance(rkey, node, ns, index)
  41. if err != nil {
  42. return nil, err
  43. }
  44. }
  45. // attach
  46. instanceKey := fmt.Sprintf("%s.%s.%d", rkey, node.ctx.GetRuleId(), index)
  47. err := s.attach(instanceKey, node.bufferLength)
  48. if err != nil {
  49. return nil, err
  50. }
  51. si = &sourceInstance{
  52. source: s.source,
  53. ctx: s.ctx,
  54. sourceInstanceChannels: s.outputs[instanceKey],
  55. }
  56. } else {
  57. ns, err := getSource(node.sourceType)
  58. if err != nil {
  59. return nil, err
  60. }
  61. si, err = start(nil, node, ns, index)
  62. if err != nil {
  63. return nil, err
  64. }
  65. }
  66. return si, nil
  67. }
  68. // removeSourceInstance remove an attach from the sourceSingleton
  69. // If all attaches are removed, close the sourceSingleton and remove it from the pool registry
  70. // ONLY apply to shared instance
  71. func removeSourceInstance(node *SourceNode) {
  72. for i := 0; i < node.concurrency; i++ {
  73. rkey := fmt.Sprintf("%s.%s", node.sourceType, node.name)
  74. pool.deleteInstance(rkey, node, i)
  75. }
  76. }
  77. //// data types
  78. /*
  79. * Pool for all keyed source instance.
  80. * Create an instance, and start the source go routine when the keyed was hit the first time.
  81. * For later hit, create the new set of channels and attach to the instance
  82. * When hit a delete (when close a rule), remove the attached channels. If all channels removed, remove the instance from the pool
  83. * For performance reason, the pool only holds the shared instance. Rule specific instance are holden by rule source node itself
  84. */
  85. type sourcePool struct {
  86. registry map[string]*sourceSingleton
  87. sync.RWMutex
  88. }
  89. func (p *sourcePool) load(k string) (*sourceSingleton, bool) {
  90. p.RLock()
  91. defer p.RUnlock()
  92. s, ok := p.registry[k]
  93. return s, ok
  94. }
  95. func (p *sourcePool) addInstance(k string, node *SourceNode, source api.Source, index int) (*sourceSingleton, error) {
  96. p.Lock()
  97. defer p.Unlock()
  98. s, ok := p.registry[k]
  99. if !ok {
  100. contextLogger := conf.Log.WithField("source_pool", k)
  101. ctx := kctx.WithValue(kctx.Background(), kctx.LoggerKey, contextLogger)
  102. // TODO cancel
  103. sctx, cancel := ctx.WithCancel()
  104. si, err := start(sctx, node, source, index)
  105. if err != nil {
  106. return nil, err
  107. }
  108. newS := &sourceSingleton{
  109. sourceInstance: si,
  110. outputs: make(map[string]*sourceInstanceChannels),
  111. cancel: cancel,
  112. }
  113. p.registry[k] = newS
  114. go newS.run(node.sourceType, node.name)
  115. s = newS
  116. }
  117. return s, nil
  118. }
  119. func (p *sourcePool) deleteInstance(k string, node *SourceNode, index int) {
  120. p.Lock()
  121. defer p.Unlock()
  122. s, ok := p.registry[k]
  123. if ok {
  124. instanceKey := fmt.Sprintf("%s.%s.%d", k, node.ctx.GetRuleId(), index)
  125. end := s.detach(instanceKey)
  126. if end {
  127. s.cancel()
  128. s.source.Close(s.ctx)
  129. delete(p.registry, k)
  130. }
  131. }
  132. }
  133. type sourceInstance struct {
  134. source api.Source
  135. ctx api.StreamContext
  136. *sourceInstanceChannels
  137. }
  138. // Hold the only instance for all shared source
  139. // And hold the reference to all shared source input channels. Must be sync when dealing with outputs
  140. type sourceSingleton struct {
  141. *sourceInstance // immutable
  142. cancel context.CancelFunc // immutable
  143. outputs map[string]*sourceInstanceChannels // read-write lock
  144. sync.RWMutex
  145. }
  146. type sourceInstanceChannels struct {
  147. dataCh *DynamicChannelBuffer
  148. errorCh chan error
  149. }
  150. func newSourceInstanceChannels(bl int) *sourceInstanceChannels {
  151. buffer := NewDynamicChannelBuffer()
  152. buffer.SetLimit(bl)
  153. errorOutput := make(chan error)
  154. return &sourceInstanceChannels{
  155. dataCh: buffer,
  156. errorCh: errorOutput,
  157. }
  158. }
  159. func (ss *sourceSingleton) run(name, key string) {
  160. logger := ss.ctx.GetLogger()
  161. logger.Infof("Start source %s shared instance %s successfully", name, key)
  162. for {
  163. select {
  164. case <-ss.ctx.Done():
  165. logger.Infof("source %s shared instance %s done", name, key)
  166. return
  167. case err := <-ss.errorCh:
  168. ss.broadcastError(err)
  169. return
  170. case data := <-ss.dataCh.Out:
  171. logger.Debugf("broadcast data %v from source pool %s:%s", data, name, key)
  172. ss.broadcast(data)
  173. }
  174. }
  175. }
  176. func (ss *sourceSingleton) broadcast(val api.SourceTuple) {
  177. logger := ss.ctx.GetLogger()
  178. var wg sync.WaitGroup
  179. ss.RLock()
  180. wg.Add(len(ss.outputs))
  181. for n, out := range ss.outputs {
  182. go func(name string, output chan<- api.SourceTuple) {
  183. select {
  184. case output <- val:
  185. logger.Debugf("broadcast from source pool to %s done", name)
  186. case <-ss.ctx.Done():
  187. // rule stop so stop waiting
  188. }
  189. wg.Done()
  190. }(n, out.dataCh.Out)
  191. }
  192. ss.RUnlock()
  193. wg.Wait()
  194. }
  195. func (ss *sourceSingleton) broadcastError(err error) {
  196. logger := ss.ctx.GetLogger()
  197. var wg sync.WaitGroup
  198. ss.RLock()
  199. wg.Add(len(ss.outputs))
  200. for n, out := range ss.outputs {
  201. go func(name string, output chan<- error) {
  202. select {
  203. case output <- err:
  204. logger.Debugf("broadcast error from source pool to %s done", name)
  205. case <-ss.ctx.Done():
  206. // rule stop so stop waiting
  207. }
  208. wg.Done()
  209. }(n, out.errorCh)
  210. }
  211. ss.RLock()
  212. logger.Debugf("broadcasting from source pool")
  213. wg.Wait()
  214. }
  215. func (ss *sourceSingleton) attach(instanceKey string, bl int) error {
  216. ss.Lock()
  217. defer ss.Unlock()
  218. if _, ok := ss.outputs[instanceKey]; !ok {
  219. ss.outputs[instanceKey] = newSourceInstanceChannels(bl)
  220. } else {
  221. // should not happen
  222. return fmt.Errorf("fail to attach source instance, already has an output of the same key %s", instanceKey)
  223. }
  224. return nil
  225. }
  226. // detach Detach an instance and return if the singleton is ended
  227. func (ss *sourceSingleton) detach(instanceKey string) bool {
  228. ss.Lock()
  229. defer ss.Unlock()
  230. if chs, ok := ss.outputs[instanceKey]; ok {
  231. chs.dataCh.Close()
  232. } else {
  233. // should not happen
  234. ss.ctx.GetLogger().Warnf("detach source instance %s, not found", instanceKey)
  235. }
  236. delete(ss.outputs, instanceKey)
  237. if len(ss.outputs) == 0 {
  238. ss.cancel()
  239. return true
  240. }
  241. return false
  242. }
  243. func start(poolCtx api.StreamContext, node *SourceNode, s api.Source, instanceIndex int) (*sourceInstance, error) {
  244. err := s.Configure(node.options.DATASOURCE, node.props)
  245. if err != nil {
  246. return nil, err
  247. }
  248. ctx := poolCtx
  249. if poolCtx == nil {
  250. ctx = node.ctx
  251. if rw, ok := s.(api.Rewindable); ok {
  252. if offset, err := ctx.GetState(OffsetKey); err != nil {
  253. return nil, err
  254. } else if offset != nil {
  255. ctx.GetLogger().Infof("Source rewind from %v", offset)
  256. err = rw.Rewind(offset)
  257. if err != nil {
  258. return nil, err
  259. }
  260. }
  261. }
  262. }
  263. chs := newSourceInstanceChannels(node.bufferLength)
  264. go s.Open(ctx.WithInstance(instanceIndex), chs.dataCh.In, chs.errorCh)
  265. return &sourceInstance{
  266. source: s,
  267. sourceInstanceChannels: chs,
  268. ctx: ctx,
  269. }, nil
  270. }