ps.go 2.4 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. moby "github.com/docker/docker/api/types"
  19. "github.com/docker/docker/api/types/filters"
  20. "github.com/docker/compose-cli/api/compose"
  21. )
  22. func (s *composeService) Ps(ctx context.Context, projectName string) ([]compose.ContainerSummary, error) {
  23. containers, err := s.apiClient.ContainerList(ctx, moby.ContainerListOptions{
  24. Filters: filters.NewArgs(
  25. projectFilter(projectName),
  26. ),
  27. })
  28. if err != nil {
  29. return nil, err
  30. }
  31. var summary []compose.ContainerSummary
  32. for _, c := range containers {
  33. var publishers []compose.PortPublisher
  34. for _, p := range c.Ports {
  35. var url string
  36. if p.PublicPort != 0 {
  37. url = fmt.Sprintf("%s:%d", p.IP, p.PublicPort)
  38. }
  39. publishers = append(publishers, compose.PortPublisher{
  40. URL: url,
  41. TargetPort: int(p.PrivatePort),
  42. PublishedPort: int(p.PublicPort),
  43. Protocol: p.Type,
  44. })
  45. }
  46. summary = append(summary, compose.ContainerSummary{
  47. ID: c.ID,
  48. Name: getCanonicalContainerName(c),
  49. Project: c.Labels[projectLabel],
  50. Service: c.Labels[serviceLabel],
  51. State: c.State,
  52. Publishers: publishers,
  53. })
  54. }
  55. return summary, nil
  56. }
  57. func groupContainerByLabel(containers []moby.Container, labelName string) (map[string][]moby.Container, []string, error) {
  58. containersByLabel := map[string][]moby.Container{}
  59. keys := []string{}
  60. for _, c := range containers {
  61. label, ok := c.Labels[labelName]
  62. if !ok {
  63. return nil, nil, fmt.Errorf("No label %q set on container %q of compose project", labelName, c.ID)
  64. }
  65. labelContainers, ok := containersByLabel[label]
  66. if !ok {
  67. labelContainers = []moby.Container{}
  68. keys = append(keys, label)
  69. }
  70. labelContainers = append(labelContainers, c)
  71. containersByLabel[label] = labelContainers
  72. }
  73. sort.Strings(keys)
  74. return containersByLabel, keys, nil
  75. }