services.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package services
  2. import (
  3. "sync"
  4. "github.com/julienschmidt/httprouter"
  5. "github.com/opencost/opencost/core/pkg/log"
  6. )
  7. // HTTPService defines an implementation prototype for an object capable of registering
  8. // endpoints on an http router which provide an service relevant to the cost-model.
  9. type HTTPService interface {
  10. // Register assigns the endpoints and returns an error on failure.
  11. Register(*httprouter.Router) error
  12. }
  13. // HTTPServices defines an implementation prototype for an object capable of managing and registering
  14. // predefined HTTPService routes
  15. type HTTPServices interface {
  16. // Add a HTTPService implementation for registration
  17. Add(service HTTPService)
  18. // RegisterAll registers all the services added with the provided router
  19. RegisterAll(*httprouter.Router) error
  20. }
  21. type defaultHTTPServices struct {
  22. sync.Mutex
  23. services []HTTPService
  24. }
  25. // Add a HTTPService implementation for
  26. func (dhs *defaultHTTPServices) Add(service HTTPService) {
  27. if service == nil {
  28. log.Warnf("Attempting to Add nil HTTPService")
  29. return
  30. }
  31. dhs.Lock()
  32. defer dhs.Unlock()
  33. dhs.services = append(dhs.services, service)
  34. }
  35. // RegisterAll registers all the services added with the provided router
  36. func (dhs *defaultHTTPServices) RegisterAll(router *httprouter.Router) error {
  37. dhs.Lock()
  38. defer dhs.Unlock()
  39. for _, svc := range dhs.services {
  40. svc.Register(router)
  41. }
  42. return nil
  43. }
  44. // NewCostModelServices creates an HTTPServices implementation containing any predefined
  45. // http services used with the cost-model
  46. func NewCostModelServices() HTTPServices {
  47. return &defaultHTTPServices{
  48. services: []HTTPService{
  49. NewClusterManagerService(),
  50. },
  51. }
  52. }