discovery.go 9.3 KB

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