hostgw.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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. extIaddr net.IP
  37. rl []netlink.Route
  38. }
  39. func New(sm subnet.Manager, network string) backend.Backend {
  40. b := &HostgwBackend{
  41. sm: sm,
  42. network: network,
  43. }
  44. return b
  45. }
  46. func (rb *HostgwBackend) Init(ctx context.Context, extIface *net.Interface, extIaddr net.IP, extEaddr net.IP) (*backend.SubnetDef, error) {
  47. rb.extIface = extIface
  48. rb.extIaddr = extIaddr
  49. if !extIaddr.Equal(extEaddr) {
  50. return nil, fmt.Errorf("your PublicIP differs from interface IP, meaning that probably you're on a NAT, which is not supported by host-gw backend")
  51. }
  52. attrs := subnet.LeaseAttrs{
  53. PublicIP: ip.FromIP(extIaddr),
  54. BackendType: "host-gw",
  55. }
  56. l, err := rb.sm.AcquireLease(ctx, rb.network, &attrs)
  57. switch err {
  58. case nil:
  59. rb.lease = l
  60. case context.Canceled, context.DeadlineExceeded:
  61. return nil, err
  62. default:
  63. return nil, fmt.Errorf("failed to acquire lease: %v", err)
  64. }
  65. /* NB: docker will create the local route to `sn` */
  66. return &backend.SubnetDef{
  67. Lease: l,
  68. MTU: extIface.MTU,
  69. }, nil
  70. }
  71. func (rb *HostgwBackend) Run(ctx context.Context) {
  72. wg := sync.WaitGroup{}
  73. log.Info("Watching for new subnet leases")
  74. evts := make(chan []subnet.Event)
  75. wg.Add(1)
  76. go func() {
  77. subnet.WatchLeases(ctx, rb.sm, rb.network, rb.lease, evts)
  78. wg.Done()
  79. }()
  80. rb.rl = make([]netlink.Route, 0, 10)
  81. wg.Add(1)
  82. go func() {
  83. rb.routeCheck(ctx)
  84. wg.Done()
  85. }()
  86. defer wg.Wait()
  87. for {
  88. select {
  89. case evtBatch := <-evts:
  90. rb.handleSubnetEvents(evtBatch)
  91. case <-ctx.Done():
  92. return
  93. }
  94. }
  95. }
  96. func (rb *HostgwBackend) handleSubnetEvents(batch []subnet.Event) {
  97. for _, evt := range batch {
  98. switch evt.Type {
  99. case subnet.EventAdded:
  100. log.Infof("Subnet added: %v via %v", evt.Lease.Subnet, evt.Lease.Attrs.PublicIP)
  101. if evt.Lease.Attrs.BackendType != "host-gw" {
  102. log.Warningf("Ignoring non-host-gw subnet: type=%v", evt.Lease.Attrs.BackendType)
  103. continue
  104. }
  105. route := netlink.Route{
  106. Dst: evt.Lease.Subnet.ToIPNet(),
  107. Gw: evt.Lease.Attrs.PublicIP.ToIP(),
  108. LinkIndex: rb.extIface.Index,
  109. }
  110. if err := netlink.RouteAdd(&route); err != nil {
  111. log.Errorf("Error adding route to %v via %v: %v", evt.Lease.Subnet, evt.Lease.Attrs.PublicIP, err)
  112. continue
  113. }
  114. rb.addToRouteList(route)
  115. case subnet.EventRemoved:
  116. log.Info("Subnet removed: ", evt.Lease.Subnet)
  117. if evt.Lease.Attrs.BackendType != "host-gw" {
  118. log.Warningf("Ignoring non-host-gw subnet: type=%v", evt.Lease.Attrs.BackendType)
  119. continue
  120. }
  121. route := netlink.Route{
  122. Dst: evt.Lease.Subnet.ToIPNet(),
  123. Gw: evt.Lease.Attrs.PublicIP.ToIP(),
  124. LinkIndex: rb.extIface.Index,
  125. }
  126. if err := netlink.RouteDel(&route); err != nil {
  127. log.Errorf("Error deleting route to %v: %v", evt.Lease.Subnet, err)
  128. continue
  129. }
  130. rb.removeFromRouteList(route)
  131. default:
  132. log.Error("Internal error: unknown event type: ", int(evt.Type))
  133. }
  134. }
  135. }
  136. func (rb *HostgwBackend) addToRouteList(route netlink.Route) {
  137. rb.rl = append(rb.rl, route)
  138. }
  139. func (rb *HostgwBackend) removeFromRouteList(route netlink.Route) {
  140. for index, r := range rb.rl {
  141. if routeEqual(r, route) {
  142. rb.rl = append(rb.rl[:index], rb.rl[index+1:]...)
  143. return
  144. }
  145. }
  146. }
  147. func (rb *HostgwBackend) routeCheck(ctx context.Context) {
  148. for {
  149. select {
  150. case <-ctx.Done():
  151. return
  152. case <-time.After(routeCheckRetries * time.Second):
  153. rb.checkSubnetExistInRoutes()
  154. }
  155. }
  156. }
  157. func (rb *HostgwBackend) checkSubnetExistInRoutes() {
  158. routeList, err := netlink.RouteList(nil, netlink.FAMILY_V4)
  159. if err == nil {
  160. for _, route := range rb.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. }
  183. }
  184. func routeEqual(x, y netlink.Route) bool {
  185. if x.Dst.IP.Equal(y.Dst.IP) && x.Gw.Equal(y.Gw) && bytes.Equal(x.Dst.Mask, y.Dst.Mask) {
  186. return true
  187. }
  188. return false
  189. }