ep_command.go 4.4 KB

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