middleware.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. // Copyright 2019 Yunion
  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 handler
  15. import (
  16. "context"
  17. "fmt"
  18. "net"
  19. "net/http"
  20. "strings"
  21. "time"
  22. "yunion.io/x/jsonutils"
  23. "yunion.io/x/log"
  24. "yunion.io/x/onecloud/pkg/appsrv"
  25. "yunion.io/x/onecloud/pkg/baremetal"
  26. baremetaltypes "yunion.io/x/onecloud/pkg/baremetal/types"
  27. "yunion.io/x/onecloud/pkg/httperrors"
  28. "yunion.io/x/onecloud/pkg/mcclient"
  29. "yunion.io/x/onecloud/pkg/mcclient/auth"
  30. )
  31. const (
  32. BM_PREFIX = "baremetals"
  33. SERVER_PREFIX = "servers"
  34. PARAMS_BMID_KEY = "<bm_id>"
  35. PARAMS_SRVID_KEY = "<srv_id>"
  36. )
  37. func bmIdPrefix() string {
  38. // baremetals/<bm_id>
  39. return fmt.Sprintf("%s/%s", BM_PREFIX, PARAMS_BMID_KEY)
  40. }
  41. func bmActionPrefix(action string) string {
  42. // baremetals/<bm_id>/action
  43. return fmt.Sprintf("%s/%s", bmIdPrefix(), action)
  44. }
  45. func srvIdPrefix() string {
  46. // baremetals/<bm_id>/servers/<srv_id>
  47. return fmt.Sprintf("%s/%s/%s", bmIdPrefix(), SERVER_PREFIX, PARAMS_SRVID_KEY)
  48. }
  49. func srvActionPrefix(action string) string {
  50. // baremetals/<bm_id>/servers/<srv_id>/action
  51. return fmt.Sprintf("%s/%s", srvIdPrefix(), action)
  52. }
  53. func bmRegisterPrefix() string {
  54. // baremetals/register-baremetal
  55. return fmt.Sprintf("%s/register-baremetal", BM_PREFIX)
  56. }
  57. type handlerFunc func(ctx *Context)
  58. func authMiddleware(h handlerFunc) appsrv.FilterHandler {
  59. return func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  60. newCtx := NewContext(ctx, w, r)
  61. h(newCtx)
  62. }
  63. }
  64. type bmObjHandlerFunc func(ctx *Context, bm *baremetal.SBaremetalInstance)
  65. func bmObjMiddleware(h bmObjHandlerFunc) appsrv.FilterHandler {
  66. return bmObjMiddlewareWithFetch(h, true)
  67. }
  68. func bmObjMiddlewareWithFetch(h bmObjHandlerFunc, fetch bool) appsrv.FilterHandler {
  69. return func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  70. newCtx := NewContext(ctx, w, r)
  71. bmId := newCtx.Params()[PARAMS_BMID_KEY]
  72. baremetal := newCtx.GetBaremetalManager().GetBaremetalById(bmId)
  73. if baremetal == nil {
  74. if fetch {
  75. err := newCtx.GetBaremetalManager().InitBaremetal(newCtx, bmId, false)
  76. if err != nil {
  77. newCtx.ResponseError(err)
  78. return
  79. }
  80. baremetal = newCtx.GetBaremetalManager().GetBaremetalById(bmId)
  81. } else {
  82. newCtx.ResponseError(httperrors.NewNotFoundError("Not found baremetal by id: %s", bmId))
  83. return
  84. }
  85. }
  86. h(newCtx, baremetal)
  87. }
  88. }
  89. type srvObjHandlerFunc func(ctx *Context, bm *baremetal.SBaremetalInstance, srv baremetaltypes.IBaremetalServer)
  90. func srvClassMiddleware(h bmObjHandlerFunc) appsrv.FilterHandler {
  91. return func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  92. newCtx := NewContext(ctx, w, r)
  93. bmId := newCtx.Params()[PARAMS_BMID_KEY]
  94. //srvId := newCtx.Params()[PARAMS_SRVID_KEY]
  95. baremetal := newCtx.GetBaremetalManager().GetBaremetalById(bmId)
  96. if baremetal == nil {
  97. newCtx.ResponseError(httperrors.NewNotFoundError("Not found baremetal by id: %s", bmId))
  98. return
  99. }
  100. if baremetal.GetServerId() != "" {
  101. newCtx.ResponseError(httperrors.NewNotAcceptableError("Baremetal %s occupied", bmId))
  102. return
  103. }
  104. h(newCtx, baremetal)
  105. }
  106. }
  107. func srvObjMiddleware(h srvObjHandlerFunc) appsrv.FilterHandler {
  108. return func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  109. newCtx := NewContext(ctx, w, r)
  110. bmId := newCtx.Params()[PARAMS_BMID_KEY]
  111. srvId := newCtx.Params()[PARAMS_SRVID_KEY]
  112. baremetal := newCtx.GetBaremetalManager().GetBaremetalById(bmId)
  113. if baremetal == nil {
  114. newCtx.ResponseError(httperrors.NewNotFoundError("Not found baremetal by id: %s", bmId))
  115. return
  116. }
  117. if baremetal.GetServerId() != srvId {
  118. newCtx.ResponseError(httperrors.NewNotFoundError("Not found server by id: %s", srvId))
  119. return
  120. }
  121. srv := baremetal.GetServer()
  122. h(newCtx, baremetal, srv)
  123. }
  124. }
  125. type bmRegisterFunc func(*Context, *baremetal.BmRegisterInput)
  126. func bmRegisterMiddleware(h bmRegisterFunc) appsrv.FilterHandler {
  127. return func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  128. newCtx := NewContext(ctx, w, r)
  129. sshPasswd, _ := newCtx.Data().GetString("ssh_password")
  130. if len(sshPasswd) == 0 {
  131. sshPasswd = "yunion@123"
  132. }
  133. hostname, err := newCtx.Data().GetString("hostname")
  134. if err != nil {
  135. newCtx.ResponseError(httperrors.NewMissingParameterError("hostname"))
  136. return
  137. }
  138. remoteIp, _ := newCtx.Data().GetString("ssh_ip")
  139. if len(remoteIp) == 0 {
  140. remoteIp, _, err = net.SplitHostPort(r.RemoteAddr)
  141. if err != nil {
  142. newCtx.ResponseError(httperrors.NewInternalServerError("Parse ip error %s", err))
  143. return
  144. }
  145. }
  146. sshPort, err := newCtx.Data().Int("ssh_port")
  147. if err != nil {
  148. newCtx.ResponseError(httperrors.NewMissingParameterError("ssh_port"))
  149. return
  150. }
  151. username, err := newCtx.Data().GetString("username")
  152. if err != nil {
  153. newCtx.ResponseError(httperrors.NewMissingParameterError("username"))
  154. return
  155. }
  156. password, err := newCtx.Data().GetString("password")
  157. if err != nil {
  158. newCtx.ResponseError(httperrors.NewMissingParameterError("password"))
  159. return
  160. }
  161. ctx, cancel := context.WithTimeout(ctx, time.Second*298)
  162. defer cancel()
  163. data := &baremetal.BmRegisterInput{
  164. Ctx: ctx,
  165. R: r,
  166. W: w,
  167. C: make(chan struct{}),
  168. SshPort: int(sshPort),
  169. SshPasswd: sshPasswd,
  170. Hostname: hostname,
  171. RemoteIp: remoteIp,
  172. Username: username,
  173. Password: password,
  174. }
  175. h(newCtx, data)
  176. select {
  177. case <-ctx.Done():
  178. log.Errorln("Register timeout")
  179. newCtx.ResponseError(httperrors.NewTimeoutError("RegisterTimeOut"))
  180. case <-data.C:
  181. return
  182. }
  183. }
  184. }
  185. type Context struct {
  186. context.Context
  187. userCred mcclient.TokenCredential
  188. params map[string]string
  189. query jsonutils.JSONObject
  190. data jsonutils.JSONObject
  191. request *http.Request
  192. writer http.ResponseWriter
  193. }
  194. func NewContext(ctx context.Context, w http.ResponseWriter, r *http.Request) *Context {
  195. params, query, body := appsrv.FetchEnv(ctx, w, r)
  196. return &Context{
  197. Context: ctx,
  198. userCred: auth.FetchUserCredential(ctx, nil),
  199. params: params,
  200. query: query,
  201. data: body,
  202. request: r,
  203. writer: w,
  204. }
  205. }
  206. func (ctx *Context) Params() map[string]string {
  207. return ctx.params
  208. }
  209. func (ctx *Context) Data() jsonutils.JSONObject {
  210. return ctx.data
  211. }
  212. func (ctx *Context) Query() jsonutils.JSONObject {
  213. return ctx.query
  214. }
  215. func (ctx *Context) UserCred() mcclient.TokenCredential {
  216. return ctx.userCred
  217. }
  218. func (ctx *Context) TaskId() string {
  219. return ctx.Request().Header.Get(mcclient.TASK_ID)
  220. }
  221. func (ctx *Context) ResponseStruct(obj interface{}) {
  222. appsrv.SendStruct(ctx.writer, obj)
  223. }
  224. func (ctx *Context) ResponseJson(obj jsonutils.JSONObject) {
  225. appsrv.SendJSON(ctx.writer, obj)
  226. }
  227. func (ctx *Context) ResponseError(err error) {
  228. httperrors.GeneralServerError(ctx, ctx.writer, err)
  229. }
  230. func (ctx *Context) Request() *http.Request {
  231. return ctx.request
  232. }
  233. func (ctx *Context) RequestRemoteIP() string {
  234. remoteAddr := ctx.Request().RemoteAddr
  235. return strings.Split(remoteAddr, ":")[0]
  236. }
  237. func (ctx *Context) ResponseOk() {
  238. obj := jsonutils.NewDict()
  239. obj.Add(jsonutils.NewString("ok"), "result")
  240. appsrv.SendJSON(ctx.writer, obj)
  241. }
  242. func (ctx *Context) GetBaremetalManager() *baremetal.SBaremetalManager {
  243. return baremetal.GetBaremetalManager()
  244. }
  245. func (ctx *Context) DelayProcess(process ProcessFunc, data jsonutils.JSONObject) {
  246. DelayProcess(process, ctx.GetBaremetalManager().GetClientSession(), ctx.TaskId(), data)
  247. }