ps.go 5.3 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. if project != nil && len(services) > 0 {
  88. names := project.ServiceNames()
  89. for _, service := range services {
  90. if !utils.StringContains(names, service) {
  91. return fmt.Errorf("no such service: %s", service)
  92. }
  93. }
  94. }
  95. containers, err := backend.Ps(ctx, name, api.PsOptions{
  96. Project: project,
  97. All: opts.All,
  98. Services: services,
  99. })
  100. if err != nil {
  101. return err
  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.Fprintln(streams.Out(), 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.Fprintln(streams.Out(), strings.Join(services, "\n"))
  123. return nil
  124. }
  125. return formatter.Print(containers, opts.Format, streams.Out(),
  126. writer(containers),
  127. "NAME", "IMAGE", "COMMAND", "SERVICE", "CREATED", "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. createdAt := time.Unix(container.Created, 0)
  134. created := units.HumanDuration(time.Now().UTC().Sub(createdAt)) + " ago"
  135. status := container.Status
  136. command := formatter2.Ellipsis(container.Command, 20)
  137. _, _ = 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)
  138. }
  139. }
  140. }
  141. func filterByStatus(containers []api.ContainerSummary, statuses []string) []api.ContainerSummary {
  142. var filtered []api.ContainerSummary
  143. for _, c := range containers {
  144. if hasStatus(c, statuses) {
  145. filtered = append(filtered, c)
  146. }
  147. }
  148. return filtered
  149. }
  150. func hasStatus(c api.ContainerSummary, statuses []string) bool {
  151. for _, status := range statuses {
  152. if c.State == status {
  153. return true
  154. }
  155. }
  156. return false
  157. }
  158. func displayablePorts(c api.ContainerSummary) string {
  159. if c.Publishers == nil {
  160. return ""
  161. }
  162. ports := make([]types.Port, len(c.Publishers))
  163. for i, pub := range c.Publishers {
  164. ports[i] = types.Port{
  165. IP: pub.URL,
  166. PrivatePort: uint16(pub.TargetPort),
  167. PublicPort: uint16(pub.PublishedPort),
  168. Type: pub.Protocol,
  169. }
  170. }
  171. return formatter2.DisplayablePorts(ports)
  172. }