hostgw_network.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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. n.rl = make([]netlink.Route, 0, 10)
  52. wg.Add(1)
  53. go func() {
  54. n.routeCheck(ctx)
  55. wg.Done()
  56. }()
  57. defer wg.Wait()
  58. for {
  59. select {
  60. case evtBatch := <-evts:
  61. n.handleSubnetEvents(evtBatch)
  62. case <-ctx.Done():
  63. return
  64. }
  65. }
  66. }
  67. func (n *network) handleSubnetEvents(batch []subnet.Event) {
  68. for _, evt := range batch {
  69. switch evt.Type {
  70. case subnet.EventAdded:
  71. log.Infof("Subnet added: %v via %v", evt.Lease.Subnet, evt.Lease.Attrs.PublicIP)
  72. if evt.Lease.Attrs.BackendType != "host-gw" {
  73. log.Warningf("Ignoring non-host-gw subnet: type=%v", evt.Lease.Attrs.BackendType)
  74. continue
  75. }
  76. route := netlink.Route{
  77. Dst: evt.Lease.Subnet.ToIPNet(),
  78. Gw: evt.Lease.Attrs.PublicIP.ToIP(),
  79. LinkIndex: n.LinkIndex(),
  80. }
  81. // Check if route exists before attempting to add it
  82. routeList, err := netlink.RouteListFiltered(netlink.FAMILY_V4, &netlink.Route{
  83. Dst: route.Dst,
  84. }, netlink.RT_FILTER_DST)
  85. if err != nil {
  86. log.Warningf("Unable to list routes: %v", err)
  87. }
  88. // Check match on Dst for match on Gw
  89. if len(routeList) > 0 && !routeList[0].Gw.Equal(route.Gw) {
  90. // Same Dst different Gw. Remove it, correct route will be added below.
  91. 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)
  92. if err := netlink.RouteDel(&routeList[0]); err != nil {
  93. log.Errorf("Error deleting route to %v: %v", evt.Lease.Subnet, err)
  94. continue
  95. }
  96. }
  97. if len(routeList) > 0 && routeList[0].Gw.Equal(route.Gw) {
  98. // Same Dst and same Gw, keep it and do not attempt to add it.
  99. log.Infof("Route to %v via %v already exists, skipping.", evt.Lease.Subnet, evt.Lease.Attrs.PublicIP)
  100. } else if err := netlink.RouteAdd(&route); err != nil {
  101. log.Errorf("Error adding route to %v via %v: %v", evt.Lease.Subnet, evt.Lease.Attrs.PublicIP, err)
  102. continue
  103. }
  104. n.addToRouteList(route)
  105. case subnet.EventRemoved:
  106. log.Info("Subnet removed: ", evt.Lease.Subnet)
  107. if evt.Lease.Attrs.BackendType != "host-gw" {
  108. log.Warningf("Ignoring non-host-gw subnet: type=%v", evt.Lease.Attrs.BackendType)
  109. continue
  110. }
  111. route := netlink.Route{
  112. Dst: evt.Lease.Subnet.ToIPNet(),
  113. Gw: evt.Lease.Attrs.PublicIP.ToIP(),
  114. LinkIndex: n.LinkIndex(),
  115. }
  116. if err := netlink.RouteDel(&route); err != nil {
  117. log.Errorf("Error deleting route to %v: %v", evt.Lease.Subnet, err)
  118. continue
  119. }
  120. n.removeFromRouteList(route)
  121. default:
  122. log.Error("Internal error: unknown event type: ", int(evt.Type))
  123. }
  124. }
  125. }
  126. func (n *network) addToRouteList(route netlink.Route) {
  127. for _, r := range n.rl {
  128. if routeEqual(r, route) {
  129. return
  130. }
  131. }
  132. n.rl = append(n.rl, route)
  133. }
  134. func (n *network) removeFromRouteList(route netlink.Route) {
  135. for index, r := range n.rl {
  136. if routeEqual(r, route) {
  137. n.rl = append(n.rl[:index], n.rl[index+1:]...)
  138. return
  139. }
  140. }
  141. }
  142. func (n *network) routeCheck(ctx context.Context) {
  143. for {
  144. select {
  145. case <-ctx.Done():
  146. return
  147. case <-time.After(routeCheckRetries * time.Second):
  148. n.checkSubnetExistInRoutes()
  149. }
  150. }
  151. }
  152. func (n *network) checkSubnetExistInRoutes() {
  153. routeList, err := netlink.RouteList(nil, netlink.FAMILY_V4)
  154. if err == nil {
  155. for _, route := range n.rl {
  156. exist := false
  157. for _, r := range routeList {
  158. if r.Dst == nil {
  159. continue
  160. }
  161. if routeEqual(r, route) {
  162. exist = true
  163. break
  164. }
  165. }
  166. if !exist {
  167. if err := netlink.RouteAdd(&route); err != nil {
  168. if nerr, ok := err.(net.Error); !ok {
  169. log.Errorf("Error recovering route to %v: %v, %v", route.Dst, route.Gw, nerr)
  170. }
  171. continue
  172. } else {
  173. log.Infof("Route recovered %v : %v", route.Dst, route.Gw)
  174. }
  175. }
  176. }
  177. }
  178. }
  179. func routeEqual(x, y netlink.Route) bool {
  180. if x.Dst.IP.Equal(y.Dst.IP) && x.Gw.Equal(y.Gw) && bytes.Equal(x.Dst.Mask, y.Dst.Mask) {
  181. return true
  182. }
  183. return false
  184. }