ep_command.go 5.6 KB

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