ps.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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("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. Deprecated, use --status instead")
  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. 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. 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. 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, 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. type portRange struct {
  161. pStart int
  162. pEnd int
  163. tStart int
  164. tEnd int
  165. IP string
  166. protocol string
  167. }
  168. func (pr portRange) String() string {
  169. var (
  170. pub string
  171. tgt string
  172. )
  173. if pr.pEnd > pr.pStart {
  174. pub = fmt.Sprintf("%s:%d-%d->", pr.IP, pr.pStart, pr.pEnd)
  175. } else if pr.pStart > 0 {
  176. pub = fmt.Sprintf("%s:%d->", pr.IP, pr.pStart)
  177. }
  178. if pr.tEnd > pr.tStart {
  179. tgt = fmt.Sprintf("%d-%d", pr.tStart, pr.tEnd)
  180. } else {
  181. tgt = fmt.Sprintf("%d", pr.tStart)
  182. }
  183. return fmt.Sprintf("%s%s/%s", pub, tgt, pr.protocol)
  184. }
  185. // DisplayablePorts is copy pasted from https://github.com/docker/cli/pull/581/files
  186. func DisplayablePorts(c api.ContainerSummary) string {
  187. if c.Publishers == nil {
  188. return ""
  189. }
  190. sort.Sort(c.Publishers)
  191. pr := portRange{}
  192. ports := []string{}
  193. for _, p := range c.Publishers {
  194. prIsRange := pr.tEnd != pr.tStart
  195. tOverlaps := p.TargetPort <= pr.tEnd
  196. // Start a new port-range if:
  197. // - the protocol is different from the current port-range
  198. // - published or target port are not consecutive to the current port-range
  199. // - the current port-range is a _range_, and the target port overlaps with the current range's target-ports
  200. if p.Protocol != pr.protocol || p.URL != pr.IP || p.PublishedPort-pr.pEnd > 1 || p.TargetPort-pr.tEnd > 1 || prIsRange && tOverlaps {
  201. // start a new port-range, and print the previous port-range (if any)
  202. if pr.pStart > 0 {
  203. ports = append(ports, pr.String())
  204. }
  205. pr = portRange{
  206. pStart: p.PublishedPort,
  207. pEnd: p.PublishedPort,
  208. tStart: p.TargetPort,
  209. tEnd: p.TargetPort,
  210. protocol: p.Protocol,
  211. IP: p.URL,
  212. }
  213. continue
  214. }
  215. pr.pEnd = p.PublishedPort
  216. pr.tEnd = p.TargetPort
  217. }
  218. if pr.tStart > 0 {
  219. ports = append(ports, pr.String())
  220. }
  221. return strings.Join(ports, ", ")
  222. }