github.com/juju/juju@v0.0.0-20240430160146-1752b71fcf00/caas/kubernetes/provider/utils/address.go (about)

     1  // Copyright 2021 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package utils
     5  
     6  import (
     7  	core "k8s.io/api/core/v1"
     8  
     9  	"github.com/juju/juju/core/network"
    10  )
    11  
    12  // GetSvcAddresses returns the network addresses for the given service.
    13  func GetSvcAddresses(svc *core.Service, includeClusterIP bool) []network.ProviderAddress {
    14  	var netAddrs []network.ProviderAddress
    15  
    16  	addressExist := func(addr string) bool {
    17  		for _, v := range netAddrs {
    18  			if addr == v.Value {
    19  				return true
    20  			}
    21  		}
    22  		return false
    23  	}
    24  	appendUniqueAddrs := func(scope network.Scope, addrs ...string) {
    25  		for _, v := range addrs {
    26  			if v != "" && v != "None" && !addressExist(v) {
    27  				netAddrs = append(netAddrs, network.NewMachineAddress(v, network.WithScope(scope)).AsProviderAddress())
    28  			}
    29  		}
    30  	}
    31  
    32  	t := svc.Spec.Type
    33  	clusterIP := svc.Spec.ClusterIP
    34  	switch t {
    35  	case core.ServiceTypeClusterIP:
    36  		appendUniqueAddrs(network.ScopeCloudLocal, clusterIP)
    37  	case core.ServiceTypeExternalName:
    38  		appendUniqueAddrs(network.ScopePublic, svc.Spec.ExternalName)
    39  	case core.ServiceTypeNodePort:
    40  		appendUniqueAddrs(network.ScopePublic, svc.Spec.ExternalIPs...)
    41  	case core.ServiceTypeLoadBalancer:
    42  		appendUniqueAddrs(network.ScopePublic, getLoadBalancerAddresses(svc)...)
    43  	}
    44  	if includeClusterIP {
    45  		// append clusterIP as a fixed internal address.
    46  		appendUniqueAddrs(network.ScopeCloudLocal, clusterIP)
    47  	}
    48  	return netAddrs
    49  }
    50  
    51  func getLoadBalancerAddresses(svc *core.Service) []string {
    52  	// different cloud providers have a different way to report back the Load Balancer address.
    53  	// This covers the cases we know about so far.
    54  	var addr []string
    55  	lpAdd := svc.Spec.LoadBalancerIP
    56  	if lpAdd != "" {
    57  		addr = append(addr, lpAdd)
    58  	}
    59  
    60  	ing := svc.Status.LoadBalancer.Ingress
    61  	if len(ing) == 0 {
    62  		return addr
    63  	}
    64  
    65  	for _, ingressAddr := range ing {
    66  		if ingressAddr.IP != "" {
    67  			addr = append(addr, ingressAddr.IP)
    68  		}
    69  		if ingressAddr.Hostname != "" {
    70  			addr = append(addr, ingressAddr.Hostname)
    71  		}
    72  	}
    73  	return addr
    74  }