hostgw.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // +build !windows
  2. // Copyright 2015 flannel authors
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. // +build !windows
  16. package hostgw
  17. import (
  18. "fmt"
  19. "sync"
  20. "github.com/flannel-io/flannel/backend"
  21. "github.com/flannel-io/flannel/pkg/ip"
  22. "github.com/flannel-io/flannel/subnet"
  23. "github.com/vishvananda/netlink"
  24. "golang.org/x/net/context"
  25. )
  26. func init() {
  27. backend.Register("host-gw", New)
  28. }
  29. type HostgwBackend struct {
  30. sm subnet.Manager
  31. extIface *backend.ExternalInterface
  32. }
  33. func New(sm subnet.Manager, extIface *backend.ExternalInterface) (backend.Backend, error) {
  34. if !extIface.ExtAddr.Equal(extIface.IfaceAddr) {
  35. return nil, fmt.Errorf("your PublicIP differs from interface IP, meaning that probably you're on a NAT, which is not supported by host-gw backend")
  36. }
  37. be := &HostgwBackend{
  38. sm: sm,
  39. extIface: extIface,
  40. }
  41. return be, nil
  42. }
  43. func (be *HostgwBackend) RegisterNetwork(ctx context.Context, wg *sync.WaitGroup, config *subnet.Config) (backend.Network, error) {
  44. n := &backend.RouteNetwork{
  45. SimpleNetwork: backend.SimpleNetwork{
  46. ExtIface: be.extIface,
  47. },
  48. SM: be.sm,
  49. BackendType: "host-gw",
  50. Mtu: be.extIface.Iface.MTU,
  51. LinkIndex: be.extIface.Iface.Index,
  52. }
  53. n.GetRoute = func(lease *subnet.Lease) *netlink.Route {
  54. return &netlink.Route{
  55. Dst: lease.Subnet.ToIPNet(),
  56. Gw: lease.Attrs.PublicIP.ToIP(),
  57. LinkIndex: n.LinkIndex,
  58. }
  59. }
  60. attrs := subnet.LeaseAttrs{
  61. PublicIP: ip.FromIP(be.extIface.ExtAddr),
  62. BackendType: "host-gw",
  63. }
  64. l, err := be.sm.AcquireLease(ctx, &attrs)
  65. switch err {
  66. case nil:
  67. n.SubnetLease = l
  68. case context.Canceled, context.DeadlineExceeded:
  69. return nil, err
  70. default:
  71. return nil, fmt.Errorf("failed to acquire lease: %v", err)
  72. }
  73. return n, nil
  74. }