source_pool.go 7.8 KB

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