top.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package container
  2. import (
  3. "fmt"
  4. "strings"
  5. "text/tabwriter"
  6. "golang.org/x/net/context"
  7. "github.com/docker/docker/cli"
  8. "github.com/docker/docker/cli/command"
  9. "github.com/spf13/cobra"
  10. )
  11. type topOptions struct {
  12. container string
  13. args []string
  14. }
  15. // NewTopCommand creates a new cobra.Command for `docker top`
  16. func NewTopCommand(dockerCli *command.DockerCli) *cobra.Command {
  17. var opts topOptions
  18. cmd := &cobra.Command{
  19. Use: "top CONTAINER [ps OPTIONS]",
  20. Short: "Display the running processes of a container",
  21. Args: cli.RequiresMinArgs(1),
  22. RunE: func(cmd *cobra.Command, args []string) error {
  23. opts.container = args[0]
  24. opts.args = args[1:]
  25. return runTop(dockerCli, &opts)
  26. },
  27. }
  28. flags := cmd.Flags()
  29. flags.SetInterspersed(false)
  30. return cmd
  31. }
  32. func runTop(dockerCli *command.DockerCli, opts *topOptions) error {
  33. ctx := context.Background()
  34. procList, err := dockerCli.Client().ContainerTop(ctx, opts.container, opts.args)
  35. if err != nil {
  36. return err
  37. }
  38. w := tabwriter.NewWriter(dockerCli.Out(), 20, 1, 3, ' ', 0)
  39. fmt.Fprintln(w, strings.Join(procList.Titles, "\t"))
  40. for _, proc := range procList.Processes {
  41. fmt.Fprintln(w, strings.Join(proc, "\t"))
  42. }
  43. w.Flush()
  44. return nil
  45. }