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. "testing"
  29. )
  30. func init() {
  31. testx.InitEnv()
  32. streamProcessor = processor.NewStreamProcessor()
  33. ruleProcessor = processor.NewRuleProcessor()
  34. rulesetProcessor = processor.NewRulesetProcessor(ruleProcessor, streamProcessor)
  35. registry = &RuleRegistry{internal: make(map[string]*rule.RuleState)}
  36. }
  37. func Test_rootHandler(t *testing.T) {
  38. r := mux.NewRouter()
  39. r.HandleFunc("/", rootHandler).Methods(http.MethodGet, http.MethodPost)
  40. req, _ := http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("any"))
  41. w := httptest.NewRecorder()
  42. r.ServeHTTP(w, req)
  43. resp := w.Result()
  44. if !reflect.DeepEqual(resp.StatusCode, 200) {
  45. t.Errorf("Expect\t %v\nBut got\t%v", 200, resp.StatusCode)
  46. }
  47. }
  48. func Test_sourcesManageHandler(t *testing.T) {
  49. req, _ := http.NewRequest(http.MethodGet, "/", bytes.NewBufferString("any"))
  50. w := httptest.NewRecorder()
  51. sourcesManageHandler(w, req, ast.TypeStream)
  52. if !reflect.DeepEqual(w.Result().StatusCode, 200) {
  53. t.Errorf("Expect\t %v\nBut got\t%v", 200, w.Result().StatusCode)
  54. }
  55. //get scan table
  56. req, _ = http.NewRequest(http.MethodGet, "http://localhost:8080/streams?kind=scan", bytes.NewBufferString("any"))
  57. w = httptest.NewRecorder()
  58. sourcesManageHandler(w, req, ast.TypeTable)
  59. if !reflect.DeepEqual(w.Result().StatusCode, 200) {
  60. t.Errorf("Expect\t %v\nBut got\t%v", 200, w.Result().StatusCode)
  61. }
  62. //get lookup table
  63. req, _ = http.NewRequest(http.MethodGet, "http://localhost:8080/streams?kind=lookup", bytes.NewBufferString("any"))
  64. w = httptest.NewRecorder()
  65. sourcesManageHandler(w, req, ast.TypeTable)
  66. if !reflect.DeepEqual(w.Result().StatusCode, 200) {
  67. t.Errorf("Expect\t %v\nBut got\t%v", 200, w.Result().StatusCode)
  68. }
  69. //create table
  70. buf := bytes.NewBuffer([]byte(` {"sql":"CREATE TABLE alertTable() WITH (DATASOURCE=\"0\", TYPE=\"memory\", KEY=\"id\", KIND=\"lookup\")"}`))
  71. req, _ = http.NewRequest(http.MethodPost, "http://localhost:8080/streams?kind=lookup", buf)
  72. w = httptest.NewRecorder()
  73. sourcesManageHandler(w, req, ast.TypeTable)
  74. var returnVal []byte
  75. returnVal, _ = io.ReadAll(w.Result().Body)
  76. fmt.Printf("returnVal %s\n", string(returnVal))
  77. //create stream
  78. buf = bytes.NewBuffer([]byte(`{"sql":"CREATE stream alert() WITH (DATASOURCE=\"0\", TYPE=\"mqtt\")"}`))
  79. req, _ = http.NewRequest(http.MethodPost, "http://localhost:8080/streams", buf)
  80. w = httptest.NewRecorder()
  81. sourcesManageHandler(w, req, ast.TypeStream)
  82. returnVal, _ = io.ReadAll(w.Result().Body)
  83. fmt.Printf("returnVal %s\n", string(returnVal))
  84. //get stream
  85. r := mux.NewRouter()
  86. r.HandleFunc("/streams/{name}", streamHandler).Methods(http.MethodGet, http.MethodDelete, http.MethodPut)
  87. req, _ = http.NewRequest(http.MethodGet, "http://localhost:8080/streams/alert", bytes.NewBufferString("any"))
  88. w = httptest.NewRecorder()
  89. r.ServeHTTP(w, req)
  90. expect := []byte(`{"Name":"alert","Options":{"datasource":"0","type":"mqtt"},"Statement":null,"StreamFields":null,"StreamType":0}`)
  91. exp := map[string]interface{}{}
  92. _ = json.NewDecoder(bytes.NewBuffer(expect)).Decode(&exp)
  93. res := map[string]interface{}{}
  94. _ = json.NewDecoder(w.Result().Body).Decode(&res)
  95. if !reflect.DeepEqual(exp, res) {
  96. t.Errorf("Expect\t%v\nBut got\t%v", exp, res)
  97. }
  98. //get table
  99. r = mux.NewRouter()
  100. r.HandleFunc("/tables/{name}", tableHandler).Methods(http.MethodGet, http.MethodDelete, http.MethodPut)
  101. req, _ = http.NewRequest(http.MethodGet, "http://localhost:8080/tables/alertTable", bytes.NewBufferString("any"))
  102. w = httptest.NewRecorder()
  103. r.ServeHTTP(w, req)
  104. expect = []byte(`{"Name":"alertTable","Options":{"datasource":"0","type":"memory", "key":"id","kind":"lookup"},"Statement":null,"StreamFields":null,"StreamType":1}`)
  105. exp = map[string]interface{}{}
  106. _ = json.NewDecoder(bytes.NewBuffer(expect)).Decode(&exp)
  107. res = map[string]interface{}{}
  108. _ = json.NewDecoder(w.Result().Body).Decode(&res)
  109. if !reflect.DeepEqual(exp, res) {
  110. t.Errorf("Expect\t%v\nBut got\t%v", exp, res)
  111. }
  112. //put table
  113. buf = bytes.NewBuffer([]byte(` {"sql":"CREATE TABLE alertTable() WITH (DATASOURCE=\"0\", TYPE=\"memory\", KEY=\"id\", KIND=\"lookup\")"}`))
  114. r = mux.NewRouter()
  115. r.HandleFunc("/tables/{name}", tableHandler).Methods(http.MethodGet, http.MethodDelete, http.MethodPut)
  116. req, _ = http.NewRequest(http.MethodPut, "http://localhost:8080/tables/alertTable", buf)
  117. w = httptest.NewRecorder()
  118. r.ServeHTTP(w, req)
  119. if !reflect.DeepEqual(w.Result().StatusCode, 200) {
  120. t.Errorf("Expect\t%v\nBut got\t%v", 200, w.Result().StatusCode)
  121. }
  122. //put stream
  123. buf = bytes.NewBuffer([]byte(`{"sql":"CREATE stream alert() WITH (DATASOURCE=\"0\", TYPE=\"httppull\")"}`))
  124. r = mux.NewRouter()
  125. r.HandleFunc("/streams/{name}", streamHandler).Methods(http.MethodGet, http.MethodDelete, http.MethodPut)
  126. req, _ = http.NewRequest(http.MethodPut, "http://localhost:8080/streams/alert", buf)
  127. w = httptest.NewRecorder()
  128. r.ServeHTTP(w, req)
  129. if !reflect.DeepEqual(w.Result().StatusCode, 200) {
  130. t.Errorf("Expect\t%v\nBut got\t%v", 200, w.Result().StatusCode)
  131. }
  132. //drop table
  133. r = mux.NewRouter()
  134. r.HandleFunc("/tables/{name}", tableHandler).Methods(http.MethodGet, http.MethodDelete, http.MethodPut)
  135. req, _ = http.NewRequest(http.MethodDelete, "http://localhost:8080/tables/alertTable", bytes.NewBufferString("any"))
  136. w = httptest.NewRecorder()
  137. r.ServeHTTP(w, req)
  138. if !reflect.DeepEqual(w.Result().StatusCode, 200) {
  139. t.Errorf("Expect\t%v\nBut got\t%v", 200, w.Result().StatusCode)
  140. }
  141. //drop stream
  142. r = mux.NewRouter()
  143. r.HandleFunc("/streams/{name}", streamHandler).Methods(http.MethodGet, http.MethodDelete, http.MethodPut)
  144. req, _ = http.NewRequest(http.MethodDelete, "http://localhost:8080/streams/alert", bytes.NewBufferString("any"))
  145. w = httptest.NewRecorder()
  146. r.ServeHTTP(w, req)
  147. if !reflect.DeepEqual(w.Result().StatusCode, 200) {
  148. t.Errorf("Expect\t%v\nBut got\t%v", 200, w.Result().StatusCode)
  149. }
  150. }
  151. func Test_rulesManageHandler(t *testing.T) {
  152. //Start rules
  153. if rules, err := ruleProcessor.GetAllRules(); err != nil {
  154. logger.Infof("Start rules error: %s", err)
  155. } else {
  156. logger.Info("Starting rules")
  157. var reply string
  158. for _, name := range rules {
  159. rule, err := ruleProcessor.GetRuleById(name)
  160. if err != nil {
  161. logger.Error(err)
  162. continue
  163. }
  164. //err = server.StartRule(rule, &reply)
  165. reply = recoverRule(rule)
  166. if 0 != len(reply) {
  167. logger.Info(reply)
  168. }
  169. }
  170. }
  171. r := mux.NewRouter()
  172. r.HandleFunc("/rules", rulesHandler).Methods(http.MethodGet, http.MethodPost)
  173. r.HandleFunc("/streams", streamsHandler).Methods(http.MethodGet, http.MethodPost)
  174. r.HandleFunc("/rules/{name}", ruleHandler).Methods(http.MethodDelete, http.MethodGet, http.MethodPut)
  175. r.HandleFunc("/streams/{name}", streamHandler).Methods(http.MethodGet, http.MethodDelete, http.MethodPut)
  176. r.HandleFunc("/rules/{name}/status", getStatusRuleHandler).Methods(http.MethodGet)
  177. r.HandleFunc("/rules/{name}/topo", getTopoRuleHandler).Methods(http.MethodGet)
  178. r.HandleFunc("/rules/{name}/start", startRuleHandler).Methods(http.MethodPost)
  179. r.HandleFunc("/rules/{name}/stop", stopRuleHandler).Methods(http.MethodPost)
  180. r.HandleFunc("/rules/{name}/restart", restartRuleHandler).Methods(http.MethodPost)
  181. buf1 := bytes.NewBuffer([]byte(`{"sql":"CREATE stream alert() WITH (DATASOURCE=\"0\", TYPE=\"mqtt\")"}`))
  182. req1, _ := http.NewRequest(http.MethodPost, "http://localhost:8080/streams", buf1)
  183. w1 := httptest.NewRecorder()
  184. r.ServeHTTP(w1, req1)
  185. //create rule with trigger false
  186. ruleJson := `{"id": "rule1","triggered": false,"sql": "select * from alert","actions": [{"log": {}}]}`
  187. buf2 := bytes.NewBuffer([]byte(ruleJson))
  188. req2, _ := http.NewRequest(http.MethodPost, "http://localhost:8080/rules", buf2)
  189. w2 := httptest.NewRecorder()
  190. r.ServeHTTP(w2, req2)
  191. // get all rules
  192. req3, _ := http.NewRequest(http.MethodGet, "http://localhost:8080/rules", bytes.NewBufferString("any"))
  193. w3 := httptest.NewRecorder()
  194. r.ServeHTTP(w3, req3)
  195. _, _ = io.ReadAll(w3.Result().Body)
  196. //update rule, will set rule to triggered
  197. ruleJson = `{"id": "rule1","triggered": false,"sql": "select * from alert","actions": [{"nop": {}}]}`
  198. buf2 = bytes.NewBuffer([]byte(ruleJson))
  199. req1, _ = http.NewRequest(http.MethodPut, "http://localhost:8080/rules/rule1", buf2)
  200. w1 = httptest.NewRecorder()
  201. r.ServeHTTP(w1, req1)
  202. if w1.Result().StatusCode != 200 {
  203. t.Errorf("Expect\t%v\nBut got\t%v", 200, w1.Result().StatusCode)
  204. }
  205. //update wron rule
  206. ruleJson = `{"id": "rule1","sql": "select * from alert1","actions": [{"nop": {}}]}`
  207. buf2 = bytes.NewBuffer([]byte(ruleJson))
  208. req1, _ = http.NewRequest(http.MethodPut, "http://localhost:8080/rules/rule1", buf2)
  209. w1 = httptest.NewRecorder()
  210. r.ServeHTTP(w1, req1)
  211. if w1.Result().StatusCode != 400 {
  212. t.Errorf("Expect\t%v\nBut got\t%v", 200, w1.Result().StatusCode)
  213. }
  214. //get rule
  215. req1, _ = http.NewRequest(http.MethodGet, "http://localhost:8080/rules/rule1", bytes.NewBufferString("any"))
  216. w1 = httptest.NewRecorder()
  217. r.ServeHTTP(w1, req1)
  218. returnVal, _ := io.ReadAll(w1.Result().Body)
  219. expect := `{"id": "rule1","triggered": false,"sql": "select * from alert","actions": [{"nop": {}}]}`
  220. if string(returnVal) != expect {
  221. t.Errorf("Expect\t%v\nBut got\t%v", expect, string(returnVal))
  222. }
  223. //get rule status
  224. req1, _ = http.NewRequest(http.MethodGet, "http://localhost:8080/rules/rule1/status", bytes.NewBufferString("any"))
  225. w1 = httptest.NewRecorder()
  226. r.ServeHTTP(w1, req1)
  227. returnVal, _ = io.ReadAll(w1.Result().Body)
  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. }