rest.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  1. // Copyright 2021-2023 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. "bytes"
  17. "encoding/json"
  18. "errors"
  19. "fmt"
  20. "github.com/lf-edge/ekuiper/internal/conf"
  21. "github.com/lf-edge/ekuiper/internal/meta"
  22. "github.com/lf-edge/ekuiper/internal/pkg/httpx"
  23. "github.com/lf-edge/ekuiper/internal/processor"
  24. "io"
  25. "net/http"
  26. "os"
  27. "path/filepath"
  28. "runtime"
  29. "strconv"
  30. "strings"
  31. "time"
  32. "github.com/gorilla/handlers"
  33. "github.com/gorilla/mux"
  34. "github.com/lf-edge/ekuiper/internal/server/middleware"
  35. "github.com/lf-edge/ekuiper/pkg/api"
  36. "github.com/lf-edge/ekuiper/pkg/ast"
  37. "github.com/lf-edge/ekuiper/pkg/errorx"
  38. "github.com/lf-edge/ekuiper/pkg/infra"
  39. )
  40. const (
  41. ContentType = "Content-Type"
  42. ContentTypeJSON = "application/json"
  43. )
  44. var uploadDir string
  45. type statementDescriptor struct {
  46. Sql string `json:"sql,omitempty"`
  47. }
  48. func decodeStatementDescriptor(reader io.ReadCloser) (statementDescriptor, error) {
  49. sd := statementDescriptor{}
  50. err := json.NewDecoder(reader).Decode(&sd)
  51. // Problems decoding
  52. if err != nil {
  53. return sd, fmt.Errorf("Error decoding the statement descriptor: %v", err)
  54. }
  55. return sd, nil
  56. }
  57. // Handle applies the specified error and error concept to the HTTP response writer
  58. func handleError(w http.ResponseWriter, err error, prefix string, logger api.Logger) {
  59. message := prefix
  60. if message != "" {
  61. message += ": "
  62. }
  63. message += err.Error()
  64. logger.Error(message)
  65. var ec int
  66. switch e := err.(type) {
  67. case *errorx.Error:
  68. switch e.Code() {
  69. case errorx.NOT_FOUND:
  70. ec = http.StatusNotFound
  71. default:
  72. ec = http.StatusBadRequest
  73. }
  74. default:
  75. ec = http.StatusBadRequest
  76. }
  77. http.Error(w, message, ec)
  78. }
  79. func jsonResponse(i interface{}, w http.ResponseWriter, logger api.Logger) {
  80. w.Header().Add(ContentType, ContentTypeJSON)
  81. jsonByte, err := json.Marshal(i)
  82. if err != nil {
  83. handleError(w, err, "", logger)
  84. }
  85. w.Header().Add("Content-Length", strconv.Itoa(len(jsonByte)))
  86. _, err = w.Write(jsonByte)
  87. // Problems encoding
  88. if err != nil {
  89. handleError(w, err, "", logger)
  90. }
  91. }
  92. func jsonByteResponse(buffer bytes.Buffer, w http.ResponseWriter, logger api.Logger) {
  93. w.Header().Add(ContentType, ContentTypeJSON)
  94. w.Header().Add("Content-Length", strconv.Itoa(buffer.Len()))
  95. _, err := w.Write(buffer.Bytes())
  96. // Problems encoding
  97. if err != nil {
  98. handleError(w, err, "", logger)
  99. }
  100. }
  101. func createRestServer(ip string, port int, needToken bool) *http.Server {
  102. dataDir, err := conf.GetDataLoc()
  103. if err != nil {
  104. panic(err)
  105. }
  106. uploadDir = filepath.Join(dataDir, "uploads")
  107. r := mux.NewRouter()
  108. r.HandleFunc("/", rootHandler).Methods(http.MethodGet, http.MethodPost)
  109. r.HandleFunc("/ping", pingHandler).Methods(http.MethodGet)
  110. r.HandleFunc("/streams", streamsHandler).Methods(http.MethodGet, http.MethodPost)
  111. r.HandleFunc("/streams/{name}", streamHandler).Methods(http.MethodGet, http.MethodDelete, http.MethodPut)
  112. r.HandleFunc("/streams/{name}/schema", streamSchemaHandler).Methods(http.MethodGet)
  113. r.HandleFunc("/tables", tablesHandler).Methods(http.MethodGet, http.MethodPost)
  114. r.HandleFunc("/tables/{name}", tableHandler).Methods(http.MethodGet, http.MethodDelete, http.MethodPut)
  115. r.HandleFunc("/tables/{name}/schema", tableSchemaHandler).Methods(http.MethodGet)
  116. r.HandleFunc("/rules", rulesHandler).Methods(http.MethodGet, http.MethodPost)
  117. r.HandleFunc("/rules/{name}", ruleHandler).Methods(http.MethodDelete, http.MethodGet, http.MethodPut)
  118. r.HandleFunc("/rules/{name}/status", getStatusRuleHandler).Methods(http.MethodGet)
  119. r.HandleFunc("/rules/{name}/start", startRuleHandler).Methods(http.MethodPost)
  120. r.HandleFunc("/rules/{name}/stop", stopRuleHandler).Methods(http.MethodPost)
  121. r.HandleFunc("/rules/{name}/restart", restartRuleHandler).Methods(http.MethodPost)
  122. r.HandleFunc("/rules/{name}/topo", getTopoRuleHandler).Methods(http.MethodGet)
  123. r.HandleFunc("/ruleset/export", exportHandler).Methods(http.MethodPost)
  124. r.HandleFunc("/ruleset/import", importHandler).Methods(http.MethodPost)
  125. r.HandleFunc("/config/uploads", fileUploadHandler).Methods(http.MethodPost, http.MethodGet)
  126. r.HandleFunc("/config/uploads/{name}", fileDeleteHandler).Methods(http.MethodDelete)
  127. r.HandleFunc("/data/export", configurationExportHandler).Methods(http.MethodGet)
  128. r.HandleFunc("/data/partial/export", configurationPartialExportHandler).Methods(http.MethodPost)
  129. r.HandleFunc("/data/import", configurationImportHandler).Methods(http.MethodPost)
  130. r.HandleFunc("/data/import/status", configurationStatusHandler).Methods(http.MethodGet)
  131. // Register extended routes
  132. for k, v := range components {
  133. logger.Infof("register rest endpoint for component %s", k)
  134. v.rest(r)
  135. }
  136. if needToken {
  137. r.Use(middleware.Auth)
  138. }
  139. server := &http.Server{
  140. Addr: fmt.Sprintf("%s:%d", ip, port),
  141. // Good practice to set timeouts to avoid Slowloris attacks.
  142. WriteTimeout: time.Second * 60 * 5,
  143. ReadTimeout: time.Second * 60 * 5,
  144. IdleTimeout: time.Second * 60,
  145. Handler: handlers.CORS(handlers.AllowedHeaders([]string{"Accept", "Accept-Language", "Content-Type", "Content-Language", "Origin", "Authorization"}), handlers.AllowedMethods([]string{"POST", "GET", "PUT", "DELETE", "HEAD"}))(r),
  146. }
  147. server.SetKeepAlivesEnabled(false)
  148. return server
  149. }
  150. type fileContent struct {
  151. Name string `json:"name"`
  152. Content string `json:"content"`
  153. }
  154. func fileUploadHandler(w http.ResponseWriter, r *http.Request) {
  155. switch r.Method {
  156. // Upload or overwrite a file
  157. case http.MethodPost:
  158. switch r.Header.Get("Content-Type") {
  159. case "application/json":
  160. fc := &fileContent{}
  161. defer r.Body.Close()
  162. err := json.NewDecoder(r.Body).Decode(fc)
  163. if err != nil {
  164. handleError(w, err, "Invalid body: Error decoding file json", logger)
  165. return
  166. }
  167. if fc.Content == "" || fc.Name == "" {
  168. handleError(w, nil, "Invalid body: name and content are required", logger)
  169. return
  170. }
  171. filePath := filepath.Join(uploadDir, fc.Name)
  172. dst, err := os.Create(filePath)
  173. defer dst.Close()
  174. if err != nil {
  175. handleError(w, err, "Error creating the file", logger)
  176. return
  177. }
  178. _, err = dst.Write([]byte(fc.Content))
  179. if err != nil {
  180. handleError(w, err, "Error writing the file", logger)
  181. return
  182. }
  183. w.WriteHeader(http.StatusCreated)
  184. w.Write([]byte(filePath))
  185. default:
  186. // Maximum upload of 1 GB files
  187. err := r.ParseMultipartForm(1024 << 20)
  188. if err != nil {
  189. handleError(w, err, "Error parse the multi part form", logger)
  190. return
  191. }
  192. // Get handler for filename, size and headers
  193. file, handler, err := r.FormFile("uploadFile")
  194. if err != nil {
  195. handleError(w, err, "Error Retrieving the File", logger)
  196. return
  197. }
  198. defer file.Close()
  199. // Create file
  200. filePath := filepath.Join(uploadDir, handler.Filename)
  201. dst, err := os.Create(filePath)
  202. defer dst.Close()
  203. if err != nil {
  204. handleError(w, err, "Error creating the file", logger)
  205. return
  206. }
  207. // Copy the uploaded file to the created file on the filesystem
  208. if _, err := io.Copy(dst, file); err != nil {
  209. handleError(w, err, "Error writing the file", logger)
  210. return
  211. }
  212. w.WriteHeader(http.StatusCreated)
  213. w.Write([]byte(filePath))
  214. }
  215. case http.MethodGet:
  216. // Get the list of files in the upload directory
  217. files, err := os.ReadDir(uploadDir)
  218. if err != nil {
  219. handleError(w, err, "Error reading the file upload dir", logger)
  220. return
  221. }
  222. fileNames := make([]string, len(files))
  223. for i, f := range files {
  224. fileNames[i] = filepath.Join(uploadDir, f.Name())
  225. }
  226. jsonResponse(fileNames, w, logger)
  227. }
  228. }
  229. func fileDeleteHandler(w http.ResponseWriter, r *http.Request) {
  230. vars := mux.Vars(r)
  231. name := vars["name"]
  232. filePath := filepath.Join(uploadDir, name)
  233. e := os.Remove(filePath)
  234. if e != nil {
  235. handleError(w, e, "Error deleting the file", logger)
  236. return
  237. }
  238. w.WriteHeader(http.StatusOK)
  239. w.Write([]byte("ok"))
  240. }
  241. type information struct {
  242. Version string `json:"version"`
  243. Os string `json:"os"`
  244. Arch string `json:"arch"`
  245. UpTimeSeconds int64 `json:"upTimeSeconds"`
  246. }
  247. // The handler for root
  248. func rootHandler(w http.ResponseWriter, r *http.Request) {
  249. defer r.Body.Close()
  250. switch r.Method {
  251. case http.MethodGet, http.MethodPost:
  252. w.WriteHeader(http.StatusOK)
  253. info := new(information)
  254. info.Version = version
  255. info.UpTimeSeconds = time.Now().Unix() - startTimeStamp
  256. info.Os = runtime.GOOS
  257. info.Arch = runtime.GOARCH
  258. byteInfo, _ := json.Marshal(info)
  259. w.Write(byteInfo)
  260. }
  261. }
  262. func pingHandler(w http.ResponseWriter, _ *http.Request) {
  263. w.WriteHeader(http.StatusOK)
  264. }
  265. func sourcesManageHandler(w http.ResponseWriter, r *http.Request, st ast.StreamType) {
  266. defer r.Body.Close()
  267. switch r.Method {
  268. case http.MethodGet:
  269. var (
  270. content []string
  271. err error
  272. kind string
  273. )
  274. if st == ast.TypeTable {
  275. kind = r.URL.Query().Get("kind")
  276. if kind == "scan" {
  277. kind = ast.StreamKindScan
  278. } else if kind == "lookup" {
  279. kind = ast.StreamKindLookup
  280. } else {
  281. kind = ""
  282. }
  283. }
  284. if kind != "" {
  285. content, err = streamProcessor.ShowTable(kind)
  286. } else {
  287. content, err = streamProcessor.ShowStream(st)
  288. }
  289. if err != nil {
  290. handleError(w, err, fmt.Sprintf("%s command error", strings.Title(ast.StreamTypeMap[st])), logger)
  291. return
  292. }
  293. jsonResponse(content, w, logger)
  294. case http.MethodPost:
  295. v, err := decodeStatementDescriptor(r.Body)
  296. if err != nil {
  297. handleError(w, err, "Invalid body", logger)
  298. return
  299. }
  300. content, err := streamProcessor.ExecStreamSql(v.Sql)
  301. if err != nil {
  302. handleError(w, err, fmt.Sprintf("%s command error", strings.Title(ast.StreamTypeMap[st])), logger)
  303. return
  304. }
  305. w.WriteHeader(http.StatusCreated)
  306. w.Write([]byte(content))
  307. }
  308. }
  309. func sourceManageHandler(w http.ResponseWriter, r *http.Request, st ast.StreamType) {
  310. defer r.Body.Close()
  311. vars := mux.Vars(r)
  312. name := vars["name"]
  313. switch r.Method {
  314. case http.MethodGet:
  315. content, err := streamProcessor.DescStream(name, st)
  316. if err != nil {
  317. handleError(w, err, fmt.Sprintf("describe %s error", ast.StreamTypeMap[st]), logger)
  318. return
  319. }
  320. jsonResponse(content, w, logger)
  321. case http.MethodDelete:
  322. content, err := streamProcessor.DropStream(name, st)
  323. if err != nil {
  324. handleError(w, err, fmt.Sprintf("delete %s error", ast.StreamTypeMap[st]), logger)
  325. return
  326. }
  327. w.WriteHeader(http.StatusOK)
  328. w.Write([]byte(content))
  329. case http.MethodPut:
  330. v, err := decodeStatementDescriptor(r.Body)
  331. if err != nil {
  332. handleError(w, err, "Invalid body", logger)
  333. return
  334. }
  335. content, err := streamProcessor.ExecReplaceStream(name, v.Sql, st)
  336. if err != nil {
  337. handleError(w, err, fmt.Sprintf("%s command error", strings.Title(ast.StreamTypeMap[st])), logger)
  338. return
  339. }
  340. w.WriteHeader(http.StatusOK)
  341. w.Write([]byte(content))
  342. }
  343. }
  344. // list or create streams
  345. func streamsHandler(w http.ResponseWriter, r *http.Request) {
  346. sourcesManageHandler(w, r, ast.TypeStream)
  347. }
  348. // describe or delete a stream
  349. func streamHandler(w http.ResponseWriter, r *http.Request) {
  350. sourceManageHandler(w, r, ast.TypeStream)
  351. }
  352. // list or create tables
  353. func tablesHandler(w http.ResponseWriter, r *http.Request) {
  354. sourcesManageHandler(w, r, ast.TypeTable)
  355. }
  356. func tableHandler(w http.ResponseWriter, r *http.Request) {
  357. sourceManageHandler(w, r, ast.TypeTable)
  358. }
  359. func streamSchemaHandler(w http.ResponseWriter, r *http.Request) {
  360. sourceSchemaHandler(w, r, ast.TypeStream)
  361. }
  362. func tableSchemaHandler(w http.ResponseWriter, r *http.Request) {
  363. sourceSchemaHandler(w, r, ast.TypeTable)
  364. }
  365. func sourceSchemaHandler(w http.ResponseWriter, r *http.Request, st ast.StreamType) {
  366. vars := mux.Vars(r)
  367. name := vars["name"]
  368. content, err := streamProcessor.GetInferredJsonSchema(name, st)
  369. if err != nil {
  370. handleError(w, err, fmt.Sprintf("get schema of %s error", ast.StreamTypeMap[st]), logger)
  371. return
  372. }
  373. jsonResponse(content, w, logger)
  374. }
  375. // list or create rules
  376. func rulesHandler(w http.ResponseWriter, r *http.Request) {
  377. defer r.Body.Close()
  378. switch r.Method {
  379. case http.MethodPost:
  380. body, err := io.ReadAll(r.Body)
  381. if err != nil {
  382. handleError(w, err, "Invalid body", logger)
  383. return
  384. }
  385. id, err := createRule("", string(body))
  386. if err != nil {
  387. handleError(w, err, "", logger)
  388. return
  389. }
  390. result := fmt.Sprintf("Rule %s was created successfully.", id)
  391. w.WriteHeader(http.StatusCreated)
  392. w.Write([]byte(result))
  393. case http.MethodGet:
  394. content, err := getAllRulesWithStatus()
  395. if err != nil {
  396. handleError(w, err, "Show rules error", logger)
  397. return
  398. }
  399. jsonResponse(content, w, logger)
  400. }
  401. }
  402. // describe or delete a rule
  403. func ruleHandler(w http.ResponseWriter, r *http.Request) {
  404. defer r.Body.Close()
  405. vars := mux.Vars(r)
  406. name := vars["name"]
  407. switch r.Method {
  408. case http.MethodGet:
  409. rule, err := ruleProcessor.GetRuleJson(name)
  410. if err != nil {
  411. handleError(w, err, "Describe rule error", logger)
  412. return
  413. }
  414. w.Header().Add(ContentType, ContentTypeJSON)
  415. w.Write([]byte(rule))
  416. case http.MethodDelete:
  417. deleteRule(name)
  418. content, err := ruleProcessor.ExecDrop(name)
  419. if err != nil {
  420. handleError(w, err, "Delete rule error", logger)
  421. return
  422. }
  423. w.WriteHeader(http.StatusOK)
  424. w.Write([]byte(content))
  425. case http.MethodPut:
  426. _, err := ruleProcessor.GetRuleById(name)
  427. if err != nil {
  428. handleError(w, err, "Rule not found", logger)
  429. return
  430. }
  431. body, err := io.ReadAll(r.Body)
  432. if err != nil {
  433. handleError(w, err, "Invalid body", logger)
  434. return
  435. }
  436. err = updateRule(name, string(body))
  437. if err != nil {
  438. handleError(w, err, "Update rule error", logger)
  439. return
  440. }
  441. // Update to db after validation
  442. _, err = ruleProcessor.ExecUpdate(name, string(body))
  443. var result string
  444. if err != nil {
  445. handleError(w, err, "Update rule error, suggest to delete it and recreate", logger)
  446. return
  447. } else {
  448. result = fmt.Sprintf("Rule %s was updated successfully.", name)
  449. }
  450. w.WriteHeader(http.StatusOK)
  451. w.Write([]byte(result))
  452. }
  453. }
  454. // get status of a rule
  455. func getStatusRuleHandler(w http.ResponseWriter, r *http.Request) {
  456. defer r.Body.Close()
  457. vars := mux.Vars(r)
  458. name := vars["name"]
  459. content, err := getRuleStatus(name)
  460. if err != nil {
  461. handleError(w, err, "get rule status error", logger)
  462. return
  463. }
  464. w.Header().Set(ContentType, ContentTypeJSON)
  465. w.WriteHeader(http.StatusOK)
  466. w.Write([]byte(content))
  467. }
  468. // start a rule
  469. func startRuleHandler(w http.ResponseWriter, r *http.Request) {
  470. defer r.Body.Close()
  471. vars := mux.Vars(r)
  472. name := vars["name"]
  473. err := startRule(name)
  474. if err != nil {
  475. handleError(w, err, "start rule error", logger)
  476. return
  477. }
  478. w.WriteHeader(http.StatusOK)
  479. w.Write([]byte(fmt.Sprintf("Rule %s was started", name)))
  480. }
  481. // stop a rule
  482. func stopRuleHandler(w http.ResponseWriter, r *http.Request) {
  483. defer r.Body.Close()
  484. vars := mux.Vars(r)
  485. name := vars["name"]
  486. result := stopRule(name)
  487. w.WriteHeader(http.StatusOK)
  488. w.Write([]byte(result))
  489. }
  490. // restart a rule
  491. func restartRuleHandler(w http.ResponseWriter, r *http.Request) {
  492. defer r.Body.Close()
  493. vars := mux.Vars(r)
  494. name := vars["name"]
  495. err := restartRule(name)
  496. if err != nil {
  497. handleError(w, err, "restart rule error", logger)
  498. return
  499. }
  500. w.WriteHeader(http.StatusOK)
  501. w.Write([]byte(fmt.Sprintf("Rule %s was restarted", name)))
  502. }
  503. // get topo of a rule
  504. func getTopoRuleHandler(w http.ResponseWriter, r *http.Request) {
  505. defer r.Body.Close()
  506. vars := mux.Vars(r)
  507. name := vars["name"]
  508. content, err := getRuleTopo(name)
  509. if err != nil {
  510. handleError(w, err, "get rule topo error", logger)
  511. return
  512. }
  513. w.Header().Set(ContentType, ContentTypeJSON)
  514. w.Write([]byte(content))
  515. }
  516. type rulesetInfo struct {
  517. Content string `json:"content"`
  518. FilePath string `json:"file"`
  519. }
  520. func importHandler(w http.ResponseWriter, r *http.Request) {
  521. rsi := &rulesetInfo{}
  522. err := json.NewDecoder(r.Body).Decode(rsi)
  523. if err != nil {
  524. handleError(w, err, "Invalid body: Error decoding json", logger)
  525. return
  526. }
  527. if rsi.Content != "" && rsi.FilePath != "" {
  528. handleError(w, errors.New("bad request"), "Invalid body: Cannot specify both content and file", logger)
  529. return
  530. } else if rsi.Content == "" && rsi.FilePath == "" {
  531. handleError(w, errors.New("bad request"), "Invalid body: must specify content or file", logger)
  532. return
  533. }
  534. content := []byte(rsi.Content)
  535. if rsi.FilePath != "" {
  536. reader, err := httpx.ReadFile(rsi.FilePath)
  537. if err != nil {
  538. handleError(w, err, "Fail to read file", logger)
  539. return
  540. }
  541. defer reader.Close()
  542. buf := new(bytes.Buffer)
  543. _, err = io.Copy(buf, reader)
  544. if err != nil {
  545. handleError(w, err, "fail to convert file", logger)
  546. return
  547. }
  548. content = buf.Bytes()
  549. }
  550. rules, counts, err := rulesetProcessor.Import(content)
  551. if err != nil {
  552. handleError(w, nil, "Import ruleset error", logger)
  553. return
  554. }
  555. infra.SafeRun(func() error {
  556. for _, name := range rules {
  557. rul, ee := ruleProcessor.GetRuleById(name)
  558. if ee != nil {
  559. logger.Error(ee)
  560. continue
  561. }
  562. reply := recoverRule(rul)
  563. if reply != "" {
  564. logger.Error(reply)
  565. }
  566. }
  567. return nil
  568. })
  569. w.Write([]byte(fmt.Sprintf("imported %d streams, %d tables and %d rules", counts[0], counts[1], counts[2])))
  570. }
  571. func exportHandler(w http.ResponseWriter, r *http.Request) {
  572. const name = "ekuiper_export.json"
  573. exported, _, err := rulesetProcessor.Export()
  574. if err != nil {
  575. handleError(w, err, "export error", logger)
  576. return
  577. }
  578. w.Header().Set("Content-Type", "application/octet-stream")
  579. w.Header().Add("Content-Disposition", "Attachment")
  580. http.ServeContent(w, r, name, time.Now(), exported)
  581. }
  582. type Configuration struct {
  583. Streams map[string]string `json:"streams"`
  584. Tables map[string]string `json:"tables"`
  585. Rules map[string]string `json:"rules"`
  586. NativePlugins map[string]string `json:"nativePlugins"`
  587. PortablePlugins map[string]string `json:"portablePlugins"`
  588. SourceConfig map[string]string `json:"sourceConfig"`
  589. SinkConfig map[string]string `json:"sinkConfig"`
  590. ConnectionConfig map[string]string `json:"connectionConfig"`
  591. Service map[string]string `json:"Service"`
  592. Schema map[string]string `json:"Schema"`
  593. }
  594. func configurationExport() ([]byte, error) {
  595. conf := &Configuration{
  596. Streams: make(map[string]string),
  597. Tables: make(map[string]string),
  598. Rules: make(map[string]string),
  599. NativePlugins: make(map[string]string),
  600. PortablePlugins: make(map[string]string),
  601. SourceConfig: make(map[string]string),
  602. SinkConfig: make(map[string]string),
  603. ConnectionConfig: make(map[string]string),
  604. Service: make(map[string]string),
  605. Schema: make(map[string]string),
  606. }
  607. ruleSet := rulesetProcessor.ExportRuleSet()
  608. if ruleSet != nil {
  609. conf.Streams = ruleSet.Streams
  610. conf.Tables = ruleSet.Tables
  611. conf.Rules = ruleSet.Rules
  612. }
  613. conf.NativePlugins = pluginExport()
  614. conf.PortablePlugins = portablePluginExport()
  615. conf.Service = serviceExport()
  616. conf.Schema = schemaExport()
  617. yamlCfg := meta.GetConfigurations()
  618. conf.SourceConfig = yamlCfg.Sources
  619. conf.SinkConfig = yamlCfg.Sinks
  620. conf.ConnectionConfig = yamlCfg.Connections
  621. return json.Marshal(conf)
  622. }
  623. func configurationExportHandler(w http.ResponseWriter, r *http.Request) {
  624. const name = "ekuiper_export.json"
  625. jsonBytes, _ := configurationExport()
  626. w.Header().Set("Content-Type", "application/octet-stream")
  627. w.Header().Add("Content-Disposition", "Attachment")
  628. http.ServeContent(w, r, name, time.Now(), bytes.NewReader(jsonBytes))
  629. }
  630. func configurationPartialExportHandler(w http.ResponseWriter, r *http.Request) {
  631. const name = "ekuiper_export.json"
  632. var rules []string
  633. _ = json.NewDecoder(r.Body).Decode(&rules)
  634. jsonBytes, _ := ruleMigrationProcessor.ConfigurationPartialExport(rules)
  635. w.Header().Set("Content-Type", "application/octet-stream")
  636. w.Header().Add("Content-Disposition", "Attachment")
  637. http.ServeContent(w, r, name, time.Now(), bytes.NewReader(jsonBytes))
  638. }
  639. func configurationReset() {
  640. _ = resetAllRules()
  641. _ = resetAllStreams()
  642. pluginReset()
  643. portablePluginsReset()
  644. serviceReset()
  645. schemaReset()
  646. meta.ResetConfigs()
  647. }
  648. func configurationImport(data []byte, reboot bool) error {
  649. conf := &Configuration{
  650. Streams: make(map[string]string),
  651. Tables: make(map[string]string),
  652. Rules: make(map[string]string),
  653. NativePlugins: make(map[string]string),
  654. PortablePlugins: make(map[string]string),
  655. SourceConfig: make(map[string]string),
  656. SinkConfig: make(map[string]string),
  657. ConnectionConfig: make(map[string]string),
  658. Service: make(map[string]string),
  659. Schema: make(map[string]string),
  660. }
  661. err := json.Unmarshal(data, conf)
  662. if err != nil {
  663. return fmt.Errorf("configuration unmarshal with error %v", err)
  664. }
  665. if reboot {
  666. err = pluginImport(conf.NativePlugins)
  667. if err != nil {
  668. return fmt.Errorf("pluginImportHandler with error %v", err)
  669. }
  670. err = schemaImport(conf.Schema)
  671. if err != nil {
  672. return fmt.Errorf("schemaImport with error %v", err)
  673. }
  674. }
  675. portablePluginImport(conf.PortablePlugins)
  676. serviceImport(conf.Service)
  677. yamlCfgSet := meta.YamlConfigurationSet{
  678. Sources: conf.SourceConfig,
  679. Sinks: conf.SinkConfig,
  680. Connections: conf.ConnectionConfig,
  681. }
  682. meta.LoadConfigurations(yamlCfgSet)
  683. ruleSet := processor.Ruleset{
  684. Streams: conf.Streams,
  685. Tables: conf.Tables,
  686. Rules: conf.Rules,
  687. }
  688. rulesetProcessor.ImportRuleSet(ruleSet)
  689. if !reboot {
  690. infra.SafeRun(func() error {
  691. for name := range ruleSet.Rules {
  692. rul, ee := ruleProcessor.GetRuleById(name)
  693. if ee != nil {
  694. logger.Error(ee)
  695. continue
  696. }
  697. reply := recoverRule(rul)
  698. if reply != "" {
  699. logger.Error(reply)
  700. }
  701. }
  702. return nil
  703. })
  704. }
  705. return nil
  706. }
  707. type configurationInfo struct {
  708. Content string `json:"content"`
  709. FilePath string `json:"file"`
  710. }
  711. func configurationImportHandler(w http.ResponseWriter, r *http.Request) {
  712. cb := r.URL.Query().Get("stop")
  713. stop := cb == "1"
  714. rsi := &configurationInfo{}
  715. err := json.NewDecoder(r.Body).Decode(rsi)
  716. if err != nil {
  717. handleError(w, err, "Invalid body: Error decoding json", logger)
  718. return
  719. }
  720. if rsi.Content != "" && rsi.FilePath != "" {
  721. handleError(w, errors.New("bad request"), "Invalid body: Cannot specify both content and file", logger)
  722. return
  723. } else if rsi.Content == "" && rsi.FilePath == "" {
  724. handleError(w, errors.New("bad request"), "Invalid body: must specify content or file", logger)
  725. return
  726. }
  727. content := []byte(rsi.Content)
  728. if rsi.FilePath != "" {
  729. reader, err := httpx.ReadFile(rsi.FilePath)
  730. if err != nil {
  731. handleError(w, err, "Fail to read file", logger)
  732. return
  733. }
  734. defer reader.Close()
  735. buf := new(bytes.Buffer)
  736. _, err = io.Copy(buf, reader)
  737. if err != nil {
  738. handleError(w, err, "fail to convert file", logger)
  739. return
  740. }
  741. content = buf.Bytes()
  742. }
  743. configurationReset()
  744. err = configurationImport(content, stop)
  745. if err != nil {
  746. handleError(w, err, "Import configuration error", logger)
  747. return
  748. }
  749. if stop {
  750. go func() {
  751. time.Sleep(1 * time.Second)
  752. os.Exit(100)
  753. }()
  754. }
  755. w.WriteHeader(http.StatusOK)
  756. }
  757. func configurationStatusExport() Configuration {
  758. conf := Configuration{
  759. Streams: make(map[string]string),
  760. Tables: make(map[string]string),
  761. Rules: make(map[string]string),
  762. NativePlugins: make(map[string]string),
  763. PortablePlugins: make(map[string]string),
  764. SourceConfig: make(map[string]string),
  765. SinkConfig: make(map[string]string),
  766. ConnectionConfig: make(map[string]string),
  767. Service: make(map[string]string),
  768. Schema: make(map[string]string),
  769. }
  770. ruleSet := rulesetProcessor.ExportRuleSetStatus()
  771. if ruleSet != nil {
  772. conf.Streams = ruleSet.Streams
  773. conf.Tables = ruleSet.Tables
  774. conf.Rules = ruleSet.Rules
  775. }
  776. conf.NativePlugins = pluginStatusExport()
  777. conf.PortablePlugins = portablePluginStatusExport()
  778. conf.Service = serviceStatusExport()
  779. conf.Schema = schemaStatusExport()
  780. yamlCfgStatus := meta.GetConfigurationStatus()
  781. conf.SourceConfig = yamlCfgStatus.Sources
  782. conf.SinkConfig = yamlCfgStatus.Sinks
  783. conf.ConnectionConfig = yamlCfgStatus.Connections
  784. return conf
  785. }
  786. func configurationStatusHandler(w http.ResponseWriter, r *http.Request) {
  787. defer r.Body.Close()
  788. content := configurationStatusExport()
  789. jsonResponse(content, w, logger)
  790. }