hostgw.go 5.4 KB

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