github.com/chenchun/docker@v1.3.2-0.20150629222414-20467faf132b/api/client/top.go (about)

     1  package client
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"net/url"
     7  	"strings"
     8  	"text/tabwriter"
     9  
    10  	"github.com/docker/docker/api/types"
    11  	flag "github.com/docker/docker/pkg/mflag"
    12  )
    13  
    14  // CmdTop displays the running processes of a container.
    15  //
    16  // Usage: docker top CONTAINER
    17  func (cli *DockerCli) CmdTop(args ...string) error {
    18  	cmd := cli.Subcmd("top", []string{"CONTAINER [ps OPTIONS]"}, "Display the running processes of a container", true)
    19  	cmd.Require(flag.Min, 1)
    20  
    21  	cmd.ParseFlags(args, true)
    22  
    23  	val := url.Values{}
    24  	if cmd.NArg() > 1 {
    25  		val.Set("ps_args", strings.Join(cmd.Args()[1:], " "))
    26  	}
    27  
    28  	stream, _, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/top?"+val.Encode(), nil, nil)
    29  	if err != nil {
    30  		return err
    31  	}
    32  
    33  	procList := types.ContainerProcessList{}
    34  	if err := json.NewDecoder(stream).Decode(&procList); err != nil {
    35  		return err
    36  	}
    37  
    38  	w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
    39  	fmt.Fprintln(w, strings.Join(procList.Titles, "\t"))
    40  
    41  	for _, proc := range procList.Processes {
    42  		fmt.Fprintln(w, strings.Join(proc, "\t"))
    43  	}
    44  	w.Flush()
    45  	return nil
    46  }