hostgw.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. // Copyright 2015 CoreOS, Inc.
  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. "fmt"
  18. "net"
  19. "sync"
  20. "time"
  21. log "github.com/coreos/flannel/Godeps/_workspace/src/github.com/golang/glog"
  22. "github.com/coreos/flannel/Godeps/_workspace/src/github.com/vishvananda/netlink"
  23. "github.com/coreos/flannel/Godeps/_workspace/src/golang.org/x/net/context"
  24. "github.com/coreos/flannel/backend"
  25. "github.com/coreos/flannel/pkg/ip"
  26. "github.com/coreos/flannel/subnet"
  27. )
  28. const (
  29. routeCheckRetries = 10
  30. )
  31. type HostgwBackend struct {
  32. sm subnet.Manager
  33. network string
  34. lease *subnet.Lease
  35. extIface *net.Interface
  36. extIP net.IP
  37. ctx context.Context
  38. cancel context.CancelFunc
  39. wg sync.WaitGroup
  40. rl []netlink.Route
  41. }
  42. func New(sm subnet.Manager, network string) backend.Backend {
  43. ctx, cancel := context.WithCancel(context.Background())
  44. b := &HostgwBackend{
  45. sm: sm,
  46. network: network,
  47. ctx: ctx,
  48. cancel: cancel,
  49. }
  50. return b
  51. }
  52. func (rb *HostgwBackend) Init(extIface *net.Interface, extIP net.IP) (*backend.SubnetDef, error) {
  53. rb.extIface = extIface
  54. rb.extIP = extIP
  55. attrs := subnet.LeaseAttrs{
  56. PublicIP: ip.FromIP(extIP),
  57. BackendType: "host-gw",
  58. }
  59. l, err := rb.sm.AcquireLease(rb.ctx, rb.network, &attrs)
  60. switch err {
  61. case nil:
  62. rb.lease = l
  63. case context.Canceled, context.DeadlineExceeded:
  64. return nil, err
  65. default:
  66. return nil, fmt.Errorf("failed to acquire lease: %v", err)
  67. }
  68. /* NB: docker will create the local route to `sn` */
  69. return &backend.SubnetDef{
  70. Net: l.Subnet,
  71. MTU: extIface.MTU,
  72. }, nil
  73. }
  74. func (rb *HostgwBackend) Run() {
  75. rb.wg.Add(1)
  76. go func() {
  77. subnet.LeaseRenewer(rb.ctx, rb.sm, rb.network, rb.lease)
  78. rb.wg.Done()
  79. }()
  80. log.Info("Watching for new subnet leases")
  81. evts := make(chan []subnet.Event)
  82. rb.wg.Add(1)
  83. go func() {
  84. subnet.WatchLeases(rb.ctx, rb.sm, rb.network, evts)
  85. rb.wg.Done()
  86. }()
  87. rb.rl = make([]netlink.Route, 0, 10)
  88. rb.wg.Add(1)
  89. go func() {
  90. rb.routeCheck(rb.ctx)
  91. rb.wg.Done()
  92. }()
  93. defer rb.wg.Wait()
  94. for {
  95. select {
  96. case evtBatch := <-evts:
  97. rb.handleSubnetEvents(evtBatch)
  98. case <-rb.ctx.Done():
  99. return
  100. }
  101. }
  102. }
  103. func (rb *HostgwBackend) Stop() {
  104. rb.cancel()
  105. }
  106. func (rb *HostgwBackend) Name() string {
  107. return "host-gw"
  108. }
  109. func (rb *HostgwBackend) handleSubnetEvents(batch []subnet.Event) {
  110. for _, evt := range batch {
  111. switch evt.Type {
  112. case subnet.SubnetAdded:
  113. log.Infof("Subnet added: %v via %v", evt.Lease.Subnet, evt.Lease.Attrs.PublicIP)
  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: rb.extIface.Index,
  122. }
  123. if err := netlink.RouteAdd(&route); err != nil {
  124. log.Errorf("Error adding route to %v via %v: %v", evt.Lease.Subnet, evt.Lease.Attrs.PublicIP, err)
  125. continue
  126. }
  127. rb.addToRouteList(route)
  128. case subnet.SubnetRemoved:
  129. log.Info("Subnet removed: ", evt.Lease.Subnet)
  130. if evt.Lease.Attrs.BackendType != "host-gw" {
  131. log.Warningf("Ignoring non-host-gw subnet: type=%v", evt.Lease.Attrs.BackendType)
  132. continue
  133. }
  134. route := netlink.Route{
  135. Dst: evt.Lease.Subnet.ToIPNet(),
  136. Gw: evt.Lease.Attrs.PublicIP.ToIP(),
  137. LinkIndex: rb.extIface.Index,
  138. }
  139. if err := netlink.RouteDel(&route); err != nil {
  140. log.Errorf("Error deleting route to %v: %v", evt.Lease.Subnet, err)
  141. continue
  142. }
  143. rb.removeFromRouteList(route)
  144. default:
  145. log.Error("Internal error: unknown event type: ", int(evt.Type))
  146. }
  147. }
  148. }
  149. func (rb *HostgwBackend) addToRouteList(route netlink.Route) {
  150. rb.rl = append(rb.rl, route)
  151. }
  152. func (rb *HostgwBackend) removeFromRouteList(route netlink.Route) {
  153. for index, r := range rb.rl {
  154. if routeEqual(r, route) {
  155. rb.rl = append(rb.rl[:index], rb.rl[index+1:]...)
  156. return
  157. }
  158. }
  159. }
  160. func (rb *HostgwBackend) routeCheck(ctx context.Context) {
  161. for {
  162. select {
  163. case <-ctx.Done():
  164. return
  165. case <-time.After(routeCheckRetries * time.Second):
  166. rb.checkSubnetExistInRoutes()
  167. }
  168. }
  169. }
  170. func (rb *HostgwBackend) checkSubnetExistInRoutes() {
  171. routeList, err := netlink.RouteList(nil, netlink.FAMILY_V4)
  172. if err == nil {
  173. for _, route := range rb.rl {
  174. exist := false
  175. for _, r := range routeList {
  176. if r.Dst == nil {
  177. continue
  178. }
  179. if routeEqual(r, route) {
  180. exist = true
  181. break
  182. }
  183. }
  184. if !exist {
  185. if err := netlink.RouteAdd(&route); err != nil {
  186. if nerr, ok := err.(net.Error); !ok {
  187. log.Errorf("Error recovering route to %v: %v, %v", route.Dst, route.Gw, nerr)
  188. }
  189. continue
  190. } else {
  191. log.Infof("Route recovered %v : %v", route.Dst, route.Gw)
  192. }
  193. }
  194. }
  195. }
  196. }
  197. func routeEqual(x, y netlink.Route) bool {
  198. if x.Dst.IP.Equal(y.Dst.IP) && x.Gw.Equal(y.Gw) && bytes.Equal(x.Dst.Mask, y.Dst.Mask) {
  199. return true
  200. }
  201. return false
  202. }