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. "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. "path"
  27. )
  28. func Plan(rule *api.Rule, storePath string) (*topo.Topo, error) {
  29. return PlanWithSourcesAndSinks(rule, storePath, nil, nil)
  30. }
  31. // For test only
  32. func PlanWithSourcesAndSinks(rule *api.Rule, storePath string, 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. store := kv.GetDefaultKVStore(path.Join(storePath, "stream"))
  48. err = store.Open()
  49. if err != nil {
  50. return nil, err
  51. }
  52. defer store.Close()
  53. // Create logical plan and optimize. Logical plans are a linked list
  54. lp, err := createLogicalPlan(stmt, rule.Options, store)
  55. if err != nil {
  56. return nil, err
  57. }
  58. tp, err := createTopo(rule, lp, sources, sinks, streamsFromStmt)
  59. if err != nil {
  60. return nil, err
  61. }
  62. return tp, nil
  63. }
  64. func createTopo(rule *api.Rule, lp LogicalPlan, sources []*node.SourceNode, sinks []*node.SinkNode, streamsFromStmt []string) (*topo.Topo, error) {
  65. // Create topology
  66. tp, err := topo.NewWithNameAndQos(rule.Id, rule.Options.Qos, rule.Options.CheckpointInterval)
  67. if err != nil {
  68. return nil, err
  69. }
  70. input, _, err := buildOps(lp, tp, rule.Options, sources, streamsFromStmt, 0)
  71. if err != nil {
  72. return nil, err
  73. }
  74. inputs := []api.Emitter{input}
  75. // Add actions
  76. if len(sinks) > 0 { // For use of mock sink in testing
  77. for _, sink := range sinks {
  78. tp.AddSink(inputs, sink)
  79. }
  80. } else {
  81. for i, m := range rule.Actions {
  82. for name, action := range m {
  83. props, ok := action.(map[string]interface{})
  84. if !ok {
  85. return nil, fmt.Errorf("expect map[string]interface{} type for the action properties, but found %v", action)
  86. }
  87. tp.AddSink(inputs, node.NewSinkNode(fmt.Sprintf("%s_%d", name, i), name, props))
  88. }
  89. }
  90. }
  91. return tp, nil
  92. }
  93. func buildOps(lp LogicalPlan, tp *topo.Topo, options *api.RuleOption, sources []*node.SourceNode, streamsFromStmt []string, index int) (api.Emitter, int, error) {
  94. var inputs []api.Emitter
  95. newIndex := index
  96. for _, c := range lp.Children() {
  97. input, ni, err := buildOps(c, tp, options, sources, streamsFromStmt, newIndex)
  98. if err != nil {
  99. return nil, 0, err
  100. }
  101. newIndex = ni
  102. inputs = append(inputs, input)
  103. }
  104. newIndex++
  105. var (
  106. op node.OperatorNode
  107. err error
  108. )
  109. switch t := lp.(type) {
  110. case *DataSourcePlan:
  111. switch t.streamStmt.StreamType {
  112. case ast.TypeStream:
  113. pp, err := operator.NewPreprocessor(t.streamFields, t.allMeta, t.metaFields, t.iet, t.timestampField, t.timestampFormat, t.isBinary)
  114. if err != nil {
  115. return nil, 0, err
  116. }
  117. var srcNode *node.SourceNode
  118. if len(sources) == 0 {
  119. node := node.NewSourceNode(string(t.name), t.streamStmt.StreamType, t.streamStmt.Options)
  120. srcNode = node
  121. } else {
  122. srcNode = getMockSource(sources, string(t.name))
  123. if srcNode == nil {
  124. return nil, 0, fmt.Errorf("can't find predefined source %s", t.name)
  125. }
  126. }
  127. tp.AddSrc(srcNode)
  128. op = Transform(pp, fmt.Sprintf("%d_preprocessor_%s", newIndex, t.name), options)
  129. inputs = []api.Emitter{srcNode}
  130. case ast.TypeTable:
  131. pp, err := operator.NewTableProcessor(string(t.name), t.streamFields, t.streamStmt.Options)
  132. if err != nil {
  133. return nil, 0, err
  134. }
  135. var srcNode *node.SourceNode
  136. if len(sources) > 0 {
  137. srcNode = getMockSource(sources, string(t.name))
  138. }
  139. if srcNode == nil {
  140. srcNode = node.NewSourceNode(string(t.name), t.streamStmt.StreamType, t.streamStmt.Options)
  141. }
  142. tp.AddSrc(srcNode)
  143. op = Transform(pp, fmt.Sprintf("%d_tableprocessor_%s", newIndex, t.name), options)
  144. inputs = []api.Emitter{srcNode}
  145. }
  146. case *WindowPlan:
  147. if t.condition != nil {
  148. wfilterOp := Transform(&operator.FilterOp{Condition: t.condition}, fmt.Sprintf("%d_windowFilter", newIndex), options)
  149. wfilterOp.SetConcurrency(options.Concurrency)
  150. tp.AddOperator(inputs, wfilterOp)
  151. inputs = []api.Emitter{wfilterOp}
  152. }
  153. op, err = node.NewWindowOp(fmt.Sprintf("%d_window", newIndex), node.WindowConfig{
  154. Type: t.wtype,
  155. Length: t.length,
  156. Interval: t.interval,
  157. }, streamsFromStmt, options)
  158. if err != nil {
  159. return nil, 0, err
  160. }
  161. case *JoinAlignPlan:
  162. op, err = node.NewJoinAlignNode(fmt.Sprintf("%d_join_aligner", newIndex), t.Emitters, options)
  163. case *JoinPlan:
  164. op = Transform(&operator.JoinOp{Joins: t.joins, From: t.from}, fmt.Sprintf("%d_join", newIndex), options)
  165. case *FilterPlan:
  166. op = Transform(&operator.FilterOp{Condition: t.condition}, fmt.Sprintf("%d_filter", newIndex), options)
  167. case *AggregatePlan:
  168. op = Transform(&operator.AggregateOp{Dimensions: t.dimensions}, fmt.Sprintf("%d_aggregate", newIndex), options)
  169. case *HavingPlan:
  170. op = Transform(&operator.HavingOp{Condition: t.condition}, fmt.Sprintf("%d_having", newIndex), options)
  171. case *OrderPlan:
  172. op = Transform(&operator.OrderOp{SortFields: t.SortFields}, fmt.Sprintf("%d_order", newIndex), options)
  173. case *ProjectPlan:
  174. op = Transform(&operator.ProjectOp{Fields: t.fields, IsAggregate: t.isAggregate, SendMeta: t.sendMeta}, fmt.Sprintf("%d_project", newIndex), options)
  175. default:
  176. return nil, 0, fmt.Errorf("unknown logical plan %v", t)
  177. }
  178. if uop, ok := op.(*node.UnaryOperator); ok {
  179. uop.SetConcurrency(options.Concurrency)
  180. }
  181. tp.AddOperator(inputs, op)
  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("need to run stream join in windows")
  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: ast.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. operator := node.New(name, xsql.FuncRegisters, options)
  310. operator.SetOperation(op)
  311. return operator
  312. }