port.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package compose
  14. import (
  15. "context"
  16. "fmt"
  17. "strconv"
  18. "strings"
  19. "github.com/docker/cli/cli/command"
  20. "github.com/spf13/cobra"
  21. "github.com/docker/compose/v2/pkg/api"
  22. )
  23. type portOptions struct {
  24. *ProjectOptions
  25. port uint16
  26. protocol string
  27. index int
  28. }
  29. func portCommand(p *ProjectOptions, dockerCli command.Cli, backend api.Service) *cobra.Command {
  30. opts := portOptions{
  31. ProjectOptions: p,
  32. }
  33. cmd := &cobra.Command{
  34. Use: "port [OPTIONS] SERVICE PRIVATE_PORT",
  35. Short: "Print the public port for a port binding",
  36. Args: cobra.MinimumNArgs(2),
  37. PreRunE: Adapt(func(ctx context.Context, args []string) error {
  38. port, err := strconv.ParseUint(args[1], 10, 16)
  39. if err != nil {
  40. return err
  41. }
  42. opts.port = uint16(port)
  43. opts.protocol = strings.ToLower(opts.protocol)
  44. return nil
  45. }),
  46. RunE: Adapt(func(ctx context.Context, args []string) error {
  47. return runPort(ctx, dockerCli, backend, opts, args[0])
  48. }),
  49. ValidArgsFunction: completeServiceNames(dockerCli, p),
  50. }
  51. cmd.Flags().StringVar(&opts.protocol, "protocol", "tcp", "tcp or udp")
  52. cmd.Flags().IntVar(&opts.index, "index", 0, "Index of the container if service has multiple replicas")
  53. return cmd
  54. }
  55. func runPort(ctx context.Context, dockerCli command.Cli, backend api.Service, opts portOptions, service string) error {
  56. projectName, err := opts.toProjectName(ctx, dockerCli)
  57. if err != nil {
  58. return err
  59. }
  60. ip, port, err := backend.Port(ctx, projectName, service, opts.port, api.PortOptions{
  61. Protocol: opts.protocol,
  62. Index: opts.index,
  63. })
  64. if err != nil {
  65. return err
  66. }
  67. _, _ = fmt.Fprintf(dockerCli.Out(), "%s:%d\n", ip, port)
  68. return nil
  69. }