planner.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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.StreamType, 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 = 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, isBatch(t.streamStmt.Options))
  124. if err != nil {
  125. return nil, 0, err
  126. }
  127. srcNode := nodes.NewSourceNode(t.name, t.streamStmt.StreamType, t.streamStmt.Options)
  128. tp.AddSrc(srcNode)
  129. op = 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 := 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 = Transform(&operators.JoinOp{Joins: t.joins, From: t.from}, fmt.Sprintf("%d_join", newIndex), options)
  151. case *FilterPlan:
  152. op = Transform(&operators.FilterOp{Condition: t.condition}, fmt.Sprintf("%d_filter", newIndex), options)
  153. case *AggregatePlan:
  154. op = Transform(&operators.AggregateOp{Dimensions: t.dimensions, Alias: t.alias}, fmt.Sprintf("%d_aggregate", newIndex), options)
  155. case *HavingPlan:
  156. op = Transform(&operators.HavingOp{Condition: t.condition}, fmt.Sprintf("%d_having", newIndex), options)
  157. case *OrderPlan:
  158. op = Transform(&operators.OrderOp{SortFields: t.SortFields}, fmt.Sprintf("%d_order", newIndex), options)
  159. case *ProjectPlan:
  160. op = 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 isBatch(options xsql.Options) bool {
  171. t, ok := options["TYPE"]
  172. if !ok || t == "file" {
  173. return true
  174. }
  175. return false
  176. }
  177. func createLogicalPlan(stmt *xsql.SelectStatement, opt *api.RuleOption, store kv.KeyValue) (LogicalPlan, error) {
  178. streamsFromStmt := xsql.GetStreams(stmt)
  179. dimensions := stmt.Dimensions
  180. var (
  181. p LogicalPlan
  182. children []LogicalPlan
  183. // If there are tables, the plan graph will be different for join/window
  184. tableChildren []LogicalPlan
  185. tableEmitters []string
  186. w *xsql.Window
  187. ds xsql.Dimensions
  188. alias, aggregateAlias xsql.Fields
  189. )
  190. for _, f := range stmt.Fields {
  191. if f.AName != "" {
  192. if !xsql.HasAggFuncs(f.Expr) {
  193. alias = append(alias, f)
  194. } else {
  195. aggregateAlias = append(aggregateAlias, f)
  196. }
  197. }
  198. }
  199. for _, s := range streamsFromStmt {
  200. streamStmt, err := xsql.GetDataSource(store, s)
  201. if err != nil {
  202. return nil, fmt.Errorf("fail to get stream %s, please check if stream is created", s)
  203. }
  204. p = DataSourcePlan{
  205. name: s,
  206. streamStmt: streamStmt,
  207. iet: opt.IsEventTime,
  208. alias: alias,
  209. allMeta: opt.SendMetaToSink,
  210. }.Init()
  211. if streamStmt.StreamType == xsql.TypeStream {
  212. children = append(children, p)
  213. } else {
  214. tableChildren = append(tableChildren, p)
  215. tableEmitters = append(tableEmitters, string(streamStmt.Name))
  216. }
  217. }
  218. if dimensions != nil {
  219. w = dimensions.GetWindow()
  220. if w != nil {
  221. if len(children) == 0 {
  222. return nil, errors.New("cannot run window for TABLE sources")
  223. }
  224. wp := WindowPlan{
  225. wtype: w.WindowType,
  226. length: w.Length.Val,
  227. isEventTime: opt.IsEventTime,
  228. }.Init()
  229. if w.Interval != nil {
  230. wp.interval = w.Interval.Val
  231. } else if w.WindowType == xsql.COUNT_WINDOW {
  232. //if no interval value is set and it's count window, then set interval to length value.
  233. wp.interval = w.Length.Val
  234. }
  235. if w.Filter != nil {
  236. wp.condition = w.Filter
  237. }
  238. // TODO calculate limit
  239. // TODO incremental aggregate
  240. wp.SetChildren(children)
  241. children = []LogicalPlan{wp}
  242. p = wp
  243. }
  244. }
  245. if stmt.Joins != nil {
  246. if len(tableChildren) > 0 {
  247. p = JoinAlignPlan{
  248. Emitters: tableEmitters,
  249. }.Init()
  250. p.SetChildren(append(children, tableChildren...))
  251. children = []LogicalPlan{p}
  252. } else if w == nil {
  253. return nil, errors.New("need to run stream join in windows")
  254. }
  255. // TODO extract on filter
  256. p = JoinPlan{
  257. from: stmt.Sources[0].(*xsql.Table),
  258. joins: stmt.Joins,
  259. }.Init()
  260. p.SetChildren(children)
  261. children = []LogicalPlan{p}
  262. }
  263. if stmt.Condition != nil {
  264. p = FilterPlan{
  265. condition: stmt.Condition,
  266. }.Init()
  267. p.SetChildren(children)
  268. children = []LogicalPlan{p}
  269. }
  270. // TODO handle aggregateAlias in optimization as it does not only happen in select fields
  271. if dimensions != nil || len(aggregateAlias) > 0 {
  272. ds = dimensions.GetGroups()
  273. if (ds != nil && len(ds) > 0) || len(aggregateAlias) > 0 {
  274. p = AggregatePlan{
  275. dimensions: ds,
  276. alias: aggregateAlias,
  277. }.Init()
  278. p.SetChildren(children)
  279. children = []LogicalPlan{p}
  280. }
  281. }
  282. if stmt.Having != nil {
  283. p = HavingPlan{
  284. condition: stmt.Having,
  285. }.Init()
  286. p.SetChildren(children)
  287. children = []LogicalPlan{p}
  288. }
  289. if stmt.SortFields != nil {
  290. p = OrderPlan{
  291. SortFields: stmt.SortFields,
  292. }.Init()
  293. p.SetChildren(children)
  294. children = []LogicalPlan{p}
  295. }
  296. if stmt.Fields != nil {
  297. p = ProjectPlan{
  298. fields: stmt.Fields,
  299. isAggregate: xsql.IsAggStatement(stmt),
  300. sendMeta: opt.SendMetaToSink,
  301. }.Init()
  302. p.SetChildren(children)
  303. }
  304. return optimize(p)
  305. }
  306. func Transform(op nodes.UnOperation, name string, options *api.RuleOption) *nodes.UnaryOperator {
  307. operator := nodes.New(name, xsql.FuncRegisters, options)
  308. operator.SetOperation(op)
  309. return operator
  310. }