backend.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package backend
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "github.com/sirupsen/logrus"
  7. "github.com/docker/api/compose"
  8. "github.com/docker/api/containers"
  9. "github.com/docker/api/context/cloud"
  10. )
  11. var (
  12. errNoType = errors.New("backend: no type")
  13. errNoName = errors.New("backend: no name")
  14. errTypeRegistered = errors.New("backend: already registered")
  15. )
  16. type initFunc func(context.Context) (Service, error)
  17. type registeredBackend struct {
  18. name string
  19. backendType string
  20. init initFunc
  21. }
  22. var backends = struct {
  23. r []*registeredBackend
  24. }{}
  25. // Service aggregates the service interfaces
  26. type Service interface {
  27. ContainerService() containers.Service
  28. ComposeService() compose.Service
  29. CloudService() cloud.Service
  30. }
  31. // Register adds a typed backend to the registry
  32. func Register(name string, backendType string, init initFunc) {
  33. if name == "" {
  34. logrus.Fatal(errNoName)
  35. }
  36. if backendType == "" {
  37. logrus.Fatal(errNoType)
  38. }
  39. for _, b := range backends.r {
  40. if b.backendType == backendType {
  41. logrus.Fatal(errTypeRegistered)
  42. }
  43. }
  44. backends.r = append(backends.r, &registeredBackend{
  45. name,
  46. backendType,
  47. init,
  48. })
  49. }
  50. // Get returns the backend registered for a particular type, it returns
  51. // an error if there is no registered backends for the given type.
  52. func Get(ctx context.Context, backendType string) (Service, error) {
  53. for _, b := range backends.r {
  54. if b.backendType == backendType {
  55. return b.init(ctx)
  56. }
  57. }
  58. return nil, fmt.Errorf("backend not found for context %q", backendType)
  59. }