udp.go 2.0 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 udp
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "golang.org/x/net/context"
  19. "github.com/coreos/flannel/backend"
  20. "github.com/coreos/flannel/pkg/ip"
  21. "github.com/coreos/flannel/subnet"
  22. )
  23. func init() {
  24. backend.Register("udp", New)
  25. }
  26. const (
  27. defaultPort = 8285
  28. )
  29. type UdpBackend struct {
  30. sm subnet.Manager
  31. extIface *backend.ExternalInterface
  32. }
  33. func New(sm subnet.Manager, extIface *backend.ExternalInterface) (backend.Backend, error) {
  34. be := UdpBackend{
  35. sm: sm,
  36. extIface: extIface,
  37. }
  38. return &be, nil
  39. }
  40. func (be *UdpBackend) RegisterNetwork(ctx context.Context, config *subnet.Config) (backend.Network, error) {
  41. cfg := struct {
  42. Port int
  43. }{
  44. Port: defaultPort,
  45. }
  46. // Parse our configuration
  47. if len(config.Backend) > 0 {
  48. if err := json.Unmarshal(config.Backend, &cfg); err != nil {
  49. return nil, fmt.Errorf("error decoding UDP backend config: %v", err)
  50. }
  51. }
  52. // Acquire the lease form subnet manager
  53. attrs := subnet.LeaseAttrs{
  54. PublicIP: ip.FromIP(be.extIface.ExtAddr),
  55. }
  56. l, err := be.sm.AcquireLease(ctx, &attrs)
  57. switch err {
  58. case nil:
  59. case context.Canceled, context.DeadlineExceeded:
  60. return nil, err
  61. default:
  62. return nil, fmt.Errorf("failed to acquire lease: %v", err)
  63. }
  64. // Tunnel's subnet is that of the whole overlay network (e.g. /16)
  65. // and not that of the individual host (e.g. /24)
  66. tunNet := ip.IP4Net{
  67. IP: l.Subnet.IP,
  68. PrefixLen: config.Network.PrefixLen,
  69. }
  70. return newNetwork(be.sm, be.extIface, cfg.Port, tunNet, l)
  71. }