backend.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 getCloudServiceFunc func() (cloud.Service, error)
  18. type registeredBackend struct {
  19. name string
  20. backendType string
  21. init initFunc
  22. getCloudService getCloudServiceFunc
  23. }
  24. var backends = struct {
  25. r []*registeredBackend
  26. }{}
  27. // Service aggregates the service interfaces
  28. type Service interface {
  29. ContainerService() containers.Service
  30. ComposeService() compose.Service
  31. }
  32. // Register adds a typed backend to the registry
  33. func Register(name string, backendType string, init initFunc, getCoudService getCloudServiceFunc) {
  34. if name == "" {
  35. logrus.Fatal(errNoName)
  36. }
  37. if backendType == "" {
  38. logrus.Fatal(errNoType)
  39. }
  40. for _, b := range backends.r {
  41. if b.backendType == backendType {
  42. logrus.Fatal(errTypeRegistered)
  43. }
  44. }
  45. backends.r = append(backends.r, &registeredBackend{
  46. name,
  47. backendType,
  48. init,
  49. getCoudService,
  50. })
  51. }
  52. // Get returns the backend registered for a particular type, it returns
  53. // an error if there is no registered backends for the given type.
  54. func Get(ctx context.Context, backendType string) (Service, error) {
  55. for _, b := range backends.r {
  56. if b.backendType == backendType {
  57. return b.init(ctx)
  58. }
  59. }
  60. return nil, fmt.Errorf("backend not found for context %q", backendType)
  61. }
  62. // GetCloudService returns the backend registered for a particular type, it returns
  63. // an error if there is no registered backends for the given type.
  64. func GetCloudService(ctx context.Context, backendType string) (cloud.Service, error) {
  65. for _, b := range backends.r {
  66. if b.backendType == backendType {
  67. return b.getCloudService()
  68. }
  69. }
  70. return nil, fmt.Errorf("backend not found for backend type %s", backendType)
  71. }