top.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package container
  2. import (
  3. "fmt"
  4. "strings"
  5. "text/tabwriter"
  6. "golang.org/x/net/context"
  7. "github.com/docker/docker/api/client"
  8. "github.com/docker/docker/cli"
  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 *client.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. cmd.SetFlagErrorFunc(flagErrorFunc)
  29. flags := cmd.Flags()
  30. flags.SetInterspersed(false)
  31. return cmd
  32. }
  33. func runTop(dockerCli *client.DockerCli, opts *topOptions) error {
  34. ctx := context.Background()
  35. procList, err := dockerCli.Client().ContainerTop(ctx, opts.container, opts.args)
  36. if err != nil {
  37. return err
  38. }
  39. w := tabwriter.NewWriter(dockerCli.Out(), 20, 1, 3, ' ', 0)
  40. fmt.Fprintln(w, strings.Join(procList.Titles, "\t"))
  41. for _, proc := range procList.Processes {
  42. fmt.Fprintln(w, strings.Join(proc, "\t"))
  43. }
  44. w.Flush()
  45. return nil
  46. }