ifaces.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. "regexp"
  19. "strconv"
  20. "strings"
  21. "github.com/pkg/errors"
  22. "yunion.io/x/jsonutils"
  23. yerrors "yunion.io/x/pkg/util/errors"
  24. "yunion.io/x/pkg/util/netutils"
  25. "yunion.io/x/sqlchemy"
  26. "yunion.io/x/onecloud/pkg/apis"
  27. "yunion.io/x/onecloud/pkg/cloudcommon/db"
  28. "yunion.io/x/onecloud/pkg/cloudcommon/validators"
  29. cnutils "yunion.io/x/onecloud/pkg/cloudnet/utils"
  30. "yunion.io/x/onecloud/pkg/mcclient"
  31. )
  32. var regexpIfname = regexp.MustCompile(`[A-Za-z][A-Za-z0-9]{0,14}`)
  33. type SIface struct {
  34. db.SStandaloneResourceBase
  35. RouterId string `length:"32" nullable:"false"`
  36. NetworkId string `length:"32" nullable:"false"`
  37. Ifname string `length:"32" nullable:"false"`
  38. PrivateKey string
  39. PublicKey string
  40. ListenPort int `nullable:"false"`
  41. IsSystem bool `nullable:"false"`
  42. }
  43. type SIfaceManager struct {
  44. db.SStandaloneResourceBaseManager
  45. }
  46. var IfaceManager *SIfaceManager
  47. func init() {
  48. IfaceManager = &SIfaceManager{
  49. SStandaloneResourceBaseManager: db.NewStandaloneResourceBaseManager(
  50. SIface{},
  51. "ifaces_tbl",
  52. "iface",
  53. "ifaces",
  54. ),
  55. }
  56. IfaceManager.SetVirtualObject(IfaceManager)
  57. }
  58. func (man *SIfaceManager) ValidateCreateData(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, data *jsonutils.JSONDict) (*jsonutils.JSONDict, error) {
  59. // router existence
  60. // PrivateKey validation , or generation
  61. // ListenPort validation, uniqueness
  62. // ListenPort generation
  63. return nil, errors.New("manually adding interface is currently not supported")
  64. }
  65. // 虚拟路由器接口列表
  66. func (man *SIfaceManager) ListItemFilter(ctx context.Context, q *sqlchemy.SQuery, userCred mcclient.TokenCredential, query jsonutils.JSONObject) (*sqlchemy.SQuery, error) {
  67. input := apis.StandaloneResourceListInput{}
  68. err := query.Unmarshal(&input)
  69. if err != nil {
  70. return nil, errors.Wrap(err, "query.Unmarshal")
  71. }
  72. q, err = man.SStandaloneResourceBaseManager.ListItemFilter(ctx, q, userCred, input)
  73. if err != nil {
  74. return nil, errors.Wrap(err, "SStandaloneResourceBaseManager.ListItemFilter")
  75. }
  76. data := query.(*jsonutils.JSONDict)
  77. q, err = validators.ApplyModelFilters(ctx, q, data, []*validators.ModelFilterOptions{
  78. {Key: "router", ModelKeyword: "router", OwnerId: userCred},
  79. })
  80. if err != nil {
  81. return nil, err
  82. }
  83. return q, nil
  84. }
  85. func (iface *SIface) ValidateUpdateCondition(ctx context.Context) error {
  86. // same as create but no generation
  87. // if privatekey updated
  88. // update peers whose peerifaceid == self.id
  89. return nil
  90. }
  91. func (iface *SIface) ValidateDeleteCondition(ctx context.Context, info jsonutils.JSONObject) error {
  92. // if networkid != "" {
  93. // return errors.New("part of network, remove it by remove network memeber")
  94. // }
  95. return nil
  96. }
  97. func (iface *SIface) CustomizeDelete(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) error {
  98. // remove ifacepeer whose peerifaceId is self.id
  99. return nil
  100. }
  101. func (iface *SIface) addOrUpdatePeer(ctx context.Context, userCred mcclient.TokenCredential,
  102. peerIface *SIface, allowedNets Subnets, peerRouter *SRouter) error {
  103. // XXX lock
  104. endpoint := ""
  105. endpointIP := peerRouter.endpointIP()
  106. if endpointIP != "" && peerIface.ListenPort > 0 {
  107. endpoint = fmt.Sprintf("%s:%d", endpointIP, peerIface.ListenPort)
  108. }
  109. persistentKeepalive := 0
  110. if endpointIP != "" {
  111. // persistent keepalive from private addr to exit addr
  112. router, err := iface.getRouter()
  113. if err != nil {
  114. return errors.WithMessagef(err, "get iface router %s", iface.RouterId)
  115. }
  116. myIP := router.endpointIP()
  117. if myIP != "" {
  118. myIPAddr, err := netutils.NewIPV4Addr(myIP)
  119. if err != nil {
  120. return err
  121. }
  122. if netutils.IsPrivate(myIPAddr) {
  123. peerIPAddr, err := netutils.NewIPV4Addr(endpointIP)
  124. if err != nil {
  125. return err
  126. }
  127. if netutils.IsExitAddress(peerIPAddr) {
  128. persistentKeepalive = 10
  129. }
  130. }
  131. }
  132. }
  133. ifacePeer, err := IfacePeerManager.getByIfacePublicKey(iface, peerIface.PublicKey)
  134. if err != nil && !IsNotFound(err) {
  135. return err
  136. }
  137. if err := IfacePeerManager.checkAllowedIPs(iface, ifacePeer, allowedNets); err != nil {
  138. return err
  139. }
  140. if ifacePeer == nil {
  141. ifacePeer := &SIfacePeer{
  142. RouterId: iface.RouterId,
  143. IfaceId: iface.Id,
  144. PeerIfaceId: peerIface.Id,
  145. PeerRouterId: peerIface.RouterId,
  146. PublicKey: peerIface.PublicKey,
  147. AllowedIPs: allowedNets.String(),
  148. Endpoint: endpoint,
  149. PersistentKeepalive: persistentKeepalive,
  150. }
  151. ifacePeer.Name = fmt.Sprintf("%s-%s", iface.Name, peerIface.Name)
  152. err := IfacePeerManager.TableSpec().Insert(ctx, ifacePeer)
  153. return err
  154. }
  155. _, err = db.Update(ifacePeer, func() error {
  156. ifacePeer.PeerIfaceId = peerIface.Id
  157. ifacePeer.PeerRouterId = peerIface.RouterId
  158. ifacePeer.Endpoint = endpoint
  159. ifacePeer.AllowedIPs = allowedNets.String()
  160. ifacePeer.PersistentKeepalive = persistentKeepalive
  161. return nil
  162. })
  163. return err
  164. }
  165. func (iface *SIface) clearPeers(ctx context.Context, userCred mcclient.TokenCredential) error {
  166. return IfacePeerManager.removeByIface(ctx, userCred, iface)
  167. }
  168. func (iface *SIface) clearPeerRefs(ctx context.Context, userCred mcclient.TokenCredential) error {
  169. return IfacePeerManager.removeByPeerIface(ctx, userCred, iface)
  170. }
  171. func (iface *SIface) clearRoutes(ctx context.Context, userCred mcclient.TokenCredential) error {
  172. return RouteManager.removeByIface(ctx, userCred, iface)
  173. }
  174. func (iface *SIface) remove(ctx context.Context, userCred mcclient.TokenCredential) error {
  175. var errs []error
  176. if err := iface.clearRoutes(ctx, userCred); err != nil {
  177. errs = append(errs, err)
  178. }
  179. if err := iface.clearPeers(ctx, userCred); err != nil {
  180. errs = append(errs, err)
  181. }
  182. if err := iface.clearPeerRefs(ctx, userCred); err != nil {
  183. errs = append(errs, err)
  184. }
  185. if len(errs) == 0 {
  186. if err := iface.Delete(ctx, userCred); err != nil {
  187. errs = append(errs, err)
  188. }
  189. }
  190. return yerrors.NewAggregate(errs)
  191. }
  192. func (iface *SIface) isTypeWireguard() bool {
  193. r := iface.ListenPort > 0 && iface.PrivateKey != "" && iface.PublicKey != ""
  194. return r
  195. }
  196. func (iface *SIface) getRouter() (*SRouter, error) {
  197. obj, err := db.FetchById(RouterManager, iface.RouterId)
  198. if err != nil {
  199. return nil, err
  200. }
  201. router := obj.(*SRouter)
  202. return router, nil
  203. }
  204. func (man *SIfaceManager) removeByFilter(ctx context.Context, userCred mcclient.TokenCredential, filter map[string]string) error {
  205. ifaces, err := man.getByFilter(filter)
  206. if err != nil {
  207. return err
  208. }
  209. var errs []error
  210. for i := range ifaces {
  211. iface := &ifaces[i]
  212. if err := iface.remove(ctx, userCred); err != nil {
  213. errs = append(errs, err)
  214. }
  215. }
  216. return yerrors.NewAggregate(errs)
  217. }
  218. func (man *SIfaceManager) removeByRouter(ctx context.Context, userCred mcclient.TokenCredential, router *SRouter) error {
  219. err := man.removeByFilter(ctx, userCred, map[string]string{
  220. "router_id": router.Id,
  221. })
  222. return err
  223. }
  224. func (man *SIfaceManager) removeByMeshNetwork(ctx context.Context, userCred mcclient.TokenCredential, mn *SMeshNetwork) error {
  225. err := man.removeByFilter(ctx, userCred, map[string]string{
  226. "network_id": mn.Id,
  227. })
  228. return err
  229. }
  230. func (man *SIfaceManager) removeByMeshNetworkRouter(ctx context.Context, userCred mcclient.TokenCredential, mn *SMeshNetwork, router *SRouter) error {
  231. err := man.removeByFilter(ctx, userCred, map[string]string{
  232. "network_id": mn.Id,
  233. "router_id": router.Id,
  234. })
  235. return err
  236. }
  237. func (man *SIfaceManager) getByRouter(router *SRouter) ([]SIface, error) {
  238. return man.getByFilter(map[string]string{
  239. "router_id": router.Id,
  240. })
  241. }
  242. func (man *SIfaceManager) getByRouterIfname(router *SRouter, ifname string) (*SIface, error) {
  243. return man.getOneByFilter(map[string]string{
  244. "router_id": router.Id,
  245. "ifname": ifname,
  246. })
  247. }
  248. func (man *SIfaceManager) getByFilter(filter map[string]string) ([]SIface, error) {
  249. ifaces := []SIface{}
  250. q := man.Query()
  251. for key, val := range filter {
  252. q = q.Equals(key, val)
  253. }
  254. if err := db.FetchModelObjects(IfaceManager, q, &ifaces); err != nil {
  255. return nil, err
  256. }
  257. return ifaces, nil
  258. }
  259. func (man *SIfaceManager) getOneByFilter(filter map[string]string) (*SIface, error) {
  260. ifaces, err := man.getByFilter(filter)
  261. if err != nil {
  262. return nil, err
  263. }
  264. if len(ifaces) == 0 {
  265. return nil, fmt.Errorf("cannot find iface for condition: %#v", filter)
  266. }
  267. if len(ifaces) > 1 {
  268. return nil, fmt.Errorf("found more than 1 ifaces for condition: %#v", filter)
  269. }
  270. return &ifaces[0], nil
  271. }
  272. func (man *SIfaceManager) checkExistenceByFilter(filter map[string]string) error {
  273. ifaces, err := man.getByFilter(filter)
  274. if err != nil {
  275. return err
  276. }
  277. if len(ifaces) > 0 {
  278. return fmt.Errorf("iface exist: %s(%s)", ifaces[0].Name, ifaces[0].Id)
  279. }
  280. return nil
  281. }
  282. func (man *SIfaceManager) getByRouterNetwork(ctx context.Context, userCred mcclient.TokenCredential, router *SRouter, mn *SMeshNetwork) ([]SIface, error) {
  283. ifaces, err := man.getByFilter(map[string]string{
  284. "router_id": router.Id,
  285. "network_id": mn.Id,
  286. })
  287. return ifaces, err
  288. }
  289. func (man *SIfaceManager) getOneByRouterNetwork(ctx context.Context, userCred mcclient.TokenCredential, router *SRouter, mn *SMeshNetwork) (*SIface, error) {
  290. iface, err := man.getOneByFilter(map[string]string{
  291. "router_id": router.Id,
  292. "network_id": mn.Id,
  293. })
  294. return iface, err
  295. }
  296. func (man *SIfaceManager) getByMeshNetworkMember(member *SMeshNetworkMember) (*SIface, error) {
  297. iface, err := man.getOneByFilter(map[string]string{
  298. "router_id": member.RouterId,
  299. "network_id": member.MeshNetworkId,
  300. })
  301. return iface, err
  302. }
  303. func (man *SIfaceManager) getNextName(filter map[string]string, base string) (string, error) {
  304. ifaces, err := man.getByFilter(filter)
  305. if err != nil {
  306. return "", err
  307. }
  308. occupied := map[int]struct{}{}
  309. for i := range ifaces {
  310. iface := &ifaces[i]
  311. if strings.HasPrefix(iface.Ifname, base) {
  312. istr := iface.Ifname[len(base):]
  313. i, err := strconv.ParseUint(istr, 10, 16)
  314. if err != nil {
  315. continue
  316. }
  317. occupied[int(i)] = struct{}{}
  318. }
  319. }
  320. for i := 0; i < 65536; i++ {
  321. if _, ok := occupied[i]; !ok {
  322. return fmt.Sprintf("%s%d", base, i), nil
  323. }
  324. }
  325. return "", fmt.Errorf("all names occupied")
  326. }
  327. func (man *SIfaceManager) addWireguardIface(ctx context.Context, userCred mcclient.TokenCredential, router *SRouter, mn *SMeshNetwork) (*SIface, error) {
  328. k := cnutils.MustNewKey()
  329. port := router.mustFindFreePort(ctx)
  330. iface := &SIface{
  331. RouterId: router.Id,
  332. PrivateKey: k.String(),
  333. PublicKey: k.PublicKey().String(),
  334. ListenPort: port,
  335. }
  336. iface.IsSystem = true
  337. { // ifname
  338. if name, err := man.getNextName(map[string]string{
  339. "router_id": router.Id,
  340. }, "wg"); err != nil {
  341. return nil, err
  342. } else {
  343. iface.Ifname = name
  344. }
  345. }
  346. { // obj name
  347. name := router.Name + "-"
  348. if mn != nil {
  349. iface.NetworkId = mn.Id
  350. name += mn.Name + "-"
  351. }
  352. name += fmt.Sprintf("%d", port)
  353. iface.Name = name
  354. }
  355. iface.SetModelManager(man, iface)
  356. err := man.TableSpec().Insert(ctx, iface)
  357. if err != nil {
  358. return nil, err
  359. }
  360. if err := RuleManager.addWireguardIfaceRules(ctx, userCred, iface); err != nil {
  361. iface.Delete(ctx, userCred)
  362. return nil, err
  363. }
  364. return iface, nil
  365. }
  366. func (man *SIfaceManager) addIface(ctx context.Context, userCred mcclient.TokenCredential, router *SRouter, ifname string) (*SIface, error) {
  367. if err := man.checkExistenceByFilter(map[string]string{
  368. "router_id": router.Id,
  369. "ifname": ifname,
  370. }); err != nil {
  371. return nil, err
  372. }
  373. iface := &SIface{
  374. RouterId: router.Id,
  375. Ifname: ifname,
  376. }
  377. iface.SetModelManager(man, iface)
  378. err := man.TableSpec().Insert(ctx, iface)
  379. if err != nil {
  380. return nil, err
  381. }
  382. return iface, nil
  383. }