discovery.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. // Copyright 2015 The etcd 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 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/http"
  22. "net/url"
  23. "path"
  24. "sort"
  25. "strconv"
  26. "strings"
  27. "time"
  28. "github.com/coreos/etcd/client"
  29. "github.com/coreos/etcd/pkg/transport"
  30. "github.com/coreos/etcd/pkg/types"
  31. "github.com/coreos/pkg/capnslog"
  32. "github.com/jonboulle/clockwork"
  33. "golang.org/x/net/context"
  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. // TODO: add ResponseHeaderTimeout back when watch on discovery service writes header early
  115. tr, err := transport.NewTransport(transport.TLSInfo{}, 30*time.Second)
  116. if err != nil {
  117. return nil, err
  118. }
  119. tr.Proxy = pf
  120. cfg := client.Config{
  121. Transport: tr,
  122. Endpoints: []string{u.String()},
  123. }
  124. c, err := client.New(cfg)
  125. if err != nil {
  126. return nil, err
  127. }
  128. dc := client.NewKeysAPIWithPrefix(c, "")
  129. return &discovery{
  130. cluster: token,
  131. c: dc,
  132. id: id,
  133. url: u,
  134. clock: clockwork.NewRealClock(),
  135. }, nil
  136. }
  137. func (d *discovery) joinCluster(config string) (string, error) {
  138. // fast path: if the cluster is full, return the error
  139. // do not need to register to the cluster in this case.
  140. if _, _, _, err := d.checkCluster(); err != nil {
  141. return "", err
  142. }
  143. if err := d.createSelf(config); err != nil {
  144. // Fails, even on a timeout, if createSelf times out.
  145. // TODO(barakmich): Retrying the same node might want to succeed here
  146. // (ie, createSelf should be idempotent for discovery).
  147. return "", err
  148. }
  149. nodes, size, index, err := d.checkCluster()
  150. if err != nil {
  151. return "", err
  152. }
  153. all, err := d.waitNodes(nodes, size, index)
  154. if err != nil {
  155. return "", err
  156. }
  157. return nodesToCluster(all, size)
  158. }
  159. func (d *discovery) getCluster() (string, error) {
  160. nodes, size, index, err := d.checkCluster()
  161. if err != nil {
  162. if err == ErrFullCluster {
  163. return nodesToCluster(nodes, size)
  164. }
  165. return "", err
  166. }
  167. all, err := d.waitNodes(nodes, size, index)
  168. if err != nil {
  169. return "", err
  170. }
  171. return nodesToCluster(all, size)
  172. }
  173. func (d *discovery) createSelf(contents string) error {
  174. ctx, cancel := context.WithTimeout(context.Background(), client.DefaultRequestTimeout)
  175. resp, err := d.c.Create(ctx, d.selfKey(), contents)
  176. cancel()
  177. if err != nil {
  178. if eerr, ok := err.(client.Error); ok && eerr.Code == client.ErrorCodeNodeExist {
  179. return ErrDuplicateID
  180. }
  181. return err
  182. }
  183. // ensure self appears on the server we connected to
  184. w := d.c.Watcher(d.selfKey(), &client.WatcherOptions{AfterIndex: resp.Node.CreatedIndex - 1})
  185. _, err = w.Next(context.Background())
  186. return err
  187. }
  188. func (d *discovery) checkCluster() ([]*client.Node, int, uint64, error) {
  189. configKey := path.Join("/", d.cluster, "_config")
  190. ctx, cancel := context.WithTimeout(context.Background(), client.DefaultRequestTimeout)
  191. // find cluster size
  192. resp, err := d.c.Get(ctx, path.Join(configKey, "size"), nil)
  193. cancel()
  194. if err != nil {
  195. if eerr, ok := err.(*client.Error); ok && eerr.Code == client.ErrorCodeKeyNotFound {
  196. return nil, 0, 0, ErrSizeNotFound
  197. }
  198. if err == client.ErrInvalidJSON {
  199. return nil, 0, 0, ErrBadDiscoveryEndpoint
  200. }
  201. if ce, ok := err.(*client.ClusterError); ok {
  202. plog.Error(ce.Detail())
  203. return d.checkClusterRetry()
  204. }
  205. return nil, 0, 0, err
  206. }
  207. size, err := strconv.Atoi(resp.Node.Value)
  208. if err != nil {
  209. return nil, 0, 0, ErrBadSizeKey
  210. }
  211. ctx, cancel = context.WithTimeout(context.Background(), client.DefaultRequestTimeout)
  212. resp, err = d.c.Get(ctx, d.cluster, nil)
  213. cancel()
  214. if err != nil {
  215. if ce, ok := err.(*client.ClusterError); ok {
  216. plog.Error(ce.Detail())
  217. return d.checkClusterRetry()
  218. }
  219. return nil, 0, 0, err
  220. }
  221. nodes := make([]*client.Node, 0)
  222. // append non-config keys to nodes
  223. for _, n := range resp.Node.Nodes {
  224. if !(path.Base(n.Key) == path.Base(configKey)) {
  225. nodes = append(nodes, n)
  226. }
  227. }
  228. snodes := sortableNodes{nodes}
  229. sort.Sort(snodes)
  230. // find self position
  231. for i := range nodes {
  232. if path.Base(nodes[i].Key) == path.Base(d.selfKey()) {
  233. break
  234. }
  235. if i >= size-1 {
  236. return nodes[:size], size, resp.Index, ErrFullCluster
  237. }
  238. }
  239. return nodes, size, resp.Index, nil
  240. }
  241. func (d *discovery) logAndBackoffForRetry(step string) {
  242. d.retries++
  243. retryTime := time.Second * (0x1 << d.retries)
  244. plog.Infof("%s: error connecting to %s, retrying in %s", step, d.url, retryTime)
  245. d.clock.Sleep(retryTime)
  246. }
  247. func (d *discovery) checkClusterRetry() ([]*client.Node, int, uint64, error) {
  248. if d.retries < nRetries {
  249. d.logAndBackoffForRetry("cluster status check")
  250. return d.checkCluster()
  251. }
  252. return nil, 0, 0, ErrTooManyRetries
  253. }
  254. func (d *discovery) waitNodesRetry() ([]*client.Node, error) {
  255. if d.retries < nRetries {
  256. d.logAndBackoffForRetry("waiting for other nodes")
  257. nodes, n, index, err := d.checkCluster()
  258. if err != nil {
  259. return nil, err
  260. }
  261. return d.waitNodes(nodes, n, index)
  262. }
  263. return nil, ErrTooManyRetries
  264. }
  265. func (d *discovery) waitNodes(nodes []*client.Node, size int, index uint64) ([]*client.Node, error) {
  266. if len(nodes) > size {
  267. nodes = nodes[:size]
  268. }
  269. // watch from the next index
  270. w := d.c.Watcher(d.cluster, &client.WatcherOptions{AfterIndex: index, Recursive: true})
  271. all := make([]*client.Node, len(nodes))
  272. copy(all, nodes)
  273. for _, n := range all {
  274. if path.Base(n.Key) == path.Base(d.selfKey()) {
  275. plog.Noticef("found self %s in the cluster", path.Base(d.selfKey()))
  276. } else {
  277. plog.Noticef("found peer %s in the cluster", path.Base(n.Key))
  278. }
  279. }
  280. // wait for others
  281. for len(all) < size {
  282. plog.Noticef("found %d peer(s), waiting for %d more", len(all), size-len(all))
  283. resp, err := w.Next(context.Background())
  284. if err != nil {
  285. if ce, ok := err.(*client.ClusterError); ok {
  286. plog.Error(ce.Detail())
  287. return d.waitNodesRetry()
  288. }
  289. return nil, err
  290. }
  291. plog.Noticef("found peer %s in the cluster", path.Base(resp.Node.Key))
  292. all = append(all, resp.Node)
  293. }
  294. plog.Noticef("found %d needed peer(s)", len(all))
  295. return all, nil
  296. }
  297. func (d *discovery) selfKey() string {
  298. return path.Join("/", d.cluster, d.id.String())
  299. }
  300. func nodesToCluster(ns []*client.Node, size int) (string, error) {
  301. s := make([]string, len(ns))
  302. for i, n := range ns {
  303. s[i] = n.Value
  304. }
  305. us := strings.Join(s, ",")
  306. m, err := types.NewURLsMap(us)
  307. if err != nil {
  308. return us, ErrInvalidURL
  309. }
  310. if m.Len() != size {
  311. return us, ErrDuplicateName
  312. }
  313. return us, nil
  314. }
  315. type sortableNodes struct{ Nodes []*client.Node }
  316. func (ns sortableNodes) Len() int { return len(ns.Nodes) }
  317. func (ns sortableNodes) Less(i, j int) bool {
  318. return ns.Nodes[i].CreatedIndex < ns.Nodes[j].CreatedIndex
  319. }
  320. func (ns sortableNodes) Swap(i, j int) { ns.Nodes[i], ns.Nodes[j] = ns.Nodes[j], ns.Nodes[i] }