hostgw.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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. 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, extIaddr net.IP, extEaddr net.IP) (*backend.SubnetDef, error) {
  53. rb.extIface = extIface
  54. rb.extIaddr = extIaddr
  55. if !extIaddr.Equal(extEaddr) {
  56. 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")
  57. }
  58. attrs := subnet.LeaseAttrs{
  59. PublicIP: ip.FromIP(extIaddr),
  60. BackendType: "host-gw",
  61. }
  62. l, err := rb.sm.AcquireLease(rb.ctx, rb.network, &attrs)
  63. switch err {
  64. case nil:
  65. rb.lease = l
  66. case context.Canceled, context.DeadlineExceeded:
  67. return nil, err
  68. default:
  69. return nil, fmt.Errorf("failed to acquire lease: %v", err)
  70. }
  71. /* NB: docker will create the local route to `sn` */
  72. return &backend.SubnetDef{
  73. Net: l.Subnet,
  74. MTU: extIface.MTU,
  75. }, nil
  76. }
  77. func (rb *HostgwBackend) Run() {
  78. rb.wg.Add(1)
  79. go func() {
  80. subnet.LeaseRenewer(rb.ctx, rb.sm, rb.network, rb.lease)
  81. rb.wg.Done()
  82. }()
  83. log.Info("Watching for new subnet leases")
  84. evts := make(chan []subnet.Event)
  85. rb.wg.Add(1)
  86. go func() {
  87. subnet.WatchLeases(rb.ctx, rb.sm, rb.network, rb.lease, evts)
  88. rb.wg.Done()
  89. }()
  90. rb.rl = make([]netlink.Route, 0, 10)
  91. rb.wg.Add(1)
  92. go func() {
  93. rb.routeCheck(rb.ctx)
  94. rb.wg.Done()
  95. }()
  96. defer rb.wg.Wait()
  97. for {
  98. select {
  99. case evtBatch := <-evts:
  100. rb.handleSubnetEvents(evtBatch)
  101. case <-rb.ctx.Done():
  102. return
  103. }
  104. }
  105. }
  106. func (rb *HostgwBackend) Stop() {
  107. rb.cancel()
  108. }
  109. func (rb *HostgwBackend) Name() string {
  110. return "host-gw"
  111. }
  112. func (rb *HostgwBackend) handleSubnetEvents(batch []subnet.Event) {
  113. for _, evt := range batch {
  114. switch evt.Type {
  115. case subnet.EventAdded:
  116. log.Infof("Subnet added: %v via %v", evt.Lease.Subnet, evt.Lease.Attrs.PublicIP)
  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.RouteAdd(&route); err != nil {
  127. log.Errorf("Error adding route to %v via %v: %v", evt.Lease.Subnet, evt.Lease.Attrs.PublicIP, err)
  128. continue
  129. }
  130. rb.addToRouteList(route)
  131. case subnet.EventRemoved:
  132. log.Info("Subnet removed: ", evt.Lease.Subnet)
  133. if evt.Lease.Attrs.BackendType != "host-gw" {
  134. log.Warningf("Ignoring non-host-gw subnet: type=%v", evt.Lease.Attrs.BackendType)
  135. continue
  136. }
  137. route := netlink.Route{
  138. Dst: evt.Lease.Subnet.ToIPNet(),
  139. Gw: evt.Lease.Attrs.PublicIP.ToIP(),
  140. LinkIndex: rb.extIface.Index,
  141. }
  142. if err := netlink.RouteDel(&route); err != nil {
  143. log.Errorf("Error deleting route to %v: %v", evt.Lease.Subnet, err)
  144. continue
  145. }
  146. rb.removeFromRouteList(route)
  147. default:
  148. log.Error("Internal error: unknown event type: ", int(evt.Type))
  149. }
  150. }
  151. }
  152. func (rb *HostgwBackend) addToRouteList(route netlink.Route) {
  153. rb.rl = append(rb.rl, route)
  154. }
  155. func (rb *HostgwBackend) removeFromRouteList(route netlink.Route) {
  156. for index, r := range rb.rl {
  157. if routeEqual(r, route) {
  158. rb.rl = append(rb.rl[:index], rb.rl[index+1:]...)
  159. return
  160. }
  161. }
  162. }
  163. func (rb *HostgwBackend) routeCheck(ctx context.Context) {
  164. for {
  165. select {
  166. case <-ctx.Done():
  167. return
  168. case <-time.After(routeCheckRetries * time.Second):
  169. rb.checkSubnetExistInRoutes()
  170. }
  171. }
  172. }
  173. func (rb *HostgwBackend) checkSubnetExistInRoutes() {
  174. routeList, err := netlink.RouteList(nil, netlink.FAMILY_V4)
  175. if err == nil {
  176. for _, route := range rb.rl {
  177. exist := false
  178. for _, r := range routeList {
  179. if r.Dst == nil {
  180. continue
  181. }
  182. if routeEqual(r, route) {
  183. exist = true
  184. break
  185. }
  186. }
  187. if !exist {
  188. if err := netlink.RouteAdd(&route); err != nil {
  189. if nerr, ok := err.(net.Error); !ok {
  190. log.Errorf("Error recovering route to %v: %v, %v", route.Dst, route.Gw, nerr)
  191. }
  192. continue
  193. } else {
  194. log.Infof("Route recovered %v : %v", route.Dst, route.Gw)
  195. }
  196. }
  197. }
  198. }
  199. }
  200. func routeEqual(x, y netlink.Route) bool {
  201. if x.Dst.IP.Equal(y.Dst.IP) && x.Gw.Equal(y.Gw) && bytes.Equal(x.Dst.Mask, y.Dst.Mask) {
  202. return true
  203. }
  204. return false
  205. }