cluster_util.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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 etcdserver
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "io/ioutil"
  19. "net/http"
  20. "sort"
  21. "time"
  22. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/go-semver/semver"
  23. "github.com/coreos/etcd/pkg/types"
  24. "github.com/coreos/etcd/version"
  25. )
  26. // isMemberBootstrapped tries to check if the given member has been bootstrapped
  27. // in the given cluster.
  28. func isMemberBootstrapped(cl *cluster, member string, rt http.RoundTripper, timeout time.Duration) bool {
  29. rcl, err := getClusterFromRemotePeers(getRemotePeerURLs(cl, member), timeout, false, rt)
  30. if err != nil {
  31. return false
  32. }
  33. id := cl.MemberByName(member).ID
  34. m := rcl.Member(id)
  35. if m == nil {
  36. return false
  37. }
  38. if len(m.ClientURLs) > 0 {
  39. return true
  40. }
  41. return false
  42. }
  43. // GetClusterFromRemotePeers takes a set of URLs representing etcd peers, and
  44. // attempts to construct a Cluster by accessing the members endpoint on one of
  45. // these URLs. The first URL to provide a response is used. If no URLs provide
  46. // a response, or a Cluster cannot be successfully created from a received
  47. // response, an error is returned.
  48. // Each request has a 10-second timeout. Because the upper limit of TTL is 5s,
  49. // 10 second is enough for building connection and finishing request.
  50. func GetClusterFromRemotePeers(urls []string, rt http.RoundTripper) (*cluster, error) {
  51. return getClusterFromRemotePeers(urls, 10*time.Second, true, rt)
  52. }
  53. // If logerr is true, it prints out more error messages.
  54. func getClusterFromRemotePeers(urls []string, timeout time.Duration, logerr bool, rt http.RoundTripper) (*cluster, error) {
  55. cc := &http.Client{
  56. Transport: rt,
  57. Timeout: timeout,
  58. }
  59. for _, u := range urls {
  60. resp, err := cc.Get(u + "/members")
  61. if err != nil {
  62. if logerr {
  63. plog.Warningf("could not get cluster response from %s: %v", u, err)
  64. }
  65. continue
  66. }
  67. b, err := ioutil.ReadAll(resp.Body)
  68. if err != nil {
  69. if logerr {
  70. plog.Warningf("could not read the body of cluster response: %v", err)
  71. }
  72. continue
  73. }
  74. var membs []*Member
  75. if err = json.Unmarshal(b, &membs); err != nil {
  76. if logerr {
  77. plog.Warningf("could not unmarshal cluster response: %v", err)
  78. }
  79. continue
  80. }
  81. id, err := types.IDFromString(resp.Header.Get("X-Etcd-Cluster-ID"))
  82. if err != nil {
  83. if logerr {
  84. plog.Warningf("could not parse the cluster ID from cluster res: %v", err)
  85. }
  86. continue
  87. }
  88. return newClusterFromMembers("", id, membs), nil
  89. }
  90. return nil, fmt.Errorf("could not retrieve cluster information from the given urls")
  91. }
  92. // getRemotePeerURLs returns peer urls of remote members in the cluster. The
  93. // returned list is sorted in ascending lexicographical order.
  94. func getRemotePeerURLs(cl Cluster, local string) []string {
  95. us := make([]string, 0)
  96. for _, m := range cl.Members() {
  97. if m.Name == local {
  98. continue
  99. }
  100. us = append(us, m.PeerURLs...)
  101. }
  102. sort.Strings(us)
  103. return us
  104. }
  105. // getVersions returns the versions of the members in the given cluster.
  106. // The key of the returned map is the member's ID. The value of the returned map
  107. // is the semver versions string, including server and cluster.
  108. // If it fails to get the version of a member, the key will be nil.
  109. func getVersions(cl Cluster, local types.ID, rt http.RoundTripper) map[string]*version.Versions {
  110. members := cl.Members()
  111. vers := make(map[string]*version.Versions)
  112. for _, m := range members {
  113. if m.ID == local {
  114. cv := "not_decided"
  115. if cl.Version() != nil {
  116. cv = cl.Version().String()
  117. }
  118. vers[m.ID.String()] = &version.Versions{Server: version.Version, Cluster: cv}
  119. continue
  120. }
  121. ver, err := getVersion(m, rt)
  122. if err != nil {
  123. plog.Warningf("cannot get the version of member %s (%v)", m.ID, err)
  124. vers[m.ID.String()] = nil
  125. } else {
  126. vers[m.ID.String()] = ver
  127. }
  128. }
  129. return vers
  130. }
  131. // decideClusterVersion decides the cluster version based on the versions map.
  132. // The returned version is the min server version in the map, or nil if the min
  133. // version in unknown.
  134. func decideClusterVersion(vers map[string]*version.Versions) *semver.Version {
  135. var cv *semver.Version
  136. lv := semver.Must(semver.NewVersion(version.Version))
  137. for mid, ver := range vers {
  138. if ver == nil {
  139. return nil
  140. }
  141. v, err := semver.NewVersion(ver.Server)
  142. if err != nil {
  143. plog.Errorf("cannot understand the version of member %s (%v)", mid, err)
  144. return nil
  145. }
  146. if lv.LessThan(*v) {
  147. plog.Warningf("the local etcd version %s is not up-to-date", lv.String())
  148. plog.Warningf("member %s has a higher version %s", mid, ver.Server)
  149. }
  150. if cv == nil {
  151. cv = v
  152. } else if v.LessThan(*cv) {
  153. cv = v
  154. }
  155. }
  156. return cv
  157. }
  158. // isCompatibleWithCluster return true if the local member has a compatible version with
  159. // the current running cluster.
  160. // The version is considered as compatible when at least one of the other members in the cluster has a
  161. // cluster version in the range of [MinClusterVersion, Version] and no known members has a cluster version
  162. // out of the range.
  163. // We set this rule since when the local member joins, another member might be offline.
  164. func isCompatibleWithCluster(cl Cluster, local types.ID, rt http.RoundTripper) bool {
  165. vers := getVersions(cl, local, rt)
  166. minV := semver.Must(semver.NewVersion(version.MinClusterVersion))
  167. maxV := semver.Must(semver.NewVersion(version.Version))
  168. maxV = &semver.Version{
  169. Major: maxV.Major,
  170. Minor: maxV.Minor,
  171. }
  172. return isCompatibleWithVers(vers, local, minV, maxV)
  173. }
  174. func isCompatibleWithVers(vers map[string]*version.Versions, local types.ID, minV, maxV *semver.Version) bool {
  175. var ok bool
  176. for id, v := range vers {
  177. // ignore comparison with local version
  178. if id == local.String() {
  179. continue
  180. }
  181. if v == nil {
  182. continue
  183. }
  184. clusterv, err := semver.NewVersion(v.Cluster)
  185. if err != nil {
  186. plog.Errorf("cannot understand the cluster version of member %s (%v)", id, err)
  187. continue
  188. }
  189. if clusterv.LessThan(*minV) {
  190. plog.Warningf("the running cluster version(%v) is lower than the minimal cluster version(%v) supported", clusterv.String(), minV.String())
  191. return false
  192. }
  193. if maxV.LessThan(*clusterv) {
  194. plog.Warningf("the running cluster version(%v) is higher than the maximum cluster version(%v) supported", clusterv.String(), maxV.String())
  195. return false
  196. }
  197. ok = true
  198. }
  199. return ok
  200. }
  201. // getVersion returns the Versions of the given member via its
  202. // peerURLs. Returns the last error if it fails to get the version.
  203. func getVersion(m *Member, rt http.RoundTripper) (*version.Versions, error) {
  204. cc := &http.Client{
  205. Transport: rt,
  206. }
  207. var (
  208. err error
  209. resp *http.Response
  210. )
  211. for _, u := range m.PeerURLs {
  212. resp, err = cc.Get(u + "/version")
  213. if err != nil {
  214. plog.Warningf("failed to reach the peerURL(%s) of member %s (%v)", u, m.ID, err)
  215. continue
  216. }
  217. // etcd 2.0 does not have version endpoint on peer url.
  218. if resp.StatusCode == http.StatusNotFound {
  219. resp.Body.Close()
  220. return &version.Versions{
  221. Server: "2.0.0",
  222. Cluster: "2.0.0",
  223. }, nil
  224. }
  225. var b []byte
  226. b, err = ioutil.ReadAll(resp.Body)
  227. resp.Body.Close()
  228. if err != nil {
  229. plog.Warningf("failed to read out the response body from the peerURL(%s) of member %s (%v)", u, m.ID, err)
  230. continue
  231. }
  232. var vers version.Versions
  233. if err = json.Unmarshal(b, &vers); err != nil {
  234. plog.Warningf("failed to unmarshal the response body got from the peerURL(%s) of member %s (%v)", u, m.ID, err)
  235. continue
  236. }
  237. return &vers, nil
  238. }
  239. return nil, err
  240. }
  241. func MustDetectDowngrade(cv *semver.Version) {
  242. lv := semver.Must(semver.NewVersion(version.Version))
  243. // only keep major.minor version for comparison against cluster version
  244. lv = &semver.Version{Major: lv.Major, Minor: lv.Minor}
  245. if cv != nil && lv.LessThan(*cv) {
  246. plog.Fatalf("cluster cannot be downgraded (current version: %s is lower than determined cluster version: %s).", version.Version, version.Cluster(cv.String()))
  247. }
  248. }