topo.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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 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. "strconv"
  25. )
  26. type PrintableTopo struct {
  27. Sources []string `json:"sources"`
  28. Edges map[string][]string `json:"edges"`
  29. }
  30. type Topo struct {
  31. sources []node.DataSourceNode
  32. sinks []*node.SinkNode
  33. ctx api.StreamContext
  34. cancel context.CancelFunc
  35. drain chan error
  36. ops []node.OperatorNode
  37. name string
  38. qos api.Qos
  39. checkpointInterval int
  40. store api.Store
  41. coordinator *checkpoint.Coordinator
  42. topo *PrintableTopo
  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: &PrintableTopo{
  50. Sources: make([]string, 0),
  51. Edges: make(map[string][]string),
  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. // completion signal
  62. s.drainErr(nil)
  63. s.cancel()
  64. s.store = nil
  65. s.coordinator = nil
  66. }
  67. func (s *Topo) AddSrc(src node.DataSourceNode) *Topo {
  68. s.sources = append(s.sources, src)
  69. s.topo.Sources = append(s.topo.Sources, fmt.Sprintf("source_%s", src.GetName()))
  70. return s
  71. }
  72. func (s *Topo) AddSink(inputs []api.Emitter, snk *node.SinkNode) *Topo {
  73. for _, input := range inputs {
  74. input.AddOutput(snk.GetInput())
  75. snk.AddInputCount()
  76. s.addEdge(input.(api.TopNode), snk, "sink")
  77. }
  78. s.sinks = append(s.sinks, snk)
  79. return s
  80. }
  81. func (s *Topo) AddOperator(inputs []api.Emitter, operator node.OperatorNode) *Topo {
  82. for _, input := range inputs {
  83. input.AddOutput(operator.GetInput())
  84. operator.AddInputCount()
  85. s.addEdge(input.(api.TopNode), operator, "op")
  86. }
  87. s.ops = append(s.ops, operator)
  88. return s
  89. }
  90. func (s *Topo) addEdge(from api.TopNode, to api.TopNode, toType string) {
  91. fromType := "op"
  92. if _, ok := from.(node.DataSourceNode); ok {
  93. fromType = "source"
  94. }
  95. f := fmt.Sprintf("%s_%s", fromType, from.GetName())
  96. t := fmt.Sprintf("%s_%s", toType, to.GetName())
  97. e, ok := s.topo.Edges[f]
  98. if !ok {
  99. e = make([]string, 0)
  100. }
  101. s.topo.Edges[f] = append(e, t)
  102. }
  103. // prepareContext setups internal context before
  104. // stream starts execution.
  105. func (s *Topo) prepareContext() {
  106. if s.ctx == nil || s.ctx.Err() != nil {
  107. contextLogger := conf.Log.WithField("rule", s.name)
  108. ctx := kctx.WithValue(kctx.Background(), kctx.LoggerKey, contextLogger)
  109. s.ctx, s.cancel = ctx.WithCancel()
  110. }
  111. }
  112. func (s *Topo) drainErr(err error) {
  113. select {
  114. case s.drain <- err:
  115. if err != nil {
  116. s.ctx.GetLogger().Errorf("topo %s drain error %v", s.name, err)
  117. }
  118. default:
  119. s.ctx.GetLogger().Infof("topo %s drain error %v, but receiver closed so ignored", s.name, err)
  120. }
  121. }
  122. func (s *Topo) Open() <-chan error {
  123. //if stream has opened, do nothing
  124. if s.ctx != nil && s.ctx.Err() == nil {
  125. s.ctx.GetLogger().Infoln("rule is already running, do nothing")
  126. return s.drain
  127. }
  128. s.prepareContext() // ensure context is set
  129. s.drain = make(chan error)
  130. log := s.ctx.GetLogger()
  131. log.Infoln("Opening stream")
  132. // open stream
  133. go func() {
  134. var err error
  135. if s.store, err = state.CreateStore(s.name, s.qos); err != nil {
  136. fmt.Println(err)
  137. s.drain <- err
  138. return
  139. }
  140. s.enableCheckpoint()
  141. // open stream sink, after log sink is ready.
  142. for _, snk := range s.sinks {
  143. snk.Open(s.ctx.WithMeta(s.name, snk.GetName(), s.store), s.drain)
  144. }
  145. //apply operators, if err bail
  146. for _, op := range s.ops {
  147. op.Exec(s.ctx.WithMeta(s.name, op.GetName(), s.store), s.drain)
  148. }
  149. // open source, if err bail
  150. for _, node := range s.sources {
  151. node.Open(s.ctx.WithMeta(s.name, node.GetName(), s.store), s.drain)
  152. }
  153. // activate checkpoint
  154. if s.coordinator != nil {
  155. s.coordinator.Activate()
  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. }