alloc.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package alloc
  2. import (
  3. "fmt"
  4. "net"
  5. "github.com/coreos/flannel/Godeps/_workspace/src/golang.org/x/net/context"
  6. "github.com/coreos/flannel/backend"
  7. "github.com/coreos/flannel/pkg/ip"
  8. "github.com/coreos/flannel/subnet"
  9. )
  10. type AllocBackend struct {
  11. sm subnet.Manager
  12. network string
  13. lease *subnet.Lease
  14. ctx context.Context
  15. cancel context.CancelFunc
  16. }
  17. func New(sm subnet.Manager, network string) backend.Backend {
  18. ctx, cancel := context.WithCancel(context.Background())
  19. return &AllocBackend{
  20. sm: sm,
  21. network: network,
  22. ctx: ctx,
  23. cancel: cancel,
  24. }
  25. }
  26. func (m *AllocBackend) Init(extIface *net.Interface, extIP net.IP) (*backend.SubnetDef, error) {
  27. attrs := subnet.LeaseAttrs{
  28. PublicIP: ip.FromIP(extIP),
  29. }
  30. l, err := m.sm.AcquireLease(m.ctx, m.network, &attrs)
  31. switch err {
  32. case nil:
  33. m.lease = l
  34. return &backend.SubnetDef{
  35. Net: l.Subnet,
  36. MTU: extIface.MTU,
  37. }, nil
  38. case context.Canceled, context.DeadlineExceeded:
  39. return nil, err
  40. default:
  41. return nil, fmt.Errorf("failed to acquire lease: %v", err)
  42. }
  43. }
  44. func (m *AllocBackend) Run() {
  45. subnet.LeaseRenewer(m.ctx, m.sm, m.network, m.lease)
  46. }
  47. func (m *AllocBackend) Stop() {
  48. m.cancel()
  49. }
  50. func (m *AllocBackend) Name() string {
  51. return "allocation"
  52. }