ep_command.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. ka := keepAliveTimeFromCmd(cmd)
  72. kat := keepAliveTimeoutFromCmd(cmd)
  73. auth := authCfgFromCmd(cmd)
  74. cfgs := []*v3.Config{}
  75. for _, ep := range endpointsFromCluster(cmd) {
  76. cfg, err := newClientCfg([]string{ep}, dt, ka, kat, sec, auth)
  77. if err != nil {
  78. ExitWithError(ExitBadArgs, err)
  79. }
  80. cfgs = append(cfgs, cfg)
  81. }
  82. var wg sync.WaitGroup
  83. errc := make(chan error, len(cfgs))
  84. for _, cfg := range cfgs {
  85. wg.Add(1)
  86. go func(cfg *v3.Config) {
  87. defer wg.Done()
  88. ep := cfg.Endpoints[0]
  89. cli, err := v3.New(*cfg)
  90. if err != nil {
  91. errc <- fmt.Errorf("%s is unhealthy: failed to connect: %v", ep, err)
  92. return
  93. }
  94. st := time.Now()
  95. // get a random key. As long as we can get the response without an error, the
  96. // endpoint is health.
  97. ctx, cancel := commandCtx(cmd)
  98. _, err = cli.Get(ctx, "health")
  99. cancel()
  100. // permission denied is OK since proposal goes through consensus to get it
  101. if err == nil || err == rpctypes.ErrPermissionDenied {
  102. fmt.Printf("%s is healthy: successfully committed proposal: took = %v\n", ep, time.Since(st))
  103. } else {
  104. errc <- fmt.Errorf("%s is unhealthy: failed to commit proposal: %v", ep, err)
  105. }
  106. }(cfg)
  107. }
  108. wg.Wait()
  109. close(errc)
  110. errs := false
  111. for err := range errc {
  112. if err != nil {
  113. errs = true
  114. fmt.Fprintln(os.Stderr, err)
  115. }
  116. }
  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 endpointsFromCluster(cmd) {
  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. }
  145. type epHashKV struct {
  146. Ep string `json:"Endpoint"`
  147. Resp *v3.HashKVResponse `json:"HashKV"`
  148. }
  149. func epHashKVCommandFunc(cmd *cobra.Command, args []string) {
  150. c := mustClientFromCmd(cmd)
  151. hashList := []epHashKV{}
  152. var err error
  153. for _, ep := range endpointsFromCluster(cmd) {
  154. ctx, cancel := commandCtx(cmd)
  155. resp, serr := c.HashKV(ctx, ep, epHashKVRev)
  156. cancel()
  157. if serr != nil {
  158. err = serr
  159. fmt.Fprintf(os.Stderr, "Failed to get the hash of endpoint %s (%v)\n", ep, serr)
  160. continue
  161. }
  162. hashList = append(hashList, epHashKV{Ep: ep, Resp: resp})
  163. }
  164. display.EndpointHashKV(hashList)
  165. if err != nil {
  166. ExitWithError(ExitError, err)
  167. }
  168. }
  169. func endpointsFromCluster(cmd *cobra.Command) []string {
  170. if !epClusterEndpoints {
  171. endpoints, err := cmd.Flags().GetStringSlice("endpoints")
  172. if err != nil {
  173. ExitWithError(ExitError, err)
  174. }
  175. return endpoints
  176. }
  177. sec := secureCfgFromCmd(cmd)
  178. dt := dialTimeoutFromCmd(cmd)
  179. ka := keepAliveTimeFromCmd(cmd)
  180. kat := keepAliveTimeoutFromCmd(cmd)
  181. eps, err := endpointsFromCmd(cmd)
  182. if err != nil {
  183. ExitWithError(ExitError, err)
  184. }
  185. // exclude auth for not asking needless password (MemberList() doesn't need authentication)
  186. cfg, err := newClientCfg(eps, dt, ka, kat, sec, nil)
  187. if err != nil {
  188. ExitWithError(ExitError, err)
  189. }
  190. c, err := v3.New(*cfg)
  191. if err != nil {
  192. ExitWithError(ExitError, err)
  193. }
  194. ctx, cancel := commandCtx(cmd)
  195. defer func() {
  196. c.Close()
  197. cancel()
  198. }()
  199. membs, err := c.MemberList(ctx)
  200. if err != nil {
  201. err = fmt.Errorf("failed to fetch endpoints from etcd cluster member list: %v", err)
  202. ExitWithError(ExitError, err)
  203. }
  204. ret := []string{}
  205. for _, m := range membs.Members {
  206. ret = append(ret, m.ClientURLs...)
  207. }
  208. return ret
  209. }