ps.go 5.2 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. "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 [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. projectName, err := opts.toProjectName()
  83. if err != nil {
  84. return err
  85. }
  86. containers, err := backend.Ps(ctx, projectName, api.PsOptions{
  87. All: opts.All,
  88. Services: services,
  89. })
  90. if err != nil {
  91. return err
  92. }
  93. SERVICES:
  94. for _, s := range services {
  95. for _, c := range containers {
  96. if c.Service == s {
  97. continue SERVICES
  98. }
  99. }
  100. return fmt.Errorf("no such service: %s", s)
  101. }
  102. if len(opts.Status) != 0 {
  103. containers = filterByStatus(containers, opts.Status)
  104. }
  105. sort.Slice(containers, func(i, j int) bool {
  106. return containers[i].Name < containers[j].Name
  107. })
  108. if opts.Quiet {
  109. for _, c := range containers {
  110. fmt.Println(c.ID)
  111. }
  112. return nil
  113. }
  114. if opts.Services {
  115. services := []string{}
  116. for _, s := range containers {
  117. if !utils.StringContains(services, s.Service) {
  118. services = append(services, s.Service)
  119. }
  120. }
  121. fmt.Println(strings.Join(services, "\n"))
  122. return nil
  123. }
  124. return formatter.Print(containers, opts.Format, os.Stdout,
  125. writer(containers),
  126. "NAME", "COMMAND", "SERVICE", "STATUS", "PORTS")
  127. }
  128. func writer(containers []api.ContainerSummary) func(w io.Writer) {
  129. return func(w io.Writer) {
  130. for _, container := range containers {
  131. ports := displayablePorts(container)
  132. status := container.State
  133. if status == "running" && container.Health != "" {
  134. status = fmt.Sprintf("%s (%s)", container.State, container.Health)
  135. } else if status == "exited" || status == "dead" {
  136. status = fmt.Sprintf("%s (%d)", container.State, container.ExitCode)
  137. }
  138. command := formatter2.Ellipsis(container.Command, 20)
  139. _, _ = fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", container.Name, strconv.Quote(command), container.Service, 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. }