hostgw_network.go 5.6 KB

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