ps.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. formatter2 "github.com/docker/cli/cli/command/formatter"
  25. "github.com/pkg/errors"
  26. "github.com/spf13/cobra"
  27. "github.com/docker/compose/v2/pkg/api"
  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 = append(p.Status, parts[1])
  49. case "source":
  50. return api.ErrNotImplemented
  51. default:
  52. return fmt.Errorf("unknown 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 (supported filters: status).")
  74. flags.StringArrayVar(&opts.Status, "status", []string{}, "Filter services by status. Values: [paused | restarting | removing | running | dead | created | exited]")
  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. return psCmd
  79. }
  80. func runPs(ctx context.Context, backend api.Service, services []string, opts psOptions) error {
  81. projectName, err := opts.toProjectName()
  82. if err != nil {
  83. return err
  84. }
  85. containers, err := backend.Ps(ctx, projectName, api.PsOptions{
  86. All: opts.All,
  87. Services: services,
  88. })
  89. if err != nil {
  90. return err
  91. }
  92. SERVICES:
  93. for _, s := range services {
  94. for _, c := range containers {
  95. if c.Service == s {
  96. continue SERVICES
  97. }
  98. }
  99. return fmt.Errorf("no such service: %s", s)
  100. }
  101. if len(opts.Status) != 0 {
  102. containers = filterByStatus(containers, opts.Status)
  103. }
  104. sort.Slice(containers, func(i, j int) bool {
  105. return containers[i].Name < containers[j].Name
  106. })
  107. if opts.Quiet {
  108. for _, c := range containers {
  109. fmt.Println(c.ID)
  110. }
  111. return nil
  112. }
  113. if opts.Services {
  114. services := []string{}
  115. for _, s := range containers {
  116. if !utils.StringContains(services, s.Service) {
  117. services = append(services, s.Service)
  118. }
  119. }
  120. fmt.Println(strings.Join(services, "\n"))
  121. return nil
  122. }
  123. return formatter.Print(containers, opts.Format, os.Stdout,
  124. writter(containers),
  125. "NAME", "COMMAND", "SERVICE", "STATUS", "PORTS")
  126. }
  127. func writter(containers []api.ContainerSummary) func(w io.Writer) {
  128. return func(w io.Writer) {
  129. for _, container := range containers {
  130. ports := DisplayablePorts(container)
  131. status := container.State
  132. if status == "running" && container.Health != "" {
  133. status = fmt.Sprintf("%s (%s)", container.State, container.Health)
  134. } else if status == "exited" || status == "dead" {
  135. status = fmt.Sprintf("%s (%d)", container.State, container.ExitCode)
  136. }
  137. command := formatter2.Ellipsis(container.Command, 20)
  138. _, _ = fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", container.Name, strconv.Quote(command), container.Service, status, ports)
  139. }
  140. }
  141. }
  142. func filterByStatus(containers []api.ContainerSummary, statuses []string) []api.ContainerSummary {
  143. var filtered []api.ContainerSummary
  144. for _, c := range containers {
  145. if hasStatus(c, statuses) {
  146. filtered = append(filtered, c)
  147. }
  148. }
  149. return filtered
  150. }
  151. func hasStatus(c api.ContainerSummary, statuses []string) bool {
  152. for _, status := range statuses {
  153. if c.State == status {
  154. return true
  155. }
  156. }
  157. return false
  158. }
  159. type portRange struct {
  160. pStart int
  161. pEnd int
  162. tStart int
  163. tEnd int
  164. IP string
  165. protocol string
  166. }
  167. func (pr portRange) String() string {
  168. var (
  169. pub string
  170. tgt string
  171. )
  172. if pr.pEnd > pr.pStart {
  173. pub = fmt.Sprintf("%s:%d-%d->", pr.IP, pr.pStart, pr.pEnd)
  174. } else if pr.pStart > 0 {
  175. pub = fmt.Sprintf("%s:%d->", pr.IP, pr.pStart)
  176. }
  177. if pr.tEnd > pr.tStart {
  178. tgt = fmt.Sprintf("%d-%d", pr.tStart, pr.tEnd)
  179. } else {
  180. tgt = fmt.Sprintf("%d", pr.tStart)
  181. }
  182. return fmt.Sprintf("%s%s/%s", pub, tgt, pr.protocol)
  183. }
  184. // DisplayablePorts is copy pasted from https://github.com/docker/cli/pull/581/files
  185. func DisplayablePorts(c api.ContainerSummary) string {
  186. if c.Publishers == nil {
  187. return ""
  188. }
  189. sort.Sort(c.Publishers)
  190. pr := portRange{}
  191. ports := []string{}
  192. for _, p := range c.Publishers {
  193. prIsRange := pr.tEnd != pr.tStart
  194. tOverlaps := p.TargetPort <= pr.tEnd
  195. // Start a new port-range if:
  196. // - the protocol is different from the current port-range
  197. // - published or target port are not consecutive to the current port-range
  198. // - the current port-range is a _range_, and the target port overlaps with the current range's target-ports
  199. if p.Protocol != pr.protocol || p.URL != pr.IP || p.PublishedPort-pr.pEnd > 1 || p.TargetPort-pr.tEnd > 1 || prIsRange && tOverlaps {
  200. // start a new port-range, and print the previous port-range (if any)
  201. if pr.pStart > 0 {
  202. ports = append(ports, pr.String())
  203. }
  204. pr = portRange{
  205. pStart: p.PublishedPort,
  206. pEnd: p.PublishedPort,
  207. tStart: p.TargetPort,
  208. tEnd: p.TargetPort,
  209. protocol: p.Protocol,
  210. IP: p.URL,
  211. }
  212. continue
  213. }
  214. pr.pEnd = p.PublishedPort
  215. pr.tEnd = p.TargetPort
  216. }
  217. if pr.tStart > 0 {
  218. ports = append(ports, pr.String())
  219. }
  220. return strings.Join(ports, ", ")
  221. }