local_manager.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. // Copyright 2015 flannel authors
  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 subnet
  15. import (
  16. "errors"
  17. "fmt"
  18. "strconv"
  19. "time"
  20. etcd "github.com/coreos/flannel/Godeps/_workspace/src/github.com/coreos/etcd/client"
  21. log "github.com/coreos/flannel/Godeps/_workspace/src/github.com/golang/glog"
  22. "github.com/coreos/flannel/Godeps/_workspace/src/golang.org/x/net/context"
  23. "github.com/coreos/flannel/pkg/ip"
  24. )
  25. const (
  26. registerRetries = 10
  27. subnetTTL = 24 * time.Hour
  28. )
  29. type LocalManager struct {
  30. registry Registry
  31. }
  32. type watchCursor struct {
  33. index uint64
  34. }
  35. func (c watchCursor) String() string {
  36. return strconv.FormatUint(c.index, 10)
  37. }
  38. func NewLocalManager(config *EtcdConfig) (Manager, error) {
  39. r, err := newEtcdSubnetRegistry(config)
  40. if err != nil {
  41. return nil, err
  42. }
  43. return newLocalManager(r), nil
  44. }
  45. func newLocalManager(r Registry) Manager {
  46. return &LocalManager{
  47. registry: r,
  48. }
  49. }
  50. func (m *LocalManager) GetNetworkConfig(ctx context.Context, network string) (*Config, error) {
  51. cfg, err := m.registry.getNetworkConfig(ctx, network)
  52. if err != nil {
  53. return nil, err
  54. }
  55. return ParseConfig(cfg)
  56. }
  57. func (m *LocalManager) AcquireLease(ctx context.Context, network string, attrs *LeaseAttrs) (*Lease, error) {
  58. config, err := m.GetNetworkConfig(ctx, network)
  59. if err != nil {
  60. return nil, err
  61. }
  62. for i := 0; i < registerRetries; i++ {
  63. l, err := m.tryAcquireLease(ctx, network, config, attrs.PublicIP, attrs)
  64. switch {
  65. case err != nil:
  66. return nil, err
  67. case l != nil:
  68. return l, nil
  69. }
  70. }
  71. return nil, errors.New("Max retries reached trying to acquire a subnet")
  72. }
  73. func findLeaseByIP(leases []Lease, pubIP ip.IP4) *Lease {
  74. for _, l := range leases {
  75. if pubIP == l.Attrs.PublicIP {
  76. return &l
  77. }
  78. }
  79. return nil
  80. }
  81. func (m *LocalManager) tryAcquireLease(ctx context.Context, network string, config *Config, extIaddr ip.IP4, attrs *LeaseAttrs) (*Lease, error) {
  82. var err error
  83. leases, _, err := m.registry.getSubnets(ctx, network)
  84. if err != nil {
  85. return nil, err
  86. }
  87. // try to reuse a subnet if there's one that matches our IP
  88. if l := findLeaseByIP(leases, extIaddr); l != nil {
  89. // make sure the existing subnet is still within the configured network
  90. if isSubnetConfigCompat(config, l.Subnet) {
  91. log.Infof("Found lease (%v) for current IP (%v), reusing", l.Subnet, extIaddr)
  92. exp, err := m.registry.updateSubnet(ctx, network, l.Subnet, attrs, subnetTTL, 0)
  93. if err != nil {
  94. return nil, err
  95. }
  96. l.Attrs = *attrs
  97. l.Expiration = exp
  98. return l, nil
  99. } else {
  100. log.Infof("Found lease (%v) for current IP (%v) but not compatible with current config, deleting", l.Subnet, extIaddr)
  101. if err := m.registry.deleteSubnet(ctx, network, l.Subnet); err != nil {
  102. return nil, err
  103. }
  104. }
  105. }
  106. // no existing match, grab a new one
  107. sn, err := m.allocateSubnet(config, leases)
  108. if err != nil {
  109. return nil, err
  110. }
  111. exp, err := m.registry.createSubnet(ctx, network, sn, attrs, subnetTTL)
  112. if err == nil {
  113. return &Lease{
  114. Subnet: sn,
  115. Attrs: *attrs,
  116. Expiration: exp,
  117. }, nil
  118. }
  119. if etcdErr, ok := err.(etcd.Error); ok && etcdErr.Code == etcd.ErrorCodeNodeExist {
  120. // if etcd returned Key Already Exists, try again.
  121. return nil, nil
  122. }
  123. return nil, err
  124. }
  125. func (m *LocalManager) allocateSubnet(config *Config, leases []Lease) (ip.IP4Net, error) {
  126. log.Infof("Picking subnet in range %s ... %s", config.SubnetMin, config.SubnetMax)
  127. var bag []ip.IP4
  128. sn := ip.IP4Net{IP: config.SubnetMin, PrefixLen: config.SubnetLen}
  129. OuterLoop:
  130. for ; sn.IP <= config.SubnetMax && len(bag) < 100; sn = sn.Next() {
  131. for _, l := range leases {
  132. if sn.Overlaps(l.Subnet) {
  133. continue OuterLoop
  134. }
  135. }
  136. bag = append(bag, sn.IP)
  137. }
  138. if len(bag) == 0 {
  139. return ip.IP4Net{}, errors.New("out of subnets")
  140. } else {
  141. i := randInt(0, len(bag))
  142. return ip.IP4Net{IP: bag[i], PrefixLen: config.SubnetLen}, nil
  143. }
  144. }
  145. func (m *LocalManager) RenewLease(ctx context.Context, network string, lease *Lease) error {
  146. // TODO(eyakubovich): propogate ctx into registry
  147. exp, err := m.registry.updateSubnet(ctx, network, lease.Subnet, &lease.Attrs, subnetTTL, 0)
  148. if err != nil {
  149. return err
  150. }
  151. lease.Expiration = exp
  152. return nil
  153. }
  154. func getNextIndex(cursor interface{}) (uint64, error) {
  155. nextIndex := uint64(0)
  156. if wc, ok := cursor.(watchCursor); ok {
  157. nextIndex = wc.index
  158. } else if s, ok := cursor.(string); ok {
  159. var err error
  160. nextIndex, err = strconv.ParseUint(s, 10, 64)
  161. if err != nil {
  162. return 0, fmt.Errorf("failed to parse cursor: %v", err)
  163. }
  164. } else {
  165. return 0, fmt.Errorf("internal error: watch cursor is of unknown type")
  166. }
  167. return nextIndex, nil
  168. }
  169. func (m *LocalManager) WatchLeases(ctx context.Context, network string, cursor interface{}) (LeaseWatchResult, error) {
  170. if cursor == nil {
  171. return m.leaseWatchReset(ctx, network)
  172. }
  173. nextIndex, err := getNextIndex(cursor)
  174. if err != nil {
  175. return LeaseWatchResult{}, err
  176. }
  177. evt, index, err := m.registry.watchSubnets(ctx, network, nextIndex)
  178. switch {
  179. case err == nil:
  180. return LeaseWatchResult{
  181. Events: []Event{evt},
  182. Cursor: watchCursor{index},
  183. }, nil
  184. case isIndexTooSmall(err):
  185. log.Warning("Watch of subnet leases failed because etcd index outside history window")
  186. return m.leaseWatchReset(ctx, network)
  187. default:
  188. return LeaseWatchResult{}, err
  189. }
  190. }
  191. func (m *LocalManager) WatchNetworks(ctx context.Context, cursor interface{}) (NetworkWatchResult, error) {
  192. if cursor == nil {
  193. return m.networkWatchReset(ctx)
  194. }
  195. nextIndex, err := getNextIndex(cursor)
  196. if err != nil {
  197. return NetworkWatchResult{}, err
  198. }
  199. DoWatch:
  200. evt, index, err := m.registry.watchNetworks(ctx, nextIndex)
  201. switch {
  202. case err == nil:
  203. return NetworkWatchResult{
  204. Events: []Event{evt},
  205. Cursor: watchCursor{index},
  206. }, nil
  207. case err == ErrTryAgain:
  208. nextIndex = index
  209. goto DoWatch
  210. case isIndexTooSmall(err):
  211. log.Warning("Watch of networks failed because etcd index outside history window")
  212. return m.networkWatchReset(ctx)
  213. default:
  214. return NetworkWatchResult{}, err
  215. }
  216. }
  217. func isIndexTooSmall(err error) bool {
  218. etcdErr, ok := err.(etcd.Error)
  219. return ok && etcdErr.Code == etcd.ErrorCodeEventIndexCleared
  220. }
  221. // leaseWatchReset is called when incremental lease watch failed and we need to grab a snapshot
  222. func (m *LocalManager) leaseWatchReset(ctx context.Context, network string) (LeaseWatchResult, error) {
  223. wr := LeaseWatchResult{}
  224. leases, index, err := m.registry.getSubnets(ctx, network)
  225. if err != nil {
  226. return wr, fmt.Errorf("failed to retrieve subnet leases: %v", err)
  227. }
  228. wr.Cursor = watchCursor{index}
  229. wr.Snapshot = leases
  230. return wr, nil
  231. }
  232. // networkWatchReset is called when incremental network watch failed and we need to grab a snapshot
  233. func (m *LocalManager) networkWatchReset(ctx context.Context) (NetworkWatchResult, error) {
  234. wr := NetworkWatchResult{}
  235. networks, index, err := m.registry.getNetworks(ctx)
  236. if err != nil {
  237. return wr, fmt.Errorf("failed to retrieve networks: %v", err)
  238. }
  239. wr.Cursor = watchCursor{index}
  240. wr.Snapshot = networks
  241. return wr, nil
  242. }
  243. func isSubnetConfigCompat(config *Config, sn ip.IP4Net) bool {
  244. if sn.IP < config.SubnetMin || sn.IP > config.SubnetMax {
  245. return false
  246. }
  247. return sn.PrefixLen == config.SubnetLen
  248. }