hostgw.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. "github.com/coreos/flannel/backend"
  20. "github.com/coreos/flannel/pkg/ip"
  21. "github.com/coreos/flannel/subnet"
  22. "github.com/vishvananda/netlink"
  23. "golang.org/x/net/context"
  24. )
  25. func init() {
  26. backend.Register("host-gw", New)
  27. }
  28. type HostgwBackend struct {
  29. sm subnet.Manager
  30. extIface *backend.ExternalInterface
  31. }
  32. func New(sm subnet.Manager, extIface *backend.ExternalInterface) (backend.Backend, error) {
  33. if !extIface.ExtAddr.Equal(extIface.IfaceAddr) {
  34. 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")
  35. }
  36. be := &HostgwBackend{
  37. sm: sm,
  38. extIface: extIface,
  39. }
  40. return be, nil
  41. }
  42. func (be *HostgwBackend) RegisterNetwork(ctx context.Context, config *subnet.Config) (backend.Network, error) {
  43. n := &backend.RouteNetwork{
  44. SimpleNetwork: backend.SimpleNetwork{
  45. ExtIface: be.extIface,
  46. },
  47. SM: be.sm,
  48. BackendType: "host-gw",
  49. Mtu: be.extIface.Iface.MTU,
  50. LinkIndex: be.extIface.Iface.Index,
  51. }
  52. n.GetRoute = func(lease *subnet.Lease) *netlink.Route {
  53. return &netlink.Route{
  54. Dst: lease.Subnet.ToIPNet(),
  55. Gw: lease.Attrs.PublicIP.ToIP(),
  56. LinkIndex: n.LinkIndex,
  57. }
  58. }
  59. attrs := subnet.LeaseAttrs{
  60. PublicIP: ip.FromIP(be.extIface.ExtAddr),
  61. BackendType: "host-gw",
  62. }
  63. l, err := be.sm.AcquireLease(ctx, &attrs)
  64. switch err {
  65. case nil:
  66. n.SubnetLease = l
  67. case context.Canceled, context.DeadlineExceeded:
  68. return nil, err
  69. default:
  70. return nil, fmt.Errorf("failed to acquire lease: %v", err)
  71. }
  72. return n, nil
  73. }