rest_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. "io"
  20. "net/http"
  21. "net/http/httptest"
  22. "os"
  23. "path/filepath"
  24. "testing"
  25. "github.com/gorilla/mux"
  26. "github.com/stretchr/testify/assert"
  27. "github.com/stretchr/testify/suite"
  28. "github.com/lf-edge/ekuiper/internal/conf"
  29. "github.com/lf-edge/ekuiper/internal/processor"
  30. "github.com/lf-edge/ekuiper/internal/testx"
  31. "github.com/lf-edge/ekuiper/internal/topo/rule"
  32. )
  33. func init() {
  34. testx.InitEnv()
  35. streamProcessor = processor.NewStreamProcessor()
  36. ruleProcessor = processor.NewRuleProcessor()
  37. rulesetProcessor = processor.NewRulesetProcessor(ruleProcessor, streamProcessor)
  38. registry = &RuleRegistry{internal: make(map[string]*rule.RuleState)}
  39. }
  40. type RestTestSuite struct {
  41. suite.Suite
  42. r *mux.Router
  43. }
  44. func (suite *RestTestSuite) SetupTest() {
  45. dataDir, err := conf.GetDataLoc()
  46. if err != nil {
  47. panic(err)
  48. }
  49. uploadDir = filepath.Join(dataDir, "uploads")
  50. r := mux.NewRouter()
  51. r.HandleFunc("/", rootHandler).Methods(http.MethodGet, http.MethodPost)
  52. r.HandleFunc("/ping", pingHandler).Methods(http.MethodGet)
  53. r.HandleFunc("/streams", streamsHandler).Methods(http.MethodGet, http.MethodPost)
  54. r.HandleFunc("/streams/{name}", streamHandler).Methods(http.MethodGet, http.MethodDelete, http.MethodPut)
  55. r.HandleFunc("/streams/{name}/schema", streamSchemaHandler).Methods(http.MethodGet)
  56. r.HandleFunc("/tables", tablesHandler).Methods(http.MethodGet, http.MethodPost)
  57. r.HandleFunc("/tables/{name}", tableHandler).Methods(http.MethodGet, http.MethodDelete, http.MethodPut)
  58. r.HandleFunc("/tables/{name}/schema", tableSchemaHandler).Methods(http.MethodGet)
  59. r.HandleFunc("/rules", rulesHandler).Methods(http.MethodGet, http.MethodPost)
  60. r.HandleFunc("/rules/{name}", ruleHandler).Methods(http.MethodDelete, http.MethodGet, http.MethodPut)
  61. r.HandleFunc("/rules/{name}/status", getStatusRuleHandler).Methods(http.MethodGet)
  62. r.HandleFunc("/rules/{name}/start", startRuleHandler).Methods(http.MethodPost)
  63. r.HandleFunc("/rules/{name}/stop", stopRuleHandler).Methods(http.MethodPost)
  64. r.HandleFunc("/rules/{name}/restart", restartRuleHandler).Methods(http.MethodPost)
  65. r.HandleFunc("/rules/{name}/topo", getTopoRuleHandler).Methods(http.MethodGet)
  66. r.HandleFunc("/ruleset/export", exportHandler).Methods(http.MethodPost)
  67. r.HandleFunc("/ruleset/import", importHandler).Methods(http.MethodPost)
  68. r.HandleFunc("/config/uploads", fileUploadHandler).Methods(http.MethodPost, http.MethodGet)
  69. r.HandleFunc("/config/uploads/{name}", fileDeleteHandler).Methods(http.MethodDelete)
  70. r.HandleFunc("/data/export", configurationExportHandler).Methods(http.MethodGet, http.MethodPost)
  71. r.HandleFunc("/data/import", configurationImportHandler).Methods(http.MethodPost)
  72. r.HandleFunc("/data/import/status", configurationStatusHandler).Methods(http.MethodGet)
  73. suite.r = r
  74. }
  75. func (suite *RestTestSuite) Test_rootHandler() {
  76. req, _ := http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("any"))
  77. w := httptest.NewRecorder()
  78. suite.r.ServeHTTP(w, req)
  79. assert.Equal(suite.T(), http.StatusOK, w.Code)
  80. }
  81. func (suite *RestTestSuite) Test_sourcesManageHandler() {
  82. req, _ := http.NewRequest(http.MethodGet, "/", bytes.NewBufferString("any"))
  83. w := httptest.NewRecorder()
  84. suite.r.ServeHTTP(w, req)
  85. assert.Equal(suite.T(), http.StatusOK, w.Code)
  86. // get scan table
  87. req, _ = http.NewRequest(http.MethodGet, "http://localhost:8080/streams?kind=scan", bytes.NewBufferString("any"))
  88. w = httptest.NewRecorder()
  89. suite.r.ServeHTTP(w, req)
  90. assert.Equal(suite.T(), http.StatusOK, w.Code)
  91. // get lookup table
  92. req, _ = http.NewRequest(http.MethodGet, "http://localhost:8080/streams?kind=lookup", bytes.NewBufferString("any"))
  93. w = httptest.NewRecorder()
  94. suite.r.ServeHTTP(w, req)
  95. assert.Equal(suite.T(), http.StatusOK, w.Code)
  96. // create table
  97. buf := bytes.NewBuffer([]byte(` {"sql":"CREATE TABLE alertTable() WITH (DATASOURCE=\"0\", TYPE=\"memory\", KEY=\"id\", KIND=\"lookup\")"}`))
  98. req, _ = http.NewRequest(http.MethodPost, "http://localhost:8080/streams?kind=lookup", buf)
  99. w = httptest.NewRecorder()
  100. suite.r.ServeHTTP(w, req)
  101. assert.Equal(suite.T(), http.StatusCreated, w.Code)
  102. var returnVal []byte
  103. returnVal, _ = io.ReadAll(w.Result().Body)
  104. fmt.Printf("returnVal %s\n", string(returnVal))
  105. // create stream
  106. buf = bytes.NewBuffer([]byte(`{"sql":"CREATE stream alert() WITH (DATASOURCE=\"0\", TYPE=\"mqtt\")"}`))
  107. req, _ = http.NewRequest(http.MethodPost, "http://localhost:8080/streams", buf)
  108. w = httptest.NewRecorder()
  109. suite.r.ServeHTTP(w, req)
  110. assert.Equal(suite.T(), http.StatusCreated, w.Code)
  111. returnVal, _ = io.ReadAll(w.Result().Body)
  112. fmt.Printf("returnVal %s\n", string(returnVal))
  113. // get stream
  114. req, _ = http.NewRequest(http.MethodGet, "http://localhost:8080/streams/alert", bytes.NewBufferString("any"))
  115. w = httptest.NewRecorder()
  116. suite.r.ServeHTTP(w, req)
  117. assert.Equal(suite.T(), http.StatusOK, w.Code)
  118. expect := []byte(`{"Name":"alert","Options":{"datasource":"0","type":"mqtt"},"Statement":null,"StreamFields":null,"StreamType":0}`)
  119. exp := map[string]interface{}{}
  120. _ = json.NewDecoder(bytes.NewBuffer(expect)).Decode(&exp)
  121. res := map[string]interface{}{}
  122. _ = json.NewDecoder(w.Result().Body).Decode(&res)
  123. assert.Equal(suite.T(), exp, res)
  124. req, _ = http.NewRequest(http.MethodGet, "http://localhost:8080/streams/alert/schema", bytes.NewBufferString("any"))
  125. w = httptest.NewRecorder()
  126. suite.r.ServeHTTP(w, req)
  127. assert.Equal(suite.T(), http.StatusOK, w.Code)
  128. // get table
  129. req, _ = http.NewRequest(http.MethodGet, "http://localhost:8080/tables/alertTable", bytes.NewBufferString("any"))
  130. w = httptest.NewRecorder()
  131. suite.r.ServeHTTP(w, req)
  132. assert.Equal(suite.T(), http.StatusOK, w.Code)
  133. expect = []byte(`{"Name":"alertTable","Options":{"datasource":"0","type":"memory", "key":"id","kind":"lookup"},"Statement":null,"StreamFields":null,"StreamType":1}`)
  134. exp = map[string]interface{}{}
  135. _ = json.NewDecoder(bytes.NewBuffer(expect)).Decode(&exp)
  136. res = map[string]interface{}{}
  137. _ = json.NewDecoder(w.Result().Body).Decode(&res)
  138. assert.Equal(suite.T(), exp, res)
  139. req, _ = http.NewRequest(http.MethodGet, "http://localhost:8080/tables/alertTable/schema", bytes.NewBufferString("any"))
  140. w = httptest.NewRecorder()
  141. suite.r.ServeHTTP(w, req)
  142. assert.Equal(suite.T(), http.StatusOK, w.Code)
  143. // put table
  144. buf = bytes.NewBuffer([]byte(` {"sql":"CREATE TABLE alertTable() WITH (DATASOURCE=\"0\", TYPE=\"memory\", KEY=\"id\", KIND=\"lookup\")"}`))
  145. req, _ = http.NewRequest(http.MethodPut, "http://localhost:8080/tables/alertTable", buf)
  146. w = httptest.NewRecorder()
  147. suite.r.ServeHTTP(w, req)
  148. assert.Equal(suite.T(), http.StatusOK, w.Code)
  149. // put stream
  150. buf = bytes.NewBuffer([]byte(`{"sql":"CREATE stream alert() WITH (DATASOURCE=\"0\", TYPE=\"httppull\")"}`))
  151. req, _ = http.NewRequest(http.MethodPut, "http://localhost:8080/streams/alert", buf)
  152. w = httptest.NewRecorder()
  153. suite.r.ServeHTTP(w, req)
  154. assert.Equal(suite.T(), http.StatusOK, w.Code)
  155. // drop table
  156. req, _ = http.NewRequest(http.MethodDelete, "http://localhost:8080/tables/alertTable", bytes.NewBufferString("any"))
  157. w = httptest.NewRecorder()
  158. suite.r.ServeHTTP(w, req)
  159. assert.Equal(suite.T(), http.StatusOK, w.Code)
  160. // drop stream
  161. req, _ = http.NewRequest(http.MethodDelete, "http://localhost:8080/streams/alert", bytes.NewBufferString("any"))
  162. w = httptest.NewRecorder()
  163. suite.r.ServeHTTP(w, req)
  164. assert.Equal(suite.T(), http.StatusOK, w.Code)
  165. }
  166. func (suite *RestTestSuite) Test_rulesManageHandler() {
  167. // Start rules
  168. if rules, err := ruleProcessor.GetAllRules(); err != nil {
  169. logger.Infof("Start rules error: %s", err)
  170. } else {
  171. logger.Info("Starting rules")
  172. var reply string
  173. for _, name := range rules {
  174. rule, err := ruleProcessor.GetRuleById(name)
  175. if err != nil {
  176. logger.Error(err)
  177. continue
  178. }
  179. // err = server.StartRule(rule, &reply)
  180. reply = recoverRule(rule)
  181. if 0 != len(reply) {
  182. logger.Info(reply)
  183. }
  184. }
  185. }
  186. buf1 := bytes.NewBuffer([]byte(`{"sql":"CREATE stream alert() WITH (DATASOURCE=\"0\", TYPE=\"mqtt\")"}`))
  187. req1, _ := http.NewRequest(http.MethodPost, "http://localhost:8080/streams", buf1)
  188. w1 := httptest.NewRecorder()
  189. suite.r.ServeHTTP(w1, req1)
  190. // create rule with trigger false
  191. ruleJson := `{"id": "rule1","triggered": false,"sql": "select * from alert","actions": [{"log": {}}]}`
  192. buf2 := bytes.NewBuffer([]byte(ruleJson))
  193. req2, _ := http.NewRequest(http.MethodPost, "http://localhost:8080/rules", buf2)
  194. w2 := httptest.NewRecorder()
  195. suite.r.ServeHTTP(w2, req2)
  196. // get all rules
  197. req3, _ := http.NewRequest(http.MethodGet, "http://localhost:8080/rules", bytes.NewBufferString("any"))
  198. w3 := httptest.NewRecorder()
  199. suite.r.ServeHTTP(w3, req3)
  200. _, _ = io.ReadAll(w3.Result().Body)
  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. suite.r.ServeHTTP(w1, req1)
  207. assert.Equal(suite.T(), http.StatusOK, w1.Code)
  208. // update wron rule
  209. ruleJson = `{"id": "rule1","sql": "select * from alert1","actions": [{"nop": {}}]}`
  210. buf2 = bytes.NewBuffer([]byte(ruleJson))
  211. req1, _ = http.NewRequest(http.MethodPut, "http://localhost:8080/rules/rule1", buf2)
  212. w1 = httptest.NewRecorder()
  213. suite.r.ServeHTTP(w1, req1)
  214. assert.Equal(suite.T(), http.StatusBadRequest, w1.Code)
  215. // get rule
  216. req1, _ = http.NewRequest(http.MethodGet, "http://localhost:8080/rules/rule1", bytes.NewBufferString("any"))
  217. w1 = httptest.NewRecorder()
  218. suite.r.ServeHTTP(w1, req1)
  219. returnVal, _ := io.ReadAll(w1.Result().Body)
  220. expect := `{"id": "rule1","triggered": false,"sql": "select * from alert","actions": [{"nop": {}}]}`
  221. assert.Equal(suite.T(), expect, string(returnVal))
  222. // get rule status
  223. req1, _ = http.NewRequest(http.MethodGet, "http://localhost:8080/rules/rule1/status", bytes.NewBufferString("any"))
  224. w1 = httptest.NewRecorder()
  225. suite.r.ServeHTTP(w1, req1)
  226. returnVal, _ = io.ReadAll(w1.Result().Body) //nolint
  227. // get rule topo
  228. req1, _ = http.NewRequest(http.MethodGet, "http://localhost:8080/rules/rule1/topo", bytes.NewBufferString("any"))
  229. w1 = httptest.NewRecorder()
  230. suite.r.ServeHTTP(w1, req1)
  231. returnVal, _ = io.ReadAll(w1.Result().Body)
  232. expect = `{"sources":["source_alert"],"edges":{"op_2_project":["sink_nop_0"],"source_alert":["op_2_project"]}}`
  233. assert.Equal(suite.T(), expect, string(returnVal))
  234. // start rule
  235. req1, _ = http.NewRequest(http.MethodPost, "http://localhost:8080/rules/rule1/start", bytes.NewBufferString("any"))
  236. w1 = httptest.NewRecorder()
  237. suite.r.ServeHTTP(w1, req1)
  238. returnVal, _ = io.ReadAll(w1.Result().Body)
  239. expect = `Rule rule1 was started`
  240. assert.Equal(suite.T(), expect, string(returnVal))
  241. // stop rule
  242. req1, _ = http.NewRequest(http.MethodPost, "http://localhost:8080/rules/rule1/stop", bytes.NewBufferString("any"))
  243. w1 = httptest.NewRecorder()
  244. suite.r.ServeHTTP(w1, req1)
  245. returnVal, _ = io.ReadAll(w1.Result().Body)
  246. expect = `Rule rule1 was stopped.`
  247. assert.Equal(suite.T(), expect, string(returnVal))
  248. // restart rule
  249. req1, _ = http.NewRequest(http.MethodPost, "http://localhost:8080/rules/rule1/restart", bytes.NewBufferString("any"))
  250. w1 = httptest.NewRecorder()
  251. suite.r.ServeHTTP(w1, req1)
  252. returnVal, _ = io.ReadAll(w1.Result().Body)
  253. expect = `Rule rule1 was restarted`
  254. assert.Equal(suite.T(), expect, string(returnVal))
  255. // delete rule
  256. req1, _ = http.NewRequest(http.MethodDelete, "http://localhost:8080/rules/rule1", bytes.NewBufferString("any"))
  257. w1 = httptest.NewRecorder()
  258. suite.r.ServeHTTP(w1, req1)
  259. // drop stream
  260. req, _ := http.NewRequest(http.MethodDelete, "http://localhost:8080/streams/alert", bytes.NewBufferString("any"))
  261. w := httptest.NewRecorder()
  262. suite.r.ServeHTTP(w, req)
  263. }
  264. func (suite *RestTestSuite) Test_ruleSetImport() {
  265. 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\":{}}}"}}`
  266. ruleSetJson := map[string]string{
  267. "content": ruleJson,
  268. }
  269. buf, _ := json.Marshal(ruleSetJson)
  270. buf2 := bytes.NewBuffer(buf)
  271. req1, _ := http.NewRequest(http.MethodPost, "http://localhost:8080/ruleset/import", buf2)
  272. w1 := httptest.NewRecorder()
  273. suite.r.ServeHTTP(w1, req1)
  274. assert.Equal(suite.T(), http.StatusOK, w1.Code)
  275. req1, _ = http.NewRequest(http.MethodPost, "http://localhost:8080/ruleset/export", bytes.NewBufferString("any"))
  276. w1 = httptest.NewRecorder()
  277. suite.r.ServeHTTP(w1, req1)
  278. assert.Equal(suite.T(), http.StatusOK, w1.Code)
  279. }
  280. func (suite *RestTestSuite) Test_dataImport() {
  281. file := "rpc_test_data/data/import_configuration.json"
  282. f, err := os.Open(file)
  283. if err != nil {
  284. fmt.Printf("fail to open file %s: %v", file, err)
  285. return
  286. }
  287. defer f.Close()
  288. buffer := new(bytes.Buffer)
  289. _, err = io.Copy(buffer, f)
  290. if err != nil {
  291. fmt.Printf("fail to convert file %s: %v", file, err)
  292. return
  293. }
  294. content := buffer.Bytes()
  295. ruleSetJson := map[string]string{
  296. "content": string(content),
  297. }
  298. buf, _ := json.Marshal(ruleSetJson)
  299. buf2 := bytes.NewBuffer(buf)
  300. req, _ := http.NewRequest(http.MethodPost, "http://localhost:8080/data/import", buf2)
  301. w := httptest.NewRecorder()
  302. suite.r.ServeHTTP(w, req)
  303. assert.Equal(suite.T(), http.StatusOK, w.Code)
  304. req, _ = http.NewRequest(http.MethodGet, "http://localhost:8080/data/import/status", bytes.NewBufferString("any"))
  305. w = httptest.NewRecorder()
  306. suite.r.ServeHTTP(w, req)
  307. suite.r.ServeHTTP(w, req)
  308. assert.Equal(suite.T(), http.StatusOK, w.Code)
  309. req, _ = http.NewRequest(http.MethodGet, "http://localhost:8080/data/export", bytes.NewBufferString("any"))
  310. w = httptest.NewRecorder()
  311. suite.r.ServeHTTP(w, req)
  312. assert.Equal(suite.T(), http.StatusOK, w.Code)
  313. req, _ = http.NewRequest(http.MethodPost, "http://localhost:8080/data/import?partial=1", bytes.NewBuffer(buf))
  314. w = httptest.NewRecorder()
  315. suite.r.ServeHTTP(w, req)
  316. assert.Equal(suite.T(), http.StatusOK, w.Code)
  317. }
  318. func (suite *RestTestSuite) Test_fileUpload() {
  319. fileJson := `{"Name": "test.txt", "Content": "test"}`
  320. req, _ := http.NewRequest(http.MethodPost, "http://localhost:8080/config/uploads", bytes.NewBufferString(fileJson))
  321. req.Header["Content-Type"] = []string{"application/json"}
  322. os.Mkdir(uploadDir, 0o777)
  323. w := httptest.NewRecorder()
  324. suite.r.ServeHTTP(w, req)
  325. assert.Equal(suite.T(), http.StatusCreated, w.Code)
  326. req, _ = http.NewRequest(http.MethodGet, "http://localhost:8080/config/uploads", bytes.NewBufferString("any"))
  327. w = httptest.NewRecorder()
  328. suite.r.ServeHTTP(w, req)
  329. assert.Equal(suite.T(), http.StatusOK, w.Code)
  330. req, _ = http.NewRequest(http.MethodDelete, "http://localhost:8080/config/uploads/test.txt", bytes.NewBufferString("any"))
  331. w = httptest.NewRecorder()
  332. suite.r.ServeHTTP(w, req)
  333. assert.Equal(suite.T(), http.StatusOK, w.Code)
  334. os.Remove(uploadDir)
  335. }
  336. func TestRestTestSuite(t *testing.T) {
  337. suite.Run(t, new(RestTestSuite))
  338. }