udp.go 5.9 KB

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