ps.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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. "io"
  18. "os"
  19. "sort"
  20. "strconv"
  21. "strings"
  22. "github.com/docker/compose/v2/cmd/formatter"
  23. "github.com/docker/compose/v2/pkg/utils"
  24. "github.com/docker/docker/api/types"
  25. formatter2 "github.com/docker/cli/cli/command/formatter"
  26. "github.com/pkg/errors"
  27. "github.com/spf13/cobra"
  28. "github.com/docker/compose/v2/pkg/api"
  29. )
  30. type psOptions struct {
  31. *projectOptions
  32. Format string
  33. All bool
  34. Quiet bool
  35. Services bool
  36. Filter string
  37. Status []string
  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, 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, backend, args, opts)
  69. }),
  70. ValidArgsFunction: serviceCompletion(p),
  71. }
  72. flags := psCmd.Flags()
  73. flags.StringVar(&opts.Format, "format", "pretty", "Format the output. Values: [pretty | json]")
  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.BoolVarP(&opts.All, "all", "a", false, "Show all stopped containers (including those created by the run command)")
  79. return psCmd
  80. }
  81. func runPs(ctx context.Context, backend api.Service, services []string, opts psOptions) error {
  82. project, name, err := opts.projectOrName()
  83. if err != nil {
  84. return err
  85. }
  86. containers, err := backend.Ps(ctx, name, api.PsOptions{
  87. Project: project,
  88. All: opts.All,
  89. Services: services,
  90. })
  91. if err != nil {
  92. return err
  93. }
  94. SERVICES:
  95. for _, s := range services {
  96. for _, c := range containers {
  97. if c.Service == s {
  98. continue SERVICES
  99. }
  100. }
  101. return fmt.Errorf("no such service: %s", s)
  102. }
  103. if len(opts.Status) != 0 {
  104. containers = filterByStatus(containers, opts.Status)
  105. }
  106. sort.Slice(containers, func(i, j int) bool {
  107. return containers[i].Name < containers[j].Name
  108. })
  109. if opts.Quiet {
  110. for _, c := range containers {
  111. fmt.Println(c.ID)
  112. }
  113. return nil
  114. }
  115. if opts.Services {
  116. services := []string{}
  117. for _, s := range containers {
  118. if !utils.StringContains(services, s.Service) {
  119. services = append(services, s.Service)
  120. }
  121. }
  122. fmt.Println(strings.Join(services, "\n"))
  123. return nil
  124. }
  125. return formatter.Print(containers, opts.Format, os.Stdout,
  126. writer(containers),
  127. "NAME", "COMMAND", "SERVICE", "STATUS", "PORTS")
  128. }
  129. func writer(containers []api.ContainerSummary) func(w io.Writer) {
  130. return func(w io.Writer) {
  131. for _, container := range containers {
  132. ports := displayablePorts(container)
  133. status := container.State
  134. if status == "running" && container.Health != "" {
  135. status = fmt.Sprintf("%s (%s)", container.State, container.Health)
  136. } else if status == "exited" || status == "dead" {
  137. status = fmt.Sprintf("%s (%d)", container.State, container.ExitCode)
  138. }
  139. command := formatter2.Ellipsis(container.Command, 20)
  140. _, _ = fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", container.Name, strconv.Quote(command), container.Service, status, ports)
  141. }
  142. }
  143. }
  144. func filterByStatus(containers []api.ContainerSummary, statuses []string) []api.ContainerSummary {
  145. var filtered []api.ContainerSummary
  146. for _, c := range containers {
  147. if hasStatus(c, statuses) {
  148. filtered = append(filtered, c)
  149. }
  150. }
  151. return filtered
  152. }
  153. func hasStatus(c api.ContainerSummary, statuses []string) bool {
  154. for _, status := range statuses {
  155. if c.State == status {
  156. return true
  157. }
  158. }
  159. return false
  160. }
  161. func displayablePorts(c api.ContainerSummary) string {
  162. if c.Publishers == nil {
  163. return ""
  164. }
  165. ports := make([]types.Port, len(c.Publishers))
  166. for i, pub := range c.Publishers {
  167. ports[i] = types.Port{
  168. IP: pub.URL,
  169. PrivatePort: uint16(pub.TargetPort),
  170. PublicPort: uint16(pub.PublishedPort),
  171. Type: pub.Protocol,
  172. }
  173. }
  174. return formatter2.DisplayablePorts(ports)
  175. }