xsql_processor.go 14 KB

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