ps.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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. formatter2 "github.com/docker/cli/cli/command/formatter"
  24. "github.com/pkg/errors"
  25. "github.com/spf13/cobra"
  26. "github.com/docker/compose/v2/pkg/api"
  27. "github.com/docker/compose/v2/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 opts.Status != "" {
  113. containers = filterByStatus(containers, opts.Status)
  114. }
  115. sort.Slice(containers, func(i, j int) bool {
  116. return containers[i].Name < containers[j].Name
  117. })
  118. if opts.Quiet {
  119. for _, c := range containers {
  120. fmt.Println(c.ID)
  121. }
  122. return nil
  123. }
  124. return formatter.Print(containers, opts.Format, os.Stdout,
  125. writter(containers),
  126. "NAME", "COMMAND", "SERVICE", "STATUS", "PORTS")
  127. }
  128. func writter(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, status string) []api.ContainerSummary {
  144. hasContainerWithState := map[string]struct{}{}
  145. for _, c := range containers {
  146. if c.State == status {
  147. hasContainerWithState[c.Service] = struct{}{}
  148. }
  149. }
  150. var filtered []api.ContainerSummary
  151. for _, c := range containers {
  152. if _, ok := hasContainerWithState[c.Service]; ok {
  153. filtered = append(filtered, c)
  154. }
  155. }
  156. return filtered
  157. }
  158. type portRange struct {
  159. pStart int
  160. pEnd int
  161. tStart int
  162. tEnd int
  163. IP string
  164. protocol string
  165. }
  166. func (pr portRange) String() string {
  167. var (
  168. pub string
  169. tgt string
  170. )
  171. if pr.pEnd > pr.pStart {
  172. pub = fmt.Sprintf("%s:%d-%d->", pr.IP, pr.pStart, pr.pEnd)
  173. } else if pr.pStart > 0 {
  174. pub = fmt.Sprintf("%s:%d->", pr.IP, pr.pStart)
  175. }
  176. if pr.tEnd > pr.tStart {
  177. tgt = fmt.Sprintf("%d-%d", pr.tStart, pr.tEnd)
  178. } else {
  179. tgt = fmt.Sprintf("%d", pr.tStart)
  180. }
  181. return fmt.Sprintf("%s%s/%s", pub, tgt, pr.protocol)
  182. }
  183. // DisplayablePorts is copy pasted from https://github.com/docker/cli/pull/581/files
  184. func DisplayablePorts(c api.ContainerSummary) string {
  185. if c.Publishers == nil {
  186. return ""
  187. }
  188. sort.Sort(c.Publishers)
  189. pr := portRange{}
  190. ports := []string{}
  191. for _, p := range c.Publishers {
  192. prIsRange := pr.tEnd != pr.tStart
  193. tOverlaps := p.TargetPort <= pr.tEnd
  194. // Start a new port-range if:
  195. // - the protocol is different from the current port-range
  196. // - published or target port are not consecutive to the current port-range
  197. // - the current port-range is a _range_, and the target port overlaps with the current range's target-ports
  198. if p.Protocol != pr.protocol || p.URL != pr.IP || p.PublishedPort-pr.pEnd > 1 || p.TargetPort-pr.tEnd > 1 || prIsRange && tOverlaps {
  199. // start a new port-range, and print the previous port-range (if any)
  200. if pr.pStart > 0 {
  201. ports = append(ports, pr.String())
  202. }
  203. pr = portRange{
  204. pStart: p.PublishedPort,
  205. pEnd: p.PublishedPort,
  206. tStart: p.TargetPort,
  207. tEnd: p.TargetPort,
  208. protocol: p.Protocol,
  209. IP: p.URL,
  210. }
  211. continue
  212. }
  213. pr.pEnd = p.PublishedPort
  214. pr.tEnd = p.TargetPort
  215. }
  216. if pr.tStart > 0 {
  217. ports = append(ports, pr.String())
  218. }
  219. return strings.Join(ports, ", ")
  220. }