xsql_processor.go 13 KB

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