hostgw_network.go 5.6 KB

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