ps.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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. "time"
  23. "github.com/docker/compose/v2/cmd/formatter"
  24. "github.com/docker/compose/v2/pkg/utils"
  25. "github.com/docker/docker/api/types"
  26. formatter2 "github.com/docker/cli/cli/command/formatter"
  27. "github.com/docker/go-units"
  28. "github.com/pkg/errors"
  29. "github.com/spf13/cobra"
  30. "github.com/docker/compose/v2/pkg/api"
  31. )
  32. type psOptions struct {
  33. *projectOptions
  34. Format string
  35. All bool
  36. Quiet bool
  37. Services bool
  38. Filter string
  39. Status []string
  40. }
  41. func (p *psOptions) parseFilter() error {
  42. if p.Filter == "" {
  43. return nil
  44. }
  45. parts := strings.SplitN(p.Filter, "=", 2)
  46. if len(parts) != 2 {
  47. return errors.New("arguments to --filter should be in form KEY=VAL")
  48. }
  49. switch parts[0] {
  50. case "status":
  51. p.Status = append(p.Status, parts[1])
  52. case "source":
  53. return api.ErrNotImplemented
  54. default:
  55. return fmt.Errorf("unknown filter %s", parts[0])
  56. }
  57. return nil
  58. }
  59. func psCommand(p *projectOptions, backend api.Service) *cobra.Command {
  60. opts := psOptions{
  61. projectOptions: p,
  62. }
  63. psCmd := &cobra.Command{
  64. Use: "ps [OPTIONS] [SERVICE...]",
  65. Short: "List containers",
  66. PreRunE: func(cmd *cobra.Command, args []string) error {
  67. return opts.parseFilter()
  68. },
  69. RunE: Adapt(func(ctx context.Context, args []string) error {
  70. return runPs(ctx, backend, args, opts)
  71. }),
  72. ValidArgsFunction: completeServiceNames(p),
  73. }
  74. flags := psCmd.Flags()
  75. flags.StringVar(&opts.Format, "format", "table", "Format the output. Values: [table | json]")
  76. flags.StringVar(&opts.Filter, "filter", "", "Filter services by a property (supported filters: status).")
  77. flags.StringArrayVar(&opts.Status, "status", []string{}, "Filter services by status. Values: [paused | restarting | removing | running | dead | created | exited]")
  78. flags.BoolVarP(&opts.Quiet, "quiet", "q", false, "Only display IDs")
  79. flags.BoolVar(&opts.Services, "services", false, "Display services")
  80. flags.BoolVarP(&opts.All, "all", "a", false, "Show all stopped containers (including those created by the run command)")
  81. return psCmd
  82. }
  83. func runPs(ctx context.Context, backend api.Service, services []string, opts psOptions) error {
  84. project, name, err := opts.projectOrName(services...)
  85. if err != nil {
  86. return err
  87. }
  88. containers, err := backend.Ps(ctx, name, api.PsOptions{
  89. Project: project,
  90. All: opts.All,
  91. Services: services,
  92. })
  93. if err != nil {
  94. return err
  95. }
  96. SERVICES:
  97. for _, s := range services {
  98. for _, c := range containers {
  99. if c.Service == s {
  100. continue SERVICES
  101. }
  102. }
  103. return fmt.Errorf("no such service: %s", s)
  104. }
  105. if len(opts.Status) != 0 {
  106. containers = filterByStatus(containers, opts.Status)
  107. }
  108. sort.Slice(containers, func(i, j int) bool {
  109. return containers[i].Name < containers[j].Name
  110. })
  111. if opts.Quiet {
  112. for _, c := range containers {
  113. fmt.Println(c.ID)
  114. }
  115. return nil
  116. }
  117. if opts.Services {
  118. services := []string{}
  119. for _, s := range containers {
  120. if !utils.StringContains(services, s.Service) {
  121. services = append(services, s.Service)
  122. }
  123. }
  124. fmt.Println(strings.Join(services, "\n"))
  125. return nil
  126. }
  127. return formatter.Print(containers, opts.Format, os.Stdout,
  128. writer(containers),
  129. "NAME", "IMAGE", "COMMAND", "SERVICE", "CREATED", "STATUS", "PORTS")
  130. }
  131. func writer(containers []api.ContainerSummary) func(w io.Writer) {
  132. return func(w io.Writer) {
  133. for _, container := range containers {
  134. ports := displayablePorts(container)
  135. createdAt := time.Unix(container.Created, 0)
  136. created := units.HumanDuration(time.Now().UTC().Sub(createdAt)) + " ago"
  137. status := container.Status
  138. command := formatter2.Ellipsis(container.Command, 20)
  139. _, _ = 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)
  140. }
  141. }
  142. }
  143. func filterByStatus(containers []api.ContainerSummary, statuses []string) []api.ContainerSummary {
  144. var filtered []api.ContainerSummary
  145. for _, c := range containers {
  146. if hasStatus(c, statuses) {
  147. filtered = append(filtered, c)
  148. }
  149. }
  150. return filtered
  151. }
  152. func hasStatus(c api.ContainerSummary, statuses []string) bool {
  153. for _, status := range statuses {
  154. if c.State == status {
  155. return true
  156. }
  157. }
  158. return false
  159. }
  160. func displayablePorts(c api.ContainerSummary) string {
  161. if c.Publishers == nil {
  162. return ""
  163. }
  164. ports := make([]types.Port, len(c.Publishers))
  165. for i, pub := range c.Publishers {
  166. ports[i] = types.Port{
  167. IP: pub.URL,
  168. PrivatePort: uint16(pub.TargetPort),
  169. PublicPort: uint16(pub.PublishedPort),
  170. Type: pub.Protocol,
  171. }
  172. }
  173. return formatter2.DisplayablePorts(ports)
  174. }