alloc.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 alloc
  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("alloc", New)
  24. }
  25. type AllocBackend struct {
  26. sm subnet.Manager
  27. extIface *backend.ExternalInterface
  28. }
  29. func New(sm subnet.Manager, extIface *backend.ExternalInterface) (backend.Backend, error) {
  30. be := AllocBackend{
  31. sm: sm,
  32. extIface: extIface,
  33. }
  34. return &be, nil
  35. }
  36. func (be *AllocBackend) RegisterNetwork(ctx context.Context, config *subnet.Config) (backend.Network, error) {
  37. attrs := subnet.LeaseAttrs{
  38. PublicIP: ip.FromIP(be.extIface.ExtAddr),
  39. }
  40. l, err := be.sm.AcquireLease(ctx, &attrs)
  41. switch err {
  42. case nil:
  43. return &backend.SimpleNetwork{
  44. SubnetLease: l,
  45. ExtIface: be.extIface,
  46. }, nil
  47. case context.Canceled, context.DeadlineExceeded:
  48. return nil, err
  49. default:
  50. return nil, fmt.Errorf("failed to acquire lease: %v", err)
  51. }
  52. }