github.1git.de/docker/cli@v26.1.3+incompatible/cli/command/container/top.go (about)

     1  package container
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"strings"
     7  
     8  	"github.com/docker/cli/cli"
     9  	"github.com/docker/cli/cli/command"
    10  	"github.com/docker/cli/cli/command/completion"
    11  	"github.com/docker/cli/cli/command/formatter/tabwriter"
    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.Cli) *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(cmd.Context(), dockerCli, &opts)
    33  		},
    34  		Annotations: map[string]string{
    35  			"aliases": "docker container top, docker top",
    36  		},
    37  		ValidArgsFunction: completion.ContainerNames(dockerCli, false),
    38  	}
    39  
    40  	flags := cmd.Flags()
    41  	flags.SetInterspersed(false)
    42  
    43  	return cmd
    44  }
    45  
    46  func runTop(ctx context.Context, dockerCli command.Cli, opts *topOptions) error {
    47  	procList, err := dockerCli.Client().ContainerTop(ctx, opts.container, opts.args)
    48  	if err != nil {
    49  		return err
    50  	}
    51  
    52  	w := tabwriter.NewWriter(dockerCli.Out(), 20, 1, 3, ' ', 0)
    53  	fmt.Fprintln(w, strings.Join(procList.Titles, "\t"))
    54  
    55  	for _, proc := range procList.Processes {
    56  		fmt.Fprintln(w, strings.Join(proc, "\t"))
    57  	}
    58  	w.Flush()
    59  	return nil
    60  }