election.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. // Copyright 2016 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 concurrency
  15. import (
  16. "context"
  17. "errors"
  18. "fmt"
  19. v3 "github.com/coreos/etcd/clientv3"
  20. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  21. "github.com/coreos/etcd/mvcc/mvccpb"
  22. )
  23. var (
  24. ErrElectionNotLeader = errors.New("election: not leader")
  25. ErrElectionNoLeader = errors.New("election: no leader")
  26. )
  27. type Election struct {
  28. session *Session
  29. keyPrefix string
  30. leaderKey string
  31. leaderRev int64
  32. leaderSession *Session
  33. hdr *pb.ResponseHeader
  34. }
  35. // NewElection returns a new election on a given key prefix.
  36. func NewElection(s *Session, pfx string) *Election {
  37. return &Election{session: s, keyPrefix: pfx + "/"}
  38. }
  39. // ResumeElection initializes an election with a known leader.
  40. func ResumeElection(s *Session, pfx string, leaderKey string, leaderRev int64) *Election {
  41. return &Election{
  42. session: s,
  43. keyPrefix: pfx,
  44. leaderKey: leaderKey,
  45. leaderRev: leaderRev,
  46. leaderSession: s,
  47. }
  48. }
  49. // Campaign puts a value as eligible for the election. It blocks until
  50. // it is elected, an error occurs, or the context is cancelled.
  51. func (e *Election) Campaign(ctx context.Context, val string) error {
  52. s := e.session
  53. client := e.session.Client()
  54. k := fmt.Sprintf("%s%x", e.keyPrefix, s.Lease())
  55. txn := client.Txn(ctx).If(v3.Compare(v3.CreateRevision(k), "=", 0))
  56. txn = txn.Then(v3.OpPut(k, val, v3.WithLease(s.Lease())))
  57. txn = txn.Else(v3.OpGet(k))
  58. resp, err := txn.Commit()
  59. if err != nil {
  60. return err
  61. }
  62. e.leaderKey, e.leaderRev, e.leaderSession = k, resp.Header.Revision, s
  63. if !resp.Succeeded {
  64. kv := resp.Responses[0].GetResponseRange().Kvs[0]
  65. e.leaderRev = kv.CreateRevision
  66. if string(kv.Value) != val {
  67. if err = e.Proclaim(ctx, val); err != nil {
  68. e.Resign(ctx)
  69. return err
  70. }
  71. }
  72. }
  73. _, err = waitDeletes(ctx, client, e.keyPrefix, e.leaderRev-1)
  74. if err != nil {
  75. // clean up in case of context cancel
  76. select {
  77. case <-ctx.Done():
  78. e.Resign(client.Ctx())
  79. default:
  80. e.leaderSession = nil
  81. }
  82. return err
  83. }
  84. e.hdr = resp.Header
  85. return nil
  86. }
  87. // Proclaim lets the leader announce a new value without another election.
  88. func (e *Election) Proclaim(ctx context.Context, val string) error {
  89. if e.leaderSession == nil {
  90. return ErrElectionNotLeader
  91. }
  92. client := e.session.Client()
  93. cmp := v3.Compare(v3.CreateRevision(e.leaderKey), "=", e.leaderRev)
  94. txn := client.Txn(ctx).If(cmp)
  95. txn = txn.Then(v3.OpPut(e.leaderKey, val, v3.WithLease(e.leaderSession.Lease())))
  96. tresp, terr := txn.Commit()
  97. if terr != nil {
  98. return terr
  99. }
  100. if !tresp.Succeeded {
  101. e.leaderKey = ""
  102. return ErrElectionNotLeader
  103. }
  104. e.hdr = tresp.Header
  105. return nil
  106. }
  107. // Resign lets a leader start a new election.
  108. func (e *Election) Resign(ctx context.Context) (err error) {
  109. if e.leaderSession == nil {
  110. return nil
  111. }
  112. client := e.session.Client()
  113. cmp := v3.Compare(v3.CreateRevision(e.leaderKey), "=", e.leaderRev)
  114. resp, err := client.Txn(ctx).If(cmp).Then(v3.OpDelete(e.leaderKey)).Commit()
  115. if err == nil {
  116. e.hdr = resp.Header
  117. }
  118. e.leaderKey = ""
  119. e.leaderSession = nil
  120. return err
  121. }
  122. // Leader returns the leader value for the current election.
  123. func (e *Election) Leader(ctx context.Context) (*v3.GetResponse, error) {
  124. client := e.session.Client()
  125. resp, err := client.Get(ctx, e.keyPrefix, v3.WithFirstCreate()...)
  126. if err != nil {
  127. return nil, err
  128. } else if len(resp.Kvs) == 0 {
  129. // no leader currently elected
  130. return nil, ErrElectionNoLeader
  131. }
  132. return resp, nil
  133. }
  134. // Observe returns a channel that reliably observes ordered leader proposals
  135. // as GetResponse values on every current elected leader key. It will not
  136. // necessarily fetch all historical leader updates, but will always post the
  137. // most recent leader value.
  138. //
  139. // The channel closes when the context is canceled or the underlying watcher
  140. // is otherwise disrupted.
  141. func (e *Election) Observe(ctx context.Context) <-chan v3.GetResponse {
  142. retc := make(chan v3.GetResponse)
  143. go e.observe(ctx, retc)
  144. return retc
  145. }
  146. func (e *Election) observe(ctx context.Context, ch chan<- v3.GetResponse) {
  147. client := e.session.Client()
  148. defer close(ch)
  149. for {
  150. resp, err := client.Get(ctx, e.keyPrefix, v3.WithFirstCreate()...)
  151. if err != nil {
  152. return
  153. }
  154. var kv *mvccpb.KeyValue
  155. var hdr *pb.ResponseHeader
  156. if len(resp.Kvs) == 0 {
  157. cctx, cancel := context.WithCancel(ctx)
  158. // wait for first key put on prefix
  159. opts := []v3.OpOption{v3.WithRev(resp.Header.Revision), v3.WithPrefix()}
  160. wch := client.Watch(cctx, e.keyPrefix, opts...)
  161. for kv == nil {
  162. wr, ok := <-wch
  163. if !ok || wr.Err() != nil {
  164. cancel()
  165. return
  166. }
  167. // only accept puts; a delete will make observe() spin
  168. for _, ev := range wr.Events {
  169. if ev.Type == mvccpb.PUT {
  170. hdr, kv = &wr.Header, ev.Kv
  171. // may have multiple revs; hdr.rev = the last rev
  172. // set to kv's rev in case batch has multiple Puts
  173. hdr.Revision = kv.ModRevision
  174. break
  175. }
  176. }
  177. }
  178. cancel()
  179. } else {
  180. hdr, kv = resp.Header, resp.Kvs[0]
  181. }
  182. select {
  183. case ch <- v3.GetResponse{Header: hdr, Kvs: []*mvccpb.KeyValue{kv}}:
  184. case <-ctx.Done():
  185. return
  186. }
  187. cctx, cancel := context.WithCancel(ctx)
  188. wch := client.Watch(cctx, string(kv.Key), v3.WithRev(hdr.Revision+1))
  189. keyDeleted := false
  190. for !keyDeleted {
  191. wr, ok := <-wch
  192. if !ok {
  193. cancel()
  194. return
  195. }
  196. for _, ev := range wr.Events {
  197. if ev.Type == mvccpb.DELETE {
  198. keyDeleted = true
  199. break
  200. }
  201. resp.Header = &wr.Header
  202. resp.Kvs = []*mvccpb.KeyValue{ev.Kv}
  203. select {
  204. case ch <- *resp:
  205. case <-cctx.Done():
  206. cancel()
  207. return
  208. }
  209. }
  210. }
  211. cancel()
  212. }
  213. }
  214. // Key returns the leader key if elected, empty string otherwise.
  215. func (e *Election) Key() string { return e.leaderKey }
  216. // Rev returns the leader key's creation revision, if elected.
  217. func (e *Election) Rev() int64 { return e.leaderRev }
  218. // Header is the response header from the last successful election proposal.
  219. func (e *Election) Header() *pb.ResponseHeader { return e.hdr }