healthcheck.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package metrics
  2. // Healthchecks hold an os.Error value describing an arbitrary up/down status.
  3. //
  4. // This is an interface so as to encourage other structs to implement
  5. // the Healthcheck API as appropriate.
  6. type Healthcheck interface {
  7. Check()
  8. Error() error
  9. Healthy()
  10. Unhealthy(error)
  11. }
  12. // Create a new Healthcheck, which will use the given function to update
  13. // its status.
  14. func NewHealthcheck(f func(Healthcheck)) Healthcheck {
  15. if UseNilMetrics {
  16. return NilHealthcheck{}
  17. }
  18. return &StandardHealthcheck{nil, f}
  19. }
  20. // No-op Healthcheck.
  21. type NilHealthcheck struct{}
  22. // No-op.
  23. func (h NilHealthcheck) Check() {}
  24. // No-op.
  25. func (h NilHealthcheck) Error() error { return nil }
  26. // No-op.
  27. func (h NilHealthcheck) Healthy() {}
  28. // No-op.
  29. func (h NilHealthcheck) Unhealthy(err error) {}
  30. // The standard implementation of a Healthcheck stores the status and a
  31. // function to call to update the status.
  32. type StandardHealthcheck struct {
  33. err error
  34. f func(Healthcheck)
  35. }
  36. // Update the healthcheck's status.
  37. func (h *StandardHealthcheck) Check() {
  38. h.f(h)
  39. }
  40. // Return the healthcheck's status, which will be nil if it is healthy.
  41. func (h *StandardHealthcheck) Error() error {
  42. return h.err
  43. }
  44. // Mark the healthcheck as healthy.
  45. func (h *StandardHealthcheck) Healthy() {
  46. h.err = nil
  47. }
  48. // Mark the healthcheck as unhealthy. The error should provide details.
  49. func (h *StandardHealthcheck) Unhealthy(err error) {
  50. h.err = err
  51. }