handler.go 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. // Copyright 2017 by the contributors.
  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 healthcheck
  15. import (
  16. "encoding/json"
  17. "net/http"
  18. "sync"
  19. )
  20. var _ Handler = &basicHandler{}
  21. // basicHandler is a basic Handler implementation.
  22. type basicHandler struct {
  23. http.ServeMux
  24. checksMutex sync.RWMutex
  25. livenessChecks map[string]Check
  26. readinessChecks map[string]Check
  27. }
  28. // NewHandler creates a new basic Handler
  29. func NewHandler() Handler {
  30. h := &basicHandler{
  31. livenessChecks: make(map[string]Check),
  32. readinessChecks: make(map[string]Check),
  33. }
  34. h.Handle("/live", http.HandlerFunc(h.LiveEndpoint))
  35. h.Handle("/ready", http.HandlerFunc(h.ReadyEndpoint))
  36. return h
  37. }
  38. func (s *basicHandler) LiveEndpoint(w http.ResponseWriter, r *http.Request) {
  39. s.handle(w, r, s.livenessChecks)
  40. }
  41. func (s *basicHandler) ReadyEndpoint(w http.ResponseWriter, r *http.Request) {
  42. s.handle(w, r, s.readinessChecks, s.livenessChecks)
  43. }
  44. func (s *basicHandler) AddLivenessCheck(name string, check Check) {
  45. s.checksMutex.Lock()
  46. defer s.checksMutex.Unlock()
  47. s.livenessChecks[name] = check
  48. }
  49. func (s *basicHandler) AddReadinessCheck(name string, check Check) {
  50. s.checksMutex.Lock()
  51. defer s.checksMutex.Unlock()
  52. s.readinessChecks[name] = check
  53. }
  54. func (s *basicHandler) collectChecks(checks map[string]Check, resultsOut map[string]string, statusOut *int) {
  55. s.checksMutex.RLock()
  56. defer s.checksMutex.RUnlock()
  57. for name, check := range checks {
  58. if err := check(); err != nil {
  59. *statusOut = http.StatusServiceUnavailable
  60. resultsOut[name] = err.Error()
  61. } else {
  62. resultsOut[name] = "OK"
  63. }
  64. }
  65. }
  66. func (s *basicHandler) handle(w http.ResponseWriter, r *http.Request, checks ...map[string]Check) {
  67. if r.Method != http.MethodGet {
  68. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  69. return
  70. }
  71. checkResults := make(map[string]string)
  72. status := http.StatusOK
  73. for _, checks := range checks {
  74. s.collectChecks(checks, checkResults, &status)
  75. }
  76. // write out the response code and content type header
  77. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  78. w.WriteHeader(status)
  79. // unless ?full=1, return an empty body. Kubernetes only cares about the
  80. // HTTP status code, so we won't waste bytes on the full body.
  81. if r.URL.Query().Get("full") != "1" {
  82. _, _ = w.Write([]byte("{}\n"))
  83. return
  84. }
  85. // otherwise, write the JSON body ignoring any encoding errors (which
  86. // shouldn't really be possible since we're encoding a map[string]string).
  87. encoder := json.NewEncoder(w)
  88. encoder.SetIndent("", " ")
  89. _ = encoder.Encode(checkResults)
  90. }