k8s.io/kubernetes@v1.31.0-alpha.0.0.20240520171757-56147500dadc/pkg/probe/util.go (about)

     1  /*
     2  Copyright 2022 The Kubernetes 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 probe
    18  
    19  import (
    20  	"fmt"
    21  	"strconv"
    22  
    23  	v1 "k8s.io/api/core/v1"
    24  	"k8s.io/apimachinery/pkg/util/intstr"
    25  )
    26  
    27  func ResolveContainerPort(param intstr.IntOrString, container *v1.Container) (int, error) {
    28  	port := -1
    29  	var err error
    30  	switch param.Type {
    31  	case intstr.Int:
    32  		port = param.IntValue()
    33  	case intstr.String:
    34  		if port, err = findPortByName(container, param.StrVal); err != nil {
    35  			// Last ditch effort - maybe it was an int stored as string?
    36  			if port, err = strconv.Atoi(param.StrVal); err != nil {
    37  				return port, err
    38  			}
    39  		}
    40  	default:
    41  		return port, fmt.Errorf("intOrString had no kind: %+v", param)
    42  	}
    43  	if port > 0 && port < 65536 {
    44  		return port, nil
    45  	}
    46  	return port, fmt.Errorf("invalid port number: %v", port)
    47  }
    48  
    49  // findPortByName is a helper function to look up a port in a container by name.
    50  func findPortByName(container *v1.Container, portName string) (int, error) {
    51  	for _, port := range container.Ports {
    52  		if port.Name == portName {
    53  			return int(port.ContainerPort), nil
    54  		}
    55  	}
    56  	return 0, fmt.Errorf("port %s not found", portName)
    57  }