ps.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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-cli/cmd/formatter"
  23. formatter2 "github.com/docker/cli/cli/command/formatter"
  24. "github.com/pkg/errors"
  25. "github.com/spf13/cobra"
  26. "github.com/docker/compose-cli/pkg/api"
  27. "github.com/docker/compose-cli/pkg/utils"
  28. )
  29. type psOptions struct {
  30. *projectOptions
  31. Format string
  32. All bool
  33. Quiet bool
  34. Services bool
  35. Filter string
  36. Status string
  37. }
  38. func (p *psOptions) parseFilter() error {
  39. if p.Filter == "" {
  40. return nil
  41. }
  42. parts := strings.SplitN(p.Filter, "=", 2)
  43. if len(parts) != 2 {
  44. return errors.New("arguments to --filter should be in form KEY=VAL")
  45. }
  46. switch parts[0] {
  47. case "status":
  48. p.Status = parts[1]
  49. case "source":
  50. return api.ErrNotImplemented
  51. default:
  52. return fmt.Errorf("unknow filter %s", parts[0])
  53. }
  54. return nil
  55. }
  56. func psCommand(p *projectOptions, backend api.Service) *cobra.Command {
  57. opts := psOptions{
  58. projectOptions: p,
  59. }
  60. psCmd := &cobra.Command{
  61. Use: "ps [SERVICE...]",
  62. Short: "List containers",
  63. PreRunE: func(cmd *cobra.Command, args []string) error {
  64. return opts.parseFilter()
  65. },
  66. RunE: Adapt(func(ctx context.Context, args []string) error {
  67. return runPs(ctx, backend, args, opts)
  68. }),
  69. ValidArgsFunction: serviceCompletion(p),
  70. }
  71. flags := psCmd.Flags()
  72. flags.StringVar(&opts.Format, "format", "pretty", "Format the output. Values: [pretty | json]")
  73. flags.StringVar(&opts.Filter, "filter", "", "Filter services by a property")
  74. flags.StringVar(&opts.Status, "status", "", "Filter services by status")
  75. flags.BoolVarP(&opts.Quiet, "quiet", "q", false, "Only display IDs")
  76. flags.BoolVar(&opts.Services, "services", false, "Display services")
  77. flags.BoolVarP(&opts.All, "all", "a", false, "Show all stopped containers (including those created by the run command)")
  78. flags.Lookup("filter").Hidden = true
  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. if opts.Services {
  94. services := []string{}
  95. for _, s := range containers {
  96. if !utils.StringContains(services, s.Service) {
  97. services = append(services, s.Service)
  98. }
  99. }
  100. fmt.Println(strings.Join(services, "\n"))
  101. return nil
  102. }
  103. SERVICES:
  104. for _, s := range services {
  105. for _, c := range containers {
  106. if c.Service == s {
  107. continue SERVICES
  108. }
  109. }
  110. return fmt.Errorf("no such service: %s", s)
  111. }
  112. if len(containers) == 0 {
  113. return api.ErrNotFound
  114. }
  115. if opts.Status != "" {
  116. containers = filterByStatus(containers, opts.Status)
  117. }
  118. sort.Slice(containers, func(i, j int) bool {
  119. return containers[i].Name < containers[j].Name
  120. })
  121. if opts.Quiet {
  122. for _, c := range containers {
  123. fmt.Println(c.ID)
  124. }
  125. return nil
  126. }
  127. return formatter.Print(containers, opts.Format, os.Stdout,
  128. writter(containers),
  129. "NAME", "COMMAND", "SERVICE", "STATUS", "PORTS")
  130. }
  131. func writter(containers []api.ContainerSummary) func(w io.Writer) {
  132. return func(w io.Writer) {
  133. for _, container := range containers {
  134. var ports []string
  135. for _, p := range container.Publishers {
  136. if p.URL == "" {
  137. ports = append(ports, fmt.Sprintf("%d/%s", p.TargetPort, p.Protocol))
  138. } else {
  139. ports = append(ports, fmt.Sprintf("%s->%d/%s", p.URL, p.TargetPort, p.Protocol))
  140. }
  141. }
  142. status := container.State
  143. if status == "running" && container.Health != "" {
  144. status = fmt.Sprintf("%s (%s)", container.State, container.Health)
  145. } else if status == "exited" || status == "dead" {
  146. status = fmt.Sprintf("%s (%d)", container.State, container.ExitCode)
  147. }
  148. command := formatter2.Ellipsis(container.Command, 20)
  149. _, _ = fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", container.Name, strconv.Quote(command), container.Service, status, strings.Join(ports, ", "))
  150. }
  151. }
  152. }
  153. func filterByStatus(containers []api.ContainerSummary, status string) []api.ContainerSummary {
  154. hasContainerWithState := map[string]struct{}{}
  155. for _, c := range containers {
  156. if c.State == status {
  157. hasContainerWithState[c.Service] = struct{}{}
  158. }
  159. }
  160. var filtered []api.ContainerSummary
  161. for _, c := range containers {
  162. if _, ok := hasContainerWithState[c.Service]; ok {
  163. filtered = append(filtered, c)
  164. }
  165. }
  166. return filtered
  167. }