registry.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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. "encoding/json"
  17. "errors"
  18. "fmt"
  19. "net"
  20. "path"
  21. "regexp"
  22. "strconv"
  23. "sync"
  24. "time"
  25. etcd "github.com/coreos/flannel/Godeps/_workspace/src/github.com/coreos/etcd/client"
  26. "github.com/coreos/flannel/Godeps/_workspace/src/github.com/coreos/etcd/pkg/transport"
  27. log "github.com/coreos/flannel/Godeps/_workspace/src/github.com/golang/glog"
  28. "github.com/coreos/flannel/Godeps/_workspace/src/golang.org/x/net/context"
  29. "github.com/coreos/flannel/pkg/ip"
  30. )
  31. var (
  32. subnetRegex *regexp.Regexp = regexp.MustCompile(`(\d+\.\d+.\d+.\d+)-(\d+)`)
  33. ErrTryAgain = errors.New("try again")
  34. )
  35. type Registry interface {
  36. getNetworkConfig(ctx context.Context, network string) (string, error)
  37. getSubnets(ctx context.Context, network string) ([]Lease, uint64, error)
  38. createSubnet(ctx context.Context, network string, sn ip.IP4Net, attrs *LeaseAttrs, ttl time.Duration) (time.Time, error)
  39. updateSubnet(ctx context.Context, network string, sn ip.IP4Net, attrs *LeaseAttrs, ttl time.Duration, asof uint64) (time.Time, error)
  40. deleteSubnet(ctx context.Context, network string, sn ip.IP4Net) error
  41. watchSubnets(ctx context.Context, network string, since uint64) (Event, uint64, error)
  42. getNetworks(ctx context.Context) ([]string, uint64, error)
  43. watchNetworks(ctx context.Context, since uint64) (Event, uint64, error)
  44. }
  45. type EtcdConfig struct {
  46. Endpoints []string
  47. Keyfile string
  48. Certfile string
  49. CAFile string
  50. Prefix string
  51. }
  52. type etcdSubnetRegistry struct {
  53. mux sync.Mutex
  54. cli etcd.KeysAPI
  55. etcdCfg *EtcdConfig
  56. networkRegex *regexp.Regexp
  57. }
  58. func newEtcdClient(c *EtcdConfig) (etcd.KeysAPI, error) {
  59. tlsInfo := transport.TLSInfo{
  60. CertFile: c.Certfile,
  61. KeyFile: c.Keyfile,
  62. CAFile: c.CAFile,
  63. }
  64. t, err := transport.NewTransport(tlsInfo)
  65. if err != nil {
  66. return nil, err
  67. }
  68. cli, err := etcd.New(etcd.Config{
  69. Endpoints: c.Endpoints,
  70. Transport: t,
  71. })
  72. if err != nil {
  73. return nil, err
  74. }
  75. return etcd.NewKeysAPI(cli), nil
  76. }
  77. func newEtcdSubnetRegistry(config *EtcdConfig) (Registry, error) {
  78. r := &etcdSubnetRegistry{
  79. etcdCfg: config,
  80. networkRegex: regexp.MustCompile(config.Prefix + `/([^/]*)(/|/config)?$`),
  81. }
  82. var err error
  83. r.cli, err = newEtcdClient(config)
  84. if err != nil {
  85. return nil, err
  86. }
  87. return r, nil
  88. }
  89. func (esr *etcdSubnetRegistry) getNetworkConfig(ctx context.Context, network string) (string, error) {
  90. key := path.Join(esr.etcdCfg.Prefix, network, "config")
  91. resp, err := esr.client().Get(ctx, key, nil)
  92. if err != nil {
  93. return "", err
  94. }
  95. return resp.Node.Value, nil
  96. }
  97. // getSubnets queries etcd to get a list of currently allocated leases for a given network.
  98. // It returns the leases along with the "as-of" etcd-index that can be used as the starting
  99. // point for etcd watch.
  100. func (esr *etcdSubnetRegistry) getSubnets(ctx context.Context, network string) ([]Lease, uint64, error) {
  101. key := path.Join(esr.etcdCfg.Prefix, network, "subnets")
  102. resp, err := esr.client().Get(ctx, key, &etcd.GetOptions{Recursive: true})
  103. if err != nil {
  104. if etcdErr, ok := err.(etcd.Error); ok && etcdErr.Code == etcd.ErrorCodeKeyNotFound {
  105. // key not found: treat it as empty set
  106. return []Lease{}, etcdErr.Index, nil
  107. }
  108. return nil, 0, err
  109. }
  110. leases := []Lease{}
  111. for _, node := range resp.Node.Nodes {
  112. if sn := parseSubnetKey(node.Key); sn != nil {
  113. attrs := &LeaseAttrs{}
  114. if err = json.Unmarshal([]byte(node.Value), attrs); err == nil {
  115. exp := time.Time{}
  116. if node.Expiration != nil {
  117. exp = *node.Expiration
  118. }
  119. lease := Lease{
  120. Subnet: *sn,
  121. Attrs: *attrs,
  122. Expiration: exp,
  123. }
  124. leases = append(leases, lease)
  125. }
  126. }
  127. }
  128. return leases, resp.Index, nil
  129. }
  130. func (esr *etcdSubnetRegistry) createSubnet(ctx context.Context, network string, sn ip.IP4Net, attrs *LeaseAttrs, ttl time.Duration) (time.Time, error) {
  131. key := path.Join(esr.etcdCfg.Prefix, network, "subnets", sn.StringSep(".", "-"))
  132. value, err := json.Marshal(attrs)
  133. if err != nil {
  134. return time.Time{}, err
  135. }
  136. opts := &etcd.SetOptions{
  137. PrevExist: etcd.PrevNoExist,
  138. TTL: ttl,
  139. }
  140. resp, err := esr.client().Set(ctx, key, string(value), opts)
  141. if err != nil {
  142. return time.Time{}, err
  143. }
  144. ensureExpiration(resp, ttl)
  145. return *resp.Node.Expiration, nil
  146. }
  147. func (esr *etcdSubnetRegistry) updateSubnet(ctx context.Context, network string, sn ip.IP4Net, attrs *LeaseAttrs, ttl time.Duration, asof uint64) (time.Time, error) {
  148. key := path.Join(esr.etcdCfg.Prefix, network, "subnets", sn.StringSep(".", "-"))
  149. value, err := json.Marshal(attrs)
  150. if err != nil {
  151. return time.Time{}, err
  152. }
  153. resp, err := esr.client().Set(ctx, key, string(value), &etcd.SetOptions{
  154. PrevIndex: asof,
  155. TTL: ttl,
  156. })
  157. if err != nil {
  158. return time.Time{}, err
  159. }
  160. ensureExpiration(resp, ttl)
  161. return *resp.Node.Expiration, nil
  162. }
  163. func (esr *etcdSubnetRegistry) deleteSubnet(ctx context.Context, network string, sn ip.IP4Net) error {
  164. key := path.Join(esr.etcdCfg.Prefix, network, "subnets", sn.StringSep(".", "-"))
  165. _, err := esr.client().Delete(ctx, key, nil)
  166. return err
  167. }
  168. func (esr *etcdSubnetRegistry) watchSubnets(ctx context.Context, network string, since uint64) (Event, uint64, error) {
  169. key := path.Join(esr.etcdCfg.Prefix, network, "subnets")
  170. opts := &etcd.WatcherOptions{
  171. AfterIndex: since,
  172. Recursive: true,
  173. }
  174. e, err := esr.client().Watcher(key, opts).Next(ctx)
  175. if err != nil {
  176. return Event{}, 0, err
  177. }
  178. evt, err := parseSubnetWatchResponse(e)
  179. return evt, e.Node.ModifiedIndex, err
  180. }
  181. // getNetworks queries etcd to get a list of network names. It returns the
  182. // networks along with the 'as-of' etcd-index that can be used as the starting
  183. // point for etcd watch.
  184. func (esr *etcdSubnetRegistry) getNetworks(ctx context.Context) ([]string, uint64, error) {
  185. resp, err := esr.client().Get(ctx, esr.etcdCfg.Prefix, &etcd.GetOptions{Recursive: true})
  186. networks := []string{}
  187. if err == nil {
  188. for _, node := range resp.Node.Nodes {
  189. // Look for '/config' on the child nodes
  190. for _, child := range node.Nodes {
  191. netname, isConfig := esr.parseNetworkKey(child.Key)
  192. if isConfig {
  193. networks = append(networks, netname)
  194. }
  195. }
  196. }
  197. return networks, resp.Index, nil
  198. }
  199. if etcdErr, ok := err.(etcd.Error); ok && etcdErr.Code == etcd.ErrorCodeKeyNotFound {
  200. // key not found: treat it as empty set
  201. return networks, etcdErr.Index, nil
  202. }
  203. return nil, 0, err
  204. }
  205. func (esr *etcdSubnetRegistry) watchNetworks(ctx context.Context, since uint64) (Event, uint64, error) {
  206. key := esr.etcdCfg.Prefix
  207. opts := &etcd.WatcherOptions{
  208. AfterIndex: since,
  209. Recursive: true,
  210. }
  211. e, err := esr.client().Watcher(key, opts).Next(ctx)
  212. if err != nil {
  213. return Event{}, 0, err
  214. }
  215. return esr.parseNetworkWatchResponse(e)
  216. }
  217. func (esr *etcdSubnetRegistry) client() etcd.KeysAPI {
  218. esr.mux.Lock()
  219. defer esr.mux.Unlock()
  220. return esr.cli
  221. }
  222. func (esr *etcdSubnetRegistry) resetClient() {
  223. esr.mux.Lock()
  224. defer esr.mux.Unlock()
  225. var err error
  226. esr.cli, err = newEtcdClient(esr.etcdCfg)
  227. if err != nil {
  228. panic(fmt.Errorf("resetClient: error recreating etcd client: %v", err))
  229. }
  230. }
  231. func ensureExpiration(resp *etcd.Response, ttl time.Duration) {
  232. if resp.Node.Expiration == nil {
  233. // should not be but calc it ourselves in this case
  234. log.Info("Expiration field missing on etcd response, calculating locally")
  235. exp := clock.Now().Add(time.Duration(ttl) * time.Second)
  236. resp.Node.Expiration = &exp
  237. }
  238. }
  239. func parseSubnetWatchResponse(resp *etcd.Response) (Event, error) {
  240. sn := parseSubnetKey(resp.Node.Key)
  241. if sn == nil {
  242. return Event{}, fmt.Errorf("%v %q: not a subnet, skipping", resp.Action, resp.Node.Key)
  243. }
  244. switch resp.Action {
  245. case "delete", "expire":
  246. return Event{
  247. EventRemoved,
  248. Lease{Subnet: *sn},
  249. "",
  250. }, nil
  251. default:
  252. attrs := &LeaseAttrs{}
  253. err := json.Unmarshal([]byte(resp.Node.Value), attrs)
  254. if err != nil {
  255. return Event{}, err
  256. }
  257. exp := time.Time{}
  258. if resp.Node.Expiration != nil {
  259. exp = *resp.Node.Expiration
  260. }
  261. evt := Event{
  262. EventAdded,
  263. Lease{
  264. Subnet: *sn,
  265. Attrs: *attrs,
  266. Expiration: exp,
  267. },
  268. "",
  269. }
  270. return evt, nil
  271. }
  272. }
  273. func (esr *etcdSubnetRegistry) parseNetworkWatchResponse(resp *etcd.Response) (Event, uint64, error) {
  274. index := resp.Node.ModifiedIndex
  275. netname, isConfig := esr.parseNetworkKey(resp.Node.Key)
  276. if netname == "" {
  277. return Event{}, index, ErrTryAgain
  278. }
  279. evt := Event{}
  280. switch resp.Action {
  281. case "delete":
  282. evt = Event{
  283. EventRemoved,
  284. Lease{},
  285. netname,
  286. }
  287. default:
  288. if !isConfig {
  289. // Ignore non .../<netname>/config keys; tell caller to try again
  290. return Event{}, index, ErrTryAgain
  291. }
  292. _, err := ParseConfig(resp.Node.Value)
  293. if err != nil {
  294. return Event{}, index, err
  295. }
  296. evt = Event{
  297. EventAdded,
  298. Lease{},
  299. netname,
  300. }
  301. }
  302. return evt, index, nil
  303. }
  304. // Returns network name from config key (eg, /coreos.com/network/foobar/config),
  305. // if the 'config' key isn't present we don't consider the network valid
  306. func (esr *etcdSubnetRegistry) parseNetworkKey(s string) (string, bool) {
  307. if parts := esr.networkRegex.FindStringSubmatch(s); len(parts) == 3 {
  308. return parts[1], parts[2] != ""
  309. }
  310. return "", false
  311. }
  312. func parseSubnetKey(s string) *ip.IP4Net {
  313. if parts := subnetRegex.FindStringSubmatch(s); len(parts) == 3 {
  314. snIp := net.ParseIP(parts[1]).To4()
  315. prefixLen, err := strconv.ParseUint(parts[2], 10, 5)
  316. if snIp != nil && err == nil {
  317. return &ip.IP4Net{IP: ip.FromIP(snIp), PrefixLen: uint(prefixLen)}
  318. }
  319. }
  320. return nil
  321. }