rest.go 15 KB

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