planner.go 9.9 KB

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