xsql_processor.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. package processors
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/emqx/kuiper/common"
  7. "github.com/emqx/kuiper/xsql"
  8. "github.com/emqx/kuiper/xsql/plans"
  9. "github.com/emqx/kuiper/xstream"
  10. "github.com/emqx/kuiper/xstream/api"
  11. "github.com/emqx/kuiper/xstream/nodes"
  12. "github.com/emqx/kuiper/xstream/operators"
  13. "path"
  14. "strings"
  15. )
  16. var log = common.Log
  17. type StreamProcessor struct {
  18. db common.KeyValue
  19. }
  20. //@params d : the directory of the DB to save the stream info
  21. func NewStreamProcessor(d string) *StreamProcessor {
  22. processor := &StreamProcessor{
  23. db: common.GetSimpleKVStore(d),
  24. }
  25. return processor
  26. }
  27. func (p *StreamProcessor) ExecStmt(statement string) (result []string, err error) {
  28. parser := xsql.NewParser(strings.NewReader(statement))
  29. stmt, err := xsql.Language.Parse(parser)
  30. if err != nil {
  31. return nil, err
  32. }
  33. switch s := stmt.(type) {
  34. case *xsql.StreamStmt:
  35. var r string
  36. r, err = p.execCreateStream(s, statement)
  37. result = append(result, r)
  38. case *xsql.ShowStreamsStatement:
  39. result, err = p.execShowStream(s)
  40. case *xsql.DescribeStreamStatement:
  41. var r string
  42. r, err = p.execDescribeStream(s)
  43. result = append(result, r)
  44. case *xsql.ExplainStreamStatement:
  45. var r string
  46. r, err = p.execExplainStream(s)
  47. result = append(result, r)
  48. case *xsql.DropStreamStatement:
  49. var r string
  50. r, err = p.execDropStream(s)
  51. result = append(result, r)
  52. default:
  53. return nil, fmt.Errorf("Invalid stream statement: %s", statement)
  54. }
  55. return
  56. }
  57. func (p *StreamProcessor) execCreateStream(stmt *xsql.StreamStmt, statement string) (string, error) {
  58. err := p.db.Open()
  59. if err != nil {
  60. return "", fmt.Errorf("Create stream fails, error when opening db: %v.", err)
  61. }
  62. defer p.db.Close()
  63. err = p.db.Set(string(stmt.Name), statement)
  64. if err != nil {
  65. return "", fmt.Errorf("Create stream fails: %v.", err)
  66. } else {
  67. info := fmt.Sprintf("Stream %s is created.", stmt.Name)
  68. log.Printf("%s", info)
  69. return info, nil
  70. }
  71. }
  72. func (p *StreamProcessor) ExecStreamSql(statement string) (string, error) {
  73. r, err := p.ExecStmt(statement)
  74. if err != nil {
  75. return "", err
  76. } else {
  77. return strings.Join(r, "\n"), err
  78. }
  79. }
  80. func (p *StreamProcessor) execShowStream(stmt *xsql.ShowStreamsStatement) ([]string, error) {
  81. keys, err := p.ShowStream()
  82. if len(keys) == 0 {
  83. keys = append(keys, "No stream definitions are found.")
  84. }
  85. return keys, err
  86. }
  87. func (p *StreamProcessor) ShowStream() ([]string, error) {
  88. err := p.db.Open()
  89. if err != nil {
  90. return nil, fmt.Errorf("Show stream fails, error when opening db: %v.", err)
  91. }
  92. defer p.db.Close()
  93. return p.db.Keys()
  94. }
  95. func (p *StreamProcessor) execDescribeStream(stmt *xsql.DescribeStreamStatement) (string, error) {
  96. streamStmt, err := p.DescStream(stmt.Name)
  97. if err != nil {
  98. return "", err
  99. }
  100. var buff bytes.Buffer
  101. buff.WriteString("Fields\n--------------------------------------------------------------------------------\n")
  102. for _, f := range streamStmt.StreamFields {
  103. buff.WriteString(f.Name + "\t")
  104. buff.WriteString(xsql.PrintFieldType(f.FieldType))
  105. buff.WriteString("\n")
  106. }
  107. buff.WriteString("\n")
  108. common.PrintMap(streamStmt.Options, &buff)
  109. return buff.String(), err
  110. }
  111. func (p *StreamProcessor) DescStream(name string) (*xsql.StreamStmt, error) {
  112. err := p.db.Open()
  113. if err != nil {
  114. return nil, fmt.Errorf("Describe stream fails, error when opening db: %v.", err)
  115. }
  116. defer p.db.Close()
  117. s, f := p.db.Get(name)
  118. if !f {
  119. return nil, fmt.Errorf("Stream %s is not found.", name)
  120. }
  121. s1 := s.(string)
  122. parser := xsql.NewParser(strings.NewReader(s1))
  123. stream, err := xsql.Language.Parse(parser)
  124. if err != nil {
  125. return nil, err
  126. }
  127. streamStmt, ok := stream.(*xsql.StreamStmt)
  128. if !ok {
  129. return nil, fmt.Errorf("Error resolving the stream %s, the data in db may be corrupted.", name)
  130. }
  131. return streamStmt, nil
  132. }
  133. func (p *StreamProcessor) execExplainStream(stmt *xsql.ExplainStreamStatement) (string, error) {
  134. err := p.db.Open()
  135. if err != nil {
  136. return "", fmt.Errorf("Explain stream fails, error when opening db: %v.", err)
  137. }
  138. defer p.db.Close()
  139. _, f := p.db.Get(stmt.Name)
  140. if !f {
  141. return "", fmt.Errorf("Stream %s is not found.", stmt.Name)
  142. }
  143. return "TO BE SUPPORTED", nil
  144. }
  145. func (p *StreamProcessor) execDropStream(stmt *xsql.DropStreamStatement) (string, error) {
  146. return p.DropStream(stmt.Name)
  147. }
  148. func (p *StreamProcessor) DropStream(name string) (string, error) {
  149. err := p.db.Open()
  150. if err != nil {
  151. return "", fmt.Errorf("Drop stream fails, error when opening db: %v.", err)
  152. }
  153. defer p.db.Close()
  154. err = p.db.Delete(name)
  155. if err != nil {
  156. return "", fmt.Errorf("Drop stream fails: %v.", err)
  157. } else {
  158. return fmt.Sprintf("Stream %s is dropped.", name), nil
  159. }
  160. }
  161. func GetStream(m *common.SimpleKVStore, name string) (stmt *xsql.StreamStmt, err error) {
  162. s, f := m.Get(name)
  163. if !f {
  164. return nil, fmt.Errorf("Cannot find key %s. ", name)
  165. }
  166. s1, _ := s.(string)
  167. parser := xsql.NewParser(strings.NewReader(s1))
  168. stream, err := xsql.Language.Parse(parser)
  169. stmt, ok := stream.(*xsql.StreamStmt)
  170. if !ok {
  171. err = fmt.Errorf("Error resolving the stream %s, the data in db may be corrupted.", name)
  172. }
  173. return
  174. }
  175. type RuleProcessor struct {
  176. db common.KeyValue
  177. rootDbDir string
  178. }
  179. func NewRuleProcessor(d string) *RuleProcessor {
  180. processor := &RuleProcessor{
  181. db: common.GetSimpleKVStore(path.Join(d, "rule")),
  182. rootDbDir: d,
  183. }
  184. return processor
  185. }
  186. func (p *RuleProcessor) ExecCreate(name, ruleJson string) (*api.Rule, error) {
  187. rule, err := p.getRuleByJson(name, ruleJson)
  188. if err != nil {
  189. return nil, err
  190. }
  191. err = p.db.Open()
  192. if err != nil {
  193. return nil, err
  194. }
  195. defer p.db.Close()
  196. err = p.db.Set(rule.Id, ruleJson)
  197. if err != nil {
  198. return nil, err
  199. } else {
  200. log.Infof("Rule %s is created.", rule.Id)
  201. }
  202. return rule, nil
  203. }
  204. func (p *RuleProcessor) GetRuleByName(name string) (*api.Rule, error) {
  205. err := p.db.Open()
  206. if err != nil {
  207. return nil, err
  208. }
  209. defer p.db.Close()
  210. s, f := p.db.Get(name)
  211. if !f {
  212. return nil, fmt.Errorf("Rule %s is not found.", name)
  213. }
  214. s1, _ := s.(string)
  215. return p.getRuleByJson(name, s1)
  216. }
  217. func (p *RuleProcessor) getRuleByJson(name, ruleJson string) (*api.Rule, error) {
  218. var rule api.Rule
  219. if err := json.Unmarshal([]byte(ruleJson), &rule); err != nil {
  220. return nil, fmt.Errorf("Parse rule %s error : %s.", ruleJson, err)
  221. }
  222. //validation
  223. if rule.Id == "" && name == "" {
  224. return nil, fmt.Errorf("Missing rule id.")
  225. }
  226. if name != "" && rule.Id != "" && name != rule.Id {
  227. return nil, fmt.Errorf("Name is not consistent with rule id.")
  228. }
  229. if rule.Id == "" {
  230. rule.Id = name
  231. }
  232. if rule.Sql == "" {
  233. return nil, fmt.Errorf("Missing rule SQL.")
  234. }
  235. if rule.Actions == nil || len(rule.Actions) == 0 {
  236. return nil, fmt.Errorf("Missing rule actions.")
  237. }
  238. return &rule, nil
  239. }
  240. func (p *RuleProcessor) ExecInitRule(rule *api.Rule) (*xstream.TopologyNew, error) {
  241. if tp, inputs, err := p.createTopo(rule); err != nil {
  242. return nil, err
  243. } else {
  244. for _, m := range rule.Actions {
  245. for name, action := range m {
  246. props, ok := action.(map[string]interface{})
  247. if !ok {
  248. return nil, fmt.Errorf("expect map[string]interface{} type for the action properties, but found %v", action)
  249. }
  250. tp.AddSink(inputs, nodes.NewSinkNode("sink_"+name, name, props))
  251. }
  252. }
  253. return tp, nil
  254. }
  255. }
  256. func (p *RuleProcessor) ExecQuery(ruleid, sql string) (*xstream.TopologyNew, error) {
  257. if tp, inputs, err := p.createTopo(&api.Rule{Id: ruleid, Sql: sql}); err != nil {
  258. return nil, err
  259. } else {
  260. tp.AddSink(inputs, nodes.NewSinkNode("sink_memory_log", "logToMemory", nil))
  261. go func() {
  262. select {
  263. case err := <-tp.Open():
  264. log.Infof("closing query for error: %v", err)
  265. tp.GetContext().SetError(err)
  266. tp.Cancel()
  267. }
  268. }()
  269. return tp, nil
  270. }
  271. }
  272. func (p *RuleProcessor) ExecDesc(name string) (string, error) {
  273. err := p.db.Open()
  274. if err != nil {
  275. return "", err
  276. }
  277. defer p.db.Close()
  278. s, f := p.db.Get(name)
  279. if !f {
  280. return "", fmt.Errorf("Rule %s is not found.", name)
  281. }
  282. s1, _ := s.(string)
  283. dst := &bytes.Buffer{}
  284. if err := json.Indent(dst, []byte(s1), "", " "); err != nil {
  285. return "", err
  286. }
  287. return fmt.Sprintln(dst.String()), nil
  288. }
  289. func (p *RuleProcessor) GetAllRules() ([]string, error) {
  290. err := p.db.Open()
  291. if err != nil {
  292. return nil, err
  293. }
  294. defer p.db.Close()
  295. return p.db.Keys()
  296. }
  297. func (p *RuleProcessor) ExecDrop(name string) (string, error) {
  298. err := p.db.Open()
  299. if err != nil {
  300. return "", err
  301. }
  302. defer p.db.Close()
  303. err = p.db.Delete(string(name))
  304. if err != nil {
  305. return "", err
  306. } else {
  307. return fmt.Sprintf("Rule %s is dropped.", name), nil
  308. }
  309. }
  310. func (p *RuleProcessor) createTopo(rule *api.Rule) (*xstream.TopologyNew, []api.Emitter, error) {
  311. return p.createTopoWithSources(rule, nil)
  312. }
  313. //For test to mock source
  314. func (p *RuleProcessor) createTopoWithSources(rule *api.Rule, sources []*nodes.SourceNode) (*xstream.TopologyNew, []api.Emitter, error) {
  315. name := rule.Id
  316. sql := rule.Sql
  317. var (
  318. isEventTime bool
  319. lateTol int64
  320. concurrency = 1
  321. bufferLength = 1024
  322. )
  323. if iet, ok := rule.Options["isEventTime"]; ok {
  324. isEventTime, ok = iet.(bool)
  325. if !ok {
  326. return nil, nil, fmt.Errorf("Invalid rule option isEventTime %v, bool type is required.", iet)
  327. }
  328. }
  329. if isEventTime {
  330. if l, ok := rule.Options["lateTolerance"]; ok {
  331. if fl, ok := l.(float64); ok {
  332. lateTol = int64(fl)
  333. } else {
  334. return nil, nil, fmt.Errorf("Invalid rule option lateTolerance %v, int type is required.", l)
  335. }
  336. }
  337. }
  338. if l, ok := rule.Options["concurrency"]; ok {
  339. if fl, ok := l.(float64); ok {
  340. concurrency = int(fl)
  341. } else {
  342. return nil, nil, fmt.Errorf("Invalid rule option concurrency %v, int type is required.", l)
  343. }
  344. }
  345. if l, ok := rule.Options["bufferLength"]; ok {
  346. if fl, ok := l.(float64); ok {
  347. bufferLength = int(fl)
  348. } else {
  349. return nil, nil, fmt.Errorf("Invalid rule option bufferLength %v, int type is required.", l)
  350. }
  351. }
  352. log.Infof("Init rule with options {isEventTime: %v, lateTolerance: %d, concurrency: %d, bufferLength: %d", isEventTime, lateTol, concurrency, bufferLength)
  353. shouldCreateSource := sources == nil
  354. parser := xsql.NewParser(strings.NewReader(sql))
  355. if stmt, err := xsql.Language.Parse(parser); err != nil {
  356. return nil, nil, fmt.Errorf("Parse SQL %s error: %s.", sql, err)
  357. } else {
  358. if selectStmt, ok := stmt.(*xsql.SelectStatement); !ok {
  359. return nil, nil, fmt.Errorf("SQL %s is not a select statement.", sql)
  360. } else {
  361. tp := xstream.NewWithName(name)
  362. var inputs []api.Emitter
  363. streamsFromStmt := xsql.GetStreams(selectStmt)
  364. if !shouldCreateSource && len(streamsFromStmt) != len(sources) {
  365. return nil, nil, fmt.Errorf("Invalid parameter sources or streams, the length cannot match the statement, expect %d sources.", len(streamsFromStmt))
  366. }
  367. store := common.GetSimpleKVStore(path.Join(p.rootDbDir, "stream"))
  368. err := store.Open()
  369. if err != nil {
  370. return nil, nil, err
  371. }
  372. defer store.Close()
  373. var alias, aggregateAlias xsql.Fields
  374. for _, f := range selectStmt.Fields {
  375. if f.AName != "" {
  376. if !xsql.HasAggFuncs(f.Expr) {
  377. alias = append(alias, f)
  378. } else {
  379. aggregateAlias = append(aggregateAlias, f)
  380. }
  381. }
  382. }
  383. for i, s := range streamsFromStmt {
  384. streamStmt, err := GetStream(store, s)
  385. if err != nil {
  386. return nil, nil, fmt.Errorf("fail to get stream %s, please check if stream is created", s)
  387. }
  388. pp, err := plans.NewPreprocessor(streamStmt, alias, isEventTime, selectStmt.Fields.IsSelectAll())
  389. if err != nil {
  390. return nil, nil, err
  391. }
  392. if shouldCreateSource {
  393. node := nodes.NewSourceNode(s, streamStmt.Options)
  394. tp.AddSrc(node)
  395. preprocessorOp := xstream.Transform(pp, "preprocessor_"+s, bufferLength)
  396. preprocessorOp.SetConcurrency(concurrency)
  397. tp.AddOperator([]api.Emitter{node}, preprocessorOp)
  398. inputs = append(inputs, preprocessorOp)
  399. } else {
  400. tp.AddSrc(sources[i])
  401. preprocessorOp := xstream.Transform(pp, "preprocessor_"+s, bufferLength)
  402. preprocessorOp.SetConcurrency(concurrency)
  403. tp.AddOperator([]api.Emitter{sources[i]}, preprocessorOp)
  404. inputs = append(inputs, preprocessorOp)
  405. }
  406. }
  407. dimensions := selectStmt.Dimensions
  408. var w *xsql.Window
  409. if dimensions != nil {
  410. w = dimensions.GetWindow()
  411. if w != nil {
  412. wop, err := operators.NewWindowOp("window", w, isEventTime, lateTol, streamsFromStmt, bufferLength)
  413. if err != nil {
  414. return nil, nil, err
  415. }
  416. tp.AddOperator(inputs, wop)
  417. inputs = []api.Emitter{wop}
  418. }
  419. }
  420. if w != nil && selectStmt.Joins != nil {
  421. joinOp := xstream.Transform(&plans.JoinPlan{Joins: selectStmt.Joins, From: selectStmt.Sources[0].(*xsql.Table)}, "join", bufferLength)
  422. joinOp.SetConcurrency(concurrency)
  423. tp.AddOperator(inputs, joinOp)
  424. inputs = []api.Emitter{joinOp}
  425. }
  426. if selectStmt.Condition != nil {
  427. filterOp := xstream.Transform(&plans.FilterPlan{Condition: selectStmt.Condition}, "filter", bufferLength)
  428. filterOp.SetConcurrency(concurrency)
  429. tp.AddOperator(inputs, filterOp)
  430. inputs = []api.Emitter{filterOp}
  431. }
  432. var ds xsql.Dimensions
  433. if dimensions != nil || len(aggregateAlias) > 0 {
  434. ds = dimensions.GetGroups()
  435. if (ds != nil && len(ds) > 0) || len(aggregateAlias) > 0 {
  436. aggregateOp := xstream.Transform(&plans.AggregatePlan{Dimensions: ds, Alias: aggregateAlias}, "aggregate", bufferLength)
  437. aggregateOp.SetConcurrency(concurrency)
  438. tp.AddOperator(inputs, aggregateOp)
  439. inputs = []api.Emitter{aggregateOp}
  440. }
  441. }
  442. if selectStmt.Having != nil {
  443. havingOp := xstream.Transform(&plans.HavingPlan{selectStmt.Having}, "having", bufferLength)
  444. havingOp.SetConcurrency(concurrency)
  445. tp.AddOperator(inputs, havingOp)
  446. inputs = []api.Emitter{havingOp}
  447. }
  448. if selectStmt.SortFields != nil {
  449. orderOp := xstream.Transform(&plans.OrderPlan{SortFields: selectStmt.SortFields}, "order", bufferLength)
  450. orderOp.SetConcurrency(concurrency)
  451. tp.AddOperator(inputs, orderOp)
  452. inputs = []api.Emitter{orderOp}
  453. }
  454. if selectStmt.Fields != nil {
  455. projectOp := xstream.Transform(&plans.ProjectPlan{Fields: selectStmt.Fields, IsAggregate: xsql.IsAggStatement(selectStmt)}, "project", bufferLength)
  456. projectOp.SetConcurrency(concurrency)
  457. tp.AddOperator(inputs, projectOp)
  458. inputs = []api.Emitter{projectOp}
  459. }
  460. return tp, inputs, nil
  461. }
  462. }
  463. }