election.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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 main
  15. import (
  16. "context"
  17. "fmt"
  18. "github.com/coreos/etcd/clientv3/concurrency"
  19. )
  20. func runElection(getClient getClientFunc, rounds int) {
  21. rcs := make([]roundClient, 15)
  22. validatec, releasec := make(chan struct{}, len(rcs)), make(chan struct{}, len(rcs))
  23. for range rcs {
  24. releasec <- struct{}{}
  25. }
  26. for i := range rcs {
  27. v := fmt.Sprintf("%d", i)
  28. observedLeader := ""
  29. validateWaiters := 0
  30. rcs[i].c = getClient()
  31. var (
  32. s *concurrency.Session
  33. err error
  34. )
  35. for {
  36. s, err = concurrency.NewSession(rcs[i].c)
  37. if err == nil {
  38. break
  39. }
  40. }
  41. e := concurrency.NewElection(s, "electors")
  42. rcs[i].acquire = func() error {
  43. <-releasec
  44. ctx, cancel := context.WithCancel(context.Background())
  45. go func() {
  46. if ol, ok := <-e.Observe(ctx); ok {
  47. observedLeader = string(ol.Kvs[0].Value)
  48. if observedLeader != v {
  49. cancel()
  50. }
  51. }
  52. }()
  53. err = e.Campaign(ctx, v)
  54. if err == nil {
  55. observedLeader = v
  56. }
  57. if observedLeader == v {
  58. validateWaiters = len(rcs)
  59. }
  60. select {
  61. case <-ctx.Done():
  62. return nil
  63. default:
  64. cancel()
  65. return err
  66. }
  67. }
  68. rcs[i].validate = func() error {
  69. if l, err := e.Leader(context.TODO()); err == nil && l != observedLeader {
  70. return fmt.Errorf("expected leader %q, got %q", observedLeader, l)
  71. }
  72. validatec <- struct{}{}
  73. return nil
  74. }
  75. rcs[i].release = func() error {
  76. for validateWaiters > 0 {
  77. select {
  78. case <-validatec:
  79. validateWaiters--
  80. default:
  81. return fmt.Errorf("waiting on followers")
  82. }
  83. }
  84. if err := e.Resign(context.TODO()); err != nil {
  85. return err
  86. }
  87. if observedLeader == v {
  88. for range rcs {
  89. releasec <- struct{}{}
  90. }
  91. }
  92. observedLeader = ""
  93. return nil
  94. }
  95. }
  96. doRounds(rcs, rounds)
  97. }