ls.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package compose
  14. import (
  15. "context"
  16. "fmt"
  17. "sort"
  18. "github.com/docker/compose-cli/api/compose"
  19. moby "github.com/docker/docker/api/types"
  20. "github.com/docker/docker/api/types/filters"
  21. )
  22. func (s *composeService) List(ctx context.Context) ([]compose.Stack, error) {
  23. list, err := s.apiClient.ContainerList(ctx, moby.ContainerListOptions{
  24. Filters: filters.NewArgs(hasProjectLabelFilter()),
  25. })
  26. if err != nil {
  27. return nil, err
  28. }
  29. return containersToStacks(list)
  30. }
  31. func containersToStacks(containers []moby.Container) ([]compose.Stack, error) {
  32. containersByLabel, keys, err := groupContainerByLabel(containers, projectLabel)
  33. if err != nil {
  34. return nil, err
  35. }
  36. var projects []compose.Stack
  37. for _, project := range keys {
  38. projects = append(projects, compose.Stack{
  39. ID: project,
  40. Name: project,
  41. Status: combinedStatus(containerToState(containersByLabel[project])),
  42. })
  43. }
  44. return projects, nil
  45. }
  46. func containerToState(containers []moby.Container) []string {
  47. statuses := []string{}
  48. for _, c := range containers {
  49. statuses = append(statuses, c.State)
  50. }
  51. return statuses
  52. }
  53. func combinedStatus(statuses []string) string {
  54. nbByStatus := map[string]int{}
  55. keys := []string{}
  56. for _, status := range statuses {
  57. nb, ok := nbByStatus[status]
  58. if !ok {
  59. nb = 0
  60. keys = append(keys, status)
  61. }
  62. nbByStatus[status] = nb + 1
  63. }
  64. sort.Strings(keys)
  65. result := ""
  66. for _, status := range keys {
  67. nb := nbByStatus[status]
  68. if result != "" {
  69. result = result + ", "
  70. }
  71. result = result + fmt.Sprintf("%s(%d)", status, nb)
  72. }
  73. return result
  74. }