discovery.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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. ErrDuplicateName = errors.New("discovery: found duplicate name")
  41. ErrFullCluster = errors.New("discovery: cluster is full")
  42. ErrTooManyRetries = errors.New("discovery: too many retries")
  43. ErrBadDiscoveryEndpoint = errors.New("discovery: bad discovery endpoint")
  44. )
  45. var (
  46. // Number of retries discovery will attempt before giving up and erroring out.
  47. nRetries = uint(math.MaxUint32)
  48. )
  49. // JoinCluster will connect to the discovery service at the given url, and
  50. // register the server represented by the given id and config to the cluster
  51. func JoinCluster(durl, dproxyurl string, id types.ID, config string) (string, error) {
  52. d, err := newDiscovery(durl, dproxyurl, id)
  53. if err != nil {
  54. return "", err
  55. }
  56. return d.joinCluster(config)
  57. }
  58. // GetCluster will connect to the discovery service at the given url and
  59. // retrieve a string describing the cluster
  60. func GetCluster(durl, dproxyurl string) (string, error) {
  61. d, err := newDiscovery(durl, dproxyurl, 0)
  62. if err != nil {
  63. return "", err
  64. }
  65. return d.getCluster()
  66. }
  67. type discovery struct {
  68. cluster string
  69. id types.ID
  70. c client.KeysAPI
  71. retries uint
  72. url *url.URL
  73. clock clockwork.Clock
  74. }
  75. // newProxyFunc builds a proxy function from the given string, which should
  76. // represent a URL that can be used as a proxy. It performs basic
  77. // sanitization of the URL and returns any error encountered.
  78. func newProxyFunc(proxy string) (func(*http.Request) (*url.URL, error), error) {
  79. if proxy == "" {
  80. return nil, nil
  81. }
  82. // Do a small amount of URL sanitization to help the user
  83. // Derived from net/http.ProxyFromEnvironment
  84. proxyURL, err := url.Parse(proxy)
  85. if err != nil || !strings.HasPrefix(proxyURL.Scheme, "http") {
  86. // proxy was bogus. Try prepending "http://" to it and
  87. // see if that parses correctly. If not, we ignore the
  88. // error and complain about the original one
  89. var err2 error
  90. proxyURL, err2 = url.Parse("http://" + proxy)
  91. if err2 == nil {
  92. err = nil
  93. }
  94. }
  95. if err != nil {
  96. return nil, fmt.Errorf("invalid proxy address %q: %v", proxy, err)
  97. }
  98. plog.Infof("using proxy %q", proxyURL.String())
  99. return http.ProxyURL(proxyURL), nil
  100. }
  101. func newDiscovery(durl, dproxyurl string, id types.ID) (*discovery, error) {
  102. u, err := url.Parse(durl)
  103. if err != nil {
  104. return nil, err
  105. }
  106. token := u.Path
  107. u.Path = ""
  108. pf, err := newProxyFunc(dproxyurl)
  109. if err != nil {
  110. return nil, err
  111. }
  112. cfg := client.Config{
  113. Transport: &http.Transport{
  114. Proxy: pf,
  115. Dial: (&net.Dialer{
  116. Timeout: 30 * time.Second,
  117. KeepAlive: 30 * time.Second,
  118. }).Dial,
  119. TLSHandshakeTimeout: 10 * time.Second,
  120. // TODO: add ResponseHeaderTimeout back when watch on discovery service writes header early
  121. },
  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] }