status.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package health
  2. import (
  3. "fmt"
  4. "log"
  5. "strings"
  6. "sync"
  7. )
  8. // todo: how to deal with multiple files?
  9. // specified in zone and a status object for each?
  10. type StatusType uint8
  11. const (
  12. StatusUnknown StatusType = iota
  13. StatusUnhealthy
  14. StatusHealthy
  15. )
  16. type Status interface {
  17. GetStatus(string) StatusType
  18. Reload() error
  19. Close() error
  20. }
  21. type statusRegistry struct {
  22. mu sync.RWMutex
  23. m map[string]Status
  24. }
  25. var registry statusRegistry
  26. type Service struct {
  27. Status StatusType
  28. }
  29. func init() {
  30. registry = statusRegistry{
  31. m: make(map[string]Status),
  32. }
  33. }
  34. func (r *statusRegistry) Add(name string, status Status) error {
  35. r.mu.Lock()
  36. defer r.mu.Unlock()
  37. r.m[name] = status
  38. return nil
  39. }
  40. func (st StatusType) String() string {
  41. switch st {
  42. case StatusHealthy:
  43. return "healthy"
  44. case StatusUnhealthy:
  45. return "unhealthy"
  46. case StatusUnknown:
  47. return "unknown"
  48. default:
  49. return fmt.Sprintf("status=%d", st)
  50. }
  51. }
  52. func GetStatus(name string) StatusType {
  53. check := strings.SplitN(name, "/", 2)
  54. if len(check) != 2 {
  55. return StatusUnknown
  56. }
  57. registry.mu.RLock()
  58. status, ok := registry.m[check[0]]
  59. registry.mu.RUnlock()
  60. log.Printf("looking up health for '%s', status register: '%s', found: %t", name, check[0], ok)
  61. if !ok {
  62. return StatusUnknown
  63. }
  64. return status.GetStatus(check[1])
  65. }