udp.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. // Copyright 2015 CoreOS, Inc.
  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. "net"
  19. "os"
  20. "sync"
  21. "syscall"
  22. log "github.com/coreos/flannel/Godeps/_workspace/src/github.com/golang/glog"
  23. "github.com/coreos/flannel/Godeps/_workspace/src/github.com/vishvananda/netlink"
  24. "github.com/coreos/flannel/Godeps/_workspace/src/golang.org/x/net/context"
  25. "github.com/coreos/flannel/backend"
  26. "github.com/coreos/flannel/pkg/ip"
  27. "github.com/coreos/flannel/subnet"
  28. )
  29. const (
  30. encapOverhead = 28 // 20 bytes IP hdr + 8 bytes UDP hdr
  31. defaultPort = 8285
  32. )
  33. type UdpBackend struct {
  34. sm subnet.Manager
  35. network string
  36. config *subnet.Config
  37. cfg struct {
  38. Port int
  39. }
  40. lease *subnet.Lease
  41. ctl *os.File
  42. ctl2 *os.File
  43. tun *os.File
  44. conn *net.UDPConn
  45. mtu int
  46. tunNet ip.IP4Net
  47. }
  48. func New(sm subnet.Manager, network string, config *subnet.Config) backend.Backend {
  49. be := UdpBackend{
  50. sm: sm,
  51. network: network,
  52. config: config,
  53. }
  54. be.cfg.Port = defaultPort
  55. return &be
  56. }
  57. func (m *UdpBackend) Init(ctx context.Context, extIface *net.Interface, extIaddr net.IP, extEaddr net.IP) (*backend.SubnetDef, error) {
  58. // Parse our configuration
  59. if len(m.config.Backend) > 0 {
  60. if err := json.Unmarshal(m.config.Backend, &m.cfg); err != nil {
  61. return nil, fmt.Errorf("error decoding UDP backend config: %v", err)
  62. }
  63. }
  64. // Acquire the lease form subnet manager
  65. attrs := subnet.LeaseAttrs{
  66. PublicIP: ip.FromIP(extEaddr),
  67. }
  68. l, err := m.sm.AcquireLease(ctx, m.network, &attrs)
  69. switch err {
  70. case nil:
  71. m.lease = l
  72. case context.Canceled, context.DeadlineExceeded:
  73. return nil, err
  74. default:
  75. return nil, fmt.Errorf("failed to acquire lease: %v", err)
  76. }
  77. // Tunnel's subnet is that of the whole overlay network (e.g. /16)
  78. // and not that of the individual host (e.g. /24)
  79. m.tunNet = ip.IP4Net{
  80. IP: l.Subnet.IP,
  81. PrefixLen: m.config.Network.PrefixLen,
  82. }
  83. // TUN MTU will be smaller b/c of encap (IP+UDP hdrs)
  84. m.mtu = extIface.MTU - encapOverhead
  85. if err = m.initTun(); err != nil {
  86. return nil, err
  87. }
  88. m.conn, err = net.ListenUDP("udp4", &net.UDPAddr{Port: m.cfg.Port})
  89. if err != nil {
  90. return nil, fmt.Errorf("failed to start listening on UDP socket: %v", err)
  91. }
  92. m.ctl, m.ctl2, err = newCtlSockets()
  93. if err != nil {
  94. return nil, fmt.Errorf("failed to create control socket: %v", err)
  95. }
  96. return &backend.SubnetDef{
  97. Lease: l,
  98. MTU: m.mtu,
  99. }, nil
  100. }
  101. func (m *UdpBackend) Run(ctx context.Context) {
  102. // one for each goroutine below
  103. wg := sync.WaitGroup{}
  104. wg.Add(1)
  105. go func() {
  106. runCProxy(m.tun, m.conn, m.ctl2, m.tunNet.IP, m.mtu)
  107. wg.Done()
  108. }()
  109. log.Info("Watching for new subnet leases")
  110. evts := make(chan []subnet.Event)
  111. wg.Add(1)
  112. go func() {
  113. subnet.WatchLeases(ctx, m.sm, m.network, m.lease, evts)
  114. wg.Done()
  115. }()
  116. for {
  117. select {
  118. case evtBatch := <-evts:
  119. m.processSubnetEvents(evtBatch)
  120. case <-ctx.Done():
  121. stopProxy(m.ctl)
  122. break
  123. }
  124. }
  125. wg.Wait()
  126. }
  127. func newCtlSockets() (*os.File, *os.File, error) {
  128. fds, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_SEQPACKET, 0)
  129. if err != nil {
  130. return nil, nil, err
  131. }
  132. f1 := os.NewFile(uintptr(fds[0]), "ctl")
  133. f2 := os.NewFile(uintptr(fds[1]), "ctl")
  134. return f1, f2, nil
  135. }
  136. func (m *UdpBackend) initTun() error {
  137. var tunName string
  138. var err error
  139. m.tun, tunName, err = ip.OpenTun("flannel%d")
  140. if err != nil {
  141. return fmt.Errorf("Failed to open TUN device: %v", err)
  142. }
  143. err = configureIface(tunName, m.tunNet, m.mtu)
  144. if err != nil {
  145. return err
  146. }
  147. return nil
  148. }
  149. func configureIface(ifname string, ipn ip.IP4Net, mtu int) error {
  150. iface, err := netlink.LinkByName(ifname)
  151. if err != nil {
  152. return fmt.Errorf("failed to lookup interface %v", ifname)
  153. }
  154. err = netlink.AddrAdd(iface, &netlink.Addr{ipn.ToIPNet(), ""})
  155. if err != nil {
  156. return fmt.Errorf("failed to add IP address %v to %v: %v", ipn.String(), ifname, err)
  157. }
  158. err = netlink.LinkSetMTU(iface, mtu)
  159. if err != nil {
  160. return fmt.Errorf("failed to set MTU for %v: %v", ifname, err)
  161. }
  162. err = netlink.LinkSetUp(iface)
  163. if err != nil {
  164. return fmt.Errorf("failed to set interface %v to UP state: %v", ifname, err)
  165. }
  166. // explicitly add a route since there might be a route for a subnet already
  167. // installed by Docker and then it won't get auto added
  168. err = netlink.RouteAdd(&netlink.Route{
  169. LinkIndex: iface.Attrs().Index,
  170. Scope: netlink.SCOPE_UNIVERSE,
  171. Dst: ipn.Network().ToIPNet(),
  172. })
  173. if err != nil && err != syscall.EEXIST {
  174. return fmt.Errorf("Failed to add route (%v -> %v): %v", ipn.Network().String(), ifname, err)
  175. }
  176. return nil
  177. }
  178. func (m *UdpBackend) processSubnetEvents(batch []subnet.Event) {
  179. for _, evt := range batch {
  180. switch evt.Type {
  181. case subnet.EventAdded:
  182. log.Info("Subnet added: ", evt.Lease.Subnet)
  183. setRoute(m.ctl, evt.Lease.Subnet, evt.Lease.Attrs.PublicIP, m.cfg.Port)
  184. case subnet.EventRemoved:
  185. log.Info("Subnet removed: ", evt.Lease.Subnet)
  186. removeRoute(m.ctl, evt.Lease.Subnet)
  187. default:
  188. log.Error("Internal error: unknown event type: ", int(evt.Type))
  189. }
  190. }
  191. }