github.com/kunnos/engine@v1.13.1/cli/command/container/top.go (about)

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