top.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. "sort"
  19. "strings"
  20. "text/tabwriter"
  21. "github.com/spf13/cobra"
  22. "github.com/docker/compose/v2/pkg/api"
  23. )
  24. type topOptions struct {
  25. *ProjectOptions
  26. }
  27. func topCommand(p *ProjectOptions, streams api.Streams, backend api.Service) *cobra.Command {
  28. opts := topOptions{
  29. ProjectOptions: p,
  30. }
  31. topCmd := &cobra.Command{
  32. Use: "top [SERVICES...]",
  33. Short: "Display the running processes",
  34. RunE: Adapt(func(ctx context.Context, args []string) error {
  35. return runTop(ctx, streams, backend, opts, args)
  36. }),
  37. ValidArgsFunction: completeServiceNames(p),
  38. }
  39. return topCmd
  40. }
  41. func runTop(ctx context.Context, streams api.Streams, backend api.Service, opts topOptions, services []string) error {
  42. projectName, err := opts.toProjectName()
  43. if err != nil {
  44. return err
  45. }
  46. containers, err := backend.Top(ctx, projectName, services)
  47. if err != nil {
  48. return err
  49. }
  50. sort.Slice(containers, func(i, j int) bool {
  51. return containers[i].Name < containers[j].Name
  52. })
  53. for _, container := range containers {
  54. fmt.Fprintf(streams.Out(), "%s\n", container.Name)
  55. err := psPrinter(streams.Out(), func(w io.Writer) {
  56. for _, proc := range container.Processes {
  57. info := []interface{}{}
  58. for _, p := range proc {
  59. info = append(info, p)
  60. }
  61. _, _ = fmt.Fprintf(w, strings.Repeat("%s\t", len(info))+"\n", info...)
  62. }
  63. fmt.Fprintln(w)
  64. },
  65. container.Titles...)
  66. if err != nil {
  67. return err
  68. }
  69. }
  70. return nil
  71. }
  72. func psPrinter(out io.Writer, printer func(writer io.Writer), headers ...string) error {
  73. w := tabwriter.NewWriter(out, 5, 1, 3, ' ', 0)
  74. _, _ = fmt.Fprintln(w, strings.Join(headers, "\t"))
  75. printer(w)
  76. return w.Flush()
  77. }