network.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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. // Search for route with same Dst Address and Interface
  81. routeAf := netlink.FAMILY_V4
  82. // XXX Comment this in as soon as we have net library with IP.To4()
  83. //
  84. // routeAf := netlink.FAMILY_V6
  85. // if route.Dst.To4() != nil {
  86. // routeAf = netlink.FAMILY_V4
  87. // }
  88. routeList, err := netlink.RouteListFiltered(routeAf, &netlink.Route{
  89. Dst: route.Dst,
  90. LinkIndex: route.LinkIndex,
  91. }, netlink.RT_FILTER_DST|netlink.RT_FILTER_OIF)
  92. if err != nil {
  93. log.Warningf("Unable to list routes: %v", err)
  94. }
  95. // Check match on Dst for match on Gw
  96. if len(routeList) > 0 && !routeList[0].Gw.Equal(route.Gw) {
  97. // Same Dst different Gw. Remove it, correct route will be added below.
  98. 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)
  99. if err := netlink.RouteDel(&route); err != nil {
  100. log.Errorf("Error deleting route to %v: %v", evt.Lease.Subnet, err)
  101. continue
  102. }
  103. }
  104. if len(routeList) > 0 && routeList[0].Gw.Equal(route.Gw) {
  105. // Same Dst and same Gw, keep it and do not attempt to add it.
  106. log.Infof("Route to %v via %v allready exists, skipping.", evt.Lease.Subnet, evt.Lease.Attrs.PublicIP)
  107. } else if err := netlink.RouteAdd(&route); err != nil {
  108. log.Errorf("Error adding route to %v via %v: %v", evt.Lease.Subnet, evt.Lease.Attrs.PublicIP, err)
  109. continue
  110. }
  111. n.addToRouteList(route)
  112. case subnet.EventRemoved:
  113. log.Info("Subnet removed: ", evt.Lease.Subnet)
  114. if evt.Lease.Attrs.BackendType != "host-gw" {
  115. log.Warningf("Ignoring non-host-gw subnet: type=%v", evt.Lease.Attrs.BackendType)
  116. continue
  117. }
  118. route := netlink.Route{
  119. Dst: evt.Lease.Subnet.ToIPNet(),
  120. Gw: evt.Lease.Attrs.PublicIP.ToIP(),
  121. LinkIndex: n.linkIndex,
  122. }
  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. n.removeFromRouteList(route)
  128. default:
  129. log.Error("Internal error: unknown event type: ", int(evt.Type))
  130. }
  131. }
  132. }
  133. func (n *network) addToRouteList(route netlink.Route) {
  134. n.rl = append(n.rl, route)
  135. }
  136. func (n *network) removeFromRouteList(route netlink.Route) {
  137. for index, r := range n.rl {
  138. if routeEqual(r, route) {
  139. n.rl = append(n.rl[:index], n.rl[index+1:]...)
  140. return
  141. }
  142. }
  143. }
  144. func (n *network) routeCheck(ctx context.Context) {
  145. for {
  146. select {
  147. case <-ctx.Done():
  148. return
  149. case <-time.After(routeCheckRetries * time.Second):
  150. n.checkSubnetExistInRoutes()
  151. }
  152. }
  153. }
  154. func (n *network) checkSubnetExistInRoutes() {
  155. routeList, err := netlink.RouteList(nil, netlink.FAMILY_V4)
  156. if err == nil {
  157. for _, route := range n.rl {
  158. exist := false
  159. for _, r := range routeList {
  160. if r.Dst == nil {
  161. continue
  162. }
  163. if routeEqual(r, route) {
  164. exist = true
  165. break
  166. }
  167. }
  168. if !exist {
  169. if err := netlink.RouteAdd(&route); err != nil {
  170. if nerr, ok := err.(net.Error); !ok {
  171. log.Errorf("Error recovering route to %v: %v, %v", route.Dst, route.Gw, nerr)
  172. }
  173. continue
  174. } else {
  175. log.Infof("Route recovered %v : %v", route.Dst, route.Gw)
  176. }
  177. }
  178. }
  179. }
  180. }
  181. func routeEqual(x, y netlink.Route) bool {
  182. if x.Dst.IP.Equal(y.Dst.IP) && x.Gw.Equal(y.Gw) && bytes.Equal(x.Dst.Mask, y.Dst.Mask) {
  183. return true
  184. }
  185. return false
  186. }