topo.go 6.2 KB

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