cluster_health.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package command
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "os"
  7. "os/signal"
  8. "time"
  9. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/codegangsta/cli"
  10. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  11. "github.com/coreos/etcd/client"
  12. )
  13. func NewClusterHealthCommand() cli.Command {
  14. return cli.Command{
  15. Name: "cluster-health",
  16. Usage: "check the health of the etcd cluster",
  17. Flags: []cli.Flag{
  18. cli.BoolFlag{Name: "forever", Usage: "forever check the health every 10 second until CTRL+C"},
  19. },
  20. Action: handleClusterHealth,
  21. }
  22. }
  23. func handleClusterHealth(c *cli.Context) {
  24. forever := c.Bool("forever")
  25. if forever {
  26. sigch := make(chan os.Signal, 1)
  27. signal.Notify(sigch, os.Interrupt)
  28. go func() {
  29. <-sigch
  30. os.Exit(0)
  31. }()
  32. }
  33. tr, err := getTransport(c)
  34. if err != nil {
  35. handleError(ExitServerError, err)
  36. }
  37. hc := http.Client{
  38. Transport: tr,
  39. }
  40. cln := mustNewClientNoSync(c)
  41. mi := client.NewMembersAPI(cln)
  42. ms, err := mi.List(context.TODO())
  43. if err != nil {
  44. fmt.Println("cluster may be unhealthy: failed to list members")
  45. handleError(ExitServerError, err)
  46. }
  47. for {
  48. health := false
  49. for _, m := range ms {
  50. if len(m.ClientURLs) == 0 {
  51. fmt.Printf("member %s is unreachable: no available published client urls\n", m.ID)
  52. continue
  53. }
  54. checked := false
  55. for _, url := range m.ClientURLs {
  56. resp, err := hc.Get(url + "/health")
  57. if err != nil {
  58. fmt.Printf("failed to check the health of member %s on %s: %v\n", m.ID, url, err)
  59. continue
  60. }
  61. result := struct{ Health string }{}
  62. d := json.NewDecoder(resp.Body)
  63. err = d.Decode(&result)
  64. resp.Body.Close()
  65. if err != nil {
  66. fmt.Printf("failed to check the health of member %s on %s: %v\n", m.ID, url, err)
  67. continue
  68. }
  69. checked = true
  70. if result.Health == "true" {
  71. health = true
  72. fmt.Printf("member %s is healthy: got healthy result from %s\n", m.ID, url)
  73. } else {
  74. fmt.Printf("member %s is unhealthy: got unhealthy result from %s\n", m.ID, url)
  75. }
  76. break
  77. }
  78. if !checked {
  79. fmt.Printf("member %s is unreachable: %v are all unreachable\n", m.ID, m.ClientURLs)
  80. }
  81. }
  82. if health {
  83. fmt.Println("cluster is healthy")
  84. } else {
  85. fmt.Println("cluster is unhealthy")
  86. }
  87. if !forever {
  88. break
  89. }
  90. fmt.Printf("\nnext check after 10 second...\n\n")
  91. time.Sleep(10 * time.Second)
  92. }
  93. }