github.com/containerd/nerdctl@v1.7.7/pkg/composer/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 composer
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  	"io"
    23  
    24  	"github.com/containerd/nerdctl/pkg/containerutil"
    25  )
    26  
    27  // PortOptions has args for getting the public port of a given private port/protocol
    28  // in a service container.
    29  type PortOptions struct {
    30  	ServiceName string
    31  	Index       int
    32  	Port        int
    33  	Protocol    string
    34  }
    35  
    36  // Port gets the corresponding public port of a given private port/protocol
    37  // on a service container.
    38  func (c *Composer) Port(ctx context.Context, writer io.Writer, po PortOptions) error {
    39  	containers, err := c.Containers(ctx, po.ServiceName)
    40  	if err != nil {
    41  		return fmt.Errorf("fail to get containers for service %s: %s", po.ServiceName, err)
    42  	}
    43  	if len(containers) == 0 {
    44  		return fmt.Errorf("no running containers from service %s", po.ServiceName)
    45  	}
    46  	if po.Index > len(containers) {
    47  		return fmt.Errorf("index (%d) out of range: only %d running instances from service %s",
    48  			po.Index, len(containers), po.ServiceName)
    49  	}
    50  	container := containers[po.Index-1]
    51  
    52  	return containerutil.PrintHostPort(ctx, writer, container, po.Port, po.Protocol)
    53  }