ep_health_command.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright 2015 CoreOS, Inc.
  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. "sync"
  18. "time"
  19. "github.com/coreos/etcd/clientv3"
  20. "github.com/coreos/etcd/pkg/flags"
  21. "github.com/spf13/cobra"
  22. )
  23. // NewEpHealthCommand returns the cobra command for "endpoint-health".
  24. func NewEpHealthCommand() *cobra.Command {
  25. cmd := &cobra.Command{
  26. Use: "endpoint-health",
  27. Short: "endpoint-health checks the healthiness of endpoints specified in `--endpoints` flag",
  28. Run: epHealthCommandFunc,
  29. }
  30. return cmd
  31. }
  32. // epHealthCommandFunc executes the "endpoint-health" command.
  33. func epHealthCommandFunc(cmd *cobra.Command, args []string) {
  34. flags.SetPflagsFromEnv("ETCDCTL", cmd.InheritedFlags())
  35. endpoints, err := cmd.Flags().GetStringSlice("endpoints")
  36. if err != nil {
  37. ExitWithError(ExitError, err)
  38. }
  39. sec := secureCfgFromCmd(cmd)
  40. dt := dialTimeoutFromCmd(cmd)
  41. cfgs := []*clientv3.Config{}
  42. for _, ep := range endpoints {
  43. cfg, err := newClientCfg([]string{ep}, dt, sec)
  44. if err != nil {
  45. ExitWithError(ExitBadArgs, err)
  46. }
  47. cfgs = append(cfgs, cfg)
  48. }
  49. var wg sync.WaitGroup
  50. for _, cfg := range cfgs {
  51. wg.Add(1)
  52. go func(cfg *clientv3.Config) {
  53. defer wg.Done()
  54. ep := cfg.Endpoints[0]
  55. cli, err := clientv3.New(*cfg)
  56. if err != nil {
  57. fmt.Printf("%s is unhealthy: failed to connect: %v\n", ep, err)
  58. return
  59. }
  60. st := time.Now()
  61. // get a random key. As long as we can get the response without an error, the
  62. // endpoint is health.
  63. ctx, cancel := commandCtx(cmd)
  64. _, err = cli.Get(ctx, "health")
  65. cancel()
  66. if err != nil {
  67. fmt.Printf("%s is unhealthy: failed to commit proposal: %v\n", ep, err)
  68. } else {
  69. fmt.Printf("%s is healthy: successfully committed proposal: took = %v\n", ep, time.Since(st))
  70. }
  71. }(cfg)
  72. }
  73. wg.Wait()
  74. }