election_command.go 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  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",
  26. Short: "Performs election operation",
  27. Run: runElectionFunc,
  28. }
  29. cmd.Flags().IntVar(&rounds, "rounds", 100, "number of rounds to run")
  30. cmd.Flags().IntVar(&totalClientConnections, "total-client-connections", 10, "total number of client connections")
  31. return cmd
  32. }
  33. func runElectionFunc(cmd *cobra.Command, args []string) {
  34. if len(args) > 0 {
  35. ExitWithError(ExitBadArgs, errors.New("election does not take any argument"))
  36. }
  37. rcs := make([]roundClient, totalClientConnections)
  38. validatec, releasec := make(chan struct{}, len(rcs)), make(chan struct{}, len(rcs))
  39. for range rcs {
  40. releasec <- struct{}{}
  41. }
  42. eps := endpointsFromFlag(cmd)
  43. dialTimeout := dialTimeoutFromCmd(cmd)
  44. for i := range rcs {
  45. v := fmt.Sprintf("%d", i)
  46. observedLeader := ""
  47. validateWaiters := 0
  48. rcs[i].c = newClient(eps, dialTimeout)
  49. var (
  50. s *concurrency.Session
  51. err error
  52. )
  53. for {
  54. s, err = concurrency.NewSession(rcs[i].c)
  55. if err == nil {
  56. break
  57. }
  58. }
  59. e := concurrency.NewElection(s, "electors")
  60. rcs[i].acquire = func() error {
  61. <-releasec
  62. ctx, cancel := context.WithCancel(context.Background())
  63. go func() {
  64. if ol, ok := <-e.Observe(ctx); ok {
  65. observedLeader = string(ol.Kvs[0].Value)
  66. if observedLeader != v {
  67. cancel()
  68. }
  69. }
  70. }()
  71. err = e.Campaign(ctx, v)
  72. if err == nil {
  73. observedLeader = v
  74. }
  75. if observedLeader == v {
  76. validateWaiters = len(rcs)
  77. }
  78. select {
  79. case <-ctx.Done():
  80. return nil
  81. default:
  82. cancel()
  83. return err
  84. }
  85. }
  86. rcs[i].validate = func() error {
  87. if l, err := e.Leader(context.TODO()); err == nil && l != observedLeader {
  88. return fmt.Errorf("expected leader %q, got %q", observedLeader, l)
  89. }
  90. validatec <- struct{}{}
  91. return nil
  92. }
  93. rcs[i].release = func() error {
  94. for validateWaiters > 0 {
  95. select {
  96. case <-validatec:
  97. validateWaiters--
  98. default:
  99. return fmt.Errorf("waiting on followers")
  100. }
  101. }
  102. if err := e.Resign(context.TODO()); err != nil {
  103. return err
  104. }
  105. if observedLeader == v {
  106. for range rcs {
  107. releasec <- struct{}{}
  108. }
  109. }
  110. observedLeader = ""
  111. return nil
  112. }
  113. }
  114. doRounds(rcs, rounds)
  115. }