route_network.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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. "golang.org/x/net/context"
  22. "github.com/flannel-io/flannel/subnet"
  23. "github.com/vishvananda/netlink"
  24. log "k8s.io/klog"
  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, ok := <-evts:
  60. if !ok {
  61. log.Infof("evts chan closed")
  62. return
  63. }
  64. n.handleSubnetEvents(evtBatch)
  65. }
  66. }
  67. }
  68. func (n *RouteNetwork) handleSubnetEvents(batch []subnet.Event) {
  69. for _, evt := range batch {
  70. switch evt.Type {
  71. case subnet.EventAdded:
  72. log.Infof("Subnet added: %v via %v", evt.Lease.Subnet, evt.Lease.Attrs.PublicIP)
  73. if evt.Lease.Attrs.BackendType != n.BackendType {
  74. log.Warningf("Ignoring non-%v subnet: type=%v", n.BackendType, evt.Lease.Attrs.BackendType)
  75. continue
  76. }
  77. route := n.GetRoute(&evt.Lease)
  78. n.addToRouteList(*route)
  79. // Check if route exists before attempting to add it
  80. routeList, err := netlink.RouteListFiltered(netlink.FAMILY_V4, &netlink.Route{Dst: route.Dst}, netlink.RT_FILTER_DST)
  81. if err != nil {
  82. log.Warningf("Unable to list routes: %v", err)
  83. }
  84. if len(routeList) > 0 && !routeEqual(routeList[0], *route) {
  85. // Same Dst different Gw or different link index. Remove it, correct route will be added below.
  86. 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)
  87. if err := netlink.RouteDel(&routeList[0]); err != nil {
  88. log.Errorf("Error deleting route to %v: %v", evt.Lease.Subnet, err)
  89. continue
  90. }
  91. n.removeFromRouteList(routeList[0])
  92. }
  93. if len(routeList) > 0 && routeEqual(routeList[0], *route) {
  94. // Same Dst and same Gw, keep it and do not attempt to add it.
  95. log.Infof("Route to %v via %v dev index %d already exists, skipping.", evt.Lease.Subnet, evt.Lease.Attrs.PublicIP, routeList[0].LinkIndex)
  96. } else if err := netlink.RouteAdd(route); err != nil {
  97. log.Errorf("Error adding route to %v via %v dev index %d: %v", evt.Lease.Subnet, evt.Lease.Attrs.PublicIP, route.LinkIndex, err)
  98. continue
  99. }
  100. case subnet.EventRemoved:
  101. log.Info("Subnet removed: ", evt.Lease.Subnet)
  102. if evt.Lease.Attrs.BackendType != n.BackendType {
  103. log.Warningf("Ignoring non-%v subnet: type=%v", n.BackendType, evt.Lease.Attrs.BackendType)
  104. continue
  105. }
  106. route := n.GetRoute(&evt.Lease)
  107. // Always remove the route from the route list.
  108. n.removeFromRouteList(*route)
  109. if err := netlink.RouteDel(route); err != nil {
  110. log.Errorf("Error deleting route to %v: %v", evt.Lease.Subnet, err)
  111. continue
  112. }
  113. default:
  114. log.Error("Internal error: unknown event type: ", int(evt.Type))
  115. }
  116. }
  117. }
  118. func (n *RouteNetwork) addToRouteList(route netlink.Route) {
  119. for _, r := range n.routes {
  120. if routeEqual(r, route) {
  121. return
  122. }
  123. }
  124. n.routes = append(n.routes, route)
  125. }
  126. func (n *RouteNetwork) removeFromRouteList(route netlink.Route) {
  127. for index, r := range n.routes {
  128. if routeEqual(r, route) {
  129. n.routes = append(n.routes[:index], n.routes[index+1:]...)
  130. return
  131. }
  132. }
  133. }
  134. func (n *RouteNetwork) routeCheck(ctx context.Context) {
  135. for {
  136. select {
  137. case <-ctx.Done():
  138. return
  139. case <-time.After(routeCheckRetries * time.Second):
  140. n.checkSubnetExistInRoutes()
  141. }
  142. }
  143. }
  144. func (n *RouteNetwork) checkSubnetExistInRoutes() {
  145. routeList, err := netlink.RouteList(nil, netlink.FAMILY_V4)
  146. if err == nil {
  147. for _, route := range n.routes {
  148. exist := false
  149. for _, r := range routeList {
  150. if r.Dst == nil {
  151. continue
  152. }
  153. if routeEqual(r, route) {
  154. exist = true
  155. break
  156. }
  157. }
  158. if !exist {
  159. if err := netlink.RouteAdd(&route); err != nil {
  160. if nerr, ok := err.(net.Error); !ok {
  161. log.Errorf("Error recovering route to %v: %v, %v", route.Dst, route.Gw, nerr)
  162. }
  163. continue
  164. } else {
  165. log.Infof("Route recovered %v : %v", route.Dst, route.Gw)
  166. }
  167. }
  168. }
  169. } else {
  170. log.Errorf("Error fetching route list. Will automatically retry: %v", err)
  171. }
  172. }
  173. func routeEqual(x, y netlink.Route) bool {
  174. // For ipip backend, when enabling directrouting, link index of some routes may change
  175. // For both ipip and host-gw backend, link index may also change if updating ExtIface
  176. 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 {
  177. return true
  178. }
  179. return false
  180. }