hostgw.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. package hostgw
  15. import (
  16. "fmt"
  17. "github.com/coreos/flannel/backend"
  18. "github.com/coreos/flannel/pkg/ip"
  19. "github.com/coreos/flannel/subnet"
  20. "golang.org/x/net/context"
  21. )
  22. func init() {
  23. backend.Register("host-gw", New)
  24. }
  25. const (
  26. routeCheckRetries = 10
  27. )
  28. type HostgwBackend struct {
  29. sm subnet.Manager
  30. extIface *backend.ExternalInterface
  31. networks map[string]*network
  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. networks: make(map[string]*network),
  41. }
  42. return be, nil
  43. }
  44. func (_ *HostgwBackend) Run(ctx context.Context) {
  45. <-ctx.Done()
  46. }
  47. func (be *HostgwBackend) RegisterNetwork(ctx context.Context, netname string, config *subnet.Config) (backend.Network, error) {
  48. n := &network{
  49. name: netname,
  50. extIface: be.extIface,
  51. sm: be.sm,
  52. }
  53. attrs := subnet.LeaseAttrs{
  54. PublicIP: ip.FromIP(be.extIface.ExtAddr),
  55. BackendType: "host-gw",
  56. }
  57. l, err := be.sm.AcquireLease(ctx, netname, &attrs)
  58. switch err {
  59. case nil:
  60. n.lease = l
  61. case context.Canceled, context.DeadlineExceeded:
  62. return nil, err
  63. default:
  64. return nil, fmt.Errorf("failed to acquire lease: %v", err)
  65. }
  66. /* NB: docker will create the local route to `sn` */
  67. be.networks[netname] = n
  68. return n, nil
  69. }