handler.go 3.0 KB

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