2016-06-06 09:38:43 -04:00
|
|
|
package container
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
|
|
|
"text/tabwriter"
|
|
|
|
|
|
|
|
"github.com/docker/docker/cli"
|
2016-09-08 13:11:39 -04:00
|
|
|
"github.com/docker/docker/cli/command"
|
2016-06-06 09:38:43 -04:00
|
|
|
"github.com/spf13/cobra"
|
2016-12-24 19:05:37 -05:00
|
|
|
"golang.org/x/net/context"
|
2016-06-06 09:38:43 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
type topOptions struct {
|
|
|
|
container string
|
|
|
|
|
|
|
|
args []string
|
|
|
|
}
|
|
|
|
|
2016-06-21 03:28:30 -04:00
|
|
|
// NewTopCommand creates a new cobra.Command for `docker top`
|
2016-09-08 13:11:39 -04:00
|
|
|
func NewTopCommand(dockerCli *command.DockerCli) *cobra.Command {
|
2016-06-06 09:38:43 -04:00
|
|
|
var opts topOptions
|
|
|
|
|
|
|
|
cmd := &cobra.Command{
|
|
|
|
Use: "top CONTAINER [ps OPTIONS]",
|
|
|
|
Short: "Display the running processes of a container",
|
|
|
|
Args: cli.RequiresMinArgs(1),
|
|
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
|
|
opts.container = args[0]
|
|
|
|
opts.args = args[1:]
|
|
|
|
return runTop(dockerCli, &opts)
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
flags := cmd.Flags()
|
|
|
|
flags.SetInterspersed(false)
|
|
|
|
|
|
|
|
return cmd
|
|
|
|
}
|
|
|
|
|
2016-09-08 13:11:39 -04:00
|
|
|
func runTop(dockerCli *command.DockerCli, opts *topOptions) error {
|
2016-06-06 09:38:43 -04:00
|
|
|
ctx := context.Background()
|
|
|
|
|
|
|
|
procList, err := dockerCli.Client().ContainerTop(ctx, opts.container, opts.args)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
w := tabwriter.NewWriter(dockerCli.Out(), 20, 1, 3, ' ', 0)
|
|
|
|
fmt.Fprintln(w, strings.Join(procList.Titles, "\t"))
|
|
|
|
|
|
|
|
for _, proc := range procList.Processes {
|
|
|
|
fmt.Fprintln(w, strings.Join(proc, "\t"))
|
|
|
|
}
|
|
|
|
w.Flush()
|
|
|
|
return nil
|
|
|
|
}
|