github.com/DaoCloud/dao@v0.0.0-20161212064103-c3dbfd13ee36/api/client/container/port.go (about)

     1  package container
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"golang.org/x/net/context"
     8  
     9  	"github.com/docker/docker/api/client"
    10  	"github.com/docker/docker/cli"
    11  	"github.com/docker/go-connections/nat"
    12  	"github.com/spf13/cobra"
    13  )
    14  
    15  type portOptions struct {
    16  	container string
    17  
    18  	port string
    19  }
    20  
    21  // NewPortCommand creats a new cobra.Command for `docker port`
    22  func NewPortCommand(dockerCli *client.DockerCli) *cobra.Command {
    23  	var opts portOptions
    24  
    25  	cmd := &cobra.Command{
    26  		Use:   "port CONTAINER [PRIVATE_PORT[/PROTO]]",
    27  		Short: "罗列为容器指定的所有端口映射信息",
    28  		Args:  cli.RequiresRangeArgs(1, 2),
    29  		RunE: func(cmd *cobra.Command, args []string) error {
    30  			opts.container = args[0]
    31  			if len(args) > 1 {
    32  				opts.port = args[1]
    33  			}
    34  			return runPort(dockerCli, &opts)
    35  		},
    36  	}
    37  
    38  	return cmd
    39  }
    40  
    41  func runPort(dockerCli *client.DockerCli, opts *portOptions) error {
    42  	ctx := context.Background()
    43  
    44  	c, err := dockerCli.Client().ContainerInspect(ctx, opts.container)
    45  	if err != nil {
    46  		return err
    47  	}
    48  
    49  	if opts.port != "" {
    50  		port := opts.port
    51  		proto := "tcp"
    52  		parts := strings.SplitN(port, "/", 2)
    53  
    54  		if len(parts) == 2 && len(parts[1]) != 0 {
    55  			port = parts[0]
    56  			proto = parts[1]
    57  		}
    58  		natPort := port + "/" + proto
    59  		newP, err := nat.NewPort(proto, port)
    60  		if err != nil {
    61  			return err
    62  		}
    63  		if frontends, exists := c.NetworkSettings.Ports[newP]; exists && frontends != nil {
    64  			for _, frontend := range frontends {
    65  				fmt.Fprintf(dockerCli.Out(), "%s:%s\n", frontend.HostIP, frontend.HostPort)
    66  			}
    67  			return nil
    68  		}
    69  		return fmt.Errorf("错误: 没有暴露端口'%s'给容器 %s", natPort, opts.container)
    70  	}
    71  
    72  	for from, frontends := range c.NetworkSettings.Ports {
    73  		for _, frontend := range frontends {
    74  			fmt.Fprintf(dockerCli.Out(), "%s -> %s:%s\n", from, frontend.HostIP, frontend.HostPort)
    75  		}
    76  	}
    77  
    78  	return nil
    79  }