ep_command.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. // Copyright 2015 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. "fmt"
  17. "os"
  18. "sync"
  19. "time"
  20. v3 "github.com/coreos/etcd/clientv3"
  21. "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  22. "github.com/coreos/etcd/pkg/flags"
  23. "github.com/spf13/cobra"
  24. )
  25. // NewEndpointCommand returns the cobra command for "endpoint".
  26. func NewEndpointCommand() *cobra.Command {
  27. ec := &cobra.Command{
  28. Use: "endpoint <subcommand>",
  29. Short: "Endpoint related commands",
  30. }
  31. ec.AddCommand(newEpHealthCommand())
  32. ec.AddCommand(newEpStatusCommand())
  33. return ec
  34. }
  35. func newEpHealthCommand() *cobra.Command {
  36. cmd := &cobra.Command{
  37. Use: "health",
  38. Short: "Checks the healthiness of endpoints specified in `--endpoints` flag",
  39. Run: epHealthCommandFunc,
  40. }
  41. return cmd
  42. }
  43. func newEpStatusCommand() *cobra.Command {
  44. return &cobra.Command{
  45. Use: "status",
  46. Short: "Prints out the status of endpoints specified in `--endpoints` flag",
  47. Long: `When --write-out is set to simple, this command prints out comma-separated status lists for each endpoint.
  48. The items in the lists are endpoint, ID, version, db size, is leader, raft term, raft index.
  49. `,
  50. Run: epStatusCommandFunc,
  51. }
  52. }
  53. type epHealth struct {
  54. Ep string `json:"endpoint"`
  55. Health bool `json:"health"`
  56. Took string `json:"took"`
  57. Error string `json:"error,omitempty"`
  58. }
  59. // epHealthCommandFunc executes the "endpoint-health" command.
  60. func epHealthCommandFunc(cmd *cobra.Command, args []string) {
  61. flags.SetPflagsFromEnv("ETCDCTL", cmd.InheritedFlags())
  62. initDisplayFromCmd(cmd)
  63. endpoints, err := cmd.Flags().GetStringSlice("endpoints")
  64. if err != nil {
  65. ExitWithError(ExitError, err)
  66. }
  67. sec := secureCfgFromCmd(cmd)
  68. dt := dialTimeoutFromCmd(cmd)
  69. auth := authCfgFromCmd(cmd)
  70. cfgs := []*v3.Config{}
  71. for _, ep := range endpoints {
  72. cfg, err := newClientCfg([]string{ep}, dt, sec, auth)
  73. if err != nil {
  74. ExitWithError(ExitBadArgs, err)
  75. }
  76. cfgs = append(cfgs, cfg)
  77. }
  78. var wg sync.WaitGroup
  79. hch := make(chan epHealth, len(cfgs))
  80. for _, cfg := range cfgs {
  81. wg.Add(1)
  82. go func(cfg *v3.Config) {
  83. defer wg.Done()
  84. ep := cfg.Endpoints[0]
  85. cli, err := v3.New(*cfg)
  86. if err != nil {
  87. hch <- epHealth{Ep: ep, Health: false, Error: err.Error()}
  88. return
  89. }
  90. st := time.Now()
  91. // get a random key. As long as we can get the response without an error, the
  92. // endpoint is health.
  93. ctx, cancel := commandCtx(cmd)
  94. _, err = cli.Get(ctx, "health")
  95. cancel()
  96. eh := epHealth{Ep: ep, Health: false, Took: time.Since(st).String()}
  97. // permission denied is OK since proposal goes through consensus to get it
  98. if err == nil || err == rpctypes.ErrPermissionDenied {
  99. eh.Health = true
  100. } else {
  101. eh.Error = err.Error()
  102. }
  103. hch <- eh
  104. }(cfg)
  105. }
  106. wg.Wait()
  107. close(hch)
  108. errs := false
  109. healthList := []epHealth{}
  110. for h := range hch {
  111. healthList = append(healthList, h)
  112. if h.Error != "" {
  113. errs = true
  114. }
  115. }
  116. display.EndpointHealth(healthList)
  117. if errs {
  118. ExitWithError(ExitError, fmt.Errorf("unhealthy cluster"))
  119. }
  120. }
  121. type epStatus struct {
  122. Ep string `json:"Endpoint"`
  123. Resp *v3.StatusResponse `json:"Status"`
  124. }
  125. func epStatusCommandFunc(cmd *cobra.Command, args []string) {
  126. c := mustClientFromCmd(cmd)
  127. statusList := []epStatus{}
  128. var err error
  129. for _, ep := range c.Endpoints() {
  130. ctx, cancel := commandCtx(cmd)
  131. resp, serr := c.Status(ctx, ep)
  132. cancel()
  133. if serr != nil {
  134. err = serr
  135. fmt.Fprintf(os.Stderr, "Failed to get the status of endpoint %s (%v)\n", ep, serr)
  136. continue
  137. }
  138. statusList = append(statusList, epStatus{Ep: ep, Resp: resp})
  139. }
  140. display.EndpointStatus(statusList)
  141. if err != nil {
  142. os.Exit(ExitError)
  143. }
  144. }