github.com/verrazzano/verrazzano@v1.7.0/platform-operator/internal/vzconfig/external_service.go (about)

     1  // Copyright (c) 2023, Oracle and/or its affiliates.
     2  // Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
     3  
     4  package vzconfig
     5  
     6  import (
     7  	"context"
     8  	"fmt"
     9  
    10  	vzapi "github.com/verrazzano/verrazzano/platform-operator/apis/verrazzano/v1alpha1"
    11  	v1 "k8s.io/api/core/v1"
    12  	"k8s.io/apimachinery/pkg/types"
    13  	"sigs.k8s.io/controller-runtime/pkg/client"
    14  )
    15  
    16  // GetExternalIP Returns the ingress IP of the service given the service type, name, and namespace
    17  func GetExternalIP(client client.Client, serviceType vzapi.IngressType, name, namespace string) (string, error) {
    18  	// Default for NodePort services
    19  	// - On MAC and Windows, container IP is not accessible.  Port forwarding from 127.0.0.1 to container IP is needed.
    20  	externalIP := "127.0.0.1"
    21  	if serviceType == vzapi.LoadBalancer || serviceType == vzapi.NodePort {
    22  		svc := v1.Service{}
    23  		if err := client.Get(context.TODO(), types.NamespacedName{Name: name, Namespace: namespace}, &svc); err != nil {
    24  			return "", fmt.Errorf("Error getting service %s/%s: %v", namespace, name, err)
    25  		}
    26  		// If externalIPs exists, use it; else use IP from status
    27  		if len(svc.Spec.ExternalIPs) > 0 {
    28  			// In case of OLCNE, the Status.LoadBalancer.Ingress field will be empty, so use the external IP if present
    29  			externalIP = svc.Spec.ExternalIPs[0]
    30  		} else if len(svc.Status.LoadBalancer.Ingress) > 0 {
    31  			externalIP = svc.Status.LoadBalancer.Ingress[0].IP
    32  		} else {
    33  			return "", fmt.Errorf("No IP found for service %v with type %v", svc.Name, serviceType)
    34  		}
    35  	}
    36  	return externalIP, nil
    37  }