udp.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. "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. publicIP ip.IP4
  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, extIface *net.Interface, extIaddr net.IP, extEaddr net.IP) (backend.Backend, error) {
  49. be := UdpBackend{
  50. sm: sm,
  51. publicIP: ip.FromIP(extEaddr),
  52. // TUN MTU will be smaller b/c of encap (IP+UDP hdrs)
  53. mtu: extIface.MTU - encapOverhead,
  54. }
  55. be.cfg.Port = defaultPort
  56. return &be, nil
  57. }
  58. func (m *UdpBackend) RegisterNetwork(ctx context.Context, network string, config *subnet.Config) (*backend.SubnetDef, error) {
  59. m.network = network
  60. // Parse our configuration
  61. if len(config.Backend) > 0 {
  62. if err := json.Unmarshal(config.Backend, &m.cfg); err != nil {
  63. return nil, fmt.Errorf("error decoding UDP backend config: %v", err)
  64. }
  65. }
  66. // Acquire the lease form subnet manager
  67. attrs := subnet.LeaseAttrs{
  68. PublicIP: m.publicIP,
  69. }
  70. l, err := m.sm.AcquireLease(ctx, m.network, &attrs)
  71. switch err {
  72. case nil:
  73. m.lease = l
  74. case context.Canceled, context.DeadlineExceeded:
  75. return nil, err
  76. default:
  77. return nil, fmt.Errorf("failed to acquire lease: %v", err)
  78. }
  79. // Tunnel's subnet is that of the whole overlay network (e.g. /16)
  80. // and not that of the individual host (e.g. /24)
  81. m.tunNet = ip.IP4Net{
  82. IP: l.Subnet.IP,
  83. PrefixLen: config.Network.PrefixLen,
  84. }
  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 (m *UdpBackend) UnregisterNetwork(ctx context.Context, name string) {
  128. }
  129. func newCtlSockets() (*os.File, *os.File, error) {
  130. fds, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_SEQPACKET, 0)
  131. if err != nil {
  132. return nil, nil, err
  133. }
  134. f1 := os.NewFile(uintptr(fds[0]), "ctl")
  135. f2 := os.NewFile(uintptr(fds[1]), "ctl")
  136. return f1, f2, nil
  137. }
  138. func (m *UdpBackend) initTun() error {
  139. var tunName string
  140. var err error
  141. m.tun, tunName, err = ip.OpenTun("flannel%d")
  142. if err != nil {
  143. return fmt.Errorf("Failed to open TUN device: %v", err)
  144. }
  145. err = configureIface(tunName, m.tunNet, m.mtu)
  146. if err != nil {
  147. return err
  148. }
  149. return nil
  150. }
  151. func configureIface(ifname string, ipn ip.IP4Net, mtu int) error {
  152. iface, err := netlink.LinkByName(ifname)
  153. if err != nil {
  154. return fmt.Errorf("failed to lookup interface %v", ifname)
  155. }
  156. err = netlink.AddrAdd(iface, &netlink.Addr{ipn.ToIPNet(), ""})
  157. if err != nil {
  158. return fmt.Errorf("failed to add IP address %v to %v: %v", ipn.String(), ifname, err)
  159. }
  160. err = netlink.LinkSetMTU(iface, mtu)
  161. if err != nil {
  162. return fmt.Errorf("failed to set MTU for %v: %v", ifname, err)
  163. }
  164. err = netlink.LinkSetUp(iface)
  165. if err != nil {
  166. return fmt.Errorf("failed to set interface %v to UP state: %v", ifname, err)
  167. }
  168. // explicitly add a route since there might be a route for a subnet already
  169. // installed by Docker and then it won't get auto added
  170. err = netlink.RouteAdd(&netlink.Route{
  171. LinkIndex: iface.Attrs().Index,
  172. Scope: netlink.SCOPE_UNIVERSE,
  173. Dst: ipn.Network().ToIPNet(),
  174. })
  175. if err != nil && err != syscall.EEXIST {
  176. return fmt.Errorf("Failed to add route (%v -> %v): %v", ipn.Network().String(), ifname, err)
  177. }
  178. return nil
  179. }
  180. func (m *UdpBackend) processSubnetEvents(batch []subnet.Event) {
  181. for _, evt := range batch {
  182. switch evt.Type {
  183. case subnet.EventAdded:
  184. log.Info("Subnet added: ", evt.Lease.Subnet)
  185. setRoute(m.ctl, evt.Lease.Subnet, evt.Lease.Attrs.PublicIP, m.cfg.Port)
  186. case subnet.EventRemoved:
  187. log.Info("Subnet removed: ", evt.Lease.Subnet)
  188. removeRoute(m.ctl, evt.Lease.Subnet)
  189. default:
  190. log.Error("Internal error: unknown event type: ", int(evt.Type))
  191. }
  192. }
  193. }