rest_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. // Copyright 2023 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package server
  15. import (
  16. "bytes"
  17. "encoding/json"
  18. "fmt"
  19. "github.com/gorilla/mux"
  20. "github.com/lf-edge/ekuiper/internal/processor"
  21. "github.com/lf-edge/ekuiper/internal/testx"
  22. "github.com/lf-edge/ekuiper/internal/topo/rule"
  23. "github.com/lf-edge/ekuiper/pkg/ast"
  24. "io"
  25. "net/http"
  26. "net/http/httptest"
  27. "reflect"
  28. "strings"
  29. "testing"
  30. )
  31. func init() {
  32. testx.InitEnv()
  33. streamProcessor = processor.NewStreamProcessor()
  34. ruleProcessor = processor.NewRuleProcessor()
  35. rulesetProcessor = processor.NewRulesetProcessor(ruleProcessor, streamProcessor)
  36. registry = &RuleRegistry{internal: make(map[string]*rule.RuleState)}
  37. }
  38. func Test_rootHandler(t *testing.T) {
  39. r := mux.NewRouter()
  40. r.HandleFunc("/", rootHandler).Methods(http.MethodGet, http.MethodPost)
  41. req, _ := http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("any"))
  42. w := httptest.NewRecorder()
  43. r.ServeHTTP(w, req)
  44. resp := w.Result()
  45. if !reflect.DeepEqual(resp.StatusCode, 200) {
  46. t.Errorf("Expect\t %v\nBut got\t%v", 200, resp.StatusCode)
  47. }
  48. }
  49. func Test_sourcesManageHandler(t *testing.T) {
  50. req, _ := http.NewRequest(http.MethodGet, "/", bytes.NewBufferString("any"))
  51. w := httptest.NewRecorder()
  52. sourcesManageHandler(w, req, ast.TypeStream)
  53. if !reflect.DeepEqual(w.Result().StatusCode, 200) {
  54. t.Errorf("Expect\t %v\nBut got\t%v", 200, w.Result().StatusCode)
  55. }
  56. //get scan table
  57. req, _ = http.NewRequest(http.MethodGet, "http://localhost:8080/streams?kind=scan", bytes.NewBufferString("any"))
  58. w = httptest.NewRecorder()
  59. sourcesManageHandler(w, req, ast.TypeTable)
  60. if !reflect.DeepEqual(w.Result().StatusCode, 200) {
  61. t.Errorf("Expect\t %v\nBut got\t%v", 200, w.Result().StatusCode)
  62. }
  63. //get lookup table
  64. req, _ = http.NewRequest(http.MethodGet, "http://localhost:8080/streams?kind=lookup", bytes.NewBufferString("any"))
  65. w = httptest.NewRecorder()
  66. sourcesManageHandler(w, req, ast.TypeTable)
  67. if !reflect.DeepEqual(w.Result().StatusCode, 200) {
  68. t.Errorf("Expect\t %v\nBut got\t%v", 200, w.Result().StatusCode)
  69. }
  70. //create table
  71. buf := bytes.NewBuffer([]byte(` {"sql":"CREATE TABLE alertTable() WITH (DATASOURCE=\"0\", TYPE=\"redis\", KIND=\"lookup\")"}`))
  72. req, _ = http.NewRequest(http.MethodPost, "http://localhost:8080/streams?kind=lookup", buf)
  73. w = httptest.NewRecorder()
  74. sourcesManageHandler(w, req, ast.TypeTable)
  75. var returnVal []byte
  76. returnVal, _ = io.ReadAll(w.Result().Body)
  77. fmt.Printf("returnVal %s\n", string(returnVal))
  78. //create stream
  79. buf = bytes.NewBuffer([]byte(`{"sql":"CREATE stream alert() WITH (DATASOURCE=\"0\", TYPE=\"mqtt\")"}`))
  80. req, _ = http.NewRequest(http.MethodPost, "http://localhost:8080/streams", buf)
  81. w = httptest.NewRecorder()
  82. sourcesManageHandler(w, req, ast.TypeStream)
  83. returnVal, _ = io.ReadAll(w.Result().Body)
  84. fmt.Printf("returnVal %s\n", string(returnVal))
  85. //get stream
  86. r := mux.NewRouter()
  87. r.HandleFunc("/streams/{name}", streamHandler).Methods(http.MethodGet, http.MethodDelete, http.MethodPut)
  88. req, _ = http.NewRequest(http.MethodGet, "http://localhost:8080/streams/alert", bytes.NewBufferString("any"))
  89. w = httptest.NewRecorder()
  90. r.ServeHTTP(w, req)
  91. expect := []byte(`{"Name":"alert","Options":{"datasource":"0","type":"mqtt"},"Statement":null,"StreamFields":null,"StreamType":0}`)
  92. exp := map[string]interface{}{}
  93. _ = json.NewDecoder(bytes.NewBuffer(expect)).Decode(&exp)
  94. res := map[string]interface{}{}
  95. _ = json.NewDecoder(w.Result().Body).Decode(&res)
  96. if !reflect.DeepEqual(exp, res) {
  97. t.Errorf("Expect\t%v\nBut got\t%v", exp, res)
  98. }
  99. //get table
  100. r = mux.NewRouter()
  101. r.HandleFunc("/tables/{name}", tableHandler).Methods(http.MethodGet, http.MethodDelete, http.MethodPut)
  102. req, _ = http.NewRequest(http.MethodGet, "http://localhost:8080/tables/alertTable", bytes.NewBufferString("any"))
  103. w = httptest.NewRecorder()
  104. r.ServeHTTP(w, req)
  105. expect = []byte(`{"Name":"alertTable","Options":{"datasource":"0","type":"redis","kind":"lookup"},"Statement":null,"StreamFields":null,"StreamType":1}`)
  106. exp = map[string]interface{}{}
  107. _ = json.NewDecoder(bytes.NewBuffer(expect)).Decode(&exp)
  108. res = map[string]interface{}{}
  109. _ = json.NewDecoder(w.Result().Body).Decode(&res)
  110. if !reflect.DeepEqual(exp, res) {
  111. t.Errorf("Expect\t%v\nBut got\t%v", exp, res)
  112. }
  113. //put table
  114. buf = bytes.NewBuffer([]byte(` {"sql":"CREATE TABLE alertTable() WITH (DATASOURCE=\"0\", TYPE=\"memory\", KEY=\"id\", KIND=\"lookup\")"}`))
  115. r = mux.NewRouter()
  116. r.HandleFunc("/tables/{name}", tableHandler).Methods(http.MethodGet, http.MethodDelete, http.MethodPut)
  117. req, _ = http.NewRequest(http.MethodPut, "http://localhost:8080/tables/alertTable", buf)
  118. w = httptest.NewRecorder()
  119. r.ServeHTTP(w, req)
  120. if !reflect.DeepEqual(w.Result().StatusCode, 200) {
  121. t.Errorf("Expect\t%v\nBut got\t%v", 200, w.Result().StatusCode)
  122. }
  123. //put stream
  124. buf = bytes.NewBuffer([]byte(`{"sql":"CREATE stream alert() WITH (DATASOURCE=\"0\", TYPE=\"httppull\")"}`))
  125. r = mux.NewRouter()
  126. r.HandleFunc("/streams/{name}", streamHandler).Methods(http.MethodGet, http.MethodDelete, http.MethodPut)
  127. req, _ = http.NewRequest(http.MethodPut, "http://localhost:8080/streams/alert", buf)
  128. w = httptest.NewRecorder()
  129. r.ServeHTTP(w, req)
  130. if !reflect.DeepEqual(w.Result().StatusCode, 200) {
  131. t.Errorf("Expect\t%v\nBut got\t%v", 200, w.Result().StatusCode)
  132. }
  133. //drop table
  134. r = mux.NewRouter()
  135. r.HandleFunc("/tables/{name}", tableHandler).Methods(http.MethodGet, http.MethodDelete, http.MethodPut)
  136. req, _ = http.NewRequest(http.MethodDelete, "http://localhost:8080/tables/alertTable", bytes.NewBufferString("any"))
  137. w = httptest.NewRecorder()
  138. r.ServeHTTP(w, req)
  139. if !reflect.DeepEqual(w.Result().StatusCode, 200) {
  140. t.Errorf("Expect\t%v\nBut got\t%v", 200, w.Result().StatusCode)
  141. }
  142. //drop stream
  143. r = mux.NewRouter()
  144. r.HandleFunc("/streams/{name}", streamHandler).Methods(http.MethodGet, http.MethodDelete, http.MethodPut)
  145. req, _ = http.NewRequest(http.MethodDelete, "http://localhost:8080/streams/alert", bytes.NewBufferString("any"))
  146. w = httptest.NewRecorder()
  147. r.ServeHTTP(w, req)
  148. if !reflect.DeepEqual(w.Result().StatusCode, 200) {
  149. t.Errorf("Expect\t%v\nBut got\t%v", 200, w.Result().StatusCode)
  150. }
  151. }
  152. func Test_rulesManageHandler(t *testing.T) {
  153. //Start rules
  154. if rules, err := ruleProcessor.GetAllRules(); err != nil {
  155. logger.Infof("Start rules error: %s", err)
  156. } else {
  157. logger.Info("Starting rules")
  158. var reply string
  159. for _, name := range rules {
  160. rule, err := ruleProcessor.GetRuleById(name)
  161. if err != nil {
  162. logger.Error(err)
  163. continue
  164. }
  165. //err = server.StartRule(rule, &reply)
  166. reply = recoverRule(rule)
  167. if 0 != len(reply) {
  168. logger.Info(reply)
  169. }
  170. }
  171. }
  172. r := mux.NewRouter()
  173. r.HandleFunc("/rules", rulesHandler).Methods(http.MethodGet, http.MethodPost)
  174. r.HandleFunc("/streams", streamsHandler).Methods(http.MethodGet, http.MethodPost)
  175. r.HandleFunc("/rules/{name}", ruleHandler).Methods(http.MethodDelete, http.MethodGet, http.MethodPut)
  176. r.HandleFunc("/streams/{name}", streamHandler).Methods(http.MethodGet, http.MethodDelete, http.MethodPut)
  177. r.HandleFunc("/rules/{name}/status", getStatusRuleHandler).Methods(http.MethodGet)
  178. r.HandleFunc("/rules/{name}/topo", getTopoRuleHandler).Methods(http.MethodGet)
  179. r.HandleFunc("/rules/{name}/start", startRuleHandler).Methods(http.MethodPost)
  180. r.HandleFunc("/rules/{name}/stop", stopRuleHandler).Methods(http.MethodPost)
  181. r.HandleFunc("/rules/{name}/restart", restartRuleHandler).Methods(http.MethodPost)
  182. buf1 := bytes.NewBuffer([]byte(`{"sql":"CREATE stream alert() WITH (DATASOURCE=\"0\", TYPE=\"mqtt\")"}`))
  183. req1, _ := http.NewRequest(http.MethodPost, "http://localhost:8080/streams", buf1)
  184. w1 := httptest.NewRecorder()
  185. r.ServeHTTP(w1, req1)
  186. //create rule with trigger false
  187. ruleJson := `{"id": "rule1","triggered": false,"sql": "select * from alert","actions": [{"log": {}}]}`
  188. buf2 := bytes.NewBuffer([]byte(ruleJson))
  189. req2, _ := http.NewRequest(http.MethodPost, "http://localhost:8080/rules", buf2)
  190. w2 := httptest.NewRecorder()
  191. r.ServeHTTP(w2, req2)
  192. // get all rules
  193. req3, _ := http.NewRequest(http.MethodGet, "http://localhost:8080/rules", bytes.NewBufferString("any"))
  194. w3 := httptest.NewRecorder()
  195. r.ServeHTTP(w3, req3)
  196. returnVal, _ := io.ReadAll(w3.Result().Body)
  197. expect := `[{"id":"rule1","name":"rule1","status":"Stopped: no context found."}]`
  198. if string(returnVal) != expect {
  199. t.Errorf("Expect\t%v\nBut got\t%v", expect, string(returnVal))
  200. }
  201. //update rule, will set rule to triggered
  202. ruleJson = `{"id": "rule1","triggered": false,"sql": "select * from alert","actions": [{"nop": {}}]}`
  203. buf2 = bytes.NewBuffer([]byte(ruleJson))
  204. req1, _ = http.NewRequest(http.MethodPut, "http://localhost:8080/rules/rule1", buf2)
  205. w1 = httptest.NewRecorder()
  206. r.ServeHTTP(w1, req1)
  207. if w1.Result().StatusCode != 200 {
  208. t.Errorf("Expect\t%v\nBut got\t%v", 200, w1.Result().StatusCode)
  209. }
  210. //get rule
  211. req1, _ = http.NewRequest(http.MethodGet, "http://localhost:8080/rules/rule1", bytes.NewBufferString("any"))
  212. w1 = httptest.NewRecorder()
  213. r.ServeHTTP(w1, req1)
  214. returnVal, _ = io.ReadAll(w1.Result().Body)
  215. expect = `{"id": "rule1","triggered": false,"sql": "select * from alert","actions": [{"nop": {}}]}`
  216. if string(returnVal) != expect {
  217. t.Errorf("Expect\t%v\nBut got\t%v", expect, string(returnVal))
  218. }
  219. //get rule status
  220. req1, _ = http.NewRequest(http.MethodGet, "http://localhost:8080/rules/rule1/status", bytes.NewBufferString("any"))
  221. w1 = httptest.NewRecorder()
  222. r.ServeHTTP(w1, req1)
  223. returnVal, _ = io.ReadAll(w1.Result().Body)
  224. expect = `"status": "running"`
  225. if !strings.Contains(string(returnVal), expect) {
  226. t.Errorf("Expect\t%v\nBut got\t%v", expect, string(returnVal))
  227. }
  228. //get rule topo
  229. req1, _ = http.NewRequest(http.MethodGet, "http://localhost:8080/rules/rule1/topo", bytes.NewBufferString("any"))
  230. w1 = httptest.NewRecorder()
  231. r.ServeHTTP(w1, req1)
  232. returnVal, _ = io.ReadAll(w1.Result().Body)
  233. expect = `{"sources":["source_alert"],"edges":{"op_2_project":["sink_nop_0"],"source_alert":["op_2_project"]}}`
  234. if string(returnVal) != expect {
  235. t.Errorf("Expect\t%v\nBut got\t%v", expect, string(returnVal))
  236. }
  237. //start rule
  238. req1, _ = http.NewRequest(http.MethodPost, "http://localhost:8080/rules/rule1/start", bytes.NewBufferString("any"))
  239. w1 = httptest.NewRecorder()
  240. r.ServeHTTP(w1, req1)
  241. returnVal, _ = io.ReadAll(w1.Result().Body)
  242. expect = `Rule rule1 was started`
  243. if string(returnVal) != expect {
  244. t.Errorf("Expect\t%v\nBut got\t%v", expect, string(returnVal))
  245. }
  246. //stop rule
  247. req1, _ = http.NewRequest(http.MethodPost, "http://localhost:8080/rules/rule1/stop", bytes.NewBufferString("any"))
  248. w1 = httptest.NewRecorder()
  249. r.ServeHTTP(w1, req1)
  250. returnVal, _ = io.ReadAll(w1.Result().Body)
  251. expect = `Rule rule1 was stopped.`
  252. if string(returnVal) != expect {
  253. t.Errorf("Expect\t%v\nBut got\t%v", expect, string(returnVal))
  254. }
  255. //restart rule
  256. req1, _ = http.NewRequest(http.MethodPost, "http://localhost:8080/rules/rule1/restart", bytes.NewBufferString("any"))
  257. w1 = httptest.NewRecorder()
  258. r.ServeHTTP(w1, req1)
  259. returnVal, _ = io.ReadAll(w1.Result().Body)
  260. expect = `Rule rule1 was restarted`
  261. if string(returnVal) != expect {
  262. t.Errorf("Expect\t%v\nBut got\t%v", expect, string(returnVal))
  263. }
  264. //delete rule
  265. req1, _ = http.NewRequest(http.MethodDelete, "http://localhost:8080/rules/rule1", bytes.NewBufferString("any"))
  266. w1 = httptest.NewRecorder()
  267. r.ServeHTTP(w1, req1)
  268. //drop stream
  269. req, _ := http.NewRequest(http.MethodDelete, "http://localhost:8080/streams/alert", bytes.NewBufferString("any"))
  270. w := httptest.NewRecorder()
  271. r.ServeHTTP(w, req)
  272. }
  273. func Test_ruleSetImport(t *testing.T) {
  274. r := mux.NewRouter()
  275. r.HandleFunc("/ruleset/import", importHandler).Methods(http.MethodPost)
  276. r.HandleFunc("/ruleset/export", exportHandler).Methods(http.MethodPost)
  277. ruleJson := `{"streams":{"plugin":"\n CREATE STREAM plugin\n ()\n WITH (FORMAT=\"json\", CONF_KEY=\"default\", TYPE=\"mqtt\", SHARED=\"false\", );\n "},"tables":{},"rules":{"rule1":"{\"id\":\"rule1\",\"name\":\"\",\"sql\":\"select name from plugin\",\"actions\":[{\"log\":{\"runAsync\":false,\"omitIfEmpty\":false,\"sendSingle\":true,\"bufferLength\":1024,\"enableCache\":false,\"format\":\"json\"}}],\"options\":{\"restartStrategy\":{}}}"}}`
  278. ruleSetJson := map[string]string{
  279. "content": ruleJson,
  280. }
  281. buf, _ := json.Marshal(ruleSetJson)
  282. buf2 := bytes.NewBuffer(buf)
  283. req1, _ := http.NewRequest(http.MethodPost, "http://localhost:8080/ruleset/import", buf2)
  284. w1 := httptest.NewRecorder()
  285. r.ServeHTTP(w1, req1)
  286. req1, _ = http.NewRequest(http.MethodPost, "http://localhost:8080/ruleset/export", bytes.NewBufferString("any"))
  287. w1 = httptest.NewRecorder()
  288. r.ServeHTTP(w1, req1)
  289. returnVal, _ := io.ReadAll(w1.Result().Body)
  290. fmt.Printf("########## %s\n", string(returnVal))
  291. }