rest.go 14 KB

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