cluster_util.go 8.4 KB

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