ps.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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. "errors"
  17. "fmt"
  18. "slices"
  19. "sort"
  20. "strings"
  21. "github.com/docker/cli/cli/command"
  22. cliformatter "github.com/docker/cli/cli/command/formatter"
  23. cliflags "github.com/docker/cli/cli/flags"
  24. "github.com/spf13/cobra"
  25. "github.com/docker/compose/v5/cmd/formatter"
  26. "github.com/docker/compose/v5/pkg/api"
  27. "github.com/docker/compose/v5/pkg/compose"
  28. )
  29. type psOptions struct {
  30. *ProjectOptions
  31. Format string
  32. All bool
  33. Quiet bool
  34. Services bool
  35. Filter string
  36. Status []string
  37. noTrunc bool
  38. Orphans bool
  39. }
  40. func (p *psOptions) parseFilter() error {
  41. if p.Filter == "" {
  42. return nil
  43. }
  44. parts := strings.SplitN(p.Filter, "=", 2)
  45. if len(parts) != 2 {
  46. return errors.New("arguments to --filter should be in form KEY=VAL")
  47. }
  48. switch parts[0] {
  49. case "status":
  50. p.Status = append(p.Status, parts[1])
  51. case "source":
  52. return api.ErrNotImplemented
  53. default:
  54. return fmt.Errorf("unknown filter %s", parts[0])
  55. }
  56. return nil
  57. }
  58. func psCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command {
  59. opts := psOptions{
  60. ProjectOptions: p,
  61. }
  62. psCmd := &cobra.Command{
  63. Use: "ps [OPTIONS] [SERVICE...]",
  64. Short: "List containers",
  65. PreRunE: func(cmd *cobra.Command, args []string) error {
  66. return opts.parseFilter()
  67. },
  68. RunE: Adapt(func(ctx context.Context, args []string) error {
  69. return runPs(ctx, dockerCli, backendOptions, args, opts)
  70. }),
  71. ValidArgsFunction: completeServiceNames(dockerCli, p),
  72. }
  73. flags := psCmd.Flags()
  74. flags.StringVar(&opts.Format, "format", "table", cliflags.FormatHelp)
  75. flags.StringVar(&opts.Filter, "filter", "", "Filter services by a property (supported filters: status)")
  76. flags.StringArrayVar(&opts.Status, "status", []string{}, "Filter services by status. Values: [paused | restarting | removing | running | dead | created | exited]")
  77. flags.BoolVarP(&opts.Quiet, "quiet", "q", false, "Only display IDs")
  78. flags.BoolVar(&opts.Services, "services", false, "Display services")
  79. flags.BoolVar(&opts.Orphans, "orphans", true, "Include orphaned services (not declared by project)")
  80. flags.BoolVarP(&opts.All, "all", "a", false, "Show all stopped containers (including those created by the run command)")
  81. flags.BoolVar(&opts.noTrunc, "no-trunc", false, "Don't truncate output")
  82. return psCmd
  83. }
  84. func runPs(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, services []string, opts psOptions) error { //nolint:gocyclo
  85. project, name, err := opts.projectOrName(ctx, dockerCli, services...)
  86. if err != nil {
  87. return err
  88. }
  89. if project != nil {
  90. names := project.ServiceNames()
  91. if len(services) > 0 {
  92. for _, service := range services {
  93. if !slices.Contains(names, service) {
  94. return fmt.Errorf("no such service: %s", service)
  95. }
  96. }
  97. } else if !opts.Orphans {
  98. // until user asks to list orphaned services, we only include those declared in project
  99. services = names
  100. }
  101. }
  102. backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...)
  103. if err != nil {
  104. return err
  105. }
  106. containers, err := backend.Ps(ctx, name, api.PsOptions{
  107. Project: project,
  108. All: opts.All || len(opts.Status) != 0,
  109. Services: services,
  110. })
  111. if err != nil {
  112. return err
  113. }
  114. if len(opts.Status) != 0 {
  115. containers = filterByStatus(containers, opts.Status)
  116. }
  117. sort.Slice(containers, func(i, j int) bool {
  118. return containers[i].Name < containers[j].Name
  119. })
  120. if opts.Quiet {
  121. for _, c := range containers {
  122. _, _ = fmt.Fprintln(dockerCli.Out(), c.ID)
  123. }
  124. return nil
  125. }
  126. if opts.Services {
  127. services := []string{}
  128. for _, c := range containers {
  129. s := c.Service
  130. if !slices.Contains(services, s) {
  131. services = append(services, s)
  132. }
  133. }
  134. _, _ = fmt.Fprintln(dockerCli.Out(), strings.Join(services, "\n"))
  135. return nil
  136. }
  137. if opts.Format == "" {
  138. opts.Format = dockerCli.ConfigFile().PsFormat
  139. }
  140. containerCtx := cliformatter.Context{
  141. Output: dockerCli.Out(),
  142. Format: formatter.NewContainerFormat(opts.Format, opts.Quiet, false),
  143. Trunc: !opts.noTrunc,
  144. }
  145. return formatter.ContainerWrite(containerCtx, containers)
  146. }
  147. func filterByStatus(containers []api.ContainerSummary, statuses []string) []api.ContainerSummary {
  148. var filtered []api.ContainerSummary
  149. for _, c := range containers {
  150. if hasStatus(c, statuses) {
  151. filtered = append(filtered, c)
  152. }
  153. }
  154. return filtered
  155. }
  156. func hasStatus(c api.ContainerSummary, statuses []string) bool {
  157. for _, status := range statuses {
  158. if c.State == status {
  159. return true
  160. }
  161. }
  162. return false
  163. }