rest.go 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048
  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, http.MethodPost)
  128. //r.HandleFunc("/data/partial/import", configurationPartialImportHandler).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. 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. func configurationImport(data []byte, reboot bool) Configuration {
  648. conf := &Configuration{
  649. Streams: make(map[string]string),
  650. Tables: make(map[string]string),
  651. Rules: make(map[string]string),
  652. NativePlugins: make(map[string]string),
  653. PortablePlugins: make(map[string]string),
  654. SourceConfig: make(map[string]string),
  655. SinkConfig: make(map[string]string),
  656. ConnectionConfig: make(map[string]string),
  657. Service: make(map[string]string),
  658. Schema: make(map[string]string),
  659. }
  660. configResponse := Configuration{
  661. Streams: make(map[string]string),
  662. Tables: make(map[string]string),
  663. Rules: make(map[string]string),
  664. NativePlugins: make(map[string]string),
  665. PortablePlugins: make(map[string]string),
  666. SourceConfig: make(map[string]string),
  667. SinkConfig: make(map[string]string),
  668. ConnectionConfig: make(map[string]string),
  669. Service: make(map[string]string),
  670. Schema: make(map[string]string),
  671. }
  672. err := json.Unmarshal(data, conf)
  673. if err != nil {
  674. configResponse.Rules["configuration"] = fmt.Errorf("configuration unmarshal with error %v", err).Error()
  675. return configResponse
  676. }
  677. if reboot {
  678. err = pluginImport(conf.NativePlugins)
  679. if err != nil {
  680. return configResponse
  681. }
  682. err = schemaImport(conf.Schema)
  683. if err != nil {
  684. return configResponse
  685. }
  686. }
  687. configResponse.PortablePlugins = portablePluginImport(conf.PortablePlugins)
  688. configResponse.Service = serviceImport(conf.Service)
  689. yamlCfgSet := meta.YamlConfigurationSet{
  690. Sources: conf.SourceConfig,
  691. Sinks: conf.SinkConfig,
  692. Connections: conf.ConnectionConfig,
  693. }
  694. confRsp := meta.LoadConfigurations(yamlCfgSet)
  695. configResponse.SourceConfig = confRsp.Sources
  696. configResponse.SinkConfig = confRsp.Sinks
  697. configResponse.ConnectionConfig = confRsp.Connections
  698. ruleSet := processor.Ruleset{
  699. Streams: conf.Streams,
  700. Tables: conf.Tables,
  701. Rules: conf.Rules,
  702. }
  703. result := rulesetProcessor.ImportRuleSet(ruleSet)
  704. configResponse.Streams = result.Streams
  705. configResponse.Tables = result.Tables
  706. configResponse.Rules = result.Rules
  707. if !reboot {
  708. infra.SafeRun(func() error {
  709. for name := range ruleSet.Rules {
  710. rul, ee := ruleProcessor.GetRuleById(name)
  711. if ee != nil {
  712. logger.Error(ee)
  713. continue
  714. }
  715. reply := recoverRule(rul)
  716. if reply != "" {
  717. logger.Error(reply)
  718. }
  719. }
  720. return nil
  721. })
  722. }
  723. return configResponse
  724. }
  725. func configurationPartialImport(data []byte) Configuration {
  726. conf := &Configuration{
  727. Streams: make(map[string]string),
  728. Tables: make(map[string]string),
  729. Rules: make(map[string]string),
  730. NativePlugins: make(map[string]string),
  731. PortablePlugins: make(map[string]string),
  732. SourceConfig: make(map[string]string),
  733. SinkConfig: make(map[string]string),
  734. ConnectionConfig: make(map[string]string),
  735. Service: make(map[string]string),
  736. Schema: make(map[string]string),
  737. }
  738. configResponse := Configuration{
  739. Streams: make(map[string]string),
  740. Tables: make(map[string]string),
  741. Rules: make(map[string]string),
  742. NativePlugins: make(map[string]string),
  743. PortablePlugins: make(map[string]string),
  744. SourceConfig: make(map[string]string),
  745. SinkConfig: make(map[string]string),
  746. ConnectionConfig: make(map[string]string),
  747. Service: make(map[string]string),
  748. Schema: make(map[string]string),
  749. }
  750. err := json.Unmarshal(data, conf)
  751. if err != nil {
  752. configResponse.Rules["configuration"] = fmt.Errorf("configuration unmarshal with error %v", err).Error()
  753. return configResponse
  754. }
  755. yamlCfgSet := meta.YamlConfigurationSet{
  756. Sources: conf.SourceConfig,
  757. Sinks: conf.SinkConfig,
  758. Connections: conf.ConnectionConfig,
  759. }
  760. confRsp := meta.LoadConfigurationsPartial(yamlCfgSet)
  761. configResponse.NativePlugins = pluginPartialImport(conf.NativePlugins)
  762. configResponse.Schema = schemaPartialImport(conf.Schema)
  763. configResponse.PortablePlugins = portablePluginPartialImport(conf.PortablePlugins)
  764. configResponse.Service = servicePartialImport(conf.Service)
  765. configResponse.SourceConfig = confRsp.Sources
  766. configResponse.SinkConfig = confRsp.Sinks
  767. configResponse.ConnectionConfig = confRsp.Connections
  768. ruleSet := processor.Ruleset{
  769. Streams: conf.Streams,
  770. Tables: conf.Tables,
  771. Rules: conf.Rules,
  772. }
  773. result := importRuleSetPartial(ruleSet)
  774. configResponse.Streams = result.Streams
  775. configResponse.Tables = result.Tables
  776. configResponse.Rules = result.Rules
  777. return configResponse
  778. }
  779. type configurationInfo struct {
  780. Content string `json:"content"`
  781. FilePath string `json:"file"`
  782. }
  783. func configurationImportHandler(w http.ResponseWriter, r *http.Request) {
  784. cb := r.URL.Query().Get("stop")
  785. stop := cb == "1"
  786. par := r.URL.Query().Get("partial")
  787. partial := par == "1"
  788. rsi := &configurationInfo{}
  789. err := json.NewDecoder(r.Body).Decode(rsi)
  790. if err != nil {
  791. handleError(w, err, "Invalid body: Error decoding json", logger)
  792. return
  793. }
  794. if rsi.Content != "" && rsi.FilePath != "" {
  795. handleError(w, errors.New("bad request"), "Invalid body: Cannot specify both content and file", logger)
  796. return
  797. } else if rsi.Content == "" && rsi.FilePath == "" {
  798. handleError(w, errors.New("bad request"), "Invalid body: must specify content or file", logger)
  799. return
  800. }
  801. content := []byte(rsi.Content)
  802. if rsi.FilePath != "" {
  803. reader, err := httpx.ReadFile(rsi.FilePath)
  804. if err != nil {
  805. handleError(w, err, "Fail to read file", logger)
  806. return
  807. }
  808. defer reader.Close()
  809. buf := new(bytes.Buffer)
  810. _, err = io.Copy(buf, reader)
  811. if err != nil {
  812. handleError(w, err, "fail to convert file", logger)
  813. return
  814. }
  815. content = buf.Bytes()
  816. }
  817. if !partial {
  818. configurationReset()
  819. result := configurationImport(content, stop)
  820. jsonResponse(result, w, logger)
  821. if stop {
  822. go func() {
  823. time.Sleep(1 * time.Second)
  824. os.Exit(100)
  825. }()
  826. }
  827. } else {
  828. result := configurationPartialImport(content)
  829. jsonResponse(result, w, logger)
  830. }
  831. w.WriteHeader(http.StatusOK)
  832. }
  833. //func configurationPartialImportHandler(w http.ResponseWriter, r *http.Request) {
  834. // rsi := &configurationInfo{}
  835. // err := json.NewDecoder(r.Body).Decode(rsi)
  836. // if err != nil {
  837. // handleError(w, err, "Invalid body: Error decoding json", logger)
  838. // return
  839. // }
  840. // if rsi.Content != "" && rsi.FilePath != "" {
  841. // handleError(w, errors.New("bad request"), "Invalid body: Cannot specify both content and file", logger)
  842. // return
  843. // } else if rsi.Content == "" && rsi.FilePath == "" {
  844. // handleError(w, errors.New("bad request"), "Invalid body: must specify content or file", logger)
  845. // return
  846. // }
  847. // content := []byte(rsi.Content)
  848. // if rsi.FilePath != "" {
  849. // reader, err := httpx.ReadFile(rsi.FilePath)
  850. // if err != nil {
  851. // handleError(w, err, "Fail to read file", logger)
  852. // return
  853. // }
  854. // defer reader.Close()
  855. // buf := new(bytes.Buffer)
  856. // _, err = io.Copy(buf, reader)
  857. // if err != nil {
  858. // handleError(w, err, "fail to convert file", logger)
  859. // return
  860. // }
  861. // content = buf.Bytes()
  862. // }
  863. // result := configurationPartialImport(content)
  864. //
  865. // jsonResponse(result, w, logger)
  866. //}
  867. func configurationStatusExport() Configuration {
  868. conf := Configuration{
  869. Streams: make(map[string]string),
  870. Tables: make(map[string]string),
  871. Rules: make(map[string]string),
  872. NativePlugins: make(map[string]string),
  873. PortablePlugins: make(map[string]string),
  874. SourceConfig: make(map[string]string),
  875. SinkConfig: make(map[string]string),
  876. ConnectionConfig: make(map[string]string),
  877. Service: make(map[string]string),
  878. Schema: make(map[string]string),
  879. }
  880. ruleSet := rulesetProcessor.ExportRuleSetStatus()
  881. if ruleSet != nil {
  882. conf.Streams = ruleSet.Streams
  883. conf.Tables = ruleSet.Tables
  884. conf.Rules = ruleSet.Rules
  885. }
  886. conf.NativePlugins = pluginStatusExport()
  887. conf.PortablePlugins = portablePluginStatusExport()
  888. conf.Service = serviceStatusExport()
  889. conf.Schema = schemaStatusExport()
  890. yamlCfgStatus := meta.GetConfigurationStatus()
  891. conf.SourceConfig = yamlCfgStatus.Sources
  892. conf.SinkConfig = yamlCfgStatus.Sinks
  893. conf.ConnectionConfig = yamlCfgStatus.Connections
  894. return conf
  895. }
  896. func configurationStatusHandler(w http.ResponseWriter, r *http.Request) {
  897. defer r.Body.Close()
  898. content := configurationStatusExport()
  899. jsonResponse(content, w, logger)
  900. }
  901. func importRuleSetPartial(all processor.Ruleset) processor.Ruleset {
  902. ruleSetRsp := processor.Ruleset{
  903. Rules: map[string]string{},
  904. Streams: map[string]string{},
  905. Tables: map[string]string{},
  906. }
  907. //replace streams
  908. for k, v := range all.Streams {
  909. _, e := streamProcessor.ExecReplaceStream(k, v, ast.TypeStream)
  910. if e != nil {
  911. ruleSetRsp.Streams[k] = e.Error()
  912. continue
  913. }
  914. }
  915. // replace tables
  916. for k, v := range all.Tables {
  917. _, e := streamProcessor.ExecReplaceStream(k, v, ast.TypeTable)
  918. if e != nil {
  919. ruleSetRsp.Tables[k] = e.Error()
  920. continue
  921. }
  922. }
  923. for k, v := range all.Rules {
  924. _, err := ruleProcessor.GetRuleJson(k)
  925. if err == nil {
  926. // the rule already exist, update
  927. err = updateRule(k, v)
  928. if err != nil {
  929. ruleSetRsp.Rules[k] = err.Error()
  930. continue
  931. }
  932. // Update to db after validation
  933. _, err = ruleProcessor.ExecUpdate(k, v)
  934. if err != nil {
  935. ruleSetRsp.Rules[k] = err.Error()
  936. continue
  937. }
  938. } else {
  939. // not found, create
  940. _, err2 := createRule(k, v)
  941. if err2 != nil {
  942. ruleSetRsp.Rules[k] = err2.Error()
  943. continue
  944. }
  945. }
  946. }
  947. return ruleSetRsp
  948. }