election_command.go 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  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 command
  15. import (
  16. "context"
  17. "errors"
  18. "fmt"
  19. "github.com/coreos/etcd/clientv3/concurrency"
  20. "github.com/spf13/cobra"
  21. )
  22. // NewElectionCommand returns the cobra command for "election runner".
  23. func NewElectionCommand() *cobra.Command {
  24. cmd := &cobra.Command{
  25. Use: "election [election name (defaults to 'elector')]",
  26. Short: "Performs election operation",
  27. Run: runElectionFunc,
  28. }
  29. cmd.Flags().IntVar(&totalClientConnections, "total-client-connections", 10, "total number of client connections")
  30. return cmd
  31. }
  32. func runElectionFunc(cmd *cobra.Command, args []string) {
  33. election := "elector"
  34. if len(args) == 1 {
  35. election = args[0]
  36. }
  37. if len(args) > 1 {
  38. ExitWithError(ExitBadArgs, errors.New("election takes at most one argument"))
  39. }
  40. rcs := make([]roundClient, totalClientConnections)
  41. validatec := make(chan struct{}, len(rcs))
  42. // nextc closes when election is ready for next round.
  43. nextc := make(chan struct{})
  44. eps := endpointsFromFlag(cmd)
  45. dialTimeout := dialTimeoutFromCmd(cmd)
  46. for i := range rcs {
  47. v := fmt.Sprintf("%d", i)
  48. observedLeader := ""
  49. validateWaiters := 0
  50. var rcNextc chan struct{}
  51. setRcNextc := func() {
  52. rcNextc = nextc
  53. }
  54. rcs[i].c = newClient(eps, dialTimeout)
  55. var (
  56. s *concurrency.Session
  57. err error
  58. )
  59. for {
  60. s, err = concurrency.NewSession(rcs[i].c)
  61. if err == nil {
  62. break
  63. }
  64. }
  65. e := concurrency.NewElection(s, election)
  66. rcs[i].acquire = func() (err error) {
  67. ctx, cancel := context.WithCancel(context.Background())
  68. donec := make(chan struct{})
  69. go func() {
  70. defer close(donec)
  71. for ctx.Err() == nil {
  72. if ol, ok := <-e.Observe(ctx); ok {
  73. observedLeader = string(ol.Kvs[0].Value)
  74. break
  75. }
  76. }
  77. if observedLeader != v {
  78. cancel()
  79. }
  80. }()
  81. err = e.Campaign(ctx, v)
  82. cancel()
  83. <-donec
  84. if err == nil {
  85. observedLeader = v
  86. }
  87. if observedLeader == v {
  88. validateWaiters = len(rcs)
  89. }
  90. select {
  91. case <-ctx.Done():
  92. return nil
  93. default:
  94. return err
  95. }
  96. }
  97. rcs[i].validate = func() error {
  98. l, err := e.Leader(context.TODO())
  99. if err == nil && string(l.Kvs[0].Value) != observedLeader {
  100. return fmt.Errorf("expected leader %q, got %q", observedLeader, l.Kvs[0].Value)
  101. }
  102. if err != nil {
  103. return err
  104. }
  105. setRcNextc()
  106. validatec <- struct{}{}
  107. return nil
  108. }
  109. rcs[i].release = func() error {
  110. for validateWaiters > 0 {
  111. select {
  112. case <-validatec:
  113. validateWaiters--
  114. default:
  115. return fmt.Errorf("waiting on followers")
  116. }
  117. }
  118. if err := e.Resign(context.TODO()); err != nil {
  119. return err
  120. }
  121. if observedLeader == v {
  122. oldNextc := nextc
  123. nextc = make(chan struct{})
  124. close(oldNextc)
  125. }
  126. <-rcNextc
  127. observedLeader = ""
  128. return nil
  129. }
  130. }
  131. // each client creates 1 key from Campaign() and delete it from Resign()
  132. // a round involves in 2*len(rcs) requests.
  133. doRounds(rcs, rounds, 2*len(rcs))
  134. }