example_election_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Copyright 2017 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_test
  15. import (
  16. "context"
  17. "fmt"
  18. "log"
  19. "sync"
  20. "time"
  21. "go.etcd.io/etcd/clientv3"
  22. "go.etcd.io/etcd/clientv3/concurrency"
  23. )
  24. func ExampleElection_Campaign() {
  25. cli, err := clientv3.New(clientv3.Config{Endpoints: endpoints})
  26. if err != nil {
  27. log.Fatal(err)
  28. }
  29. defer cli.Close()
  30. // create two separate sessions for election competition
  31. s1, err := concurrency.NewSession(cli)
  32. if err != nil {
  33. log.Fatal(err)
  34. }
  35. defer s1.Close()
  36. e1 := concurrency.NewElection(s1, "/my-election/")
  37. s2, err := concurrency.NewSession(cli)
  38. if err != nil {
  39. log.Fatal(err)
  40. }
  41. defer s2.Close()
  42. e2 := concurrency.NewElection(s2, "/my-election/")
  43. // create competing candidates, with e1 initially losing to e2
  44. var wg sync.WaitGroup
  45. wg.Add(2)
  46. electc := make(chan *concurrency.Election, 2)
  47. go func() {
  48. defer wg.Done()
  49. // delay candidacy so e2 wins first
  50. time.Sleep(3 * time.Second)
  51. if err := e1.Campaign(context.Background(), "e1"); err != nil {
  52. log.Fatal(err)
  53. }
  54. electc <- e1
  55. }()
  56. go func() {
  57. defer wg.Done()
  58. if err := e2.Campaign(context.Background(), "e2"); err != nil {
  59. log.Fatal(err)
  60. }
  61. electc <- e2
  62. }()
  63. cctx, cancel := context.WithCancel(context.TODO())
  64. defer cancel()
  65. e := <-electc
  66. fmt.Println("completed first election with", string((<-e.Observe(cctx)).Kvs[0].Value))
  67. // resign so next candidate can be elected
  68. if err := e.Resign(context.TODO()); err != nil {
  69. log.Fatal(err)
  70. }
  71. e = <-electc
  72. fmt.Println("completed second election with", string((<-e.Observe(cctx)).Kvs[0].Value))
  73. wg.Wait()
  74. // Output:
  75. // completed first election with e2
  76. // completed second election with e1
  77. }