rest.go 14 KB

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