planner.go 12 KB

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