rest.go 11 KB

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