rest.go 14 KB

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