source_pool.go 8.9 KB

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