elect_command.go 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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. "os"
  19. "os/signal"
  20. "syscall"
  21. "go.etcd.io/etcd/clientv3"
  22. "go.etcd.io/etcd/clientv3/concurrency"
  23. "github.com/spf13/cobra"
  24. )
  25. var (
  26. electListen bool
  27. )
  28. // NewElectCommand returns the cobra command for "elect".
  29. func NewElectCommand() *cobra.Command {
  30. cmd := &cobra.Command{
  31. Use: "elect <election-name> [proposal]",
  32. Short: "Observes and participates in leader election",
  33. Run: electCommandFunc,
  34. }
  35. cmd.Flags().BoolVarP(&electListen, "listen", "l", false, "observation mode")
  36. return cmd
  37. }
  38. func electCommandFunc(cmd *cobra.Command, args []string) {
  39. if len(args) != 1 && len(args) != 2 {
  40. ExitWithError(ExitBadArgs, errors.New("elect takes one election name argument and an optional proposal argument"))
  41. }
  42. c := mustClientFromCmd(cmd)
  43. var err error
  44. if len(args) == 1 {
  45. if !electListen {
  46. ExitWithError(ExitBadArgs, errors.New("no proposal argument but -l not set"))
  47. }
  48. err = observe(c, args[0])
  49. } else {
  50. if electListen {
  51. ExitWithError(ExitBadArgs, errors.New("proposal given but -l is set"))
  52. }
  53. err = campaign(c, args[0], args[1])
  54. }
  55. if err != nil {
  56. ExitWithError(ExitError, err)
  57. }
  58. }
  59. func observe(c *clientv3.Client, election string) error {
  60. s, err := concurrency.NewSession(c)
  61. if err != nil {
  62. return err
  63. }
  64. e := concurrency.NewElection(s, election)
  65. ctx, cancel := context.WithCancel(context.TODO())
  66. donec := make(chan struct{})
  67. sigc := make(chan os.Signal, 1)
  68. signal.Notify(sigc, syscall.SIGINT, syscall.SIGTERM)
  69. go func() {
  70. <-sigc
  71. cancel()
  72. }()
  73. go func() {
  74. for resp := range e.Observe(ctx) {
  75. display.Get(resp)
  76. }
  77. close(donec)
  78. }()
  79. <-donec
  80. select {
  81. case <-ctx.Done():
  82. default:
  83. return errors.New("elect: observer lost")
  84. }
  85. return nil
  86. }
  87. func campaign(c *clientv3.Client, election string, prop string) error {
  88. s, err := concurrency.NewSession(c)
  89. if err != nil {
  90. return err
  91. }
  92. e := concurrency.NewElection(s, election)
  93. ctx, cancel := context.WithCancel(context.TODO())
  94. donec := make(chan struct{})
  95. sigc := make(chan os.Signal, 1)
  96. signal.Notify(sigc, syscall.SIGINT, syscall.SIGTERM)
  97. go func() {
  98. <-sigc
  99. cancel()
  100. close(donec)
  101. }()
  102. if err = e.Campaign(ctx, prop); err != nil {
  103. return err
  104. }
  105. // print key since elected
  106. resp, err := c.Get(ctx, e.Key())
  107. if err != nil {
  108. return err
  109. }
  110. display.Get(*resp)
  111. select {
  112. case <-donec:
  113. case <-s.Done():
  114. return errors.New("elect: session expired")
  115. }
  116. return e.Resign(context.TODO())
  117. }