route_network.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. // +build !windows
  2. // Copyright 2017 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. package backend
  16. import (
  17. "bytes"
  18. "net"
  19. "sync"
  20. "time"
  21. log "github.com/golang/glog"
  22. "golang.org/x/net/context"
  23. "github.com/coreos/flannel/subnet"
  24. "github.com/vishvananda/netlink"
  25. )
  26. const (
  27. routeCheckRetries = 10
  28. )
  29. type RouteNetwork struct {
  30. SimpleNetwork
  31. BackendType string
  32. routes []netlink.Route
  33. SM subnet.Manager
  34. GetRoute func(lease *subnet.Lease) *netlink.Route
  35. Mtu int
  36. LinkIndex int
  37. }
  38. func (n *RouteNetwork) MTU() int {
  39. return n.Mtu
  40. }
  41. func (n *RouteNetwork) Run(ctx context.Context) {
  42. wg := sync.WaitGroup{}
  43. log.Info("Watching for new subnet leases")
  44. evts := make(chan []subnet.Event)
  45. wg.Add(1)
  46. go func() {
  47. subnet.WatchLeases(ctx, n.SM, n.SubnetLease, evts)
  48. wg.Done()
  49. }()
  50. n.routes = make([]netlink.Route, 0, 10)
  51. wg.Add(1)
  52. go func() {
  53. n.routeCheck(ctx)
  54. wg.Done()
  55. }()
  56. defer wg.Wait()
  57. for {
  58. select {
  59. case evtBatch := <-evts:
  60. n.handleSubnetEvents(evtBatch)
  61. case <-ctx.Done():
  62. return
  63. }
  64. }
  65. }
  66. func (n *RouteNetwork) handleSubnetEvents(batch []subnet.Event) {
  67. for _, evt := range batch {
  68. switch evt.Type {
  69. case subnet.EventAdded:
  70. log.Infof("Subnet added: %v via %v", evt.Lease.Subnet, evt.Lease.Attrs.PublicIP)
  71. if evt.Lease.Attrs.BackendType != n.BackendType {
  72. log.Warningf("Ignoring non-%v subnet: type=%v", n.BackendType, evt.Lease.Attrs.BackendType)
  73. continue
  74. }
  75. route := n.GetRoute(&evt.Lease)
  76. n.addToRouteList(*route)
  77. // Check if route exists before attempting to add it
  78. routeList, err := netlink.RouteListFiltered(netlink.FAMILY_V4, &netlink.Route{Dst: route.Dst}, netlink.RT_FILTER_DST)
  79. if err != nil {
  80. log.Warningf("Unable to list routes: %v", err)
  81. }
  82. if len(routeList) > 0 && !routeEqual(routeList[0], *route) {
  83. // Same Dst different Gw or different link index. Remove it, correct route will be added below.
  84. log.Warningf("Replacing existing route to %v via %v dev index %d with %v via %v dev index %d.", evt.Lease.Subnet, routeList[0].Gw, routeList[0].LinkIndex, evt.Lease.Subnet, evt.Lease.Attrs.PublicIP, route.LinkIndex)
  85. if err := netlink.RouteDel(&routeList[0]); err != nil {
  86. log.Errorf("Error deleting route to %v: %v", evt.Lease.Subnet, err)
  87. continue
  88. }
  89. n.removeFromRouteList(routeList[0])
  90. }
  91. if len(routeList) > 0 && routeEqual(routeList[0], *route) {
  92. // Same Dst and same Gw, keep it and do not attempt to add it.
  93. log.Infof("Route to %v via %v dev index %d already exists, skipping.", evt.Lease.Subnet, evt.Lease.Attrs.PublicIP, routeList[0].LinkIndex)
  94. } else if err := netlink.RouteAdd(route); err != nil {
  95. log.Errorf("Error adding route to %v via %v dev index %d: %v", evt.Lease.Subnet, evt.Lease.Attrs.PublicIP, route.LinkIndex, err)
  96. continue
  97. }
  98. case subnet.EventRemoved:
  99. log.Info("Subnet removed: ", evt.Lease.Subnet)
  100. if evt.Lease.Attrs.BackendType != n.BackendType {
  101. log.Warningf("Ignoring non-%v subnet: type=%v", n.BackendType, evt.Lease.Attrs.BackendType)
  102. continue
  103. }
  104. route := n.GetRoute(&evt.Lease)
  105. // Always remove the route from the route list.
  106. n.removeFromRouteList(*route)
  107. if err := netlink.RouteDel(route); err != nil {
  108. log.Errorf("Error deleting route to %v: %v", evt.Lease.Subnet, err)
  109. continue
  110. }
  111. default:
  112. log.Error("Internal error: unknown event type: ", int(evt.Type))
  113. }
  114. }
  115. }
  116. func (n *RouteNetwork) addToRouteList(route netlink.Route) {
  117. for _, r := range n.routes {
  118. if routeEqual(r, route) {
  119. return
  120. }
  121. }
  122. n.routes = append(n.routes, route)
  123. }
  124. func (n *RouteNetwork) removeFromRouteList(route netlink.Route) {
  125. for index, r := range n.routes {
  126. if routeEqual(r, route) {
  127. n.routes = append(n.routes[:index], n.routes[index+1:]...)
  128. return
  129. }
  130. }
  131. }
  132. func (n *RouteNetwork) routeCheck(ctx context.Context) {
  133. for {
  134. select {
  135. case <-ctx.Done():
  136. return
  137. case <-time.After(routeCheckRetries * time.Second):
  138. n.checkSubnetExistInRoutes()
  139. }
  140. }
  141. }
  142. func (n *RouteNetwork) checkSubnetExistInRoutes() {
  143. routeList, err := netlink.RouteList(nil, netlink.FAMILY_V4)
  144. if err == nil {
  145. for _, route := range n.routes {
  146. exist := false
  147. for _, r := range routeList {
  148. if r.Dst == nil {
  149. continue
  150. }
  151. if routeEqual(r, route) {
  152. exist = true
  153. break
  154. }
  155. }
  156. if !exist {
  157. if err := netlink.RouteAdd(&route); err != nil {
  158. if nerr, ok := err.(net.Error); !ok {
  159. log.Errorf("Error recovering route to %v: %v, %v", route.Dst, route.Gw, nerr)
  160. }
  161. continue
  162. } else {
  163. log.Infof("Route recovered %v : %v", route.Dst, route.Gw)
  164. }
  165. }
  166. }
  167. } else {
  168. log.Errorf("Error fetching route list. Will automatically retry: %v", err)
  169. }
  170. }
  171. func routeEqual(x, y netlink.Route) bool {
  172. // For ipip backend, when enabling directrouting, link index of some routes may change
  173. // For both ipip and host-gw backend, link index may also change if updating ExtIface
  174. if x.Dst.IP.Equal(y.Dst.IP) && x.Gw.Equal(y.Gw) && bytes.Equal(x.Dst.Mask, y.Dst.Mask) && x.LinkIndex == y.LinkIndex {
  175. return true
  176. }
  177. return false
  178. }