registry.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package registry
  2. import (
  3. "context"
  4. "reflect"
  5. "sort"
  6. )
  7. type Descriptor struct {
  8. Name string
  9. Instance Service
  10. InitPriority Priority
  11. }
  12. var services []*Descriptor
  13. func RegisterService(instance Service) {
  14. services = append(services, &Descriptor{
  15. Name: reflect.TypeOf(instance).Elem().Name(),
  16. Instance: instance,
  17. InitPriority: Low,
  18. })
  19. }
  20. func Register(descriptor *Descriptor) {
  21. services = append(services, descriptor)
  22. }
  23. func GetServices() []*Descriptor {
  24. sort.Slice(services, func(i, j int) bool {
  25. return services[i].InitPriority > services[j].InitPriority
  26. })
  27. return services
  28. }
  29. // Service interface is the lowest common shape that services
  30. // are expected to forfill to be started within Grafana.
  31. type Service interface {
  32. // Init is called by Grafana main process which gives the service
  33. // the possibility do some initial work before its started. Things
  34. // like adding routes, bus handlers should be done in the Init function
  35. Init() error
  36. }
  37. // CanBeDisabled allows the services to decide if it should
  38. // be started or not by itself. This is useful for services
  39. // that might not always be started, ex alerting.
  40. // This will be called after `Init()`.
  41. type CanBeDisabled interface {
  42. // IsDisabled should return a bool saying if it can be started or not.
  43. IsDisabled() bool
  44. }
  45. // BackgroundService should be implemented for services that have
  46. // long running tasks in the background.
  47. type BackgroundService interface {
  48. // Run starts the background process of the service after `Init` have been called
  49. // on all services. The `context.Context` passed into the function should be used
  50. // to subscribe to ctx.Done() so the service can be notified when Grafana shuts down.
  51. Run(ctx context.Context) error
  52. }
  53. // IsDisabled takes an service and return true if its disabled
  54. func IsDisabled(srv Service) bool {
  55. canBeDisabled, ok := srv.(CanBeDisabled)
  56. return ok && canBeDisabled.IsDisabled()
  57. }
  58. type Priority int
  59. const (
  60. High Priority = 100
  61. Low Priority = 0
  62. )