registry.go 2.3 KB

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