discovery.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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 discovery provides an implementation of the cluster discovery that
  15. // is used by etcd.
  16. package discovery
  17. import (
  18. "errors"
  19. "fmt"
  20. "math"
  21. "net"
  22. "net/http"
  23. "net/url"
  24. "path"
  25. "sort"
  26. "strconv"
  27. "strings"
  28. "time"
  29. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/pkg/capnslog"
  30. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/jonboulle/clockwork"
  31. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  32. "github.com/coreos/etcd/client"
  33. "github.com/coreos/etcd/pkg/types"
  34. )
  35. var (
  36. plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "discovery")
  37. ErrInvalidURL = errors.New("discovery: invalid URL")
  38. ErrBadSizeKey = errors.New("discovery: size key is bad")
  39. ErrSizeNotFound = errors.New("discovery: size key not found")
  40. ErrTokenNotFound = errors.New("discovery: token not found")
  41. ErrDuplicateID = errors.New("discovery: found duplicate id")
  42. ErrDuplicateName = errors.New("discovery: found duplicate name")
  43. ErrFullCluster = errors.New("discovery: cluster is full")
  44. ErrTooManyRetries = errors.New("discovery: too many retries")
  45. ErrBadDiscoveryEndpoint = errors.New("discovery: bad discovery endpoint")
  46. )
  47. var (
  48. // Number of retries discovery will attempt before giving up and erroring out.
  49. nRetries = uint(math.MaxUint32)
  50. )
  51. // JoinCluster will connect to the discovery service at the given url, and
  52. // register the server represented by the given id and config to the cluster
  53. func JoinCluster(durl, dproxyurl string, id types.ID, config string) (string, error) {
  54. d, err := newDiscovery(durl, dproxyurl, id)
  55. if err != nil {
  56. return "", err
  57. }
  58. return d.joinCluster(config)
  59. }
  60. // GetCluster will connect to the discovery service at the given url and
  61. // retrieve a string describing the cluster
  62. func GetCluster(durl, dproxyurl string) (string, error) {
  63. d, err := newDiscovery(durl, dproxyurl, 0)
  64. if err != nil {
  65. return "", err
  66. }
  67. return d.getCluster()
  68. }
  69. type discovery struct {
  70. cluster string
  71. id types.ID
  72. c client.KeysAPI
  73. retries uint
  74. url *url.URL
  75. clock clockwork.Clock
  76. }
  77. // newProxyFunc builds a proxy function from the given string, which should
  78. // represent a URL that can be used as a proxy. It performs basic
  79. // sanitization of the URL and returns any error encountered.
  80. func newProxyFunc(proxy string) (func(*http.Request) (*url.URL, error), error) {
  81. if proxy == "" {
  82. return nil, nil
  83. }
  84. // Do a small amount of URL sanitization to help the user
  85. // Derived from net/http.ProxyFromEnvironment
  86. proxyURL, err := url.Parse(proxy)
  87. if err != nil || !strings.HasPrefix(proxyURL.Scheme, "http") {
  88. // proxy was bogus. Try prepending "http://" to it and
  89. // see if that parses correctly. If not, we ignore the
  90. // error and complain about the original one
  91. var err2 error
  92. proxyURL, err2 = url.Parse("http://" + proxy)
  93. if err2 == nil {
  94. err = nil
  95. }
  96. }
  97. if err != nil {
  98. return nil, fmt.Errorf("invalid proxy address %q: %v", proxy, err)
  99. }
  100. plog.Infof("using proxy %q", proxyURL.String())
  101. return http.ProxyURL(proxyURL), nil
  102. }
  103. func newDiscovery(durl, dproxyurl string, id types.ID) (*discovery, error) {
  104. u, err := url.Parse(durl)
  105. if err != nil {
  106. return nil, err
  107. }
  108. token := u.Path
  109. u.Path = ""
  110. pf, err := newProxyFunc(dproxyurl)
  111. if err != nil {
  112. return nil, err
  113. }
  114. cfg := client.Config{
  115. Transport: &http.Transport{
  116. Proxy: pf,
  117. Dial: (&net.Dialer{
  118. Timeout: 30 * time.Second,
  119. KeepAlive: 30 * time.Second,
  120. }).Dial,
  121. TLSHandshakeTimeout: 10 * time.Second,
  122. // TODO: add ResponseHeaderTimeout back when watch on discovery service writes header early
  123. },
  124. Endpoints: []string{u.String()},
  125. }
  126. c, err := client.New(cfg)
  127. if err != nil {
  128. return nil, err
  129. }
  130. dc := client.NewKeysAPIWithPrefix(c, "")
  131. return &discovery{
  132. cluster: token,
  133. c: dc,
  134. id: id,
  135. url: u,
  136. clock: clockwork.NewRealClock(),
  137. }, nil
  138. }
  139. func (d *discovery) joinCluster(config string) (string, error) {
  140. // fast path: if the cluster is full, return the error
  141. // do not need to register to the cluster in this case.
  142. if _, _, _, err := d.checkCluster(); err != nil {
  143. return "", err
  144. }
  145. if err := d.createSelf(config); err != nil {
  146. // Fails, even on a timeout, if createSelf times out.
  147. // TODO(barakmich): Retrying the same node might want to succeed here
  148. // (ie, createSelf should be idempotent for discovery).
  149. return "", err
  150. }
  151. nodes, size, index, err := d.checkCluster()
  152. if err != nil {
  153. return "", err
  154. }
  155. all, err := d.waitNodes(nodes, size, index)
  156. if err != nil {
  157. return "", err
  158. }
  159. return nodesToCluster(all, size)
  160. }
  161. func (d *discovery) getCluster() (string, error) {
  162. nodes, size, index, err := d.checkCluster()
  163. if err != nil {
  164. if err == ErrFullCluster {
  165. return nodesToCluster(nodes, size)
  166. }
  167. return "", err
  168. }
  169. all, err := d.waitNodes(nodes, size, index)
  170. if err != nil {
  171. return "", err
  172. }
  173. return nodesToCluster(all, size)
  174. }
  175. func (d *discovery) createSelf(contents string) error {
  176. ctx, cancel := context.WithTimeout(context.Background(), client.DefaultRequestTimeout)
  177. resp, err := d.c.Create(ctx, d.selfKey(), contents)
  178. cancel()
  179. if err != nil {
  180. if eerr, ok := err.(client.Error); ok && eerr.Code == client.ErrorCodeNodeExist {
  181. return ErrDuplicateID
  182. }
  183. return err
  184. }
  185. // ensure self appears on the server we connected to
  186. w := d.c.Watcher(d.selfKey(), &client.WatcherOptions{AfterIndex: resp.Node.CreatedIndex - 1})
  187. _, err = w.Next(context.Background())
  188. return err
  189. }
  190. func (d *discovery) checkCluster() ([]*client.Node, int, uint64, error) {
  191. configKey := path.Join("/", d.cluster, "_config")
  192. ctx, cancel := context.WithTimeout(context.Background(), client.DefaultRequestTimeout)
  193. // find cluster size
  194. resp, err := d.c.Get(ctx, path.Join(configKey, "size"), nil)
  195. cancel()
  196. if err != nil {
  197. if eerr, ok := err.(*client.Error); ok && eerr.Code == client.ErrorCodeKeyNotFound {
  198. return nil, 0, 0, ErrSizeNotFound
  199. }
  200. if err == client.ErrInvalidJSON {
  201. return nil, 0, 0, ErrBadDiscoveryEndpoint
  202. }
  203. if ce, ok := err.(*client.ClusterError); ok {
  204. plog.Error(ce.Detail())
  205. return d.checkClusterRetry()
  206. }
  207. return nil, 0, 0, err
  208. }
  209. size, err := strconv.Atoi(resp.Node.Value)
  210. if err != nil {
  211. return nil, 0, 0, ErrBadSizeKey
  212. }
  213. ctx, cancel = context.WithTimeout(context.Background(), client.DefaultRequestTimeout)
  214. resp, err = d.c.Get(ctx, d.cluster, nil)
  215. cancel()
  216. if err != nil {
  217. if ce, ok := err.(*client.ClusterError); ok {
  218. plog.Error(ce.Detail())
  219. return d.checkClusterRetry()
  220. }
  221. return nil, 0, 0, err
  222. }
  223. nodes := make([]*client.Node, 0)
  224. // append non-config keys to nodes
  225. for _, n := range resp.Node.Nodes {
  226. if !(path.Base(n.Key) == path.Base(configKey)) {
  227. nodes = append(nodes, n)
  228. }
  229. }
  230. snodes := sortableNodes{nodes}
  231. sort.Sort(snodes)
  232. // find self position
  233. for i := range nodes {
  234. if path.Base(nodes[i].Key) == path.Base(d.selfKey()) {
  235. break
  236. }
  237. if i >= size-1 {
  238. return nodes[:size], size, resp.Index, ErrFullCluster
  239. }
  240. }
  241. return nodes, size, resp.Index, nil
  242. }
  243. func (d *discovery) logAndBackoffForRetry(step string) {
  244. d.retries++
  245. retryTime := time.Second * (0x1 << d.retries)
  246. plog.Infof("%s: error connecting to %s, retrying in %s", step, d.url, retryTime)
  247. d.clock.Sleep(retryTime)
  248. }
  249. func (d *discovery) checkClusterRetry() ([]*client.Node, int, uint64, error) {
  250. if d.retries < nRetries {
  251. d.logAndBackoffForRetry("cluster status check")
  252. return d.checkCluster()
  253. }
  254. return nil, 0, 0, ErrTooManyRetries
  255. }
  256. func (d *discovery) waitNodesRetry() ([]*client.Node, error) {
  257. if d.retries < nRetries {
  258. d.logAndBackoffForRetry("waiting for other nodes")
  259. nodes, n, index, err := d.checkCluster()
  260. if err != nil {
  261. return nil, err
  262. }
  263. return d.waitNodes(nodes, n, index)
  264. }
  265. return nil, ErrTooManyRetries
  266. }
  267. func (d *discovery) waitNodes(nodes []*client.Node, size int, index uint64) ([]*client.Node, error) {
  268. if len(nodes) > size {
  269. nodes = nodes[:size]
  270. }
  271. // watch from the next index
  272. w := d.c.Watcher(d.cluster, &client.WatcherOptions{AfterIndex: index, Recursive: true})
  273. all := make([]*client.Node, len(nodes))
  274. copy(all, nodes)
  275. for _, n := range all {
  276. if path.Base(n.Key) == path.Base(d.selfKey()) {
  277. plog.Noticef("found self %s in the cluster", path.Base(d.selfKey()))
  278. } else {
  279. plog.Noticef("found peer %s in the cluster", path.Base(n.Key))
  280. }
  281. }
  282. // wait for others
  283. for len(all) < size {
  284. plog.Noticef("found %d peer(s), waiting for %d more", len(all), size-len(all))
  285. resp, err := w.Next(context.Background())
  286. if err != nil {
  287. if ce, ok := err.(*client.ClusterError); ok {
  288. plog.Error(ce.Detail())
  289. return d.waitNodesRetry()
  290. }
  291. return nil, err
  292. }
  293. plog.Noticef("found peer %s in the cluster", path.Base(resp.Node.Key))
  294. all = append(all, resp.Node)
  295. }
  296. plog.Noticef("found %d needed peer(s)", len(all))
  297. return all, nil
  298. }
  299. func (d *discovery) selfKey() string {
  300. return path.Join("/", d.cluster, d.id.String())
  301. }
  302. func nodesToCluster(ns []*client.Node, size int) (string, error) {
  303. s := make([]string, len(ns))
  304. for i, n := range ns {
  305. s[i] = n.Value
  306. }
  307. us := strings.Join(s, ",")
  308. m, err := types.NewURLsMap(us)
  309. if err != nil {
  310. return us, ErrInvalidURL
  311. }
  312. if m.Len() != size {
  313. return us, ErrDuplicateName
  314. }
  315. return us, nil
  316. }
  317. type sortableNodes struct{ Nodes []*client.Node }
  318. func (ns sortableNodes) Len() int { return len(ns.Nodes) }
  319. func (ns sortableNodes) Less(i, j int) bool {
  320. return ns.Nodes[i].CreatedIndex < ns.Nodes[j].CreatedIndex
  321. }
  322. func (ns sortableNodes) Swap(i, j int) { ns.Nodes[i], ns.Nodes[j] = ns.Nodes[j], ns.Nodes[i] }