planner.go 9.4 KB

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