| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- /*
- Copyright 2020 Docker Compose CLI authors
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- */
- package compose
- import (
- "context"
- "fmt"
- "sort"
- "github.com/docker/compose-cli/api/compose"
- moby "github.com/docker/docker/api/types"
- "github.com/docker/docker/api/types/filters"
- )
- func (s *composeService) List(ctx context.Context) ([]compose.Stack, error) {
- list, err := s.apiClient.ContainerList(ctx, moby.ContainerListOptions{
- Filters: filters.NewArgs(hasProjectLabelFilter()),
- })
- if err != nil {
- return nil, err
- }
- return containersToStacks(list)
- }
- func containersToStacks(containers []moby.Container) ([]compose.Stack, error) {
- containersByLabel, keys, err := groupContainerByLabel(containers, projectLabel)
- if err != nil {
- return nil, err
- }
- var projects []compose.Stack
- for _, project := range keys {
- projects = append(projects, compose.Stack{
- ID: project,
- Name: project,
- Status: combinedStatus(containerToState(containersByLabel[project])),
- })
- }
- return projects, nil
- }
- func containerToState(containers []moby.Container) []string {
- statuses := []string{}
- for _, c := range containers {
- statuses = append(statuses, c.State)
- }
- return statuses
- }
- func combinedStatus(statuses []string) string {
- nbByStatus := map[string]int{}
- keys := []string{}
- for _, status := range statuses {
- nb, ok := nbByStatus[status]
- if !ok {
- nb = 0
- keys = append(keys, status)
- }
- nbByStatus[status] = nb + 1
- }
- sort.Strings(keys)
- result := ""
- for _, status := range keys {
- nb := nbByStatus[status]
- if result != "" {
- result = result + ", "
- }
- result = result + fmt.Sprintf("%s(%d)", status, nb)
- }
- return result
- }
|