election_command.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  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 runner
  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. for i := range rcs {
  46. v := fmt.Sprintf("%d", i)
  47. observedLeader := ""
  48. validateWaiters := 0
  49. var rcNextc chan struct{}
  50. setRcNextc := func() {
  51. rcNextc = nextc
  52. }
  53. rcs[i].c = newClient(eps, dialTimeout)
  54. var (
  55. s *concurrency.Session
  56. err error
  57. )
  58. for {
  59. s, err = concurrency.NewSession(rcs[i].c)
  60. if err == nil {
  61. break
  62. }
  63. }
  64. e := concurrency.NewElection(s, election)
  65. rcs[i].acquire = func() (err error) {
  66. ctx, cancel := context.WithCancel(context.Background())
  67. donec := make(chan struct{})
  68. go func() {
  69. defer close(donec)
  70. for ctx.Err() == nil {
  71. if ol, ok := <-e.Observe(ctx); ok {
  72. observedLeader = string(ol.Kvs[0].Value)
  73. break
  74. }
  75. }
  76. if observedLeader != v {
  77. cancel()
  78. }
  79. }()
  80. err = e.Campaign(ctx, v)
  81. cancel()
  82. <-donec
  83. if err == nil {
  84. observedLeader = v
  85. }
  86. if observedLeader == v {
  87. validateWaiters = len(rcs)
  88. }
  89. select {
  90. case <-ctx.Done():
  91. return nil
  92. default:
  93. return err
  94. }
  95. }
  96. rcs[i].validate = func() error {
  97. l, err := e.Leader(context.TODO())
  98. if err == nil && string(l.Kvs[0].Value) != observedLeader {
  99. return fmt.Errorf("expected leader %q, got %q", observedLeader, l.Kvs[0].Value)
  100. }
  101. if err != nil {
  102. return err
  103. }
  104. setRcNextc()
  105. validatec <- struct{}{}
  106. return nil
  107. }
  108. rcs[i].release = func() error {
  109. for validateWaiters > 0 {
  110. select {
  111. case <-validatec:
  112. validateWaiters--
  113. default:
  114. return fmt.Errorf("waiting on followers")
  115. }
  116. }
  117. if err := e.Resign(context.TODO()); err != nil {
  118. return err
  119. }
  120. if observedLeader == v {
  121. oldNextc := nextc
  122. nextc = make(chan struct{})
  123. close(oldNextc)
  124. }
  125. <-rcNextc
  126. observedLeader = ""
  127. return nil
  128. }
  129. }
  130. // each client creates 1 key from Campaign() and delete it from Resign()
  131. // a round involves in 2*len(rcs) requests.
  132. doRounds(rcs, rounds, 2*len(rcs))
  133. }