ps.go 4.5 KB

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