hostgw_network.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. n.removeFromRouteList(routeList[0])
  101. }
  102. if len(routeList) > 0 && routeList[0].Gw.Equal(route.Gw) {
  103. // Same Dst and same Gw, keep it and do not attempt to add it.
  104. log.Infof("Route to %v via %v already exists, skipping.", evt.Lease.Subnet, evt.Lease.Attrs.PublicIP)
  105. } else if err := netlink.RouteAdd(&route); err != nil {
  106. log.Errorf("Error adding route to %v via %v: %v", evt.Lease.Subnet, evt.Lease.Attrs.PublicIP, err)
  107. continue
  108. }
  109. case subnet.EventRemoved:
  110. log.Info("Subnet removed: ", evt.Lease.Subnet)
  111. if evt.Lease.Attrs.BackendType != "host-gw" {
  112. log.Warningf("Ignoring non-host-gw subnet: type=%v", evt.Lease.Attrs.BackendType)
  113. continue
  114. }
  115. route := netlink.Route{
  116. Dst: evt.Lease.Subnet.ToIPNet(),
  117. Gw: evt.Lease.Attrs.PublicIP.ToIP(),
  118. LinkIndex: n.LinkIndex(),
  119. }
  120. // Always remove the route from the route list.
  121. n.removeFromRouteList(route)
  122. if err := netlink.RouteDel(&route); err != nil {
  123. log.Errorf("Error deleting route to %v: %v", evt.Lease.Subnet, err)
  124. continue
  125. }
  126. default:
  127. log.Error("Internal error: unknown event type: ", int(evt.Type))
  128. }
  129. }
  130. }
  131. func (n *network) addToRouteList(route netlink.Route) {
  132. for _, r := range n.rl {
  133. if routeEqual(r, route) {
  134. return
  135. }
  136. }
  137. n.rl = append(n.rl, route)
  138. }
  139. func (n *network) removeFromRouteList(route netlink.Route) {
  140. for index, r := range n.rl {
  141. if routeEqual(r, route) {
  142. n.rl = append(n.rl[:index], n.rl[index+1:]...)
  143. return
  144. }
  145. }
  146. }
  147. func (n *network) routeCheck(ctx context.Context) {
  148. for {
  149. select {
  150. case <-ctx.Done():
  151. return
  152. case <-time.After(routeCheckRetries * time.Second):
  153. n.checkSubnetExistInRoutes()
  154. }
  155. }
  156. }
  157. func (n *network) checkSubnetExistInRoutes() {
  158. routeList, err := netlink.RouteList(nil, netlink.FAMILY_V4)
  159. if err == nil {
  160. for _, route := range n.rl {
  161. exist := false
  162. for _, r := range routeList {
  163. if r.Dst == nil {
  164. continue
  165. }
  166. if routeEqual(r, route) {
  167. exist = true
  168. break
  169. }
  170. }
  171. if !exist {
  172. if err := netlink.RouteAdd(&route); err != nil {
  173. if nerr, ok := err.(net.Error); !ok {
  174. log.Errorf("Error recovering route to %v: %v, %v", route.Dst, route.Gw, nerr)
  175. }
  176. continue
  177. } else {
  178. log.Infof("Route recovered %v : %v", route.Dst, route.Gw)
  179. }
  180. }
  181. }
  182. } else {
  183. log.Errorf("Error fetching route list. Will automatically retry: %v", err)
  184. }
  185. }
  186. func routeEqual(x, y netlink.Route) bool {
  187. if x.Dst.IP.Equal(y.Dst.IP) && x.Gw.Equal(y.Gw) && bytes.Equal(x.Dst.Mask, y.Dst.Mask) {
  188. return true
  189. }
  190. return false
  191. }