topo.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. // Copyright 2021-2023 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 topo
  15. import (
  16. "context"
  17. "fmt"
  18. "strconv"
  19. "sync"
  20. "github.com/lf-edge/ekuiper/internal/conf"
  21. "github.com/lf-edge/ekuiper/internal/topo/checkpoint"
  22. kctx "github.com/lf-edge/ekuiper/internal/topo/context"
  23. "github.com/lf-edge/ekuiper/internal/topo/node"
  24. "github.com/lf-edge/ekuiper/internal/topo/node/metric"
  25. "github.com/lf-edge/ekuiper/internal/topo/state"
  26. "github.com/lf-edge/ekuiper/pkg/api"
  27. "github.com/lf-edge/ekuiper/pkg/infra"
  28. )
  29. type Topo struct {
  30. sources []node.DataSourceNode
  31. sinks []*node.SinkNode
  32. ctx api.StreamContext
  33. cancel context.CancelFunc
  34. drain chan error
  35. ops []node.OperatorNode
  36. name string
  37. qos api.Qos
  38. checkpointInterval int
  39. store api.Store
  40. coordinator *checkpoint.Coordinator
  41. topo *api.PrintableTopo
  42. mu sync.Mutex
  43. }
  44. func NewWithNameAndQos(name string, qos api.Qos, checkpointInterval int) (*Topo, error) {
  45. tp := &Topo{
  46. name: name,
  47. qos: qos,
  48. checkpointInterval: checkpointInterval,
  49. topo: &api.PrintableTopo{
  50. Sources: make([]string, 0),
  51. Edges: make(map[string][]interface{}),
  52. },
  53. }
  54. return tp, nil
  55. }
  56. func (s *Topo) GetContext() api.StreamContext {
  57. return s.ctx
  58. }
  59. // Cancel may be called multiple times so must be idempotent
  60. func (s *Topo) Cancel() {
  61. s.mu.Lock()
  62. defer s.mu.Unlock()
  63. // completion signal
  64. infra.DrainError(s.ctx, nil, s.drain)
  65. if s.cancel != nil {
  66. s.cancel()
  67. }
  68. s.store = nil
  69. s.coordinator = nil
  70. }
  71. func (s *Topo) AddSrc(src node.DataSourceNode) *Topo {
  72. s.sources = append(s.sources, src)
  73. s.topo.Sources = append(s.topo.Sources, fmt.Sprintf("source_%s", src.GetName()))
  74. return s
  75. }
  76. func (s *Topo) AddSink(inputs []api.Emitter, snk *node.SinkNode) *Topo {
  77. for _, input := range inputs {
  78. input.AddOutput(snk.GetInput())
  79. snk.AddInputCount()
  80. s.addEdge(input.(api.TopNode), snk, "sink")
  81. }
  82. s.sinks = append(s.sinks, snk)
  83. return s
  84. }
  85. func (s *Topo) AddOperator(inputs []api.Emitter, operator node.OperatorNode) *Topo {
  86. for _, input := range inputs {
  87. input.AddOutput(operator.GetInput())
  88. operator.AddInputCount()
  89. s.addEdge(input.(api.TopNode), operator, "op")
  90. }
  91. s.ops = append(s.ops, operator)
  92. return s
  93. }
  94. func (s *Topo) addEdge(from api.TopNode, to api.TopNode, toType string) {
  95. fromType := "op"
  96. if _, ok := from.(node.DataSourceNode); ok {
  97. fromType = "source"
  98. }
  99. f := fmt.Sprintf("%s_%s", fromType, from.GetName())
  100. t := fmt.Sprintf("%s_%s", toType, to.GetName())
  101. e, ok := s.topo.Edges[f]
  102. if !ok {
  103. e = make([]interface{}, 0)
  104. }
  105. s.topo.Edges[f] = append(e, t)
  106. }
  107. // prepareContext setups internal context before
  108. // stream starts execution.
  109. func (s *Topo) prepareContext() {
  110. if s.ctx == nil || s.ctx.Err() != nil {
  111. contextLogger := conf.Log.WithField("rule", s.name)
  112. ctx := kctx.WithValue(kctx.Background(), kctx.LoggerKey, contextLogger)
  113. s.ctx, s.cancel = ctx.WithCancel()
  114. }
  115. }
  116. func (s *Topo) Open() <-chan error {
  117. // if stream has opened, do nothing
  118. if s.ctx != nil && s.ctx.Err() == nil {
  119. s.ctx.GetLogger().Infoln("rule is already running, do nothing")
  120. return s.drain
  121. }
  122. s.prepareContext() // ensure context is set
  123. s.drain = make(chan error)
  124. log := s.ctx.GetLogger()
  125. log.Infoln("Opening stream")
  126. go func() {
  127. err := infra.SafeRun(func() error {
  128. s.mu.Lock()
  129. defer s.mu.Unlock()
  130. var err error
  131. if s.store, err = state.CreateStore(s.name, s.qos); err != nil {
  132. return fmt.Errorf("topo %s create store error %v", s.name, err)
  133. }
  134. s.enableCheckpoint()
  135. // open stream sink, after log sink is ready.
  136. for _, snk := range s.sinks {
  137. snk.Open(s.ctx.WithMeta(s.name, snk.GetName(), s.store), s.drain)
  138. }
  139. // apply operators, if err bail
  140. for _, op := range s.ops {
  141. op.Exec(s.ctx.WithMeta(s.name, op.GetName(), s.store), s.drain)
  142. }
  143. // open source, if err bail
  144. for _, source := range s.sources {
  145. source.Open(s.ctx.WithMeta(s.name, source.GetName(), s.store), s.drain)
  146. }
  147. // activate checkpoint
  148. if s.coordinator != nil {
  149. s.coordinator.Activate()
  150. }
  151. return nil
  152. })
  153. if err != nil {
  154. infra.DrainError(s.ctx, err, s.drain)
  155. }
  156. }()
  157. return s.drain
  158. }
  159. func (s *Topo) enableCheckpoint() error {
  160. if s.qos >= api.AtLeastOnce {
  161. var sources []checkpoint.StreamTask
  162. for _, r := range s.sources {
  163. sources = append(sources, r)
  164. }
  165. var ops []checkpoint.NonSourceTask
  166. for _, r := range s.ops {
  167. ops = append(ops, r)
  168. }
  169. var sinks []checkpoint.SinkTask
  170. for _, r := range s.sinks {
  171. sinks = append(sinks, r)
  172. }
  173. c := checkpoint.NewCoordinator(s.name, sources, ops, sinks, s.qos, s.store, s.checkpointInterval, s.ctx)
  174. s.coordinator = c
  175. }
  176. return nil
  177. }
  178. func (s *Topo) GetCoordinator() *checkpoint.Coordinator {
  179. return s.coordinator
  180. }
  181. func (s *Topo) GetMetrics() (keys []string, values []interface{}) {
  182. for _, sn := range s.sources {
  183. for ins, metrics := range sn.GetMetrics() {
  184. for i, v := range metrics {
  185. keys = append(keys, "source_"+sn.GetName()+"_"+strconv.Itoa(ins)+"_"+metric.MetricNames[i])
  186. values = append(values, v)
  187. }
  188. }
  189. }
  190. for _, so := range s.ops {
  191. for ins, metrics := range so.GetMetrics() {
  192. for i, v := range metrics {
  193. keys = append(keys, "op_"+so.GetName()+"_"+strconv.Itoa(ins)+"_"+metric.MetricNames[i])
  194. values = append(values, v)
  195. }
  196. }
  197. }
  198. for _, sn := range s.sinks {
  199. for ins, metrics := range sn.GetMetrics() {
  200. for i, v := range metrics {
  201. keys = append(keys, "sink_"+sn.GetName()+"_"+strconv.Itoa(ins)+"_"+metric.MetricNames[i])
  202. values = append(values, v)
  203. }
  204. }
  205. }
  206. return
  207. }
  208. func (s *Topo) RemoveMetrics() {
  209. for _, sn := range s.sources {
  210. sn.RemoveMetrics(s.name)
  211. }
  212. for _, so := range s.ops {
  213. so.RemoveMetrics(s.name)
  214. }
  215. for _, sn := range s.sinks {
  216. sn.RemoveMetrics(s.name)
  217. }
  218. }
  219. func (s *Topo) GetTopo() *api.PrintableTopo {
  220. return s.topo
  221. }