planner.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. package planner
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/lf-edge/ekuiper/internal/conf"
  6. "github.com/lf-edge/ekuiper/internal/topo"
  7. "github.com/lf-edge/ekuiper/internal/topo/node"
  8. "github.com/lf-edge/ekuiper/internal/topo/operator"
  9. "github.com/lf-edge/ekuiper/internal/xsql"
  10. "github.com/lf-edge/ekuiper/pkg/api"
  11. "github.com/lf-edge/ekuiper/pkg/ast"
  12. "github.com/lf-edge/ekuiper/pkg/kv"
  13. "path"
  14. )
  15. func Plan(rule *api.Rule, storePath string) (*topo.Topo, error) {
  16. return PlanWithSourcesAndSinks(rule, storePath, nil, nil)
  17. }
  18. // For test only
  19. func PlanWithSourcesAndSinks(rule *api.Rule, storePath string, sources []*node.SourceNode, sinks []*node.SinkNode) (*topo.Topo, error) {
  20. sql := rule.Sql
  21. conf.Log.Infof("Init rule with options %+v", rule.Options)
  22. stmt, err := xsql.GetStatementFromSql(sql)
  23. if err != nil {
  24. return nil, err
  25. }
  26. // validation
  27. streamsFromStmt := xsql.GetStreams(stmt)
  28. //if len(sources) > 0 && len(sources) != len(streamsFromStmt) {
  29. // return nil, fmt.Errorf("Invalid parameter sources or streams, the length cannot match the statement, expect %d sources.", len(streamsFromStmt))
  30. //}
  31. if rule.Options.SendMetaToSink && (len(streamsFromStmt) > 1 || stmt.Dimensions != nil) {
  32. return nil, fmt.Errorf("Invalid option sendMetaToSink, it can not be applied to window")
  33. }
  34. store := kv.GetDefaultKVStore(path.Join(storePath, "stream"))
  35. err = store.Open()
  36. if err != nil {
  37. return nil, err
  38. }
  39. defer store.Close()
  40. // Create logical plan and optimize. Logical plans are a linked list
  41. lp, err := createLogicalPlan(stmt, rule.Options, store)
  42. if err != nil {
  43. return nil, err
  44. }
  45. tp, err := createTopo(rule, lp, sources, sinks, streamsFromStmt)
  46. if err != nil {
  47. return nil, err
  48. }
  49. return tp, nil
  50. }
  51. func createTopo(rule *api.Rule, lp LogicalPlan, sources []*node.SourceNode, sinks []*node.SinkNode, streamsFromStmt []string) (*topo.Topo, error) {
  52. // Create topology
  53. tp, err := topo.NewWithNameAndQos(rule.Id, rule.Options.Qos, rule.Options.CheckpointInterval)
  54. if err != nil {
  55. return nil, err
  56. }
  57. input, _, err := buildOps(lp, tp, rule.Options, sources, streamsFromStmt, 0)
  58. if err != nil {
  59. return nil, err
  60. }
  61. inputs := []api.Emitter{input}
  62. // Add actions
  63. if len(sinks) > 0 { // For use of mock sink in testing
  64. for _, sink := range sinks {
  65. tp.AddSink(inputs, sink)
  66. }
  67. } else {
  68. for i, m := range rule.Actions {
  69. for name, action := range m {
  70. props, ok := action.(map[string]interface{})
  71. if !ok {
  72. return nil, fmt.Errorf("expect map[string]interface{} type for the action properties, but found %v", action)
  73. }
  74. tp.AddSink(inputs, node.NewSinkNode(fmt.Sprintf("%s_%d", name, i), name, props))
  75. }
  76. }
  77. }
  78. return tp, nil
  79. }
  80. func buildOps(lp LogicalPlan, tp *topo.Topo, options *api.RuleOption, sources []*node.SourceNode, streamsFromStmt []string, index int) (api.Emitter, int, error) {
  81. var inputs []api.Emitter
  82. newIndex := index
  83. for _, c := range lp.Children() {
  84. input, ni, err := buildOps(c, tp, options, sources, streamsFromStmt, newIndex)
  85. if err != nil {
  86. return nil, 0, err
  87. }
  88. newIndex = ni
  89. inputs = append(inputs, input)
  90. }
  91. newIndex++
  92. var (
  93. op node.OperatorNode
  94. err error
  95. )
  96. switch t := lp.(type) {
  97. case *DataSourcePlan:
  98. switch t.streamStmt.StreamType {
  99. case ast.TypeStream:
  100. pp, err := operator.NewPreprocessor(t.streamFields, t.allMeta, t.metaFields, t.iet, t.timestampField, t.timestampFormat, t.isBinary)
  101. if err != nil {
  102. return nil, 0, err
  103. }
  104. var srcNode *node.SourceNode
  105. if len(sources) == 0 {
  106. node := node.NewSourceNode(string(t.name), t.streamStmt.StreamType, t.streamStmt.Options)
  107. srcNode = node
  108. } else {
  109. srcNode = getMockSource(sources, string(t.name))
  110. if srcNode == nil {
  111. return nil, 0, fmt.Errorf("can't find predefined source %s", t.name)
  112. }
  113. }
  114. tp.AddSrc(srcNode)
  115. op = Transform(pp, fmt.Sprintf("%d_preprocessor_%s", newIndex, t.name), options)
  116. inputs = []api.Emitter{srcNode}
  117. case ast.TypeTable:
  118. pp, err := operator.NewTableProcessor(string(t.name), t.streamFields, t.streamStmt.Options)
  119. if err != nil {
  120. return nil, 0, err
  121. }
  122. var srcNode *node.SourceNode
  123. if len(sources) > 0 {
  124. srcNode = getMockSource(sources, string(t.name))
  125. }
  126. if srcNode == nil {
  127. srcNode = node.NewSourceNode(string(t.name), t.streamStmt.StreamType, t.streamStmt.Options)
  128. }
  129. tp.AddSrc(srcNode)
  130. op = Transform(pp, fmt.Sprintf("%d_tableprocessor_%s", newIndex, t.name), options)
  131. inputs = []api.Emitter{srcNode}
  132. }
  133. case *WindowPlan:
  134. if t.condition != nil {
  135. wfilterOp := Transform(&operator.FilterOp{Condition: t.condition}, fmt.Sprintf("%d_windowFilter", newIndex), options)
  136. wfilterOp.SetConcurrency(options.Concurrency)
  137. tp.AddOperator(inputs, wfilterOp)
  138. inputs = []api.Emitter{wfilterOp}
  139. }
  140. op, err = node.NewWindowOp(fmt.Sprintf("%d_window", newIndex), node.WindowConfig{
  141. Type: t.wtype,
  142. Length: t.length,
  143. Interval: t.interval,
  144. }, streamsFromStmt, options)
  145. if err != nil {
  146. return nil, 0, err
  147. }
  148. case *JoinAlignPlan:
  149. op, err = node.NewJoinAlignNode(fmt.Sprintf("%d_join_aligner", newIndex), t.Emitters, options)
  150. case *JoinPlan:
  151. op = Transform(&operator.JoinOp{Joins: t.joins, From: t.from}, fmt.Sprintf("%d_join", newIndex), options)
  152. case *FilterPlan:
  153. op = Transform(&operator.FilterOp{Condition: t.condition}, fmt.Sprintf("%d_filter", newIndex), options)
  154. case *AggregatePlan:
  155. op = Transform(&operator.AggregateOp{Dimensions: t.dimensions}, fmt.Sprintf("%d_aggregate", newIndex), options)
  156. case *HavingPlan:
  157. op = Transform(&operator.HavingOp{Condition: t.condition}, fmt.Sprintf("%d_having", newIndex), options)
  158. case *OrderPlan:
  159. op = Transform(&operator.OrderOp{SortFields: t.SortFields}, fmt.Sprintf("%d_order", newIndex), options)
  160. case *ProjectPlan:
  161. op = Transform(&operator.ProjectOp{Fields: t.fields, IsAggregate: t.isAggregate, SendMeta: t.sendMeta}, fmt.Sprintf("%d_project", newIndex), options)
  162. default:
  163. return nil, 0, fmt.Errorf("unknown logical plan %v", t)
  164. }
  165. if uop, ok := op.(*node.UnaryOperator); ok {
  166. uop.SetConcurrency(options.Concurrency)
  167. }
  168. tp.AddOperator(inputs, op)
  169. return op, newIndex, nil
  170. }
  171. func getMockSource(sources []*node.SourceNode, name string) *node.SourceNode {
  172. for _, source := range sources {
  173. if name == source.GetName() {
  174. return source
  175. }
  176. }
  177. return nil
  178. }
  179. func createLogicalPlan(stmt *ast.SelectStatement, opt *api.RuleOption, store kv.KeyValue) (LogicalPlan, error) {
  180. dimensions := stmt.Dimensions
  181. var (
  182. p LogicalPlan
  183. children []LogicalPlan
  184. // If there are tables, the plan graph will be different for join/window
  185. tableChildren []LogicalPlan
  186. tableEmitters []string
  187. w *ast.Window
  188. ds ast.Dimensions
  189. )
  190. streamStmts, err := decorateStmt(stmt, store)
  191. if err != nil {
  192. return nil, err
  193. }
  194. for _, streamStmt := range streamStmts {
  195. p = DataSourcePlan{
  196. name: streamStmt.Name,
  197. streamStmt: streamStmt,
  198. iet: opt.IsEventTime,
  199. allMeta: opt.SendMetaToSink,
  200. }.Init()
  201. if streamStmt.StreamType == ast.TypeStream {
  202. children = append(children, p)
  203. } else {
  204. tableChildren = append(tableChildren, p)
  205. tableEmitters = append(tableEmitters, string(streamStmt.Name))
  206. }
  207. }
  208. if dimensions != nil {
  209. w = dimensions.GetWindow()
  210. if w != nil {
  211. if len(children) == 0 {
  212. return nil, errors.New("cannot run window for TABLE sources")
  213. }
  214. wp := WindowPlan{
  215. wtype: w.WindowType,
  216. length: w.Length.Val,
  217. isEventTime: opt.IsEventTime,
  218. }.Init()
  219. if w.Interval != nil {
  220. wp.interval = w.Interval.Val
  221. } else if w.WindowType == ast.COUNT_WINDOW {
  222. //if no interval value is set and it's count window, then set interval to length value.
  223. wp.interval = w.Length.Val
  224. }
  225. if w.Filter != nil {
  226. wp.condition = w.Filter
  227. }
  228. // TODO calculate limit
  229. // TODO incremental aggregate
  230. wp.SetChildren(children)
  231. children = []LogicalPlan{wp}
  232. p = wp
  233. }
  234. }
  235. if stmt.Joins != nil {
  236. if len(tableChildren) > 0 {
  237. p = JoinAlignPlan{
  238. Emitters: tableEmitters,
  239. }.Init()
  240. p.SetChildren(append(children, tableChildren...))
  241. children = []LogicalPlan{p}
  242. } else if w == nil {
  243. return nil, errors.New("need to run stream join in windows")
  244. }
  245. // TODO extract on filter
  246. p = JoinPlan{
  247. from: stmt.Sources[0].(*ast.Table),
  248. joins: stmt.Joins,
  249. }.Init()
  250. p.SetChildren(children)
  251. children = []LogicalPlan{p}
  252. }
  253. if stmt.Condition != nil {
  254. p = FilterPlan{
  255. condition: stmt.Condition,
  256. }.Init()
  257. p.SetChildren(children)
  258. children = []LogicalPlan{p}
  259. }
  260. // TODO handle aggregateAlias in optimization as it does not only happen in select fields
  261. if dimensions != nil {
  262. ds = dimensions.GetGroups()
  263. if ds != nil && len(ds) > 0 {
  264. p = AggregatePlan{
  265. dimensions: ds,
  266. }.Init()
  267. p.SetChildren(children)
  268. children = []LogicalPlan{p}
  269. }
  270. }
  271. if stmt.Having != nil {
  272. p = HavingPlan{
  273. condition: stmt.Having,
  274. }.Init()
  275. p.SetChildren(children)
  276. children = []LogicalPlan{p}
  277. }
  278. if stmt.SortFields != nil {
  279. p = OrderPlan{
  280. SortFields: stmt.SortFields,
  281. }.Init()
  282. p.SetChildren(children)
  283. children = []LogicalPlan{p}
  284. }
  285. if stmt.Fields != nil {
  286. p = ProjectPlan{
  287. fields: stmt.Fields,
  288. isAggregate: ast.IsAggStatement(stmt),
  289. sendMeta: opt.SendMetaToSink,
  290. }.Init()
  291. p.SetChildren(children)
  292. }
  293. return optimize(p)
  294. }
  295. func Transform(op node.UnOperation, name string, options *api.RuleOption) *node.UnaryOperator {
  296. operator := node.New(name, xsql.FuncRegisters, options)
  297. operator.SetOperation(op)
  298. return operator
  299. }