rest.go 16 KB

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