cluster.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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 membership
  15. import (
  16. "bytes"
  17. "context"
  18. "crypto/sha1"
  19. "encoding/binary"
  20. "encoding/json"
  21. "fmt"
  22. "path"
  23. "sort"
  24. "strings"
  25. "sync"
  26. "time"
  27. "github.com/coreos/etcd/mvcc/backend"
  28. "github.com/coreos/etcd/pkg/netutil"
  29. "github.com/coreos/etcd/pkg/types"
  30. "github.com/coreos/etcd/raft"
  31. "github.com/coreos/etcd/raft/raftpb"
  32. "github.com/coreos/etcd/store"
  33. "github.com/coreos/etcd/version"
  34. "github.com/coreos/go-semver/semver"
  35. )
  36. // RaftCluster is a list of Members that belong to the same raft cluster
  37. type RaftCluster struct {
  38. id types.ID
  39. token string
  40. store store.Store
  41. be backend.Backend
  42. sync.Mutex // guards the fields below
  43. version *semver.Version
  44. members map[types.ID]*Member
  45. // removed contains the ids of removed members in the cluster.
  46. // removed id cannot be reused.
  47. removed map[types.ID]bool
  48. }
  49. func NewClusterFromURLsMap(token string, urlsmap types.URLsMap) (*RaftCluster, error) {
  50. c := NewCluster(token)
  51. for name, urls := range urlsmap {
  52. m := NewMember(name, urls, token, nil)
  53. if _, ok := c.members[m.ID]; ok {
  54. return nil, fmt.Errorf("member exists with identical ID %v", m)
  55. }
  56. if uint64(m.ID) == raft.None {
  57. return nil, fmt.Errorf("cannot use %x as member id", raft.None)
  58. }
  59. c.members[m.ID] = m
  60. }
  61. c.genID()
  62. return c, nil
  63. }
  64. func NewClusterFromMembers(token string, id types.ID, membs []*Member) *RaftCluster {
  65. c := NewCluster(token)
  66. c.id = id
  67. for _, m := range membs {
  68. c.members[m.ID] = m
  69. }
  70. return c
  71. }
  72. func NewCluster(token string) *RaftCluster {
  73. return &RaftCluster{
  74. token: token,
  75. members: make(map[types.ID]*Member),
  76. removed: make(map[types.ID]bool),
  77. }
  78. }
  79. func (c *RaftCluster) ID() types.ID { return c.id }
  80. func (c *RaftCluster) Members() []*Member {
  81. c.Lock()
  82. defer c.Unlock()
  83. var ms MembersByID
  84. for _, m := range c.members {
  85. ms = append(ms, m.Clone())
  86. }
  87. sort.Sort(ms)
  88. return []*Member(ms)
  89. }
  90. func (c *RaftCluster) Member(id types.ID) *Member {
  91. c.Lock()
  92. defer c.Unlock()
  93. return c.members[id].Clone()
  94. }
  95. // MemberByName returns a Member with the given name if exists.
  96. // If more than one member has the given name, it will panic.
  97. func (c *RaftCluster) MemberByName(name string) *Member {
  98. c.Lock()
  99. defer c.Unlock()
  100. var memb *Member
  101. for _, m := range c.members {
  102. if m.Name == name {
  103. if memb != nil {
  104. plog.Panicf("two members with the given name %q exist", name)
  105. }
  106. memb = m
  107. }
  108. }
  109. return memb.Clone()
  110. }
  111. func (c *RaftCluster) MemberIDs() []types.ID {
  112. c.Lock()
  113. defer c.Unlock()
  114. var ids []types.ID
  115. for _, m := range c.members {
  116. ids = append(ids, m.ID)
  117. }
  118. sort.Sort(types.IDSlice(ids))
  119. return ids
  120. }
  121. func (c *RaftCluster) IsIDRemoved(id types.ID) bool {
  122. c.Lock()
  123. defer c.Unlock()
  124. return c.removed[id]
  125. }
  126. // PeerURLs returns a list of all peer addresses.
  127. // The returned list is sorted in ascending lexicographical order.
  128. func (c *RaftCluster) PeerURLs() []string {
  129. c.Lock()
  130. defer c.Unlock()
  131. urls := make([]string, 0)
  132. for _, p := range c.members {
  133. urls = append(urls, p.PeerURLs...)
  134. }
  135. sort.Strings(urls)
  136. return urls
  137. }
  138. // ClientURLs returns a list of all client addresses.
  139. // The returned list is sorted in ascending lexicographical order.
  140. func (c *RaftCluster) ClientURLs() []string {
  141. c.Lock()
  142. defer c.Unlock()
  143. urls := make([]string, 0)
  144. for _, p := range c.members {
  145. urls = append(urls, p.ClientURLs...)
  146. }
  147. sort.Strings(urls)
  148. return urls
  149. }
  150. func (c *RaftCluster) String() string {
  151. c.Lock()
  152. defer c.Unlock()
  153. b := &bytes.Buffer{}
  154. fmt.Fprintf(b, "{ClusterID:%s ", c.id)
  155. var ms []string
  156. for _, m := range c.members {
  157. ms = append(ms, fmt.Sprintf("%+v", m))
  158. }
  159. fmt.Fprintf(b, "Members:[%s] ", strings.Join(ms, " "))
  160. var ids []string
  161. for id := range c.removed {
  162. ids = append(ids, id.String())
  163. }
  164. fmt.Fprintf(b, "RemovedMemberIDs:[%s]}", strings.Join(ids, " "))
  165. return b.String()
  166. }
  167. func (c *RaftCluster) genID() {
  168. mIDs := c.MemberIDs()
  169. b := make([]byte, 8*len(mIDs))
  170. for i, id := range mIDs {
  171. binary.BigEndian.PutUint64(b[8*i:], uint64(id))
  172. }
  173. hash := sha1.Sum(b)
  174. c.id = types.ID(binary.BigEndian.Uint64(hash[:8]))
  175. }
  176. func (c *RaftCluster) SetID(id types.ID) { c.id = id }
  177. func (c *RaftCluster) SetStore(st store.Store) { c.store = st }
  178. func (c *RaftCluster) SetBackend(be backend.Backend) {
  179. c.be = be
  180. mustCreateBackendBuckets(c.be)
  181. }
  182. func (c *RaftCluster) Recover(onSet func(*semver.Version)) {
  183. c.Lock()
  184. defer c.Unlock()
  185. c.members, c.removed = membersFromStore(c.store)
  186. c.version = clusterVersionFromStore(c.store)
  187. mustDetectDowngrade(c.version)
  188. onSet(c.version)
  189. for _, m := range c.members {
  190. plog.Infof("added member %s %v to cluster %s from store", m.ID, m.PeerURLs, c.id)
  191. }
  192. if c.version != nil {
  193. plog.Infof("set the cluster version to %v from store", version.Cluster(c.version.String()))
  194. }
  195. }
  196. // ValidateConfigurationChange takes a proposed ConfChange and
  197. // ensures that it is still valid.
  198. func (c *RaftCluster) ValidateConfigurationChange(cc raftpb.ConfChange) error {
  199. members, removed := membersFromStore(c.store)
  200. id := types.ID(cc.NodeID)
  201. if removed[id] {
  202. return ErrIDRemoved
  203. }
  204. switch cc.Type {
  205. case raftpb.ConfChangeAddNode:
  206. if members[id] != nil {
  207. return ErrIDExists
  208. }
  209. urls := make(map[string]bool)
  210. for _, m := range members {
  211. for _, u := range m.PeerURLs {
  212. urls[u] = true
  213. }
  214. }
  215. m := new(Member)
  216. if err := json.Unmarshal(cc.Context, m); err != nil {
  217. plog.Panicf("unmarshal member should never fail: %v", err)
  218. }
  219. for _, u := range m.PeerURLs {
  220. if urls[u] {
  221. return ErrPeerURLexists
  222. }
  223. }
  224. case raftpb.ConfChangeRemoveNode:
  225. if members[id] == nil {
  226. return ErrIDNotFound
  227. }
  228. case raftpb.ConfChangeUpdateNode:
  229. if members[id] == nil {
  230. return ErrIDNotFound
  231. }
  232. urls := make(map[string]bool)
  233. for _, m := range members {
  234. if m.ID == id {
  235. continue
  236. }
  237. for _, u := range m.PeerURLs {
  238. urls[u] = true
  239. }
  240. }
  241. m := new(Member)
  242. if err := json.Unmarshal(cc.Context, m); err != nil {
  243. plog.Panicf("unmarshal member should never fail: %v", err)
  244. }
  245. for _, u := range m.PeerURLs {
  246. if urls[u] {
  247. return ErrPeerURLexists
  248. }
  249. }
  250. default:
  251. plog.Panicf("ConfChange type should be either AddNode, RemoveNode or UpdateNode")
  252. }
  253. return nil
  254. }
  255. // AddMember adds a new Member into the cluster, and saves the given member's
  256. // raftAttributes into the store. The given member should have empty attributes.
  257. // A Member with a matching id must not exist.
  258. func (c *RaftCluster) AddMember(m *Member) {
  259. c.Lock()
  260. defer c.Unlock()
  261. if c.store != nil {
  262. mustSaveMemberToStore(c.store, m)
  263. }
  264. if c.be != nil {
  265. mustSaveMemberToBackend(c.be, m)
  266. }
  267. c.members[m.ID] = m
  268. plog.Infof("added member %s %v to cluster %s", m.ID, m.PeerURLs, c.id)
  269. }
  270. // RemoveMember removes a member from the store.
  271. // The given id MUST exist, or the function panics.
  272. func (c *RaftCluster) RemoveMember(id types.ID) {
  273. c.Lock()
  274. defer c.Unlock()
  275. if c.store != nil {
  276. mustDeleteMemberFromStore(c.store, id)
  277. }
  278. if c.be != nil {
  279. mustDeleteMemberFromBackend(c.be, id)
  280. }
  281. delete(c.members, id)
  282. c.removed[id] = true
  283. plog.Infof("removed member %s from cluster %s", id, c.id)
  284. }
  285. func (c *RaftCluster) UpdateAttributes(id types.ID, attr Attributes) {
  286. c.Lock()
  287. defer c.Unlock()
  288. if m, ok := c.members[id]; ok {
  289. m.Attributes = attr
  290. if c.store != nil {
  291. mustUpdateMemberAttrInStore(c.store, m)
  292. }
  293. if c.be != nil {
  294. mustSaveMemberToBackend(c.be, m)
  295. }
  296. return
  297. }
  298. _, ok := c.removed[id]
  299. if !ok {
  300. plog.Panicf("error updating attributes of unknown member %s", id)
  301. }
  302. plog.Warningf("skipped updating attributes of removed member %s", id)
  303. }
  304. func (c *RaftCluster) UpdateRaftAttributes(id types.ID, raftAttr RaftAttributes) {
  305. c.Lock()
  306. defer c.Unlock()
  307. c.members[id].RaftAttributes = raftAttr
  308. if c.store != nil {
  309. mustUpdateMemberInStore(c.store, c.members[id])
  310. }
  311. if c.be != nil {
  312. mustSaveMemberToBackend(c.be, c.members[id])
  313. }
  314. plog.Noticef("updated member %s %v in cluster %s", id, raftAttr.PeerURLs, c.id)
  315. }
  316. func (c *RaftCluster) Version() *semver.Version {
  317. c.Lock()
  318. defer c.Unlock()
  319. if c.version == nil {
  320. return nil
  321. }
  322. return semver.Must(semver.NewVersion(c.version.String()))
  323. }
  324. func (c *RaftCluster) SetVersion(ver *semver.Version, onSet func(*semver.Version)) {
  325. c.Lock()
  326. defer c.Unlock()
  327. if c.version != nil {
  328. plog.Noticef("updated the cluster version from %v to %v", version.Cluster(c.version.String()), version.Cluster(ver.String()))
  329. } else {
  330. plog.Noticef("set the initial cluster version to %v", version.Cluster(ver.String()))
  331. }
  332. c.version = ver
  333. mustDetectDowngrade(c.version)
  334. if c.store != nil {
  335. mustSaveClusterVersionToStore(c.store, ver)
  336. }
  337. if c.be != nil {
  338. mustSaveClusterVersionToBackend(c.be, ver)
  339. }
  340. onSet(ver)
  341. }
  342. func (c *RaftCluster) IsReadyToAddNewMember() bool {
  343. nmembers := 1
  344. nstarted := 0
  345. for _, member := range c.members {
  346. if member.IsStarted() {
  347. nstarted++
  348. }
  349. nmembers++
  350. }
  351. if nstarted == 1 && nmembers == 2 {
  352. // a case of adding a new node to 1-member cluster for restoring cluster data
  353. // https://github.com/coreos/etcd/blob/master/Documentation/v2/admin_guide.md#restoring-the-cluster
  354. plog.Debugf("The number of started member is 1. This cluster can accept add member request.")
  355. return true
  356. }
  357. nquorum := nmembers/2 + 1
  358. if nstarted < nquorum {
  359. plog.Warningf("Reject add member request: the number of started member (%d) will be less than the quorum number of the cluster (%d)", nstarted, nquorum)
  360. return false
  361. }
  362. return true
  363. }
  364. func (c *RaftCluster) IsReadyToRemoveMember(id uint64) bool {
  365. nmembers := 0
  366. nstarted := 0
  367. for _, member := range c.members {
  368. if uint64(member.ID) == id {
  369. continue
  370. }
  371. if member.IsStarted() {
  372. nstarted++
  373. }
  374. nmembers++
  375. }
  376. nquorum := nmembers/2 + 1
  377. if nstarted < nquorum {
  378. plog.Warningf("Reject remove member request: the number of started member (%d) will be less than the quorum number of the cluster (%d)", nstarted, nquorum)
  379. return false
  380. }
  381. return true
  382. }
  383. func membersFromStore(st store.Store) (map[types.ID]*Member, map[types.ID]bool) {
  384. members := make(map[types.ID]*Member)
  385. removed := make(map[types.ID]bool)
  386. e, err := st.Get(StoreMembersPrefix, true, true)
  387. if err != nil {
  388. if isKeyNotFound(err) {
  389. return members, removed
  390. }
  391. plog.Panicf("get storeMembers should never fail: %v", err)
  392. }
  393. for _, n := range e.Node.Nodes {
  394. var m *Member
  395. m, err = nodeToMember(n)
  396. if err != nil {
  397. plog.Panicf("nodeToMember should never fail: %v", err)
  398. }
  399. members[m.ID] = m
  400. }
  401. e, err = st.Get(storeRemovedMembersPrefix, true, true)
  402. if err != nil {
  403. if isKeyNotFound(err) {
  404. return members, removed
  405. }
  406. plog.Panicf("get storeRemovedMembers should never fail: %v", err)
  407. }
  408. for _, n := range e.Node.Nodes {
  409. removed[MustParseMemberIDFromKey(n.Key)] = true
  410. }
  411. return members, removed
  412. }
  413. func clusterVersionFromStore(st store.Store) *semver.Version {
  414. e, err := st.Get(path.Join(storePrefix, "version"), false, false)
  415. if err != nil {
  416. if isKeyNotFound(err) {
  417. return nil
  418. }
  419. plog.Panicf("unexpected error (%v) when getting cluster version from store", err)
  420. }
  421. return semver.Must(semver.NewVersion(*e.Node.Value))
  422. }
  423. // ValidateClusterAndAssignIDs validates the local cluster by matching the PeerURLs
  424. // with the existing cluster. If the validation succeeds, it assigns the IDs
  425. // from the existing cluster to the local cluster.
  426. // If the validation fails, an error will be returned.
  427. func ValidateClusterAndAssignIDs(local *RaftCluster, existing *RaftCluster) error {
  428. ems := existing.Members()
  429. lms := local.Members()
  430. if len(ems) != len(lms) {
  431. return fmt.Errorf("member count is unequal")
  432. }
  433. sort.Sort(MembersByPeerURLs(ems))
  434. sort.Sort(MembersByPeerURLs(lms))
  435. ctx, cancel := context.WithTimeout(context.TODO(), 30*time.Second)
  436. defer cancel()
  437. for i := range ems {
  438. if ok, err := netutil.URLStringsEqual(ctx, ems[i].PeerURLs, lms[i].PeerURLs); !ok {
  439. return fmt.Errorf("unmatched member while checking PeerURLs (%v)", err)
  440. }
  441. lms[i].ID = ems[i].ID
  442. }
  443. local.members = make(map[types.ID]*Member)
  444. for _, m := range lms {
  445. local.members[m.ID] = m
  446. }
  447. return nil
  448. }
  449. func mustDetectDowngrade(cv *semver.Version) {
  450. lv := semver.Must(semver.NewVersion(version.Version))
  451. // only keep major.minor version for comparison against cluster version
  452. lv = &semver.Version{Major: lv.Major, Minor: lv.Minor}
  453. if cv != nil && lv.LessThan(*cv) {
  454. plog.Fatalf("cluster cannot be downgraded (current version: %s is lower than determined cluster version: %s).", version.Version, version.Cluster(cv.String()))
  455. }
  456. }