planner.go 10 KB

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