planner.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. package planner
  2. import (
  3. "fmt"
  4. "github.com/emqx/kuiper/common"
  5. "github.com/emqx/kuiper/common/kv"
  6. "github.com/emqx/kuiper/xsql"
  7. "github.com/emqx/kuiper/xstream"
  8. "github.com/emqx/kuiper/xstream/api"
  9. "github.com/emqx/kuiper/xstream/nodes"
  10. "github.com/emqx/kuiper/xstream/operators"
  11. "path"
  12. "strings"
  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. pp, err := operators.NewPreprocessor(t.streamFields, t.alias, t.allMeta, t.metaFields, t.iet, t.timestampField, t.timestampFormat, t.isBinary)
  98. if err != nil {
  99. return nil, 0, err
  100. }
  101. var srcNode *nodes.SourceNode
  102. if len(sources) == 0 {
  103. node := nodes.NewSourceNode(t.name, t.streamStmt.Options)
  104. srcNode = node
  105. } else {
  106. found := false
  107. for _, source := range sources {
  108. if t.name == source.GetName() {
  109. srcNode = source
  110. found = true
  111. }
  112. }
  113. if !found {
  114. return nil, 0, fmt.Errorf("can't find predefined source %s", t.name)
  115. }
  116. }
  117. tp.AddSrc(srcNode)
  118. op = xstream.Transform(pp, fmt.Sprintf("%d_preprocessor_%s", newIndex, t.name), options)
  119. inputs = []api.Emitter{srcNode}
  120. case *WindowPlan:
  121. if t.condition != nil {
  122. wfilterOp := xstream.Transform(&operators.FilterOp{Condition: t.condition}, fmt.Sprintf("%d_windowFilter", newIndex), options)
  123. wfilterOp.SetConcurrency(options.Concurrency)
  124. tp.AddOperator(inputs, wfilterOp)
  125. inputs = []api.Emitter{wfilterOp}
  126. }
  127. op, err = nodes.NewWindowOp(fmt.Sprintf("%d_window", newIndex), nodes.WindowConfig{
  128. Type: t.wtype,
  129. Length: t.length,
  130. Interval: t.interval,
  131. }, streamsFromStmt, options)
  132. if err != nil {
  133. return nil, 0, err
  134. }
  135. case *JoinPlan:
  136. op = xstream.Transform(&operators.JoinOp{Joins: t.joins, From: t.from}, fmt.Sprintf("%d_join", newIndex), options)
  137. case *FilterPlan:
  138. op = xstream.Transform(&operators.FilterOp{Condition: t.condition}, fmt.Sprintf("%d_filter", newIndex), options)
  139. case *AggregatePlan:
  140. op = xstream.Transform(&operators.AggregateOp{Dimensions: t.dimensions, Alias: t.alias}, fmt.Sprintf("%d_aggregate", newIndex), options)
  141. case *HavingPlan:
  142. op = xstream.Transform(&operators.HavingOp{Condition: t.condition}, fmt.Sprintf("%d_having", newIndex), options)
  143. case *OrderPlan:
  144. op = xstream.Transform(&operators.OrderOp{SortFields: t.SortFields}, fmt.Sprintf("%d_order", newIndex), options)
  145. case *ProjectPlan:
  146. op = xstream.Transform(&operators.ProjectOp{Fields: t.fields, IsAggregate: t.isAggregate, SendMeta: t.sendMeta}, fmt.Sprintf("%d_project", newIndex), options)
  147. default:
  148. return nil, 0, fmt.Errorf("unknown logical plan %v", t)
  149. }
  150. if uop, ok := op.(*nodes.UnaryOperator); ok {
  151. uop.SetConcurrency(options.Concurrency)
  152. }
  153. tp.AddOperator(inputs, op)
  154. return op, newIndex, nil
  155. }
  156. func getStream(m kv.KeyValue, name string) (stmt *xsql.StreamStmt, err error) {
  157. var s string
  158. f, err := m.Get(name, &s)
  159. if !f || err != nil {
  160. return nil, fmt.Errorf("Cannot find key %s. ", name)
  161. }
  162. parser := xsql.NewParser(strings.NewReader(s))
  163. stream, err := xsql.Language.Parse(parser)
  164. stmt, ok := stream.(*xsql.StreamStmt)
  165. if !ok {
  166. err = fmt.Errorf("Error resolving the stream %s, the data in db may be corrupted.", name)
  167. }
  168. return
  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. w *xsql.Window
  177. ds xsql.Dimensions
  178. alias, aggregateAlias xsql.Fields
  179. )
  180. for _, f := range stmt.Fields {
  181. if f.AName != "" {
  182. if !xsql.HasAggFuncs(f.Expr) {
  183. alias = append(alias, f)
  184. } else {
  185. aggregateAlias = append(aggregateAlias, f)
  186. }
  187. }
  188. }
  189. for _, s := range streamsFromStmt {
  190. streamStmt, err := getStream(store, s)
  191. if err != nil {
  192. return nil, fmt.Errorf("fail to get stream %s, please check if stream is created", s)
  193. }
  194. p = DataSourcePlan{
  195. name: s,
  196. streamStmt: streamStmt,
  197. iet: opt.IsEventTime,
  198. alias: alias,
  199. allMeta: opt.SendMetaToSink,
  200. }.Init()
  201. children = append(children, p)
  202. }
  203. if dimensions != nil {
  204. w = dimensions.GetWindow()
  205. if w != nil {
  206. wp := WindowPlan{
  207. wtype: w.WindowType,
  208. length: w.Length.Val,
  209. isEventTime: opt.IsEventTime,
  210. }.Init()
  211. if w.Interval != nil {
  212. wp.interval = w.Interval.Val
  213. } else if w.WindowType == xsql.COUNT_WINDOW {
  214. //if no interval value is set and it's count window, then set interval to length value.
  215. wp.interval = w.Length.Val
  216. }
  217. if w.Filter != nil {
  218. wp.condition = w.Filter
  219. }
  220. // TODO calculate limit
  221. // TODO incremental aggregate
  222. wp.SetChildren(children)
  223. children = []LogicalPlan{wp}
  224. p = wp
  225. }
  226. }
  227. if w != nil && stmt.Joins != nil {
  228. // TODO extract on filter
  229. p = JoinPlan{
  230. from: stmt.Sources[0].(*xsql.Table),
  231. joins: stmt.Joins,
  232. }.Init()
  233. p.SetChildren(children)
  234. children = []LogicalPlan{p}
  235. }
  236. if stmt.Condition != nil {
  237. p = FilterPlan{
  238. condition: stmt.Condition,
  239. }.Init()
  240. p.SetChildren(children)
  241. children = []LogicalPlan{p}
  242. }
  243. // TODO handle aggregateAlias in optimization as it does not only happen in select fields
  244. if dimensions != nil || len(aggregateAlias) > 0 {
  245. ds = dimensions.GetGroups()
  246. if (ds != nil && len(ds) > 0) || len(aggregateAlias) > 0 {
  247. p = AggregatePlan{
  248. dimensions: ds,
  249. alias: aggregateAlias,
  250. }.Init()
  251. p.SetChildren(children)
  252. children = []LogicalPlan{p}
  253. }
  254. }
  255. if stmt.Having != nil {
  256. p = HavingPlan{
  257. condition: stmt.Having,
  258. }.Init()
  259. p.SetChildren(children)
  260. children = []LogicalPlan{p}
  261. }
  262. if stmt.SortFields != nil {
  263. p = OrderPlan{
  264. SortFields: stmt.SortFields,
  265. }.Init()
  266. p.SetChildren(children)
  267. children = []LogicalPlan{p}
  268. }
  269. if stmt.Fields != nil {
  270. p = ProjectPlan{
  271. fields: stmt.Fields,
  272. isAggregate: xsql.IsAggStatement(stmt),
  273. sendMeta: opt.SendMetaToSink,
  274. }.Init()
  275. p.SetChildren(children)
  276. children = []LogicalPlan{p}
  277. }
  278. return optimize(p)
  279. }