rest.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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 tot he 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. r, err := ruleProcessor.ExecCreate("", string(body))
  361. var result string
  362. if err != nil {
  363. handleError(w, err, "Create rule error", logger)
  364. return
  365. } else {
  366. result = fmt.Sprintf("Rule %s was created successfully.", r.Id)
  367. }
  368. go func() {
  369. panicOrError := infra.SafeRun(func() error {
  370. //Start the rule
  371. rs, err := createRuleState(r)
  372. if err != nil {
  373. return err
  374. } else {
  375. err = doStartRule(rs)
  376. return err
  377. }
  378. })
  379. if panicOrError != nil {
  380. logger.Errorf("Rule %s start failed: %s", r.Id, panicOrError)
  381. }
  382. }()
  383. w.WriteHeader(http.StatusCreated)
  384. w.Write([]byte(result))
  385. case http.MethodGet:
  386. content, err := getAllRulesWithStatus()
  387. if err != nil {
  388. handleError(w, err, "Show rules error", logger)
  389. return
  390. }
  391. jsonResponse(content, w, logger)
  392. }
  393. }
  394. // describe or delete a rule
  395. func ruleHandler(w http.ResponseWriter, r *http.Request) {
  396. defer r.Body.Close()
  397. vars := mux.Vars(r)
  398. name := vars["name"]
  399. switch r.Method {
  400. case http.MethodGet:
  401. rule, err := ruleProcessor.GetRuleJson(name)
  402. if err != nil {
  403. handleError(w, err, "describe rule error", logger)
  404. return
  405. }
  406. w.Header().Add(ContentType, ContentTypeJSON)
  407. w.Write([]byte(rule))
  408. case http.MethodDelete:
  409. deleteRule(name)
  410. content, err := ruleProcessor.ExecDrop(name)
  411. if err != nil {
  412. handleError(w, err, "delete rule error", logger)
  413. return
  414. }
  415. w.WriteHeader(http.StatusOK)
  416. w.Write([]byte(content))
  417. case http.MethodPut:
  418. _, err := ruleProcessor.GetRuleById(name)
  419. if err != nil {
  420. handleError(w, err, "not found this rule", logger)
  421. return
  422. }
  423. body, err := io.ReadAll(r.Body)
  424. if err != nil {
  425. handleError(w, err, "Invalid body", logger)
  426. return
  427. }
  428. r, err := ruleProcessor.ExecUpdate(name, string(body))
  429. var result string
  430. if err != nil {
  431. handleError(w, err, "Update rule error", logger)
  432. return
  433. } else {
  434. result = fmt.Sprintf("Rule %s was updated successfully.", r.Id)
  435. }
  436. err = restartRule(name)
  437. if err != nil {
  438. handleError(w, err, "restart rule error", logger)
  439. return
  440. }
  441. w.WriteHeader(http.StatusOK)
  442. w.Write([]byte(result))
  443. }
  444. }
  445. // get status of a rule
  446. func getStatusRuleHandler(w http.ResponseWriter, r *http.Request) {
  447. defer r.Body.Close()
  448. vars := mux.Vars(r)
  449. name := vars["name"]
  450. content, err := getRuleStatus(name)
  451. if err != nil {
  452. handleError(w, err, "get rule status error", logger)
  453. return
  454. }
  455. w.Header().Set(ContentType, ContentTypeJSON)
  456. w.WriteHeader(http.StatusOK)
  457. w.Write([]byte(content))
  458. }
  459. // start a rule
  460. func startRuleHandler(w http.ResponseWriter, r *http.Request) {
  461. defer r.Body.Close()
  462. vars := mux.Vars(r)
  463. name := vars["name"]
  464. err := startRule(name)
  465. if err != nil {
  466. handleError(w, err, "start rule error", logger)
  467. return
  468. }
  469. w.WriteHeader(http.StatusOK)
  470. w.Write([]byte(fmt.Sprintf("Rule %s was started", name)))
  471. }
  472. // stop a rule
  473. func stopRuleHandler(w http.ResponseWriter, r *http.Request) {
  474. defer r.Body.Close()
  475. vars := mux.Vars(r)
  476. name := vars["name"]
  477. result := stopRule(name)
  478. w.WriteHeader(http.StatusOK)
  479. w.Write([]byte(result))
  480. }
  481. // restart a rule
  482. func restartRuleHandler(w http.ResponseWriter, r *http.Request) {
  483. defer r.Body.Close()
  484. vars := mux.Vars(r)
  485. name := vars["name"]
  486. err := restartRule(name)
  487. if err != nil {
  488. handleError(w, err, "restart rule error", logger)
  489. return
  490. }
  491. w.WriteHeader(http.StatusOK)
  492. w.Write([]byte(fmt.Sprintf("Rule %s was restarted", name)))
  493. }
  494. // get topo of a rule
  495. func getTopoRuleHandler(w http.ResponseWriter, r *http.Request) {
  496. defer r.Body.Close()
  497. vars := mux.Vars(r)
  498. name := vars["name"]
  499. content, err := getRuleTopo(name)
  500. if err != nil {
  501. handleError(w, err, "get rule topo error", logger)
  502. return
  503. }
  504. w.Header().Set(ContentType, ContentTypeJSON)
  505. w.Write([]byte(content))
  506. }
  507. type rulesetInfo struct {
  508. Content string `json:"content"`
  509. FilePath string `json:"file"`
  510. }
  511. func importHandler(w http.ResponseWriter, r *http.Request) {
  512. rsi := &rulesetInfo{}
  513. err := json.NewDecoder(r.Body).Decode(rsi)
  514. if err != nil {
  515. handleError(w, err, "Invalid body: Error decoding json", logger)
  516. return
  517. }
  518. if rsi.Content != "" && rsi.FilePath != "" {
  519. handleError(w, nil, "Invalid body: Cannot specify both content and file", logger)
  520. return
  521. } else if rsi.Content == "" && rsi.FilePath == "" {
  522. handleError(w, nil, "Invalid body: must specify content or file", logger)
  523. return
  524. }
  525. content := []byte(rsi.Content)
  526. if rsi.FilePath != "" {
  527. reader, err := httpx.ReadFile(rsi.FilePath)
  528. if err != nil {
  529. handleError(w, nil, "Fail to read file", logger)
  530. return
  531. }
  532. defer reader.Close()
  533. buf := new(bytes.Buffer)
  534. _, err = io.Copy(buf, reader)
  535. if err != nil {
  536. handleError(w, err, "fail to convert file", logger)
  537. return
  538. }
  539. content = buf.Bytes()
  540. }
  541. rules, counts, err := rulesetProcessor.Import(content)
  542. if err != nil {
  543. handleError(w, nil, "Import ruleset error", logger)
  544. return
  545. }
  546. infra.SafeRun(func() error {
  547. for _, name := range rules {
  548. err := startRule(name)
  549. if err != nil {
  550. logger.Error(err)
  551. }
  552. }
  553. return nil
  554. })
  555. w.Write([]byte(fmt.Sprintf("imported %d streams, %d tables and %d rules", counts[0], counts[1], counts[2])))
  556. }
  557. func exportHandler(w http.ResponseWriter, r *http.Request) {
  558. const name = "ekuiper_export.json"
  559. exported, _, err := rulesetProcessor.Export()
  560. if err != nil {
  561. handleError(w, err, "export error", logger)
  562. return
  563. }
  564. w.Header().Set("Content-Type", "application/octet-stream")
  565. w.Header().Add("Content-Disposition", "Attachment")
  566. http.ServeContent(w, r, name, time.Now(), exported)
  567. }