hostgw.go 2.2 KB

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