udp_network.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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. "fmt"
  17. "net"
  18. "os"
  19. "sync"
  20. "syscall"
  21. log "github.com/golang/glog"
  22. "github.com/vishvananda/netlink"
  23. "golang.org/x/net/context"
  24. "github.com/coreos/flannel/backend"
  25. "github.com/coreos/flannel/pkg/ip"
  26. "github.com/coreos/flannel/subnet"
  27. )
  28. const (
  29. encapOverhead = 28 // 20 bytes IP hdr + 8 bytes UDP hdr
  30. )
  31. type network struct {
  32. backend.SimpleNetwork
  33. name string
  34. port int
  35. ctl *os.File
  36. ctl2 *os.File
  37. tun *os.File
  38. conn *net.UDPConn
  39. tunNet ip.IP4Net
  40. sm subnet.Manager
  41. }
  42. func newNetwork(sm subnet.Manager, extIface *backend.ExternalInterface, port int, nw ip.IP4Net, l *subnet.Lease) (*network, error) {
  43. n := &network{
  44. SimpleNetwork: backend.SimpleNetwork{
  45. SubnetLease: l,
  46. ExtIface: extIface,
  47. },
  48. port: port,
  49. sm: sm,
  50. }
  51. n.tunNet = nw
  52. if err := n.initTun(); err != nil {
  53. return nil, err
  54. }
  55. var err error
  56. n.conn, err = net.ListenUDP("udp4", &net.UDPAddr{IP: extIface.IfaceAddr, Port: port})
  57. if err != nil {
  58. return nil, fmt.Errorf("failed to start listening on UDP socket: %v", err)
  59. }
  60. n.ctl, n.ctl2, err = newCtlSockets()
  61. if err != nil {
  62. return nil, fmt.Errorf("failed to create control socket: %v", err)
  63. }
  64. return n, nil
  65. }
  66. func (n *network) Run(ctx context.Context) {
  67. defer func() {
  68. n.tun.Close()
  69. n.conn.Close()
  70. n.ctl.Close()
  71. n.ctl2.Close()
  72. }()
  73. // one for each goroutine below
  74. wg := sync.WaitGroup{}
  75. defer wg.Wait()
  76. wg.Add(1)
  77. go func() {
  78. runCProxy(n.tun, n.conn, n.ctl2, n.tunNet.IP, n.MTU())
  79. wg.Done()
  80. }()
  81. log.Info("Watching for new subnet leases")
  82. evts := make(chan []subnet.Event)
  83. wg.Add(1)
  84. go func() {
  85. subnet.WatchLeases(ctx, n.sm, n.SubnetLease, evts)
  86. wg.Done()
  87. }()
  88. for {
  89. select {
  90. case evtBatch := <-evts:
  91. n.processSubnetEvents(evtBatch)
  92. case <-ctx.Done():
  93. stopProxy(n.ctl)
  94. return
  95. }
  96. }
  97. }
  98. func (n *network) MTU() int {
  99. return n.ExtIface.Iface.MTU - encapOverhead
  100. }
  101. func newCtlSockets() (*os.File, *os.File, error) {
  102. fds, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_SEQPACKET, 0)
  103. if err != nil {
  104. return nil, nil, err
  105. }
  106. f1 := os.NewFile(uintptr(fds[0]), "ctl")
  107. f2 := os.NewFile(uintptr(fds[1]), "ctl")
  108. return f1, f2, nil
  109. }
  110. func (n *network) initTun() error {
  111. var tunName string
  112. var err error
  113. n.tun, tunName, err = ip.OpenTun("flannel%d")
  114. if err != nil {
  115. return fmt.Errorf("failed to open TUN device: %v", err)
  116. }
  117. err = configureIface(tunName, n.tunNet, n.MTU())
  118. return err
  119. }
  120. func configureIface(ifname string, ipn ip.IP4Net, mtu int) error {
  121. iface, err := netlink.LinkByName(ifname)
  122. if err != nil {
  123. return fmt.Errorf("failed to lookup interface %v", ifname)
  124. }
  125. err = netlink.AddrAdd(iface, &netlink.Addr{IPNet: ipn.ToIPNet(), Label: ""})
  126. if err != nil {
  127. return fmt.Errorf("failed to add IP address %v to %v: %v", ipn.String(), ifname, err)
  128. }
  129. err = netlink.LinkSetMTU(iface, mtu)
  130. if err != nil {
  131. return fmt.Errorf("failed to set MTU for %v: %v", ifname, err)
  132. }
  133. err = netlink.LinkSetUp(iface)
  134. if err != nil {
  135. return fmt.Errorf("failed to set interface %v to UP state: %v", ifname, err)
  136. }
  137. // explicitly add a route since there might be a route for a subnet already
  138. // installed by Docker and then it won't get auto added
  139. err = netlink.RouteAdd(&netlink.Route{
  140. LinkIndex: iface.Attrs().Index,
  141. Scope: netlink.SCOPE_UNIVERSE,
  142. Dst: ipn.Network().ToIPNet(),
  143. })
  144. if err != nil && err != syscall.EEXIST {
  145. return fmt.Errorf("failed to add route (%v -> %v): %v", ipn.Network().String(), ifname, err)
  146. }
  147. return nil
  148. }
  149. func (n *network) processSubnetEvents(batch []subnet.Event) {
  150. for _, evt := range batch {
  151. switch evt.Type {
  152. case subnet.EventAdded:
  153. log.Info("Subnet added: ", evt.Lease.Subnet)
  154. setRoute(n.ctl, evt.Lease.Subnet, evt.Lease.Attrs.PublicIP, n.port)
  155. case subnet.EventRemoved:
  156. log.Info("Subnet removed: ", evt.Lease.Subnet)
  157. removeRoute(n.ctl, evt.Lease.Subnet)
  158. default:
  159. log.Error("Internal error: unknown event type: ", int(evt.Type))
  160. }
  161. }
  162. }