port.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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/v5/pkg/api"
  22. "github.com/docker/compose/v5/pkg/compose"
  23. )
  24. type portOptions struct {
  25. *ProjectOptions
  26. port uint16
  27. protocol string
  28. index int
  29. }
  30. func portCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command {
  31. opts := portOptions{
  32. ProjectOptions: p,
  33. }
  34. cmd := &cobra.Command{
  35. Use: "port [OPTIONS] SERVICE PRIVATE_PORT",
  36. Short: "Print the public port for a port binding",
  37. Args: cobra.MinimumNArgs(2),
  38. PreRunE: Adapt(func(ctx context.Context, args []string) error {
  39. port, err := strconv.ParseUint(args[1], 10, 16)
  40. if err != nil {
  41. return err
  42. }
  43. opts.port = uint16(port)
  44. opts.protocol = strings.ToLower(opts.protocol)
  45. return nil
  46. }),
  47. RunE: Adapt(func(ctx context.Context, args []string) error {
  48. return runPort(ctx, dockerCli, backendOptions, opts, args[0])
  49. }),
  50. ValidArgsFunction: completeServiceNames(dockerCli, p),
  51. }
  52. cmd.Flags().StringVar(&opts.protocol, "protocol", "tcp", "tcp or udp")
  53. cmd.Flags().IntVar(&opts.index, "index", 0, "Index of the container if service has multiple replicas")
  54. return cmd
  55. }
  56. func runPort(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, opts portOptions, service string) error {
  57. projectName, err := opts.toProjectName(ctx, dockerCli)
  58. if err != nil {
  59. return err
  60. }
  61. backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...)
  62. if err != nil {
  63. return err
  64. }
  65. ip, port, err := backend.Port(ctx, projectName, service, opts.port, api.PortOptions{
  66. Protocol: opts.protocol,
  67. Index: opts.index,
  68. })
  69. if err != nil {
  70. return err
  71. }
  72. _, _ = fmt.Fprintf(dockerCli.Out(), "%s:%d\n", ip, port)
  73. return nil
  74. }