planner.go 9.9 KB

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