election.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. // Copyright 2016 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 concurrency
  15. import (
  16. "errors"
  17. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  18. v3 "github.com/coreos/etcd/clientv3"
  19. "github.com/coreos/etcd/storage/storagepb"
  20. )
  21. var (
  22. ErrElectionNotLeader = errors.New("election: not leader")
  23. ErrElectionNoLeader = errors.New("election: no leader")
  24. )
  25. type Election struct {
  26. client *v3.Client
  27. keyPrefix string
  28. leaderKey string
  29. leaderRev int64
  30. leaderSession *Session
  31. }
  32. // NewElection returns a new election on a given key prefix.
  33. func NewElection(client *v3.Client, pfx string) *Election {
  34. return &Election{client: client, keyPrefix: pfx}
  35. }
  36. // Campaign puts a value as eligible for the election. It blocks until
  37. // it is elected, an error occurs, or the context is cancelled.
  38. func (e *Election) Campaign(ctx context.Context, val string) error {
  39. s, serr := NewSession(e.client)
  40. if serr != nil {
  41. return serr
  42. }
  43. k, rev, err := NewUniqueKV(ctx, e.client, e.keyPrefix, val, v3.WithLease(s.Lease()))
  44. if err == nil {
  45. err = waitDeletes(ctx, e.client, e.keyPrefix, v3.WithPrefix(), v3.WithRev(rev-1))
  46. }
  47. if err != nil {
  48. // clean up in case of context cancel
  49. select {
  50. case <-ctx.Done():
  51. e.client.Delete(e.client.Ctx(), k)
  52. default:
  53. }
  54. return err
  55. }
  56. e.leaderKey, e.leaderRev, e.leaderSession = k, rev, s
  57. return nil
  58. }
  59. // Proclaim lets the leader announce a new value without another election.
  60. func (e *Election) Proclaim(ctx context.Context, val string) error {
  61. if e.leaderSession == nil {
  62. return ErrElectionNotLeader
  63. }
  64. cmp := v3.Compare(v3.CreatedRevision(e.leaderKey), "=", e.leaderRev)
  65. txn := e.client.Txn(ctx).If(cmp)
  66. txn = txn.Then(v3.OpPut(e.leaderKey, val, v3.WithLease(e.leaderSession.Lease())))
  67. tresp, terr := txn.Commit()
  68. if terr != nil {
  69. return terr
  70. }
  71. if !tresp.Succeeded {
  72. e.leaderKey = ""
  73. return ErrElectionNotLeader
  74. }
  75. return nil
  76. }
  77. // Resign lets a leader start a new election.
  78. func (e *Election) Resign() (err error) {
  79. if e.leaderSession == nil {
  80. return nil
  81. }
  82. _, err = e.client.Delete(e.client.Ctx(), e.leaderKey)
  83. e.leaderKey = ""
  84. e.leaderSession = nil
  85. return err
  86. }
  87. // Leader returns the leader value for the current election.
  88. func (e *Election) Leader() (string, error) {
  89. resp, err := e.client.Get(e.client.Ctx(), e.keyPrefix, v3.WithFirstCreate()...)
  90. if err != nil {
  91. return "", err
  92. } else if len(resp.Kvs) == 0 {
  93. // no leader currently elected
  94. return "", ErrElectionNoLeader
  95. }
  96. return string(resp.Kvs[0].Value), nil
  97. }
  98. // Observe returns a channel that observes all leader proposal values as
  99. // GetResponse values on the current leader key. The channel closes when
  100. // the context is cancelled or the underlying watcher is otherwise disrupted.
  101. func (e *Election) Observe(ctx context.Context) <-chan v3.GetResponse {
  102. retc := make(chan v3.GetResponse)
  103. go e.observe(ctx, retc)
  104. return retc
  105. }
  106. func (e *Election) observe(ctx context.Context, ch chan<- v3.GetResponse) {
  107. defer close(ch)
  108. for {
  109. resp, err := e.client.Get(ctx, e.keyPrefix, v3.WithFirstCreate()...)
  110. if err != nil {
  111. return
  112. }
  113. var kv *storagepb.KeyValue
  114. cctx, cancel := context.WithCancel(ctx)
  115. if len(resp.Kvs) == 0 {
  116. // wait for first key put on prefix
  117. opts := []v3.OpOption{v3.WithRev(resp.Header.Revision), v3.WithPrefix()}
  118. wch := e.client.Watch(cctx, e.keyPrefix, opts...)
  119. for kv == nil {
  120. wr, ok := <-wch
  121. if !ok || wr.Err() != nil {
  122. cancel()
  123. return
  124. }
  125. // only accept PUTs; a DELETE will make observe() spin
  126. for _, ev := range wr.Events {
  127. if ev.Type == storagepb.PUT {
  128. kv = ev.Kv
  129. break
  130. }
  131. }
  132. }
  133. } else {
  134. kv = resp.Kvs[0]
  135. }
  136. wch := e.client.Watch(cctx, string(kv.Key), v3.WithRev(kv.ModRevision))
  137. keyDeleted := false
  138. for !keyDeleted {
  139. wr, ok := <-wch
  140. if !ok {
  141. return
  142. }
  143. for _, ev := range wr.Events {
  144. if ev.Type == storagepb.DELETE {
  145. keyDeleted = true
  146. break
  147. }
  148. resp.Header = &wr.Header
  149. resp.Kvs = []*storagepb.KeyValue{ev.Kv}
  150. select {
  151. case ch <- *resp:
  152. case <-cctx.Done():
  153. return
  154. }
  155. }
  156. }
  157. cancel()
  158. }
  159. }
  160. // Key returns the leader key if elected, empty string otherwise.
  161. func (e *Election) Key() string { return e.leaderKey }