port.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. "github.com/spf13/cobra"
  19. "github.com/docker/compose-cli/api/compose"
  20. )
  21. type portOptions struct {
  22. *projectOptions
  23. protocol string
  24. index int
  25. }
  26. func portCommand(p *projectOptions, backend compose.Service) *cobra.Command {
  27. opts := portOptions{
  28. projectOptions: p,
  29. }
  30. cmd := &cobra.Command{
  31. Use: "port [options] [--] SERVICE PRIVATE_PORT",
  32. Short: "Print the public port for a port binding.",
  33. Args: cobra.MinimumNArgs(2),
  34. RunE: Adapt(func(ctx context.Context, args []string) error {
  35. port, err := strconv.Atoi(args[1])
  36. if err != nil {
  37. return err
  38. }
  39. return runPort(ctx, backend, opts, args[0], port)
  40. }),
  41. }
  42. cmd.Flags().StringVar(&opts.protocol, "protocol", "tcp", "tcp or udp")
  43. cmd.Flags().IntVar(&opts.index, "index", 1, "index of the container if service has multiple replicas")
  44. return cmd
  45. }
  46. func runPort(ctx context.Context, backend compose.Service, opts portOptions, service string, port int) error {
  47. projectName, err := opts.toProjectName()
  48. if err != nil {
  49. return err
  50. }
  51. ip, port, err := backend.Port(ctx, projectName, service, port, compose.PortOptions{
  52. Protocol: opts.protocol,
  53. Index: opts.index,
  54. })
  55. if err != nil {
  56. return err
  57. }
  58. fmt.Printf("%s:%d\n", ip, port)
  59. return nil
  60. }