ps.go 4.6 KB

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