rest.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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. content, err := streamProcessor.ShowStream(st)
  253. if err != nil {
  254. handleError(w, err, fmt.Sprintf("%s command error", strings.Title(ast.StreamTypeMap[st])), logger)
  255. return
  256. }
  257. jsonResponse(content, w, logger)
  258. case http.MethodPost:
  259. v, err := decodeStatementDescriptor(r.Body)
  260. if err != nil {
  261. handleError(w, err, "Invalid body", logger)
  262. return
  263. }
  264. content, err := streamProcessor.ExecStreamSql(v.Sql)
  265. if err != nil {
  266. handleError(w, err, fmt.Sprintf("%s command error", strings.Title(ast.StreamTypeMap[st])), logger)
  267. return
  268. }
  269. w.WriteHeader(http.StatusCreated)
  270. w.Write([]byte(content))
  271. }
  272. }
  273. func sourceManageHandler(w http.ResponseWriter, r *http.Request, st ast.StreamType) {
  274. defer r.Body.Close()
  275. vars := mux.Vars(r)
  276. name := vars["name"]
  277. switch r.Method {
  278. case http.MethodGet:
  279. content, err := streamProcessor.DescStream(name, st)
  280. if err != nil {
  281. handleError(w, err, fmt.Sprintf("describe %s error", ast.StreamTypeMap[st]), logger)
  282. return
  283. }
  284. jsonResponse(content, w, logger)
  285. case http.MethodDelete:
  286. content, err := streamProcessor.DropStream(name, st)
  287. if err != nil {
  288. handleError(w, err, fmt.Sprintf("delete %s error", ast.StreamTypeMap[st]), logger)
  289. return
  290. }
  291. w.WriteHeader(http.StatusOK)
  292. w.Write([]byte(content))
  293. case http.MethodPut:
  294. v, err := decodeStatementDescriptor(r.Body)
  295. if err != nil {
  296. handleError(w, err, "Invalid body", logger)
  297. return
  298. }
  299. content, err := streamProcessor.ExecReplaceStream(name, v.Sql, st)
  300. if err != nil {
  301. handleError(w, err, fmt.Sprintf("%s command error", strings.Title(ast.StreamTypeMap[st])), logger)
  302. return
  303. }
  304. w.WriteHeader(http.StatusOK)
  305. w.Write([]byte(content))
  306. }
  307. }
  308. // list or create streams
  309. func streamsHandler(w http.ResponseWriter, r *http.Request) {
  310. sourcesManageHandler(w, r, ast.TypeStream)
  311. }
  312. // describe or delete a stream
  313. func streamHandler(w http.ResponseWriter, r *http.Request) {
  314. sourceManageHandler(w, r, ast.TypeStream)
  315. }
  316. // list or create tables
  317. func tablesHandler(w http.ResponseWriter, r *http.Request) {
  318. sourcesManageHandler(w, r, ast.TypeTable)
  319. }
  320. func tableHandler(w http.ResponseWriter, r *http.Request) {
  321. sourceManageHandler(w, r, ast.TypeTable)
  322. }
  323. // list or create rules
  324. func rulesHandler(w http.ResponseWriter, r *http.Request) {
  325. defer r.Body.Close()
  326. switch r.Method {
  327. case http.MethodPost:
  328. body, err := io.ReadAll(r.Body)
  329. if err != nil {
  330. handleError(w, err, "Invalid body", logger)
  331. return
  332. }
  333. r, err := ruleProcessor.ExecCreate("", string(body))
  334. var result string
  335. if err != nil {
  336. handleError(w, err, "Create rule error", logger)
  337. return
  338. } else {
  339. result = fmt.Sprintf("Rule %s was created successfully.", r.Id)
  340. }
  341. go func() {
  342. panicOrError := infra.SafeRun(func() error {
  343. //Start the rule
  344. rs, err := createRuleState(r)
  345. if err != nil {
  346. return err
  347. } else {
  348. err = doStartRule(rs)
  349. return err
  350. }
  351. })
  352. if panicOrError != nil {
  353. logger.Errorf("Rule %s start failed: %s", r.Id, panicOrError)
  354. }
  355. }()
  356. w.WriteHeader(http.StatusCreated)
  357. w.Write([]byte(result))
  358. case http.MethodGet:
  359. content, err := getAllRulesWithStatus()
  360. if err != nil {
  361. handleError(w, err, "Show rules error", logger)
  362. return
  363. }
  364. jsonResponse(content, w, logger)
  365. }
  366. }
  367. // describe or delete a rule
  368. func ruleHandler(w http.ResponseWriter, r *http.Request) {
  369. defer r.Body.Close()
  370. vars := mux.Vars(r)
  371. name := vars["name"]
  372. switch r.Method {
  373. case http.MethodGet:
  374. rule, err := ruleProcessor.GetRuleJson(name)
  375. if err != nil {
  376. handleError(w, err, "describe rule error", logger)
  377. return
  378. }
  379. w.Header().Add(ContentType, ContentTypeJSON)
  380. w.Write([]byte(rule))
  381. case http.MethodDelete:
  382. deleteRule(name)
  383. content, err := ruleProcessor.ExecDrop(name)
  384. if err != nil {
  385. handleError(w, err, "delete rule error", logger)
  386. return
  387. }
  388. w.WriteHeader(http.StatusOK)
  389. w.Write([]byte(content))
  390. case http.MethodPut:
  391. _, err := ruleProcessor.GetRuleById(name)
  392. if err != nil {
  393. handleError(w, err, "not found this rule", logger)
  394. return
  395. }
  396. body, err := io.ReadAll(r.Body)
  397. if err != nil {
  398. handleError(w, err, "Invalid body", logger)
  399. return
  400. }
  401. r, err := ruleProcessor.ExecUpdate(name, string(body))
  402. var result string
  403. if err != nil {
  404. handleError(w, err, "Update rule error", logger)
  405. return
  406. } else {
  407. result = fmt.Sprintf("Rule %s was updated successfully.", r.Id)
  408. }
  409. err = restartRule(name)
  410. if err != nil {
  411. handleError(w, err, "restart rule error", logger)
  412. return
  413. }
  414. w.WriteHeader(http.StatusOK)
  415. w.Write([]byte(result))
  416. }
  417. }
  418. // get status of a rule
  419. func getStatusRuleHandler(w http.ResponseWriter, r *http.Request) {
  420. defer r.Body.Close()
  421. vars := mux.Vars(r)
  422. name := vars["name"]
  423. content, err := getRuleStatus(name)
  424. if err != nil {
  425. handleError(w, err, "get rule status error", logger)
  426. return
  427. }
  428. w.Header().Set(ContentType, ContentTypeJSON)
  429. w.WriteHeader(http.StatusOK)
  430. w.Write([]byte(content))
  431. }
  432. // start a rule
  433. func startRuleHandler(w http.ResponseWriter, r *http.Request) {
  434. defer r.Body.Close()
  435. vars := mux.Vars(r)
  436. name := vars["name"]
  437. err := startRule(name)
  438. if err != nil {
  439. handleError(w, err, "start rule error", logger)
  440. return
  441. }
  442. w.WriteHeader(http.StatusOK)
  443. w.Write([]byte(fmt.Sprintf("Rule %s was started", name)))
  444. }
  445. // stop a rule
  446. func stopRuleHandler(w http.ResponseWriter, r *http.Request) {
  447. defer r.Body.Close()
  448. vars := mux.Vars(r)
  449. name := vars["name"]
  450. result := stopRule(name)
  451. w.WriteHeader(http.StatusOK)
  452. w.Write([]byte(result))
  453. }
  454. // restart a rule
  455. func restartRuleHandler(w http.ResponseWriter, r *http.Request) {
  456. defer r.Body.Close()
  457. vars := mux.Vars(r)
  458. name := vars["name"]
  459. err := restartRule(name)
  460. if err != nil {
  461. handleError(w, err, "restart rule error", logger)
  462. return
  463. }
  464. w.WriteHeader(http.StatusOK)
  465. w.Write([]byte(fmt.Sprintf("Rule %s was restarted", name)))
  466. }
  467. // get topo of a rule
  468. func getTopoRuleHandler(w http.ResponseWriter, r *http.Request) {
  469. defer r.Body.Close()
  470. vars := mux.Vars(r)
  471. name := vars["name"]
  472. content, err := getRuleTopo(name)
  473. if err != nil {
  474. handleError(w, err, "get rule topo error", logger)
  475. return
  476. }
  477. w.Header().Set(ContentType, ContentTypeJSON)
  478. w.Write([]byte(content))
  479. }