ps.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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. "sort"
  19. "strconv"
  20. "strings"
  21. "time"
  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/docker/go-units"
  27. "github.com/pkg/errors"
  28. "github.com/spf13/cobra"
  29. "github.com/docker/compose/v2/pkg/api"
  30. )
  31. type psOptions struct {
  32. *ProjectOptions
  33. Format string
  34. All bool
  35. Quiet bool
  36. Services bool
  37. Filter string
  38. Status []string
  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, streams api.Streams, backend api.Service) *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, streams, backend, args, opts)
  70. }),
  71. ValidArgsFunction: completeServiceNames(p),
  72. }
  73. flags := psCmd.Flags()
  74. flags.StringVar(&opts.Format, "format", "table", "Format the output. Values: [table | json]")
  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.BoolVarP(&opts.All, "all", "a", false, "Show all stopped containers (including those created by the run command)")
  80. return psCmd
  81. }
  82. func runPs(ctx context.Context, streams api.Streams, backend api.Service, services []string, opts psOptions) error {
  83. project, name, err := opts.projectOrName(services...)
  84. if err != nil {
  85. return err
  86. }
  87. containers, err := backend.Ps(ctx, name, api.PsOptions{
  88. Project: project,
  89. All: opts.All,
  90. Services: services,
  91. })
  92. if err != nil {
  93. return err
  94. }
  95. SERVICES:
  96. for _, s := range services {
  97. for _, c := range containers {
  98. if c.Service == s {
  99. continue SERVICES
  100. }
  101. }
  102. return fmt.Errorf("no such service: %s", s)
  103. }
  104. if len(opts.Status) != 0 {
  105. containers = filterByStatus(containers, opts.Status)
  106. }
  107. sort.Slice(containers, func(i, j int) bool {
  108. return containers[i].Name < containers[j].Name
  109. })
  110. if opts.Quiet {
  111. for _, c := range containers {
  112. fmt.Fprintln(streams.Out(), c.ID)
  113. }
  114. return nil
  115. }
  116. if opts.Services {
  117. services := []string{}
  118. for _, s := range containers {
  119. if !utils.StringContains(services, s.Service) {
  120. services = append(services, s.Service)
  121. }
  122. }
  123. fmt.Fprintln(streams.Out(), strings.Join(services, "\n"))
  124. return nil
  125. }
  126. return formatter.Print(containers, opts.Format, streams.Out(),
  127. writer(containers),
  128. "NAME", "IMAGE", "COMMAND", "SERVICE", "CREATED", "STATUS", "PORTS")
  129. }
  130. func writer(containers []api.ContainerSummary) func(w io.Writer) {
  131. return func(w io.Writer) {
  132. for _, container := range containers {
  133. ports := displayablePorts(container)
  134. createdAt := time.Unix(container.Created, 0)
  135. created := units.HumanDuration(time.Now().UTC().Sub(createdAt)) + " ago"
  136. status := container.Status
  137. command := formatter2.Ellipsis(container.Command, 20)
  138. _, _ = fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\t%s\n", container.Name, container.Image, strconv.Quote(command), container.Service, created, status, ports)
  139. }
  140. }
  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. }
  159. func displayablePorts(c api.ContainerSummary) string {
  160. if c.Publishers == nil {
  161. return ""
  162. }
  163. ports := make([]types.Port, len(c.Publishers))
  164. for i, pub := range c.Publishers {
  165. ports[i] = types.Port{
  166. IP: pub.URL,
  167. PrivatePort: uint16(pub.TargetPort),
  168. PublicPort: uint16(pub.PublishedPort),
  169. Type: pub.Protocol,
  170. }
  171. }
  172. return formatter2.DisplayablePorts(ports)
  173. }