route_network.go 5.5 KB

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