ps.go 2.5 KB

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