rest.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. // Copyright 2021-2022 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package server
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "github.com/gorilla/handlers"
  19. "github.com/gorilla/mux"
  20. "github.com/lf-edge/ekuiper/internal/server/middleware"
  21. "github.com/lf-edge/ekuiper/pkg/api"
  22. "github.com/lf-edge/ekuiper/pkg/ast"
  23. "github.com/lf-edge/ekuiper/pkg/errorx"
  24. "github.com/lf-edge/ekuiper/pkg/infra"
  25. "io"
  26. "io/ioutil"
  27. "net/http"
  28. "runtime"
  29. "strings"
  30. "time"
  31. )
  32. const (
  33. ContentType = "Content-Type"
  34. ContentTypeJSON = "application/json"
  35. )
  36. type statementDescriptor struct {
  37. Sql string `json:"sql,omitempty"`
  38. }
  39. func decodeStatementDescriptor(reader io.ReadCloser) (statementDescriptor, error) {
  40. sd := statementDescriptor{}
  41. err := json.NewDecoder(reader).Decode(&sd)
  42. // Problems decoding
  43. if err != nil {
  44. return sd, fmt.Errorf("Error decoding the statement descriptor: %v", err)
  45. }
  46. return sd, nil
  47. }
  48. // Handle applies the specified error and error concept tot he HTTP response writer
  49. func handleError(w http.ResponseWriter, err error, prefix string, logger api.Logger) {
  50. message := prefix
  51. if message != "" {
  52. message += ": "
  53. }
  54. message += err.Error()
  55. logger.Error(message)
  56. var ec int
  57. switch e := err.(type) {
  58. case *errorx.Error:
  59. switch e.Code() {
  60. case errorx.NOT_FOUND:
  61. ec = http.StatusNotFound
  62. default:
  63. ec = http.StatusBadRequest
  64. }
  65. default:
  66. ec = http.StatusBadRequest
  67. }
  68. http.Error(w, message, ec)
  69. }
  70. func jsonResponse(i interface{}, w http.ResponseWriter, logger api.Logger) {
  71. w.Header().Add(ContentType, ContentTypeJSON)
  72. enc := json.NewEncoder(w)
  73. err := enc.Encode(i)
  74. // Problems encoding
  75. if err != nil {
  76. handleError(w, err, "", logger)
  77. }
  78. }
  79. func createRestServer(ip string, port int, needToken bool) *http.Server {
  80. r := mux.NewRouter()
  81. r.HandleFunc("/", rootHandler).Methods(http.MethodGet, http.MethodPost)
  82. r.HandleFunc("/ping", pingHandler).Methods(http.MethodGet)
  83. r.HandleFunc("/streams", streamsHandler).Methods(http.MethodGet, http.MethodPost)
  84. r.HandleFunc("/streams/{name}", streamHandler).Methods(http.MethodGet, http.MethodDelete, http.MethodPut)
  85. r.HandleFunc("/tables", tablesHandler).Methods(http.MethodGet, http.MethodPost)
  86. r.HandleFunc("/tables/{name}", tableHandler).Methods(http.MethodGet, http.MethodDelete, http.MethodPut)
  87. r.HandleFunc("/rules", rulesHandler).Methods(http.MethodGet, http.MethodPost)
  88. r.HandleFunc("/rules/{name}", ruleHandler).Methods(http.MethodDelete, http.MethodGet, http.MethodPut)
  89. r.HandleFunc("/rules/{name}/status", getStatusRuleHandler).Methods(http.MethodGet)
  90. r.HandleFunc("/rules/{name}/start", startRuleHandler).Methods(http.MethodPost)
  91. r.HandleFunc("/rules/{name}/stop", stopRuleHandler).Methods(http.MethodPost)
  92. r.HandleFunc("/rules/{name}/restart", restartRuleHandler).Methods(http.MethodPost)
  93. r.HandleFunc("/rules/{name}/topo", getTopoRuleHandler).Methods(http.MethodGet)
  94. // Register extended routes
  95. for k, v := range components {
  96. logger.Infof("register rest endpoint for component %s", k)
  97. v.rest(r)
  98. }
  99. if needToken {
  100. r.Use(middleware.Auth)
  101. }
  102. server := &http.Server{
  103. Addr: fmt.Sprintf("%s:%d", ip, port),
  104. // Good practice to set timeouts to avoid Slowloris attacks.
  105. WriteTimeout: time.Second * 60 * 5,
  106. ReadTimeout: time.Second * 60 * 5,
  107. IdleTimeout: time.Second * 60,
  108. Handler: handlers.CORS(handlers.AllowedHeaders([]string{"Accept", "Accept-Language", "Content-Type", "Content-Language", "Origin", "Authorization"}), handlers.AllowedMethods([]string{"POST", "GET", "PUT", "DELETE", "HEAD"}))(r),
  109. }
  110. server.SetKeepAlivesEnabled(false)
  111. return server
  112. }
  113. type information struct {
  114. Version string `json:"version"`
  115. Os string `json:"os"`
  116. Arch string `json:"arch"`
  117. UpTimeSeconds int64 `json:"upTimeSeconds"`
  118. }
  119. //The handler for root
  120. func rootHandler(w http.ResponseWriter, r *http.Request) {
  121. defer r.Body.Close()
  122. switch r.Method {
  123. case http.MethodGet, http.MethodPost:
  124. w.WriteHeader(http.StatusOK)
  125. info := new(information)
  126. info.Version = version
  127. info.UpTimeSeconds = time.Now().Unix() - startTimeStamp
  128. info.Os = runtime.GOOS
  129. info.Arch = runtime.GOARCH
  130. byteInfo, _ := json.Marshal(info)
  131. w.Write(byteInfo)
  132. }
  133. }
  134. func pingHandler(w http.ResponseWriter, _ *http.Request) {
  135. w.WriteHeader(http.StatusOK)
  136. }
  137. func sourcesManageHandler(w http.ResponseWriter, r *http.Request, st ast.StreamType) {
  138. defer r.Body.Close()
  139. switch r.Method {
  140. case http.MethodGet:
  141. content, err := streamProcessor.ShowStream(st)
  142. if err != nil {
  143. handleError(w, err, fmt.Sprintf("%s command error", strings.Title(ast.StreamTypeMap[st])), logger)
  144. return
  145. }
  146. jsonResponse(content, w, logger)
  147. case http.MethodPost:
  148. v, err := decodeStatementDescriptor(r.Body)
  149. if err != nil {
  150. handleError(w, err, "Invalid body", logger)
  151. return
  152. }
  153. content, err := streamProcessor.ExecStreamSql(v.Sql)
  154. if err != nil {
  155. handleError(w, err, fmt.Sprintf("%s command error", strings.Title(ast.StreamTypeMap[st])), logger)
  156. return
  157. }
  158. w.WriteHeader(http.StatusCreated)
  159. w.Write([]byte(content))
  160. }
  161. }
  162. func sourceManageHandler(w http.ResponseWriter, r *http.Request, st ast.StreamType) {
  163. defer r.Body.Close()
  164. vars := mux.Vars(r)
  165. name := vars["name"]
  166. switch r.Method {
  167. case http.MethodGet:
  168. content, err := streamProcessor.DescStream(name, st)
  169. if err != nil {
  170. handleError(w, err, fmt.Sprintf("describe %s error", ast.StreamTypeMap[st]), logger)
  171. return
  172. }
  173. jsonResponse(content, w, logger)
  174. case http.MethodDelete:
  175. content, err := streamProcessor.DropStream(name, st)
  176. if err != nil {
  177. handleError(w, err, fmt.Sprintf("delete %s error", ast.StreamTypeMap[st]), logger)
  178. return
  179. }
  180. w.WriteHeader(http.StatusOK)
  181. w.Write([]byte(content))
  182. case http.MethodPut:
  183. v, err := decodeStatementDescriptor(r.Body)
  184. if err != nil {
  185. handleError(w, err, "Invalid body", logger)
  186. return
  187. }
  188. content, err := streamProcessor.ExecReplaceStream(name, v.Sql, st)
  189. if err != nil {
  190. handleError(w, err, fmt.Sprintf("%s command error", strings.Title(ast.StreamTypeMap[st])), logger)
  191. return
  192. }
  193. w.WriteHeader(http.StatusOK)
  194. w.Write([]byte(content))
  195. }
  196. }
  197. //list or create streams
  198. func streamsHandler(w http.ResponseWriter, r *http.Request) {
  199. sourcesManageHandler(w, r, ast.TypeStream)
  200. }
  201. //describe or delete a stream
  202. func streamHandler(w http.ResponseWriter, r *http.Request) {
  203. sourceManageHandler(w, r, ast.TypeStream)
  204. }
  205. //list or create tables
  206. func tablesHandler(w http.ResponseWriter, r *http.Request) {
  207. sourcesManageHandler(w, r, ast.TypeTable)
  208. }
  209. func tableHandler(w http.ResponseWriter, r *http.Request) {
  210. sourceManageHandler(w, r, ast.TypeTable)
  211. }
  212. //list or create rules
  213. func rulesHandler(w http.ResponseWriter, r *http.Request) {
  214. defer r.Body.Close()
  215. switch r.Method {
  216. case http.MethodPost:
  217. body, err := ioutil.ReadAll(r.Body)
  218. if err != nil {
  219. handleError(w, err, "Invalid body", logger)
  220. return
  221. }
  222. r, err := ruleProcessor.ExecCreate("", string(body))
  223. var result string
  224. if err != nil {
  225. handleError(w, err, "Create rule error", logger)
  226. return
  227. } else {
  228. result = fmt.Sprintf("Rule %s was created successfully.", r.Id)
  229. }
  230. go func() {
  231. panicOrError := infra.SafeRun(func() error {
  232. //Start the rule
  233. rs, err := createRuleState(r)
  234. if err != nil {
  235. return err
  236. } else {
  237. err = doStartRule(rs)
  238. return err
  239. }
  240. })
  241. if panicOrError != nil {
  242. logger.Errorf("Rule %s start failed: %s", r.Id, panicOrError)
  243. }
  244. }()
  245. w.WriteHeader(http.StatusCreated)
  246. w.Write([]byte(result))
  247. case http.MethodGet:
  248. content, err := getAllRulesWithStatus()
  249. if err != nil {
  250. handleError(w, err, "Show rules error", logger)
  251. return
  252. }
  253. jsonResponse(content, w, logger)
  254. }
  255. }
  256. //describe or delete a rule
  257. func ruleHandler(w http.ResponseWriter, r *http.Request) {
  258. defer r.Body.Close()
  259. vars := mux.Vars(r)
  260. name := vars["name"]
  261. switch r.Method {
  262. case http.MethodGet:
  263. rule, err := ruleProcessor.GetRuleByName(name)
  264. if err != nil {
  265. handleError(w, err, "describe rule error", logger)
  266. return
  267. }
  268. jsonResponse(rule, w, logger)
  269. case http.MethodDelete:
  270. deleteRule(name)
  271. content, err := ruleProcessor.ExecDrop(name)
  272. if err != nil {
  273. handleError(w, err, "delete rule error", logger)
  274. return
  275. }
  276. w.WriteHeader(http.StatusOK)
  277. w.Write([]byte(content))
  278. case http.MethodPut:
  279. _, err := ruleProcessor.GetRuleByName(name)
  280. if err != nil {
  281. handleError(w, err, "not found this rule", logger)
  282. return
  283. }
  284. body, err := ioutil.ReadAll(r.Body)
  285. if err != nil {
  286. handleError(w, err, "Invalid body", logger)
  287. return
  288. }
  289. r, err := ruleProcessor.ExecUpdate(name, string(body))
  290. var result string
  291. if err != nil {
  292. handleError(w, err, "Update rule error", logger)
  293. return
  294. } else {
  295. result = fmt.Sprintf("Rule %s was updated successfully.", r.Id)
  296. }
  297. err = restartRule(name)
  298. if err != nil {
  299. handleError(w, err, "restart rule error", logger)
  300. return
  301. }
  302. w.WriteHeader(http.StatusOK)
  303. w.Write([]byte(result))
  304. }
  305. }
  306. //get status of a rule
  307. func getStatusRuleHandler(w http.ResponseWriter, r *http.Request) {
  308. defer r.Body.Close()
  309. vars := mux.Vars(r)
  310. name := vars["name"]
  311. content, err := getRuleStatus(name)
  312. if err != nil {
  313. handleError(w, err, "get rule status error", logger)
  314. return
  315. }
  316. w.WriteHeader(http.StatusOK)
  317. w.Write([]byte(content))
  318. }
  319. //start a rule
  320. func startRuleHandler(w http.ResponseWriter, r *http.Request) {
  321. defer r.Body.Close()
  322. vars := mux.Vars(r)
  323. name := vars["name"]
  324. err := startRule(name)
  325. if err != nil {
  326. handleError(w, err, "start rule error", logger)
  327. return
  328. }
  329. w.WriteHeader(http.StatusOK)
  330. w.Write([]byte(fmt.Sprintf("Rule %s was started", name)))
  331. }
  332. //stop a rule
  333. func stopRuleHandler(w http.ResponseWriter, r *http.Request) {
  334. defer r.Body.Close()
  335. vars := mux.Vars(r)
  336. name := vars["name"]
  337. result := stopRule(name)
  338. w.WriteHeader(http.StatusOK)
  339. w.Write([]byte(result))
  340. }
  341. //restart a rule
  342. func restartRuleHandler(w http.ResponseWriter, r *http.Request) {
  343. defer r.Body.Close()
  344. vars := mux.Vars(r)
  345. name := vars["name"]
  346. err := restartRule(name)
  347. if err != nil {
  348. handleError(w, err, "restart rule error", logger)
  349. return
  350. }
  351. w.WriteHeader(http.StatusOK)
  352. w.Write([]byte(fmt.Sprintf("Rule %s was restarted", name)))
  353. }
  354. //get topo of a rule
  355. func getTopoRuleHandler(w http.ResponseWriter, r *http.Request) {
  356. defer r.Body.Close()
  357. vars := mux.Vars(r)
  358. name := vars["name"]
  359. content, err := getRuleTopo(name)
  360. if err != nil {
  361. handleError(w, err, "get rule topo error", logger)
  362. return
  363. }
  364. w.Header().Set(ContentType, ContentTypeJSON)
  365. w.Write([]byte(content))
  366. }