top.go 2.3 KB

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