github.com/xeptore/docker-cli@v20.10.14+incompatible/cli/command/container/top.go (about)

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