healthcheck.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. // Force the compiler to check that NilHealthcheck implements Healthcheck.
  23. var _ Healthcheck = NilHealthcheck{}
  24. // No-op.
  25. func (h NilHealthcheck) Check() {}
  26. // No-op.
  27. func (h NilHealthcheck) Error() error { return nil }
  28. // No-op.
  29. func (h NilHealthcheck) Healthy() {}
  30. // No-op.
  31. func (h NilHealthcheck) Unhealthy(err error) {}
  32. // The standard implementation of a Healthcheck stores the status and a
  33. // function to call to update the status.
  34. type StandardHealthcheck struct {
  35. err error
  36. f func(Healthcheck)
  37. }
  38. // Force the compiler to check that StandardHealthcheck implements Healthcheck.
  39. var _ Healthcheck = &StandardHealthcheck{}
  40. // Update the healthcheck's status.
  41. func (h *StandardHealthcheck) Check() {
  42. h.f(h)
  43. }
  44. // Return the healthcheck's status, which will be nil if it is healthy.
  45. func (h *StandardHealthcheck) Error() error {
  46. return h.err
  47. }
  48. // Mark the healthcheck as healthy.
  49. func (h *StandardHealthcheck) Healthy() {
  50. h.err = nil
  51. }
  52. // Mark the healthcheck as unhealthy. The error should provide details.
  53. func (h *StandardHealthcheck) Unhealthy(err error) {
  54. h.err = err
  55. }