hostgw.go 5.0 KB

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