name.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package docker
  2. import (
  3. "fmt"
  4. "strconv"
  5. "golang.org/x/net/context"
  6. "github.com/docker/engine-api/client"
  7. "github.com/docker/engine-api/types"
  8. "github.com/docker/engine-api/types/filters"
  9. "github.com/docker/libcompose/labels"
  10. )
  11. const format = "%s_%s_%d"
  12. // Namer defines method to provide container name.
  13. type Namer interface {
  14. Next() (string, int)
  15. }
  16. type defaultNamer struct {
  17. project string
  18. service string
  19. oneOff bool
  20. currentNumber int
  21. }
  22. type singleNamer struct {
  23. name string
  24. }
  25. // NewSingleNamer returns a namer that only allows a single name.
  26. func NewSingleNamer(name string) Namer {
  27. return &singleNamer{name}
  28. }
  29. // NewNamer returns a namer that returns names based on the specified project and
  30. // service name and an inner counter, e.g. project_service_1, project_service_2…
  31. func NewNamer(ctx context.Context, client client.APIClient, project, service string, oneOff bool) (Namer, error) {
  32. namer := &defaultNamer{
  33. project: project,
  34. service: service,
  35. oneOff: oneOff,
  36. }
  37. filter := filters.NewArgs()
  38. filter.Add("label", fmt.Sprintf("%s=%s", labels.PROJECT.Str(), project))
  39. filter.Add("label", fmt.Sprintf("%s=%s", labels.SERVICE.Str(), service))
  40. if oneOff {
  41. filter.Add("label", fmt.Sprintf("%s=%s", labels.ONEOFF.Str(), "True"))
  42. } else {
  43. filter.Add("label", fmt.Sprintf("%s=%s", labels.ONEOFF.Str(), "False"))
  44. }
  45. containers, err := client.ContainerList(ctx, types.ContainerListOptions{
  46. All: true,
  47. Filter: filter,
  48. })
  49. if err != nil {
  50. return nil, err
  51. }
  52. maxNumber := 0
  53. for _, container := range containers {
  54. numberLabel := container.Labels[labels.NUMBER.Str()]
  55. if numberLabel == "" {
  56. namer.currentNumber = 1
  57. return namer, nil
  58. }
  59. number, err := strconv.Atoi(numberLabel)
  60. if err != nil {
  61. return nil, err
  62. }
  63. if number > maxNumber {
  64. maxNumber = number
  65. }
  66. }
  67. namer.currentNumber = maxNumber + 1
  68. return namer, nil
  69. }
  70. func (i *defaultNamer) Next() (string, int) {
  71. service := i.service
  72. if i.oneOff {
  73. service = i.service + "_run"
  74. }
  75. name := fmt.Sprintf(format, i.project, service, i.currentNumber)
  76. number := i.currentNumber
  77. i.currentNumber = i.currentNumber + 1
  78. return name, number
  79. }
  80. func (s *singleNamer) Next() (string, int) {
  81. return s.name, 1
  82. }