local_manager.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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) RevokeLease(ctx context.Context, network string, sn ip.IP4Net) error {
  146. return m.registry.deleteSubnet(ctx, network, sn)
  147. }
  148. func (m *LocalManager) RenewLease(ctx context.Context, network string, lease *Lease) error {
  149. // TODO(eyakubovich): propogate ctx into registry
  150. exp, err := m.registry.updateSubnet(ctx, network, lease.Subnet, &lease.Attrs, subnetTTL, 0)
  151. if err != nil {
  152. return err
  153. }
  154. lease.Expiration = exp
  155. return nil
  156. }
  157. func getNextIndex(cursor interface{}) (uint64, error) {
  158. nextIndex := uint64(0)
  159. if wc, ok := cursor.(watchCursor); ok {
  160. nextIndex = wc.index
  161. } else if s, ok := cursor.(string); ok {
  162. var err error
  163. nextIndex, err = strconv.ParseUint(s, 10, 64)
  164. if err != nil {
  165. return 0, fmt.Errorf("failed to parse cursor: %v", err)
  166. }
  167. } else {
  168. return 0, fmt.Errorf("internal error: watch cursor is of unknown type")
  169. }
  170. return nextIndex, nil
  171. }
  172. func (m *LocalManager) leaseWatchReset(ctx context.Context, network string, sn ip.IP4Net) (LeaseWatchResult, error) {
  173. l, index, err := m.registry.getSubnet(ctx, network, sn)
  174. if err != nil {
  175. return LeaseWatchResult{}, err
  176. }
  177. return LeaseWatchResult{
  178. Snapshot: []Lease{*l},
  179. Cursor: watchCursor{index},
  180. }, nil
  181. }
  182. func (m *LocalManager) WatchLease(ctx context.Context, network string, sn ip.IP4Net, cursor interface{}) (LeaseWatchResult, error) {
  183. if cursor == nil {
  184. return m.leaseWatchReset(ctx, network, sn)
  185. }
  186. nextIndex, err := getNextIndex(cursor)
  187. if err != nil {
  188. return LeaseWatchResult{}, err
  189. }
  190. evt, index, err := m.registry.watchSubnet(ctx, network, nextIndex, sn)
  191. switch {
  192. case err == nil:
  193. return LeaseWatchResult{
  194. Events: []Event{evt},
  195. Cursor: watchCursor{index},
  196. }, nil
  197. case isIndexTooSmall(err):
  198. log.Warning("Watch of subnet leases failed because etcd index outside history window")
  199. return m.leaseWatchReset(ctx, network, sn)
  200. default:
  201. return LeaseWatchResult{}, err
  202. }
  203. }
  204. func (m *LocalManager) WatchLeases(ctx context.Context, network string, cursor interface{}) (LeaseWatchResult, error) {
  205. if cursor == nil {
  206. return m.leasesWatchReset(ctx, network)
  207. }
  208. nextIndex, err := getNextIndex(cursor)
  209. if err != nil {
  210. return LeaseWatchResult{}, err
  211. }
  212. evt, index, err := m.registry.watchSubnets(ctx, network, nextIndex)
  213. switch {
  214. case err == nil:
  215. return LeaseWatchResult{
  216. Events: []Event{evt},
  217. Cursor: watchCursor{index},
  218. }, nil
  219. case isIndexTooSmall(err):
  220. log.Warning("Watch of subnet leases failed because etcd index outside history window")
  221. return m.leasesWatchReset(ctx, network)
  222. default:
  223. return LeaseWatchResult{}, err
  224. }
  225. }
  226. func (m *LocalManager) WatchNetworks(ctx context.Context, cursor interface{}) (NetworkWatchResult, error) {
  227. if cursor == nil {
  228. return m.networkWatchReset(ctx)
  229. }
  230. nextIndex, err := getNextIndex(cursor)
  231. if err != nil {
  232. return NetworkWatchResult{}, err
  233. }
  234. DoWatch:
  235. evt, index, err := m.registry.watchNetworks(ctx, nextIndex)
  236. switch {
  237. case err == nil:
  238. return NetworkWatchResult{
  239. Events: []Event{evt},
  240. Cursor: watchCursor{index},
  241. }, nil
  242. case err == ErrTryAgain:
  243. nextIndex = index
  244. goto DoWatch
  245. case isIndexTooSmall(err):
  246. log.Warning("Watch of networks failed because etcd index outside history window")
  247. return m.networkWatchReset(ctx)
  248. default:
  249. return NetworkWatchResult{}, err
  250. }
  251. }
  252. func isIndexTooSmall(err error) bool {
  253. etcdErr, ok := err.(etcd.Error)
  254. return ok && etcdErr.Code == etcd.ErrorCodeEventIndexCleared
  255. }
  256. // leasesWatchReset is called when incremental lease watch failed and we need to grab a snapshot
  257. func (m *LocalManager) leasesWatchReset(ctx context.Context, network string) (LeaseWatchResult, error) {
  258. wr := LeaseWatchResult{}
  259. leases, index, err := m.registry.getSubnets(ctx, network)
  260. if err != nil {
  261. return wr, fmt.Errorf("failed to retrieve subnet leases: %v", err)
  262. }
  263. wr.Cursor = watchCursor{index}
  264. wr.Snapshot = leases
  265. return wr, nil
  266. }
  267. // networkWatchReset is called when incremental network watch failed and we need to grab a snapshot
  268. func (m *LocalManager) networkWatchReset(ctx context.Context) (NetworkWatchResult, error) {
  269. wr := NetworkWatchResult{}
  270. networks, index, err := m.registry.getNetworks(ctx)
  271. if err != nil {
  272. return wr, fmt.Errorf("failed to retrieve networks: %v", err)
  273. }
  274. wr.Cursor = watchCursor{index}
  275. wr.Snapshot = networks
  276. return wr, nil
  277. }
  278. func isSubnetConfigCompat(config *Config, sn ip.IP4Net) bool {
  279. if sn.IP < config.SubnetMin || sn.IP > config.SubnetMax {
  280. return false
  281. }
  282. return sn.PrefixLen == config.SubnetLen
  283. }