ps.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. "sort"
  17. "golang.org/x/sync/errgroup"
  18. "github.com/docker/compose/v2/pkg/api"
  19. )
  20. func (s *composeService) Ps(ctx context.Context, projectName string, options api.PsOptions) ([]api.ContainerSummary, error) {
  21. oneOff := oneOffExclude
  22. if options.All {
  23. oneOff = oneOffInclude
  24. }
  25. containers, err := s.getContainers(ctx, projectName, oneOff, true, options.Services...)
  26. if err != nil {
  27. return nil, err
  28. }
  29. summary := make([]api.ContainerSummary, len(containers))
  30. eg, ctx := errgroup.WithContext(ctx)
  31. for i, container := range containers {
  32. i, container := i, container
  33. eg.Go(func() error {
  34. var publishers []api.PortPublisher
  35. sort.Slice(container.Ports, func(i, j int) bool {
  36. return container.Ports[i].PrivatePort < container.Ports[j].PrivatePort
  37. })
  38. for _, p := range container.Ports {
  39. publishers = append(publishers, api.PortPublisher{
  40. URL: p.IP,
  41. TargetPort: int(p.PrivatePort),
  42. PublishedPort: int(p.PublicPort),
  43. Protocol: p.Type,
  44. })
  45. }
  46. inspect, err := s.apiClient.ContainerInspect(ctx, container.ID)
  47. if err != nil {
  48. return err
  49. }
  50. var (
  51. health string
  52. exitCode int
  53. )
  54. if inspect.State != nil {
  55. switch inspect.State.Status {
  56. case "running":
  57. if inspect.State.Health != nil {
  58. health = inspect.State.Health.Status
  59. }
  60. case "exited", "dead":
  61. exitCode = inspect.State.ExitCode
  62. }
  63. }
  64. summary[i] = api.ContainerSummary{
  65. ID: container.ID,
  66. Name: getCanonicalContainerName(container),
  67. Project: container.Labels[api.ProjectLabel],
  68. Service: container.Labels[api.ServiceLabel],
  69. Command: container.Command,
  70. State: container.State,
  71. Health: health,
  72. ExitCode: exitCode,
  73. Publishers: publishers,
  74. }
  75. return nil
  76. })
  77. }
  78. return summary, eg.Wait()
  79. }