rest.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074
  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. "reflect"
  29. "runtime"
  30. "strconv"
  31. "strings"
  32. "time"
  33. "github.com/gorilla/handlers"
  34. "github.com/gorilla/mux"
  35. "github.com/lf-edge/ekuiper/internal/server/middleware"
  36. "github.com/lf-edge/ekuiper/pkg/api"
  37. "github.com/lf-edge/ekuiper/pkg/ast"
  38. "github.com/lf-edge/ekuiper/pkg/errorx"
  39. "github.com/lf-edge/ekuiper/pkg/infra"
  40. )
  41. const (
  42. ContentType = "Content-Type"
  43. ContentTypeJSON = "application/json"
  44. )
  45. var uploadDir string
  46. type statementDescriptor struct {
  47. Sql string `json:"sql,omitempty"`
  48. }
  49. func decodeStatementDescriptor(reader io.ReadCloser) (statementDescriptor, error) {
  50. sd := statementDescriptor{}
  51. err := json.NewDecoder(reader).Decode(&sd)
  52. // Problems decoding
  53. if err != nil {
  54. return sd, fmt.Errorf("Error decoding the statement descriptor: %v", err)
  55. }
  56. return sd, nil
  57. }
  58. // Handle applies the specified error and error concept to the HTTP response writer
  59. func handleError(w http.ResponseWriter, err error, prefix string, logger api.Logger) {
  60. message := prefix
  61. if message != "" {
  62. message += ": "
  63. }
  64. message += err.Error()
  65. logger.Error(message)
  66. var ec int
  67. switch e := err.(type) {
  68. case *errorx.Error:
  69. switch e.Code() {
  70. case errorx.NOT_FOUND:
  71. ec = http.StatusNotFound
  72. default:
  73. ec = http.StatusBadRequest
  74. }
  75. default:
  76. ec = http.StatusBadRequest
  77. }
  78. http.Error(w, message, ec)
  79. }
  80. func jsonResponse(i interface{}, w http.ResponseWriter, logger api.Logger) {
  81. w.Header().Add(ContentType, ContentTypeJSON)
  82. jsonByte, err := json.Marshal(i)
  83. if err != nil {
  84. handleError(w, err, "", logger)
  85. }
  86. w.Header().Add("Content-Length", strconv.Itoa(len(jsonByte)))
  87. _, err = w.Write(jsonByte)
  88. // Problems encoding
  89. if err != nil {
  90. handleError(w, err, "", logger)
  91. }
  92. }
  93. func jsonByteResponse(buffer bytes.Buffer, w http.ResponseWriter, logger api.Logger) {
  94. w.Header().Add(ContentType, ContentTypeJSON)
  95. w.Header().Add("Content-Length", strconv.Itoa(buffer.Len()))
  96. _, err := w.Write(buffer.Bytes())
  97. // Problems encoding
  98. if err != nil {
  99. handleError(w, err, "", logger)
  100. }
  101. }
  102. func createRestServer(ip string, port int, needToken bool) *http.Server {
  103. dataDir, err := conf.GetDataLoc()
  104. if err != nil {
  105. panic(err)
  106. }
  107. uploadDir = filepath.Join(dataDir, "uploads")
  108. r := mux.NewRouter()
  109. r.HandleFunc("/", rootHandler).Methods(http.MethodGet, http.MethodPost)
  110. r.HandleFunc("/ping", pingHandler).Methods(http.MethodGet)
  111. r.HandleFunc("/streams", streamsHandler).Methods(http.MethodGet, http.MethodPost)
  112. r.HandleFunc("/streams/{name}", streamHandler).Methods(http.MethodGet, http.MethodDelete, http.MethodPut)
  113. r.HandleFunc("/streams/{name}/schema", streamSchemaHandler).Methods(http.MethodGet)
  114. r.HandleFunc("/tables", tablesHandler).Methods(http.MethodGet, http.MethodPost)
  115. r.HandleFunc("/tables/{name}", tableHandler).Methods(http.MethodGet, http.MethodDelete, http.MethodPut)
  116. r.HandleFunc("/tables/{name}/schema", tableSchemaHandler).Methods(http.MethodGet)
  117. r.HandleFunc("/rules", rulesHandler).Methods(http.MethodGet, http.MethodPost)
  118. r.HandleFunc("/rules/{name}", ruleHandler).Methods(http.MethodDelete, http.MethodGet, http.MethodPut)
  119. r.HandleFunc("/rules/{name}/status", getStatusRuleHandler).Methods(http.MethodGet)
  120. r.HandleFunc("/rules/{name}/start", startRuleHandler).Methods(http.MethodPost)
  121. r.HandleFunc("/rules/{name}/stop", stopRuleHandler).Methods(http.MethodPost)
  122. r.HandleFunc("/rules/{name}/restart", restartRuleHandler).Methods(http.MethodPost)
  123. r.HandleFunc("/rules/{name}/topo", getTopoRuleHandler).Methods(http.MethodGet)
  124. r.HandleFunc("/ruleset/export", exportHandler).Methods(http.MethodPost)
  125. r.HandleFunc("/ruleset/import", importHandler).Methods(http.MethodPost)
  126. r.HandleFunc("/config/uploads", fileUploadHandler).Methods(http.MethodPost, http.MethodGet)
  127. r.HandleFunc("/config/uploads/{name}", fileDeleteHandler).Methods(http.MethodDelete)
  128. r.HandleFunc("/data/export", configurationExportHandler).Methods(http.MethodGet, 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. var jsonBytes []byte
  625. const name = "ekuiper_export.json"
  626. switch r.Method {
  627. case http.MethodGet:
  628. jsonBytes, _ = configurationExport()
  629. case http.MethodPost:
  630. var rules []string
  631. _ = json.NewDecoder(r.Body).Decode(&rules)
  632. jsonBytes, _ = ruleMigrationProcessor.ConfigurationPartialExport(rules)
  633. }
  634. w.Header().Set("Content-Type", "application/octet-stream")
  635. w.Header().Add("Content-Disposition", "Attachment")
  636. http.ServeContent(w, r, name, time.Now(), bytes.NewReader(jsonBytes))
  637. }
  638. func configurationReset() {
  639. _ = resetAllRules()
  640. _ = resetAllStreams()
  641. pluginReset()
  642. portablePluginsReset()
  643. serviceReset()
  644. schemaReset()
  645. meta.ResetConfigs()
  646. }
  647. type ImportConfigurationStatus struct {
  648. ErrorMsg string
  649. ConfigResponse Configuration
  650. }
  651. func configurationImport(data []byte, reboot bool) ImportConfigurationStatus {
  652. conf := &Configuration{
  653. Streams: make(map[string]string),
  654. Tables: make(map[string]string),
  655. Rules: make(map[string]string),
  656. NativePlugins: make(map[string]string),
  657. PortablePlugins: make(map[string]string),
  658. SourceConfig: make(map[string]string),
  659. SinkConfig: make(map[string]string),
  660. ConnectionConfig: make(map[string]string),
  661. Service: make(map[string]string),
  662. Schema: make(map[string]string),
  663. }
  664. importStatus := ImportConfigurationStatus{}
  665. configResponse := Configuration{
  666. Streams: make(map[string]string),
  667. Tables: make(map[string]string),
  668. Rules: make(map[string]string),
  669. NativePlugins: make(map[string]string),
  670. PortablePlugins: make(map[string]string),
  671. SourceConfig: make(map[string]string),
  672. SinkConfig: make(map[string]string),
  673. ConnectionConfig: make(map[string]string),
  674. Service: make(map[string]string),
  675. Schema: make(map[string]string),
  676. }
  677. ResponseNil := Configuration{
  678. Streams: make(map[string]string),
  679. Tables: make(map[string]string),
  680. Rules: make(map[string]string),
  681. NativePlugins: make(map[string]string),
  682. PortablePlugins: make(map[string]string),
  683. SourceConfig: make(map[string]string),
  684. SinkConfig: make(map[string]string),
  685. ConnectionConfig: make(map[string]string),
  686. Service: make(map[string]string),
  687. Schema: make(map[string]string),
  688. }
  689. err := json.Unmarshal(data, conf)
  690. if err != nil {
  691. importStatus.ErrorMsg = fmt.Errorf("configuration unmarshal with error %v", err).Error()
  692. return importStatus
  693. }
  694. if reboot {
  695. err = pluginImport(conf.NativePlugins)
  696. if err != nil {
  697. importStatus.ErrorMsg = fmt.Errorf("pluginImport NativePlugins import error %v", err).Error()
  698. return importStatus
  699. }
  700. err = schemaImport(conf.Schema)
  701. if err != nil {
  702. importStatus.ErrorMsg = fmt.Errorf("schemaImport Schema import error %v", err).Error()
  703. return importStatus
  704. }
  705. }
  706. configResponse.PortablePlugins = portablePluginImport(conf.PortablePlugins)
  707. configResponse.Service = serviceImport(conf.Service)
  708. yamlCfgSet := meta.YamlConfigurationSet{
  709. Sources: conf.SourceConfig,
  710. Sinks: conf.SinkConfig,
  711. Connections: conf.ConnectionConfig,
  712. }
  713. confRsp := meta.LoadConfigurations(yamlCfgSet)
  714. configResponse.SourceConfig = confRsp.Sources
  715. configResponse.SinkConfig = confRsp.Sinks
  716. configResponse.ConnectionConfig = confRsp.Connections
  717. ruleSet := processor.Ruleset{
  718. Streams: conf.Streams,
  719. Tables: conf.Tables,
  720. Rules: conf.Rules,
  721. }
  722. result := rulesetProcessor.ImportRuleSet(ruleSet)
  723. configResponse.Streams = result.Streams
  724. configResponse.Tables = result.Tables
  725. configResponse.Rules = result.Rules
  726. if !reboot {
  727. infra.SafeRun(func() error {
  728. for name := range ruleSet.Rules {
  729. rul, ee := ruleProcessor.GetRuleById(name)
  730. if ee != nil {
  731. logger.Error(ee)
  732. continue
  733. }
  734. reply := recoverRule(rul)
  735. if reply != "" {
  736. logger.Error(reply)
  737. }
  738. }
  739. return nil
  740. })
  741. }
  742. if reflect.DeepEqual(ResponseNil, configResponse) {
  743. importStatus.ConfigResponse = ResponseNil
  744. } else {
  745. importStatus.ErrorMsg = "process error"
  746. importStatus.ConfigResponse = configResponse
  747. }
  748. return importStatus
  749. }
  750. func configurationPartialImport(data []byte) ImportConfigurationStatus {
  751. conf := &Configuration{
  752. Streams: make(map[string]string),
  753. Tables: make(map[string]string),
  754. Rules: make(map[string]string),
  755. NativePlugins: make(map[string]string),
  756. PortablePlugins: make(map[string]string),
  757. SourceConfig: make(map[string]string),
  758. SinkConfig: make(map[string]string),
  759. ConnectionConfig: make(map[string]string),
  760. Service: make(map[string]string),
  761. Schema: make(map[string]string),
  762. }
  763. importStatus := ImportConfigurationStatus{}
  764. configResponse := Configuration{
  765. Streams: make(map[string]string),
  766. Tables: make(map[string]string),
  767. Rules: make(map[string]string),
  768. NativePlugins: make(map[string]string),
  769. PortablePlugins: make(map[string]string),
  770. SourceConfig: make(map[string]string),
  771. SinkConfig: make(map[string]string),
  772. ConnectionConfig: make(map[string]string),
  773. Service: make(map[string]string),
  774. Schema: make(map[string]string),
  775. }
  776. ResponseNil := Configuration{
  777. Streams: make(map[string]string),
  778. Tables: make(map[string]string),
  779. Rules: make(map[string]string),
  780. NativePlugins: make(map[string]string),
  781. PortablePlugins: make(map[string]string),
  782. SourceConfig: make(map[string]string),
  783. SinkConfig: make(map[string]string),
  784. ConnectionConfig: make(map[string]string),
  785. Service: make(map[string]string),
  786. Schema: make(map[string]string),
  787. }
  788. err := json.Unmarshal(data, conf)
  789. if err != nil {
  790. importStatus.ErrorMsg = fmt.Errorf("configuration unmarshal with error %v", err).Error()
  791. return importStatus
  792. }
  793. yamlCfgSet := meta.YamlConfigurationSet{
  794. Sources: conf.SourceConfig,
  795. Sinks: conf.SinkConfig,
  796. Connections: conf.ConnectionConfig,
  797. }
  798. confRsp := meta.LoadConfigurationsPartial(yamlCfgSet)
  799. configResponse.NativePlugins = pluginPartialImport(conf.NativePlugins)
  800. configResponse.Schema = schemaPartialImport(conf.Schema)
  801. configResponse.PortablePlugins = portablePluginPartialImport(conf.PortablePlugins)
  802. configResponse.Service = servicePartialImport(conf.Service)
  803. configResponse.SourceConfig = confRsp.Sources
  804. configResponse.SinkConfig = confRsp.Sinks
  805. configResponse.ConnectionConfig = confRsp.Connections
  806. ruleSet := processor.Ruleset{
  807. Streams: conf.Streams,
  808. Tables: conf.Tables,
  809. Rules: conf.Rules,
  810. }
  811. result := importRuleSetPartial(ruleSet)
  812. configResponse.Streams = result.Streams
  813. configResponse.Tables = result.Tables
  814. configResponse.Rules = result.Rules
  815. if reflect.DeepEqual(ResponseNil, configResponse) {
  816. importStatus.ConfigResponse = ResponseNil
  817. } else {
  818. importStatus.ErrorMsg = "process error"
  819. importStatus.ConfigResponse = configResponse
  820. }
  821. return importStatus
  822. }
  823. type configurationInfo struct {
  824. Content string `json:"content"`
  825. FilePath string `json:"file"`
  826. }
  827. func configurationImportHandler(w http.ResponseWriter, r *http.Request) {
  828. cb := r.URL.Query().Get("stop")
  829. stop := cb == "1"
  830. par := r.URL.Query().Get("partial")
  831. partial := par == "1"
  832. rsi := &configurationInfo{}
  833. err := json.NewDecoder(r.Body).Decode(rsi)
  834. if err != nil {
  835. handleError(w, err, "Invalid body: Error decoding json", logger)
  836. return
  837. }
  838. if rsi.Content != "" && rsi.FilePath != "" {
  839. handleError(w, errors.New("bad request"), "Invalid body: Cannot specify both content and file", logger)
  840. return
  841. } else if rsi.Content == "" && rsi.FilePath == "" {
  842. handleError(w, errors.New("bad request"), "Invalid body: must specify content or file", logger)
  843. return
  844. }
  845. content := []byte(rsi.Content)
  846. if rsi.FilePath != "" {
  847. reader, err := httpx.ReadFile(rsi.FilePath)
  848. if err != nil {
  849. handleError(w, err, "Fail to read file", logger)
  850. return
  851. }
  852. defer reader.Close()
  853. buf := new(bytes.Buffer)
  854. _, err = io.Copy(buf, reader)
  855. if err != nil {
  856. handleError(w, err, "fail to convert file", logger)
  857. return
  858. }
  859. content = buf.Bytes()
  860. }
  861. if !partial {
  862. configurationReset()
  863. result := configurationImport(content, stop)
  864. if result.ErrorMsg != "" {
  865. w.WriteHeader(http.StatusBadRequest)
  866. jsonResponse(result, w, logger)
  867. } else {
  868. w.WriteHeader(http.StatusOK)
  869. jsonResponse(result, w, logger)
  870. }
  871. if stop {
  872. go func() {
  873. time.Sleep(1 * time.Second)
  874. os.Exit(100)
  875. }()
  876. }
  877. } else {
  878. result := configurationPartialImport(content)
  879. if result.ErrorMsg != "" {
  880. w.WriteHeader(http.StatusBadRequest)
  881. jsonResponse(result, w, logger)
  882. } else {
  883. w.WriteHeader(http.StatusOK)
  884. jsonResponse(result, w, logger)
  885. }
  886. }
  887. }
  888. func configurationStatusExport() Configuration {
  889. conf := Configuration{
  890. Streams: make(map[string]string),
  891. Tables: make(map[string]string),
  892. Rules: make(map[string]string),
  893. NativePlugins: make(map[string]string),
  894. PortablePlugins: make(map[string]string),
  895. SourceConfig: make(map[string]string),
  896. SinkConfig: make(map[string]string),
  897. ConnectionConfig: make(map[string]string),
  898. Service: make(map[string]string),
  899. Schema: make(map[string]string),
  900. }
  901. ruleSet := rulesetProcessor.ExportRuleSetStatus()
  902. if ruleSet != nil {
  903. conf.Streams = ruleSet.Streams
  904. conf.Tables = ruleSet.Tables
  905. conf.Rules = ruleSet.Rules
  906. }
  907. conf.NativePlugins = pluginStatusExport()
  908. conf.PortablePlugins = portablePluginStatusExport()
  909. conf.Service = serviceStatusExport()
  910. conf.Schema = schemaStatusExport()
  911. yamlCfgStatus := meta.GetConfigurationStatus()
  912. conf.SourceConfig = yamlCfgStatus.Sources
  913. conf.SinkConfig = yamlCfgStatus.Sinks
  914. conf.ConnectionConfig = yamlCfgStatus.Connections
  915. return conf
  916. }
  917. func configurationStatusHandler(w http.ResponseWriter, r *http.Request) {
  918. defer r.Body.Close()
  919. content := configurationStatusExport()
  920. jsonResponse(content, w, logger)
  921. }
  922. func importRuleSetPartial(all processor.Ruleset) processor.Ruleset {
  923. ruleSetRsp := processor.Ruleset{
  924. Rules: map[string]string{},
  925. Streams: map[string]string{},
  926. Tables: map[string]string{},
  927. }
  928. //replace streams
  929. for k, v := range all.Streams {
  930. _, e := streamProcessor.ExecReplaceStream(k, v, ast.TypeStream)
  931. if e != nil {
  932. ruleSetRsp.Streams[k] = e.Error()
  933. continue
  934. }
  935. }
  936. // replace tables
  937. for k, v := range all.Tables {
  938. _, e := streamProcessor.ExecReplaceStream(k, v, ast.TypeTable)
  939. if e != nil {
  940. ruleSetRsp.Tables[k] = e.Error()
  941. continue
  942. }
  943. }
  944. for k, v := range all.Rules {
  945. _, err := ruleProcessor.GetRuleJson(k)
  946. if err == nil {
  947. // the rule already exist, update
  948. err = updateRule(k, v)
  949. if err != nil {
  950. ruleSetRsp.Rules[k] = err.Error()
  951. continue
  952. }
  953. // Update to db after validation
  954. _, err = ruleProcessor.ExecUpdate(k, v)
  955. if err != nil {
  956. ruleSetRsp.Rules[k] = err.Error()
  957. continue
  958. }
  959. } else {
  960. // not found, create
  961. _, err2 := createRule(k, v)
  962. if err2 != nil {
  963. ruleSetRsp.Rules[k] = err2.Error()
  964. continue
  965. }
  966. }
  967. }
  968. return ruleSetRsp
  969. }