routes.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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 models
  15. import (
  16. "context"
  17. "fmt"
  18. "yunion.io/x/jsonutils"
  19. "yunion.io/x/pkg/errors"
  20. "yunion.io/x/pkg/util/rand"
  21. "yunion.io/x/sqlchemy"
  22. "yunion.io/x/onecloud/pkg/apis"
  23. api "yunion.io/x/onecloud/pkg/apis/cloudnet"
  24. "yunion.io/x/onecloud/pkg/cloudcommon/db"
  25. "yunion.io/x/onecloud/pkg/cloudcommon/validators"
  26. "yunion.io/x/onecloud/pkg/httperrors"
  27. "yunion.io/x/onecloud/pkg/mcclient"
  28. )
  29. type SRoute struct {
  30. db.SStandaloneResourceBase
  31. IfaceId string `length:"32" nullable:"false" list:"user" create:"required"`
  32. Ifname string `length:"32" nullable:"false" list:"user" create:"optional"`
  33. Network string `length:"32" nullable:"false" list:"user" update:"user" create:"required"`
  34. Gateway string `length:"32" nullable:"false" list:"user" update:"user" create:"optional"`
  35. RouterId string `length:"32" nullable:"false" list:"user" create:"optional"`
  36. }
  37. type SRouteManager struct {
  38. db.SStandaloneResourceBaseManager
  39. }
  40. var RouteManager *SRouteManager
  41. func init() {
  42. RouteManager = &SRouteManager{
  43. SStandaloneResourceBaseManager: db.NewStandaloneResourceBaseManager(
  44. SRoute{},
  45. "routes_tbl",
  46. "route",
  47. "routes",
  48. ),
  49. }
  50. RouteManager.SetVirtualObject(RouteManager)
  51. }
  52. func (man *SRouteManager) ValidateCreateData(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, data *jsonutils.JSONDict) (*jsonutils.JSONDict, error) {
  53. input := apis.StandaloneResourceCreateInput{}
  54. err := data.Unmarshal(&input)
  55. if err != nil {
  56. return nil, httperrors.NewInternalServerError("unmarshal StandaloneResourceCreateInput fail %s", err)
  57. }
  58. input, err = man.SStandaloneResourceBaseManager.ValidateCreateData(ctx, userCred, ownerId, query, input)
  59. if err != nil {
  60. return nil, err
  61. }
  62. data.Update(jsonutils.Marshal(input))
  63. ifaceV := validators.NewModelIdOrNameValidator("iface", "iface", ownerId)
  64. networkV := validators.NewIPv4PrefixValidator("network")
  65. gatewayV := validators.NewIPv4AddrValidator("gateway")
  66. vs := []validators.IValidator{
  67. networkV,
  68. gatewayV.Optional(true),
  69. ifaceV,
  70. }
  71. for _, v := range vs {
  72. if err := v.Validate(ctx, data); err != nil {
  73. return nil, err
  74. }
  75. }
  76. iface := ifaceV.Model.(*SIface)
  77. network := networkV.Value.String()
  78. routerId := iface.RouterId
  79. {
  80. if routes, err := man.getByFilter(map[string]string{
  81. "router_id": routerId,
  82. "network": network,
  83. }); err != nil {
  84. return nil, httperrors.NewConflictError("query existing route to network %s: %v", network, err)
  85. } else if len(routes) > 0 {
  86. return nil, httperrors.NewConflictError("route to %s already exist: %s(%s)", network, routes[0].Name, routes[0].Id)
  87. }
  88. }
  89. data.Set("router_id", jsonutils.NewString(routerId))
  90. data.Set("ifname", jsonutils.NewString(iface.Ifname))
  91. routerV := validators.NewModelIdOrNameValidator("router", "router", ownerId)
  92. if err := routerV.Validate(ctx, data); err != nil {
  93. return nil, err
  94. }
  95. if !data.Contains("name") {
  96. router := routerV.Model.(*SRouter)
  97. data.Set("name", jsonutils.NewString(
  98. router.Name+"-"+iface.Name+"-"+rand.String(4)),
  99. )
  100. }
  101. return data, nil
  102. }
  103. // 虚拟路由器路由列表
  104. func (man *SRouteManager) ListItemFilter(ctx context.Context, q *sqlchemy.SQuery, userCred mcclient.TokenCredential, query jsonutils.JSONObject) (*sqlchemy.SQuery, error) {
  105. input := apis.StandaloneResourceListInput{}
  106. err := query.Unmarshal(&input)
  107. if err != nil {
  108. return nil, err
  109. }
  110. q, err = man.SStandaloneResourceBaseManager.ListItemFilter(ctx, q, userCred, input)
  111. if err != nil {
  112. return nil, err
  113. }
  114. data := query.(*jsonutils.JSONDict)
  115. q, err = validators.ApplyModelFilters(ctx, q, data, []*validators.ModelFilterOptions{
  116. {Key: "router", ModelKeyword: "router", OwnerId: userCred},
  117. {Key: "iface", ModelKeyword: "iface", OwnerId: userCred},
  118. })
  119. if err != nil {
  120. return nil, err
  121. }
  122. return q, nil
  123. }
  124. func (route *SRoute) ValidateUpdateData(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, input api.RouteUpdateInput) (api.RouteUpdateInput, error) {
  125. var err error
  126. input.StandaloneResourceBaseUpdateInput, err = route.SStandaloneResourceBase.ValidateUpdateData(ctx, userCred, query, input.StandaloneResourceBaseUpdateInput)
  127. if err != nil {
  128. return input, errors.Wrap(err, "SStandaloneResourceBase.ValidateUpdateData")
  129. }
  130. data := jsonutils.Marshal(input).(*jsonutils.JSONDict)
  131. vs := []validators.IValidator{
  132. validators.NewIPv4PrefixValidator("network"),
  133. validators.NewIPv4AddrValidator("gateway"),
  134. }
  135. for _, v := range vs {
  136. v.Optional(true)
  137. if err := v.Validate(ctx, data); err != nil {
  138. return input, err
  139. }
  140. }
  141. return input, nil
  142. }
  143. func (man *SRouteManager) removeByIface(ctx context.Context, userCred mcclient.TokenCredential, iface *SIface) error {
  144. routes := []SRoute{}
  145. q := man.Query().Equals("iface_id", iface.Id)
  146. if err := db.FetchModelObjects(RouteManager, q, &routes); err != nil {
  147. return err
  148. }
  149. var errs []error
  150. for j := range routes {
  151. if err := routes[j].Delete(ctx, userCred); err != nil {
  152. errs = append(errs, err)
  153. }
  154. }
  155. return errors.NewAggregate(errs)
  156. }
  157. func (man *SRouteManager) getByFilter(filter map[string]string) ([]SRoute, error) {
  158. routes := []SRoute{}
  159. q := man.Query()
  160. for key, val := range filter {
  161. q = q.Equals(key, val)
  162. }
  163. if err := db.FetchModelObjects(RouteManager, q, &routes); err != nil {
  164. return nil, err
  165. }
  166. return routes, nil
  167. }
  168. func (man *SRouteManager) getOneByFilter(filter map[string]string) (*SRoute, error) {
  169. routes, err := man.getByFilter(filter)
  170. if err != nil {
  171. return nil, err
  172. }
  173. if len(routes) == 0 {
  174. return nil, errNotFound(fmt.Errorf("cannot find iface route: %#v", filter))
  175. }
  176. if len(routes) > 1 {
  177. return nil, errMoreThanOne(fmt.Errorf("found more than 1 iface routes: %#v", filter))
  178. }
  179. return &routes[0], nil
  180. }
  181. func (man *SRouteManager) checkExistenceByFilter(filter map[string]string) error {
  182. ifaces, err := man.getByFilter(filter)
  183. if err != nil {
  184. return err
  185. }
  186. if len(ifaces) > 0 {
  187. return fmt.Errorf("iface exist: %s(%s)", ifaces[0].Name, ifaces[0].Id)
  188. }
  189. return nil
  190. }
  191. func (man *SRouteManager) getByIface(iface *SIface) ([]SRoute, error) {
  192. filter := map[string]string{
  193. "router_id": iface.RouterId,
  194. "iface_id": iface.Id,
  195. }
  196. routes, err := man.getByFilter(filter)
  197. if err != nil {
  198. return nil, err
  199. }
  200. return routes, nil
  201. }
  202. func (man *SRouteManager) getByRouter(router *SRouter) ([]SRoute, error) {
  203. filter := map[string]string{
  204. "router_id": router.Id,
  205. }
  206. routes, err := man.getByFilter(filter)
  207. if err != nil {
  208. return nil, err
  209. }
  210. return routes, nil
  211. }
  212. func (route *SRoute) routeLine() string {
  213. line := route.Network
  214. if route.Gateway != "" {
  215. line += " via " + route.Gateway
  216. }
  217. if route.Ifname != "" {
  218. line += " dev " + route.Ifname
  219. }
  220. return line
  221. }
  222. func (man *SRouteManager) routeLinesByIface(iface *SIface) ([]string, error) {
  223. routes, err := man.getByIface(iface)
  224. if err != nil {
  225. return nil, err
  226. }
  227. lines := []string{}
  228. for i := range routes {
  229. route := &routes[i]
  230. line := route.routeLine()
  231. if line != "" {
  232. lines = append(lines, line)
  233. }
  234. }
  235. return lines, nil
  236. }
  237. func (man *SRouteManager) routeLinesRouter(router *SRouter) (map[string][]string, error) {
  238. routes, err := man.getByRouter(router)
  239. if err != nil {
  240. return nil, err
  241. }
  242. r := map[string][]string{}
  243. for i := range routes {
  244. route := &routes[i]
  245. line := route.routeLine()
  246. if line != "" {
  247. lines := r[route.Ifname]
  248. lines = append(lines, line)
  249. r[route.Ifname] = lines
  250. }
  251. }
  252. return r, nil
  253. }