github.com/containerd/nerdctl@v1.7.7/cmd/nerdctl/compose_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 "fmt" 21 "strconv" 22 23 "github.com/containerd/nerdctl/pkg/clientutil" 24 "github.com/containerd/nerdctl/pkg/cmd/compose" 25 "github.com/containerd/nerdctl/pkg/composer" 26 "github.com/spf13/cobra" 27 ) 28 29 func newComposePortCommand() *cobra.Command { 30 var composePortCommand = &cobra.Command{ 31 Use: "port [flags] SERVICE PRIVATE_PORT", 32 Short: "Print the public port for a port binding", 33 Args: cobra.ExactArgs(2), 34 RunE: composePortAction, 35 SilenceUsage: true, 36 SilenceErrors: true, 37 } 38 composePortCommand.Flags().Int("index", 1, "index of the container if the service has multiple instances.") 39 composePortCommand.Flags().String("protocol", "tcp", "protocol of the port (tcp|udp)") 40 41 return composePortCommand 42 } 43 44 func composePortAction(cmd *cobra.Command, args []string) error { 45 globalOptions, err := processRootCmdFlags(cmd) 46 if err != nil { 47 return err 48 } 49 index, err := cmd.Flags().GetInt("index") 50 if err != nil { 51 return err 52 } 53 if index < 1 { 54 return fmt.Errorf("index starts from 1 and should be equal or greater than 1, given index: %d", index) 55 } 56 57 protocol, err := cmd.Flags().GetString("protocol") 58 if err != nil { 59 return err 60 } 61 switch protocol { 62 case "tcp", "udp": 63 default: 64 return fmt.Errorf("unsupported protocol: %s (only tcp and udp are supported)", protocol) 65 } 66 67 port, err := strconv.Atoi(args[1]) 68 if err != nil { 69 return err 70 } 71 if port <= 0 { 72 return fmt.Errorf("unexpected port: %d", port) 73 } 74 75 client, ctx, cancel, err := clientutil.NewClient(cmd.Context(), globalOptions.Namespace, globalOptions.Address) 76 if err != nil { 77 return err 78 } 79 defer cancel() 80 options, err := getComposeOptions(cmd, globalOptions.DebugFull, globalOptions.Experimental) 81 if err != nil { 82 return err 83 } 84 c, err := compose.New(client, globalOptions, options, cmd.OutOrStdout(), cmd.ErrOrStderr()) 85 if err != nil { 86 return err 87 } 88 89 po := composer.PortOptions{ 90 ServiceName: args[0], 91 Index: index, 92 Port: port, 93 Protocol: protocol, 94 } 95 96 return c.Port(ctx, cmd.OutOrStdout(), po) 97 }