rest.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. // Copyright 2021-2022 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/lf-edge/ekuiper/internal/conf"
  20. "github.com/lf-edge/ekuiper/internal/pkg/httpx"
  21. "io"
  22. "net/http"
  23. "os"
  24. "path/filepath"
  25. "runtime"
  26. "strconv"
  27. "strings"
  28. "time"
  29. "github.com/gorilla/handlers"
  30. "github.com/gorilla/mux"
  31. "github.com/lf-edge/ekuiper/internal/server/middleware"
  32. "github.com/lf-edge/ekuiper/pkg/api"
  33. "github.com/lf-edge/ekuiper/pkg/ast"
  34. "github.com/lf-edge/ekuiper/pkg/errorx"
  35. "github.com/lf-edge/ekuiper/pkg/infra"
  36. )
  37. const (
  38. ContentType = "Content-Type"
  39. ContentTypeJSON = "application/json"
  40. )
  41. var uploadDir string
  42. type statementDescriptor struct {
  43. Sql string `json:"sql,omitempty"`
  44. }
  45. func decodeStatementDescriptor(reader io.ReadCloser) (statementDescriptor, error) {
  46. sd := statementDescriptor{}
  47. err := json.NewDecoder(reader).Decode(&sd)
  48. // Problems decoding
  49. if err != nil {
  50. return sd, fmt.Errorf("Error decoding the statement descriptor: %v", err)
  51. }
  52. return sd, nil
  53. }
  54. // Handle applies the specified error and error concept to the HTTP response writer
  55. func handleError(w http.ResponseWriter, err error, prefix string, logger api.Logger) {
  56. message := prefix
  57. if message != "" {
  58. message += ": "
  59. }
  60. message += err.Error()
  61. logger.Error(message)
  62. var ec int
  63. switch e := err.(type) {
  64. case *errorx.Error:
  65. switch e.Code() {
  66. case errorx.NOT_FOUND:
  67. ec = http.StatusNotFound
  68. default:
  69. ec = http.StatusBadRequest
  70. }
  71. default:
  72. ec = http.StatusBadRequest
  73. }
  74. http.Error(w, message, ec)
  75. }
  76. func jsonResponse(i interface{}, w http.ResponseWriter, logger api.Logger) {
  77. w.Header().Add(ContentType, ContentTypeJSON)
  78. jsonByte, err := json.Marshal(i)
  79. if err != nil {
  80. handleError(w, err, "", logger)
  81. }
  82. w.Header().Add("Content-Length", strconv.Itoa(len(jsonByte)))
  83. _, err = w.Write(jsonByte)
  84. // Problems encoding
  85. if err != nil {
  86. handleError(w, err, "", logger)
  87. }
  88. }
  89. func jsonByteResponse(buffer bytes.Buffer, w http.ResponseWriter, logger api.Logger) {
  90. w.Header().Add(ContentType, ContentTypeJSON)
  91. w.Header().Add("Content-Length", strconv.Itoa(buffer.Len()))
  92. _, err := w.Write(buffer.Bytes())
  93. // Problems encoding
  94. if err != nil {
  95. handleError(w, err, "", logger)
  96. }
  97. }
  98. func createRestServer(ip string, port int, needToken bool) *http.Server {
  99. dataDir, err := conf.GetDataLoc()
  100. if err != nil {
  101. panic(err)
  102. }
  103. uploadDir = filepath.Join(dataDir, "uploads")
  104. r := mux.NewRouter()
  105. r.HandleFunc("/", rootHandler).Methods(http.MethodGet, http.MethodPost)
  106. r.HandleFunc("/ping", pingHandler).Methods(http.MethodGet)
  107. r.HandleFunc("/streams", streamsHandler).Methods(http.MethodGet, http.MethodPost)
  108. r.HandleFunc("/streams/{name}", streamHandler).Methods(http.MethodGet, http.MethodDelete, http.MethodPut)
  109. r.HandleFunc("/streams/{name}/schema", streamSchemaHandler).Methods(http.MethodGet)
  110. r.HandleFunc("/tables", tablesHandler).Methods(http.MethodGet, http.MethodPost)
  111. r.HandleFunc("/tables/{name}", tableHandler).Methods(http.MethodGet, http.MethodDelete, http.MethodPut)
  112. r.HandleFunc("/tables/{name}/schema", tableSchemaHandler).Methods(http.MethodGet)
  113. r.HandleFunc("/rules", rulesHandler).Methods(http.MethodGet, http.MethodPost)
  114. r.HandleFunc("/rules/{name}", ruleHandler).Methods(http.MethodDelete, http.MethodGet, http.MethodPut)
  115. r.HandleFunc("/rules/{name}/status", getStatusRuleHandler).Methods(http.MethodGet)
  116. r.HandleFunc("/rules/{name}/start", startRuleHandler).Methods(http.MethodPost)
  117. r.HandleFunc("/rules/{name}/stop", stopRuleHandler).Methods(http.MethodPost)
  118. r.HandleFunc("/rules/{name}/restart", restartRuleHandler).Methods(http.MethodPost)
  119. r.HandleFunc("/rules/{name}/topo", getTopoRuleHandler).Methods(http.MethodGet)
  120. r.HandleFunc("/ruleset/export", exportHandler).Methods(http.MethodPost)
  121. r.HandleFunc("/ruleset/import", importHandler).Methods(http.MethodPost)
  122. r.HandleFunc("/config/uploads", fileUploadHandler).Methods(http.MethodPost, http.MethodGet)
  123. r.HandleFunc("/config/uploads/{name}", fileDeleteHandler).Methods(http.MethodDelete)
  124. // Register extended routes
  125. for k, v := range components {
  126. logger.Infof("register rest endpoint for component %s", k)
  127. v.rest(r)
  128. }
  129. if needToken {
  130. r.Use(middleware.Auth)
  131. }
  132. server := &http.Server{
  133. Addr: fmt.Sprintf("%s:%d", ip, port),
  134. // Good practice to set timeouts to avoid Slowloris attacks.
  135. WriteTimeout: time.Second * 60 * 5,
  136. ReadTimeout: time.Second * 60 * 5,
  137. IdleTimeout: time.Second * 60,
  138. Handler: handlers.CORS(handlers.AllowedHeaders([]string{"Accept", "Accept-Language", "Content-Type", "Content-Language", "Origin", "Authorization"}), handlers.AllowedMethods([]string{"POST", "GET", "PUT", "DELETE", "HEAD"}))(r),
  139. }
  140. server.SetKeepAlivesEnabled(false)
  141. return server
  142. }
  143. type fileContent struct {
  144. Name string `json:"name"`
  145. Content string `json:"content"`
  146. }
  147. func fileUploadHandler(w http.ResponseWriter, r *http.Request) {
  148. switch r.Method {
  149. // Upload or overwrite a file
  150. case http.MethodPost:
  151. switch r.Header.Get("Content-Type") {
  152. case "application/json":
  153. fc := &fileContent{}
  154. defer r.Body.Close()
  155. err := json.NewDecoder(r.Body).Decode(fc)
  156. if err != nil {
  157. handleError(w, err, "Invalid body: Error decoding file json", logger)
  158. return
  159. }
  160. if fc.Content == "" || fc.Name == "" {
  161. handleError(w, nil, "Invalid body: name and content are required", logger)
  162. return
  163. }
  164. filePath := filepath.Join(uploadDir, fc.Name)
  165. dst, err := os.Create(filePath)
  166. defer dst.Close()
  167. if err != nil {
  168. handleError(w, err, "Error creating the file", logger)
  169. return
  170. }
  171. _, err = dst.Write([]byte(fc.Content))
  172. if err != nil {
  173. handleError(w, err, "Error writing the file", logger)
  174. return
  175. }
  176. w.WriteHeader(http.StatusCreated)
  177. w.Write([]byte(filePath))
  178. default:
  179. // Maximum upload of 1 GB files
  180. err := r.ParseMultipartForm(1024 << 20)
  181. if err != nil {
  182. handleError(w, err, "Error parse the multi part form", logger)
  183. return
  184. }
  185. // Get handler for filename, size and headers
  186. file, handler, err := r.FormFile("uploadFile")
  187. if err != nil {
  188. handleError(w, err, "Error Retrieving the File", logger)
  189. return
  190. }
  191. defer file.Close()
  192. // Create file
  193. filePath := filepath.Join(uploadDir, handler.Filename)
  194. dst, err := os.Create(filePath)
  195. defer dst.Close()
  196. if err != nil {
  197. handleError(w, err, "Error creating the file", logger)
  198. return
  199. }
  200. // Copy the uploaded file to the created file on the filesystem
  201. if _, err := io.Copy(dst, file); err != nil {
  202. handleError(w, err, "Error writing the file", logger)
  203. return
  204. }
  205. w.WriteHeader(http.StatusCreated)
  206. w.Write([]byte(filePath))
  207. }
  208. case http.MethodGet:
  209. // Get the list of files in the upload directory
  210. files, err := os.ReadDir(uploadDir)
  211. if err != nil {
  212. handleError(w, err, "Error reading the file upload dir", logger)
  213. return
  214. }
  215. fileNames := make([]string, len(files))
  216. for i, f := range files {
  217. fileNames[i] = filepath.Join(uploadDir, f.Name())
  218. }
  219. jsonResponse(fileNames, w, logger)
  220. }
  221. }
  222. func fileDeleteHandler(w http.ResponseWriter, r *http.Request) {
  223. vars := mux.Vars(r)
  224. name := vars["name"]
  225. filePath := filepath.Join(uploadDir, name)
  226. e := os.Remove(filePath)
  227. if e != nil {
  228. handleError(w, e, "Error deleting the file", logger)
  229. return
  230. }
  231. w.WriteHeader(http.StatusOK)
  232. w.Write([]byte("ok"))
  233. }
  234. type information struct {
  235. Version string `json:"version"`
  236. Os string `json:"os"`
  237. Arch string `json:"arch"`
  238. UpTimeSeconds int64 `json:"upTimeSeconds"`
  239. }
  240. // The handler for root
  241. func rootHandler(w http.ResponseWriter, r *http.Request) {
  242. defer r.Body.Close()
  243. switch r.Method {
  244. case http.MethodGet, http.MethodPost:
  245. w.WriteHeader(http.StatusOK)
  246. info := new(information)
  247. info.Version = version
  248. info.UpTimeSeconds = time.Now().Unix() - startTimeStamp
  249. info.Os = runtime.GOOS
  250. info.Arch = runtime.GOARCH
  251. byteInfo, _ := json.Marshal(info)
  252. w.Write(byteInfo)
  253. }
  254. }
  255. func pingHandler(w http.ResponseWriter, _ *http.Request) {
  256. w.WriteHeader(http.StatusOK)
  257. }
  258. func sourcesManageHandler(w http.ResponseWriter, r *http.Request, st ast.StreamType) {
  259. defer r.Body.Close()
  260. switch r.Method {
  261. case http.MethodGet:
  262. var (
  263. content []string
  264. err error
  265. kind string
  266. )
  267. if st == ast.TypeTable {
  268. kind = r.URL.Query().Get("kind")
  269. if kind == "scan" {
  270. kind = ast.StreamKindScan
  271. } else if kind == "lookup" {
  272. kind = ast.StreamKindLookup
  273. } else {
  274. kind = ""
  275. }
  276. }
  277. if kind != "" {
  278. content, err = streamProcessor.ShowTable(kind)
  279. } else {
  280. content, err = streamProcessor.ShowStream(st)
  281. }
  282. if err != nil {
  283. handleError(w, err, fmt.Sprintf("%s command error", strings.Title(ast.StreamTypeMap[st])), logger)
  284. return
  285. }
  286. jsonResponse(content, w, logger)
  287. case http.MethodPost:
  288. v, err := decodeStatementDescriptor(r.Body)
  289. if err != nil {
  290. handleError(w, err, "Invalid body", logger)
  291. return
  292. }
  293. content, err := streamProcessor.ExecStreamSql(v.Sql)
  294. if err != nil {
  295. handleError(w, err, fmt.Sprintf("%s command error", strings.Title(ast.StreamTypeMap[st])), logger)
  296. return
  297. }
  298. w.WriteHeader(http.StatusCreated)
  299. w.Write([]byte(content))
  300. }
  301. }
  302. func sourceManageHandler(w http.ResponseWriter, r *http.Request, st ast.StreamType) {
  303. defer r.Body.Close()
  304. vars := mux.Vars(r)
  305. name := vars["name"]
  306. switch r.Method {
  307. case http.MethodGet:
  308. content, err := streamProcessor.DescStream(name, st)
  309. if err != nil {
  310. handleError(w, err, fmt.Sprintf("describe %s error", ast.StreamTypeMap[st]), logger)
  311. return
  312. }
  313. jsonResponse(content, w, logger)
  314. case http.MethodDelete:
  315. content, err := streamProcessor.DropStream(name, st)
  316. if err != nil {
  317. handleError(w, err, fmt.Sprintf("delete %s error", ast.StreamTypeMap[st]), logger)
  318. return
  319. }
  320. w.WriteHeader(http.StatusOK)
  321. w.Write([]byte(content))
  322. case http.MethodPut:
  323. v, err := decodeStatementDescriptor(r.Body)
  324. if err != nil {
  325. handleError(w, err, "Invalid body", logger)
  326. return
  327. }
  328. content, err := streamProcessor.ExecReplaceStream(name, v.Sql, st)
  329. if err != nil {
  330. handleError(w, err, fmt.Sprintf("%s command error", strings.Title(ast.StreamTypeMap[st])), logger)
  331. return
  332. }
  333. w.WriteHeader(http.StatusOK)
  334. w.Write([]byte(content))
  335. }
  336. }
  337. // list or create streams
  338. func streamsHandler(w http.ResponseWriter, r *http.Request) {
  339. sourcesManageHandler(w, r, ast.TypeStream)
  340. }
  341. // describe or delete a stream
  342. func streamHandler(w http.ResponseWriter, r *http.Request) {
  343. sourceManageHandler(w, r, ast.TypeStream)
  344. }
  345. // list or create tables
  346. func tablesHandler(w http.ResponseWriter, r *http.Request) {
  347. sourcesManageHandler(w, r, ast.TypeTable)
  348. }
  349. func tableHandler(w http.ResponseWriter, r *http.Request) {
  350. sourceManageHandler(w, r, ast.TypeTable)
  351. }
  352. func streamSchemaHandler(w http.ResponseWriter, r *http.Request) {
  353. sourceSchemaHandler(w, r, ast.TypeStream)
  354. }
  355. func tableSchemaHandler(w http.ResponseWriter, r *http.Request) {
  356. sourceSchemaHandler(w, r, ast.TypeTable)
  357. }
  358. func sourceSchemaHandler(w http.ResponseWriter, r *http.Request, st ast.StreamType) {
  359. vars := mux.Vars(r)
  360. name := vars["name"]
  361. content, err := streamProcessor.GetInferredJsonSchema(name, st)
  362. if err != nil {
  363. handleError(w, err, fmt.Sprintf("get schema of %s error", ast.StreamTypeMap[st]), logger)
  364. return
  365. }
  366. jsonResponse(content, w, logger)
  367. }
  368. // list or create rules
  369. func rulesHandler(w http.ResponseWriter, r *http.Request) {
  370. defer r.Body.Close()
  371. switch r.Method {
  372. case http.MethodPost:
  373. body, err := io.ReadAll(r.Body)
  374. if err != nil {
  375. handleError(w, err, "Invalid body", logger)
  376. return
  377. }
  378. id, err := createRule("", string(body))
  379. if err != nil {
  380. handleError(w, err, "", logger)
  381. return
  382. }
  383. result := fmt.Sprintf("Rule %s was created successfully.", id)
  384. w.WriteHeader(http.StatusCreated)
  385. w.Write([]byte(result))
  386. case http.MethodGet:
  387. content, err := getAllRulesWithStatus()
  388. if err != nil {
  389. handleError(w, err, "Show rules error", logger)
  390. return
  391. }
  392. jsonResponse(content, w, logger)
  393. }
  394. }
  395. // describe or delete a rule
  396. func ruleHandler(w http.ResponseWriter, r *http.Request) {
  397. defer r.Body.Close()
  398. vars := mux.Vars(r)
  399. name := vars["name"]
  400. switch r.Method {
  401. case http.MethodGet:
  402. rule, err := ruleProcessor.GetRuleJson(name)
  403. if err != nil {
  404. handleError(w, err, "describe rule error", logger)
  405. return
  406. }
  407. w.Header().Add(ContentType, ContentTypeJSON)
  408. w.Write([]byte(rule))
  409. case http.MethodDelete:
  410. deleteRule(name)
  411. content, err := ruleProcessor.ExecDrop(name)
  412. if err != nil {
  413. handleError(w, err, "delete rule error", logger)
  414. return
  415. }
  416. w.WriteHeader(http.StatusOK)
  417. w.Write([]byte(content))
  418. case http.MethodPut:
  419. _, err := ruleProcessor.GetRuleById(name)
  420. if err != nil {
  421. handleError(w, err, "not found this rule", logger)
  422. return
  423. }
  424. body, err := io.ReadAll(r.Body)
  425. if err != nil {
  426. handleError(w, err, "Invalid body", logger)
  427. return
  428. }
  429. err = updateRule(name, string(body))
  430. if err != nil {
  431. handleError(w, err, "restart rule error", logger)
  432. return
  433. }
  434. // Update to db after validation
  435. _, err = ruleProcessor.ExecUpdate(name, string(body))
  436. var result string
  437. if err != nil {
  438. handleError(w, err, "Update rule error, suggest to delete it and recreate", logger)
  439. return
  440. } else {
  441. result = fmt.Sprintf("Rule %s was updated successfully.", name)
  442. }
  443. w.WriteHeader(http.StatusOK)
  444. w.Write([]byte(result))
  445. }
  446. }
  447. // get status of a rule
  448. func getStatusRuleHandler(w http.ResponseWriter, r *http.Request) {
  449. defer r.Body.Close()
  450. vars := mux.Vars(r)
  451. name := vars["name"]
  452. content, err := getRuleStatus(name)
  453. if err != nil {
  454. handleError(w, err, "get rule status error", logger)
  455. return
  456. }
  457. w.Header().Set(ContentType, ContentTypeJSON)
  458. w.WriteHeader(http.StatusOK)
  459. w.Write([]byte(content))
  460. }
  461. // start a rule
  462. func startRuleHandler(w http.ResponseWriter, r *http.Request) {
  463. defer r.Body.Close()
  464. vars := mux.Vars(r)
  465. name := vars["name"]
  466. err := startRule(name)
  467. if err != nil {
  468. handleError(w, err, "start rule error", logger)
  469. return
  470. }
  471. w.WriteHeader(http.StatusOK)
  472. w.Write([]byte(fmt.Sprintf("Rule %s was started", name)))
  473. }
  474. // stop a rule
  475. func stopRuleHandler(w http.ResponseWriter, r *http.Request) {
  476. defer r.Body.Close()
  477. vars := mux.Vars(r)
  478. name := vars["name"]
  479. result := stopRule(name)
  480. w.WriteHeader(http.StatusOK)
  481. w.Write([]byte(result))
  482. }
  483. // restart a rule
  484. func restartRuleHandler(w http.ResponseWriter, r *http.Request) {
  485. defer r.Body.Close()
  486. vars := mux.Vars(r)
  487. name := vars["name"]
  488. err := restartRule(name)
  489. if err != nil {
  490. handleError(w, err, "restart rule error", logger)
  491. return
  492. }
  493. w.WriteHeader(http.StatusOK)
  494. w.Write([]byte(fmt.Sprintf("Rule %s was restarted", name)))
  495. }
  496. // get topo of a rule
  497. func getTopoRuleHandler(w http.ResponseWriter, r *http.Request) {
  498. defer r.Body.Close()
  499. vars := mux.Vars(r)
  500. name := vars["name"]
  501. content, err := getRuleTopo(name)
  502. if err != nil {
  503. handleError(w, err, "get rule topo error", logger)
  504. return
  505. }
  506. w.Header().Set(ContentType, ContentTypeJSON)
  507. w.Write([]byte(content))
  508. }
  509. type rulesetInfo struct {
  510. Content string `json:"content"`
  511. FilePath string `json:"file"`
  512. }
  513. func importHandler(w http.ResponseWriter, r *http.Request) {
  514. rsi := &rulesetInfo{}
  515. err := json.NewDecoder(r.Body).Decode(rsi)
  516. if err != nil {
  517. handleError(w, err, "Invalid body: Error decoding json", logger)
  518. return
  519. }
  520. if rsi.Content != "" && rsi.FilePath != "" {
  521. handleError(w, nil, "Invalid body: Cannot specify both content and file", logger)
  522. return
  523. } else if rsi.Content == "" && rsi.FilePath == "" {
  524. handleError(w, nil, "Invalid body: must specify content or file", logger)
  525. return
  526. }
  527. content := []byte(rsi.Content)
  528. if rsi.FilePath != "" {
  529. reader, err := httpx.ReadFile(rsi.FilePath)
  530. if err != nil {
  531. handleError(w, nil, "Fail to read file", logger)
  532. return
  533. }
  534. defer reader.Close()
  535. buf := new(bytes.Buffer)
  536. _, err = io.Copy(buf, reader)
  537. if err != nil {
  538. handleError(w, err, "fail to convert file", logger)
  539. return
  540. }
  541. content = buf.Bytes()
  542. }
  543. rules, counts, err := rulesetProcessor.Import(content)
  544. if err != nil {
  545. handleError(w, nil, "Import ruleset error", logger)
  546. return
  547. }
  548. infra.SafeRun(func() error {
  549. for _, name := range rules {
  550. rul, ee := ruleProcessor.GetRuleById(name)
  551. if ee != nil {
  552. logger.Error(ee)
  553. continue
  554. }
  555. reply := recoverRule(rul)
  556. if reply != "" {
  557. logger.Error(reply)
  558. }
  559. }
  560. return nil
  561. })
  562. w.Write([]byte(fmt.Sprintf("imported %d streams, %d tables and %d rules", counts[0], counts[1], counts[2])))
  563. }
  564. func exportHandler(w http.ResponseWriter, r *http.Request) {
  565. const name = "ekuiper_export.json"
  566. exported, _, err := rulesetProcessor.Export()
  567. if err != nil {
  568. handleError(w, err, "export error", logger)
  569. return
  570. }
  571. w.Header().Set("Content-Type", "application/octet-stream")
  572. w.Header().Add("Content-Disposition", "Attachment")
  573. http.ServeContent(w, r, name, time.Now(), exported)
  574. }