discovery.go 9.0 KB

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