subnet.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. package subnet
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "regexp"
  8. "strconv"
  9. "time"
  10. "github.com/coreos/flannel/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd"
  11. log "github.com/coreos/flannel/Godeps/_workspace/src/github.com/golang/glog"
  12. "github.com/coreos/flannel/pkg/ip"
  13. "github.com/coreos/flannel/pkg/task"
  14. )
  15. const (
  16. registerRetries = 10
  17. subnetTTL = 24 * 3600
  18. renewMargin = time.Hour
  19. )
  20. // etcd error codes
  21. const (
  22. etcdKeyNotFound = 100
  23. etcdKeyAlreadyExists = 105
  24. etcdEventIndexCleared = 401
  25. )
  26. const (
  27. SubnetAdded = iota
  28. SubnetRemoved
  29. )
  30. var (
  31. subnetRegex *regexp.Regexp = regexp.MustCompile(`(\d+\.\d+.\d+.\d+)-(\d+)`)
  32. )
  33. type LeaseAttrs struct {
  34. PublicIP ip.IP4
  35. BackendType string `json:",omitempty"`
  36. BackendData json.RawMessage `json:",omitempty"`
  37. }
  38. type SubnetLease struct {
  39. Network ip.IP4Net
  40. Attrs LeaseAttrs
  41. }
  42. type SubnetManager struct {
  43. registry subnetRegistry
  44. config *Config
  45. myLease SubnetLease
  46. leaseExp time.Time
  47. lastIndex uint64
  48. leases []SubnetLease
  49. }
  50. type EventType int
  51. type Event struct {
  52. Type EventType
  53. Lease SubnetLease
  54. }
  55. type EventBatch []Event
  56. func NewSubnetManager(etcdEndpoint []string, prefix string) (*SubnetManager, error) {
  57. esr := newEtcdSubnetRegistry(etcdEndpoint, prefix)
  58. return newSubnetManager(esr)
  59. }
  60. func (sm *SubnetManager) AcquireLease(attrs *LeaseAttrs, cancel chan bool) (ip.IP4Net, error) {
  61. for {
  62. sn, err := sm.acquireLeaseOnce(attrs, cancel)
  63. switch {
  64. case err == nil:
  65. log.Info("Subnet lease acquired: ", sn)
  66. return sn, nil
  67. case err == task.ErrCanceled:
  68. return ip.IP4Net{}, err
  69. default:
  70. log.Error("Failed to acquire subnet: ", err)
  71. }
  72. select {
  73. case <-time.After(time.Second):
  74. case <-cancel:
  75. return ip.IP4Net{}, task.ErrCanceled
  76. }
  77. }
  78. }
  79. func findLeaseByIP(leases []SubnetLease, pubIP ip.IP4) *SubnetLease {
  80. for _, l := range leases {
  81. if pubIP == l.Attrs.PublicIP {
  82. return &l
  83. }
  84. }
  85. return nil
  86. }
  87. func (sm *SubnetManager) tryAcquireLease(extIP ip.IP4, attrs *LeaseAttrs) (ip.IP4Net, error) {
  88. var err error
  89. sm.leases, err = sm.getLeases()
  90. if err != nil {
  91. return ip.IP4Net{}, err
  92. }
  93. attrBytes, err := json.Marshal(attrs)
  94. if err != nil {
  95. log.Errorf("marshal failed: %#v, %v", attrs, err)
  96. return ip.IP4Net{}, err
  97. }
  98. // try to reuse a subnet if there's one that matches our IP
  99. if l := findLeaseByIP(sm.leases, extIP); l != nil {
  100. resp, err := sm.registry.updateSubnet(l.Network.StringSep(".", "-"), string(attrBytes), subnetTTL)
  101. if err != nil {
  102. return ip.IP4Net{}, err
  103. }
  104. sm.myLease.Network = l.Network
  105. sm.myLease.Attrs = *attrs
  106. sm.leaseExp = *resp.Node.Expiration
  107. return l.Network, nil
  108. }
  109. // no existing match, grab a new one
  110. sn, err := sm.allocateSubnet()
  111. if err != nil {
  112. return ip.IP4Net{}, err
  113. }
  114. resp, err := sm.registry.createSubnet(sn.StringSep(".", "-"), string(attrBytes), subnetTTL)
  115. switch {
  116. case err == nil:
  117. sm.myLease.Network = sn
  118. sm.myLease.Attrs = *attrs
  119. sm.leaseExp = *resp.Node.Expiration
  120. return sn, nil
  121. // if etcd returned Key Already Exists, try again.
  122. case err.(*etcd.EtcdError).ErrorCode == etcdKeyAlreadyExists:
  123. return ip.IP4Net{}, nil
  124. default:
  125. return ip.IP4Net{}, err
  126. }
  127. }
  128. func (sm *SubnetManager) acquireLeaseOnce(attrs *LeaseAttrs, cancel chan bool) (ip.IP4Net, error) {
  129. for i := 0; i < registerRetries; i++ {
  130. sn, err := sm.tryAcquireLease(attrs.PublicIP, attrs)
  131. switch {
  132. case err != nil:
  133. return ip.IP4Net{}, err
  134. case sn.IP != 0:
  135. return sn, nil
  136. }
  137. // before moving on, check for cancel
  138. if interrupted(cancel) {
  139. return ip.IP4Net{}, task.ErrCanceled
  140. }
  141. }
  142. return ip.IP4Net{}, errors.New("Max retries reached trying to acquire a subnet")
  143. }
  144. func (sm *SubnetManager) GetConfig() *Config {
  145. return sm.config
  146. }
  147. /// Implementation
  148. func parseSubnetKey(s string) (ip.IP4Net, error) {
  149. if parts := subnetRegex.FindStringSubmatch(s); len(parts) == 3 {
  150. snIp := net.ParseIP(parts[1]).To4()
  151. prefixLen, err := strconv.ParseUint(parts[2], 10, 5)
  152. if snIp != nil && err == nil {
  153. return ip.IP4Net{IP: ip.FromIP(snIp), PrefixLen: uint(prefixLen)}, nil
  154. }
  155. }
  156. return ip.IP4Net{}, errors.New("Error parsing IP Subnet")
  157. }
  158. func newSubnetManager(r subnetRegistry) (*SubnetManager, error) {
  159. cfgResp, err := r.getConfig()
  160. if err != nil {
  161. return nil, err
  162. }
  163. cfg, err := ParseConfig(cfgResp.Node.Value)
  164. if err != nil {
  165. return nil, err
  166. }
  167. sm := SubnetManager{
  168. registry: r,
  169. config: cfg,
  170. }
  171. return &sm, nil
  172. }
  173. func (sm *SubnetManager) getLeases() ([]SubnetLease, error) {
  174. resp, err := sm.registry.getSubnets()
  175. var leases []SubnetLease
  176. switch {
  177. case err == nil:
  178. for _, node := range resp.Node.Nodes {
  179. sn, err := parseSubnetKey(node.Key)
  180. if err == nil {
  181. var attrs LeaseAttrs
  182. if err = json.Unmarshal([]byte(node.Value), &attrs); err == nil {
  183. lease := SubnetLease{sn, attrs}
  184. leases = append(leases, lease)
  185. }
  186. }
  187. }
  188. sm.lastIndex = resp.EtcdIndex
  189. case err.(*etcd.EtcdError).ErrorCode == etcdKeyNotFound:
  190. // key not found: treat it as empty set
  191. sm.lastIndex = err.(*etcd.EtcdError).Index
  192. default:
  193. return nil, err
  194. }
  195. return leases, nil
  196. }
  197. func deleteLease(l []SubnetLease, i int) []SubnetLease {
  198. l[i], l = l[len(l)-1], l[:len(l)-1]
  199. return l
  200. }
  201. func (sm *SubnetManager) applyLeases(newLeases []SubnetLease) EventBatch {
  202. var batch EventBatch
  203. for _, l := range newLeases {
  204. // skip self
  205. if l.Network.Equal(sm.myLease.Network) {
  206. continue
  207. }
  208. found := false
  209. for i, c := range sm.leases {
  210. if c.Network.Equal(l.Network) {
  211. sm.leases = deleteLease(sm.leases, i)
  212. found = true
  213. break
  214. }
  215. }
  216. if !found {
  217. // new subnet
  218. batch = append(batch, Event{SubnetAdded, l})
  219. }
  220. }
  221. // everything left in sm.leases has been deleted
  222. for _, c := range sm.leases {
  223. batch = append(batch, Event{SubnetRemoved, c})
  224. }
  225. sm.leases = newLeases
  226. return batch
  227. }
  228. func (sm *SubnetManager) applySubnetChange(action string, ipn ip.IP4Net, data string) (Event, error) {
  229. switch action {
  230. case "delete", "expire":
  231. for i, l := range sm.leases {
  232. if l.Network.Equal(ipn) {
  233. deleteLease(sm.leases, i)
  234. return Event{SubnetRemoved, l}, nil
  235. }
  236. }
  237. log.Errorf("Removed subnet (%s) was not found", ipn)
  238. return Event{
  239. SubnetRemoved,
  240. SubnetLease{ipn, LeaseAttrs{}},
  241. }, nil
  242. default:
  243. var attrs LeaseAttrs
  244. err := json.Unmarshal([]byte(data), &attrs)
  245. if err != nil {
  246. return Event{}, err
  247. }
  248. for i, l := range sm.leases {
  249. if l.Network.Equal(ipn) {
  250. sm.leases[i] = SubnetLease{ipn, attrs}
  251. return Event{SubnetAdded, sm.leases[i]}, nil
  252. }
  253. }
  254. sm.leases = append(sm.leases, SubnetLease{ipn, attrs})
  255. return Event{SubnetAdded, sm.leases[len(sm.leases)-1]}, nil
  256. }
  257. }
  258. func (sm *SubnetManager) allocateSubnet() (ip.IP4Net, error) {
  259. log.Infof("Picking subnet in range %s ... %s", sm.config.SubnetMin, sm.config.SubnetMax)
  260. var bag []ip.IP4
  261. sn := ip.IP4Net{IP: sm.config.SubnetMin, PrefixLen: sm.config.SubnetLen}
  262. OuterLoop:
  263. for ; sn.IP <= sm.config.SubnetMax && len(bag) < 100; sn = sn.Next() {
  264. for _, l := range sm.leases {
  265. if sn.Overlaps(l.Network) {
  266. continue OuterLoop
  267. }
  268. }
  269. bag = append(bag, sn.IP)
  270. }
  271. if len(bag) == 0 {
  272. return ip.IP4Net{}, errors.New("out of subnets")
  273. } else {
  274. i := randInt(0, len(bag))
  275. return ip.IP4Net{IP: bag[i], PrefixLen: sm.config.SubnetLen}, nil
  276. }
  277. }
  278. func (sm *SubnetManager) WatchLeases(receiver chan EventBatch, cancel chan bool) {
  279. // "catch up" by replaying all the leases we discovered during
  280. // AcquireLease
  281. var batch EventBatch
  282. for _, l := range sm.leases {
  283. if !sm.myLease.Network.Equal(l.Network) {
  284. batch = append(batch, Event{SubnetAdded, l})
  285. }
  286. }
  287. if len(batch) > 0 {
  288. receiver <- batch
  289. }
  290. for {
  291. resp, err := sm.registry.watchSubnets(sm.lastIndex+1, cancel)
  292. // watchSubnets exited by cancel chan being signaled
  293. if err == nil && resp == nil {
  294. return
  295. }
  296. var batch *EventBatch
  297. if err == nil {
  298. batch, err = sm.parseSubnetWatchResponse(resp)
  299. } else {
  300. batch, err = sm.parseSubnetWatchError(err)
  301. }
  302. if err != nil {
  303. log.Errorf("%v", err)
  304. time.Sleep(time.Second)
  305. continue
  306. }
  307. if batch != nil {
  308. receiver <- *batch
  309. }
  310. }
  311. }
  312. func (sm *SubnetManager) parseSubnetWatchResponse(resp *etcd.Response) (batch *EventBatch, err error) {
  313. sm.lastIndex = resp.Node.ModifiedIndex
  314. sn, err := parseSubnetKey(resp.Node.Key)
  315. if err != nil {
  316. err = fmt.Errorf("Error parsing subnet IP: %s", resp.Node.Key)
  317. return
  318. }
  319. // Don't process our own changes
  320. if !sm.myLease.Network.Equal(sn) {
  321. evt, err := sm.applySubnetChange(resp.Action, sn, resp.Node.Value)
  322. if err != nil {
  323. return nil, err
  324. }
  325. batch = &EventBatch{evt}
  326. }
  327. return
  328. }
  329. func (sm *SubnetManager) parseSubnetWatchError(err error) (batch *EventBatch, out error) {
  330. etcdErr, ok := err.(*etcd.EtcdError)
  331. if ok && etcdErr.ErrorCode == etcdEventIndexCleared {
  332. // etcd maintains a history window for events and it's possible to fall behind.
  333. // to recover, get the current state and then "diff" against our cache to generate
  334. // events for the caller
  335. log.Warning("Watch of subnet leases failed because etcd index outside history window")
  336. leases, err := sm.getLeases()
  337. if err == nil {
  338. lb := sm.applyLeases(leases)
  339. batch = &lb
  340. } else {
  341. out = fmt.Errorf("Failed to retrieve subnet leases: %v", err)
  342. }
  343. } else {
  344. out = fmt.Errorf("Watch of subnet leases failed: %v", err)
  345. }
  346. return
  347. }
  348. func (sm *SubnetManager) LeaseRenewer(cancel chan bool) {
  349. dur := sm.leaseExp.Sub(time.Now()) - renewMargin
  350. for {
  351. select {
  352. case <-time.After(dur):
  353. attrBytes, err := json.Marshal(sm.myLease.Attrs)
  354. if err != nil {
  355. log.Error("Error renewing lease (trying again in 1 min): ", err)
  356. dur = time.Minute
  357. continue
  358. }
  359. resp, err := sm.registry.updateSubnet(sm.myLease.Network.StringSep(".", "-"), string(attrBytes), subnetTTL)
  360. if err != nil {
  361. log.Error("Error renewing lease (trying again in 1 min): ", err)
  362. dur = time.Minute
  363. continue
  364. }
  365. sm.leaseExp = *resp.Node.Expiration
  366. log.Info("Lease renewed, new expiration: ", sm.leaseExp)
  367. dur = sm.leaseExp.Sub(time.Now()) - renewMargin
  368. case <-cancel:
  369. return
  370. }
  371. }
  372. }
  373. func interrupted(cancel chan bool) bool {
  374. select {
  375. case <-cancel:
  376. return true
  377. default:
  378. return false
  379. }
  380. }