planner.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. isSchemaless := t.streamStmt.StreamFields == nil
  110. switch t.streamStmt.StreamType {
  111. case ast.TypeStream:
  112. pp, err := operator.NewPreprocessor(isSchemaless, t.streamFields, t.allMeta, t.metaFields, t.iet, t.timestampField, t.timestampFormat, t.isBinary, t.streamStmt.Options.STRICT_VALIDATION)
  113. if err != nil {
  114. return nil, 0, err
  115. }
  116. var srcNode *node.SourceNode
  117. if len(sources) == 0 {
  118. sourceNode := node.NewSourceNode(string(t.name), t.streamStmt.StreamType, pp, t.streamStmt.Options, options.SendError)
  119. srcNode = sourceNode
  120. } else {
  121. srcNode = getMockSource(sources, string(t.name))
  122. if srcNode == nil {
  123. return nil, 0, fmt.Errorf("can't find predefined source %s", t.name)
  124. }
  125. }
  126. tp.AddSrc(srcNode)
  127. inputs = []api.Emitter{srcNode}
  128. op = srcNode
  129. case ast.TypeTable:
  130. pp, err := operator.NewTableProcessor(isSchemaless, string(t.name), t.streamFields, t.streamStmt.Options)
  131. if err != nil {
  132. return nil, 0, err
  133. }
  134. var srcNode *node.SourceNode
  135. if len(sources) > 0 {
  136. srcNode = getMockSource(sources, string(t.name))
  137. }
  138. if srcNode == nil {
  139. srcNode = node.NewSourceNode(string(t.name), t.streamStmt.StreamType, pp, t.streamStmt.Options, options.SendError)
  140. }
  141. tp.AddSrc(srcNode)
  142. inputs = []api.Emitter{srcNode}
  143. op = srcNode
  144. }
  145. case *WindowPlan:
  146. if t.condition != nil {
  147. wfilterOp := Transform(&operator.FilterOp{Condition: t.condition}, fmt.Sprintf("%d_windowFilter", newIndex), options)
  148. wfilterOp.SetConcurrency(options.Concurrency)
  149. tp.AddOperator(inputs, wfilterOp)
  150. inputs = []api.Emitter{wfilterOp}
  151. }
  152. op, err = node.NewWindowOp(fmt.Sprintf("%d_window", newIndex), node.WindowConfig{
  153. Type: t.wtype,
  154. Length: t.length,
  155. Interval: t.interval,
  156. }, streamsFromStmt, options)
  157. if err != nil {
  158. return nil, 0, err
  159. }
  160. case *JoinAlignPlan:
  161. op, err = node.NewJoinAlignNode(fmt.Sprintf("%d_join_aligner", newIndex), t.Emitters, options)
  162. case *JoinPlan:
  163. op = Transform(&operator.JoinOp{Joins: t.joins, From: t.from}, fmt.Sprintf("%d_join", newIndex), options)
  164. case *FilterPlan:
  165. op = Transform(&operator.FilterOp{Condition: t.condition}, fmt.Sprintf("%d_filter", newIndex), options)
  166. case *AggregatePlan:
  167. op = Transform(&operator.AggregateOp{Dimensions: t.dimensions}, fmt.Sprintf("%d_aggregate", newIndex), options)
  168. case *HavingPlan:
  169. op = Transform(&operator.HavingOp{Condition: t.condition}, fmt.Sprintf("%d_having", newIndex), options)
  170. case *OrderPlan:
  171. op = Transform(&operator.OrderOp{SortFields: t.SortFields}, fmt.Sprintf("%d_order", newIndex), options)
  172. case *ProjectPlan:
  173. op = Transform(&operator.ProjectOp{Fields: t.fields, IsAggregate: t.isAggregate, SendMeta: t.sendMeta}, fmt.Sprintf("%d_project", newIndex), options)
  174. default:
  175. return nil, 0, fmt.Errorf("unknown logical plan %v", t)
  176. }
  177. if uop, ok := op.(*node.UnaryOperator); ok {
  178. uop.SetConcurrency(options.Concurrency)
  179. }
  180. if onode, ok := op.(node.OperatorNode); ok {
  181. tp.AddOperator(inputs, onode)
  182. }
  183. return op, newIndex, nil
  184. }
  185. func getMockSource(sources []*node.SourceNode, name string) *node.SourceNode {
  186. for _, source := range sources {
  187. if name == source.GetName() {
  188. return source
  189. }
  190. }
  191. return nil
  192. }
  193. func createLogicalPlan(stmt *ast.SelectStatement, opt *api.RuleOption, store kv.KeyValue) (LogicalPlan, error) {
  194. dimensions := stmt.Dimensions
  195. var (
  196. p LogicalPlan
  197. children []LogicalPlan
  198. // If there are tables, the plan graph will be different for join/window
  199. tableChildren []LogicalPlan
  200. tableEmitters []string
  201. w *ast.Window
  202. ds ast.Dimensions
  203. )
  204. streamStmts, err := decorateStmt(stmt, store)
  205. if err != nil {
  206. return nil, err
  207. }
  208. for _, streamStmt := range streamStmts {
  209. p = DataSourcePlan{
  210. name: streamStmt.Name,
  211. streamStmt: streamStmt,
  212. iet: opt.IsEventTime,
  213. allMeta: opt.SendMetaToSink,
  214. }.Init()
  215. if streamStmt.StreamType == ast.TypeStream {
  216. children = append(children, p)
  217. } else {
  218. tableChildren = append(tableChildren, p)
  219. tableEmitters = append(tableEmitters, string(streamStmt.Name))
  220. }
  221. }
  222. if dimensions != nil {
  223. w = dimensions.GetWindow()
  224. if w != nil {
  225. if len(children) == 0 {
  226. return nil, errors.New("cannot run window for TABLE sources")
  227. }
  228. wp := WindowPlan{
  229. wtype: w.WindowType,
  230. length: w.Length.Val,
  231. isEventTime: opt.IsEventTime,
  232. }.Init()
  233. if w.Interval != nil {
  234. wp.interval = w.Interval.Val
  235. } else if w.WindowType == ast.COUNT_WINDOW {
  236. //if no interval value is set and it's count window, then set interval to length value.
  237. wp.interval = w.Length.Val
  238. }
  239. if w.Filter != nil {
  240. wp.condition = w.Filter
  241. }
  242. // TODO calculate limit
  243. // TODO incremental aggregate
  244. wp.SetChildren(children)
  245. children = []LogicalPlan{wp}
  246. p = wp
  247. }
  248. }
  249. if stmt.Joins != nil {
  250. if len(tableChildren) > 0 {
  251. p = JoinAlignPlan{
  252. Emitters: tableEmitters,
  253. }.Init()
  254. p.SetChildren(append(children, tableChildren...))
  255. children = []LogicalPlan{p}
  256. } else if w == nil {
  257. return nil, errors.New("a time window or count window is required to join multiple streams")
  258. }
  259. // TODO extract on filter
  260. p = JoinPlan{
  261. from: stmt.Sources[0].(*ast.Table),
  262. joins: stmt.Joins,
  263. }.Init()
  264. p.SetChildren(children)
  265. children = []LogicalPlan{p}
  266. }
  267. if stmt.Condition != nil {
  268. p = FilterPlan{
  269. condition: stmt.Condition,
  270. }.Init()
  271. p.SetChildren(children)
  272. children = []LogicalPlan{p}
  273. }
  274. // TODO handle aggregateAlias in optimization as it does not only happen in select fields
  275. if dimensions != nil {
  276. ds = dimensions.GetGroups()
  277. if ds != nil && len(ds) > 0 {
  278. p = AggregatePlan{
  279. dimensions: ds,
  280. }.Init()
  281. p.SetChildren(children)
  282. children = []LogicalPlan{p}
  283. }
  284. }
  285. if stmt.Having != nil {
  286. p = HavingPlan{
  287. condition: stmt.Having,
  288. }.Init()
  289. p.SetChildren(children)
  290. children = []LogicalPlan{p}
  291. }
  292. if stmt.SortFields != nil {
  293. p = OrderPlan{
  294. SortFields: stmt.SortFields,
  295. }.Init()
  296. p.SetChildren(children)
  297. children = []LogicalPlan{p}
  298. }
  299. if stmt.Fields != nil {
  300. p = ProjectPlan{
  301. fields: stmt.Fields,
  302. isAggregate: xsql.IsAggStatement(stmt),
  303. sendMeta: opt.SendMetaToSink,
  304. }.Init()
  305. p.SetChildren(children)
  306. }
  307. return optimize(p)
  308. }
  309. func Transform(op node.UnOperation, name string, options *api.RuleOption) *node.UnaryOperator {
  310. unaryOperator := node.New(name, options)
  311. unaryOperator.SetOperation(op)
  312. return unaryOperator
  313. }