hostgw.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. "golang.org/x/net/context"
  22. )
  23. func init() {
  24. backend.Register("host-gw", New)
  25. }
  26. const (
  27. routeCheckRetries = 10
  28. )
  29. type HostgwBackend struct {
  30. sm subnet.Manager
  31. extIface *backend.ExternalInterface
  32. networks map[string]*network
  33. }
  34. func New(sm subnet.Manager, extIface *backend.ExternalInterface) (backend.Backend, error) {
  35. if !extIface.ExtAddr.Equal(extIface.IfaceAddr) {
  36. 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")
  37. }
  38. be := &HostgwBackend{
  39. sm: sm,
  40. extIface: extIface,
  41. networks: make(map[string]*network),
  42. }
  43. return be, nil
  44. }
  45. func (be *HostgwBackend) RegisterNetwork(ctx context.Context, config *subnet.Config) (backend.Network, error) {
  46. n := &network{
  47. extIface: be.extIface,
  48. sm: be.sm,
  49. }
  50. attrs := subnet.LeaseAttrs{
  51. PublicIP: ip.FromIP(be.extIface.ExtAddr),
  52. BackendType: "host-gw",
  53. }
  54. l, err := be.sm.AcquireLease(ctx, &attrs)
  55. switch err {
  56. case nil:
  57. n.lease = l
  58. case context.Canceled, context.DeadlineExceeded:
  59. return nil, err
  60. default:
  61. return nil, fmt.Errorf("failed to acquire lease: %v", err)
  62. }
  63. return n, nil
  64. }