network.go 5.1 KB

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