udp_amd64.go 2.1 KB

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