ps.go 4.9 KB

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