udp_amd64.go 2.1 KB

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