network.go 4.6 KB

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