ep_health_command.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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/spf13/cobra"
  21. "golang.org/x/net/context"
  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. endpoints, err := cmd.Flags().GetStringSlice("endpoints")
  35. if err != nil {
  36. ExitWithError(ExitError, err)
  37. }
  38. sec := secureCfgFromCmd(cmd)
  39. dt := dialTimeoutFromCmd(cmd)
  40. cfgs := []*clientv3.Config{}
  41. for _, ep := range endpoints {
  42. cfg, err := newClientCfg([]string{ep}, dt, sec)
  43. if err != nil {
  44. ExitWithError(ExitBadArgs, err)
  45. }
  46. cfgs = append(cfgs, cfg)
  47. }
  48. var wg sync.WaitGroup
  49. for _, cfg := range cfgs {
  50. wg.Add(1)
  51. go func(cfg *clientv3.Config) {
  52. defer wg.Done()
  53. ep := cfg.Endpoints[0]
  54. cli, err := clientv3.New(*cfg)
  55. if err != nil {
  56. fmt.Printf("%s is unhealthy: failed to connect: %v\n", ep, err)
  57. return
  58. }
  59. st := time.Now()
  60. // get a random key. As long as we can get the response without an error, the
  61. // endpoint is health.
  62. _, err = cli.Get(context.TODO(), "health")
  63. if err != nil {
  64. fmt.Printf("%s is unhealthy: failed to commit proposal: %v\n", ep, err)
  65. } else {
  66. fmt.Printf("%s is healthy: successfully committed proposal: took = %v\n", ep, time.Since(st))
  67. }
  68. }(cfg)
  69. }
  70. wg.Wait()
  71. }