github.com/containerd/nerdctl@v1.7.7/cmd/nerdctl/container_port.go (about) 1 /* 2 Copyright The containerd Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package main 18 19 import ( 20 "context" 21 "fmt" 22 "strconv" 23 "strings" 24 25 "github.com/containerd/nerdctl/pkg/clientutil" 26 "github.com/containerd/nerdctl/pkg/containerutil" 27 "github.com/containerd/nerdctl/pkg/idutil/containerwalker" 28 29 "github.com/spf13/cobra" 30 ) 31 32 func newPortCommand() *cobra.Command { 33 var portCommand = &cobra.Command{ 34 Use: "port [flags] CONTAINER [PRIVATE_PORT[/PROTO]]", 35 Args: cobra.RangeArgs(1, 2), 36 Short: "List port mappings or a specific mapping for the container", 37 RunE: portAction, 38 ValidArgsFunction: portShellComplete, 39 SilenceUsage: true, 40 SilenceErrors: true, 41 } 42 return portCommand 43 } 44 45 func portAction(cmd *cobra.Command, args []string) error { 46 globalOptions, err := processRootCmdFlags(cmd) 47 if err != nil { 48 return err 49 } 50 argPort := -1 51 argProto := "" 52 portProto := "" 53 if len(args) == 2 { 54 portProto = args[1] 55 } 56 57 if portProto != "" { 58 splitBySlash := strings.Split(portProto, "/") 59 var err error 60 argPort, err = strconv.Atoi(splitBySlash[0]) 61 if err != nil { 62 return err 63 } 64 if argPort <= 0 { 65 return fmt.Errorf("unexpected port %d", argPort) 66 } 67 switch len(splitBySlash) { 68 case 1: 69 argProto = "tcp" 70 case 2: 71 argProto = strings.ToLower(splitBySlash[1]) 72 default: 73 return fmt.Errorf("failed to parse %q", portProto) 74 } 75 } 76 client, ctx, cancel, err := clientutil.NewClient(cmd.Context(), globalOptions.Namespace, globalOptions.Address) 77 if err != nil { 78 return err 79 } 80 defer cancel() 81 82 walker := &containerwalker.ContainerWalker{ 83 Client: client, 84 OnFound: func(ctx context.Context, found containerwalker.Found) error { 85 if found.MatchCount > 1 { 86 return fmt.Errorf("multiple IDs found with provided prefix: %s", found.Req) 87 } 88 return containerutil.PrintHostPort(ctx, cmd.OutOrStdout(), found.Container, argPort, argProto) 89 }, 90 } 91 req := args[0] 92 n, err := walker.Walk(ctx, req) 93 if err != nil { 94 return err 95 } else if n == 0 { 96 return fmt.Errorf("no such container %s", req) 97 } 98 return nil 99 } 100 101 func portShellComplete(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { 102 return shellCompleteContainerNames(cmd, nil) 103 }