udp_network_amd64.go 4.5 KB

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