github.com/cilium/cilium@v1.16.2/pkg/node/types/nodename.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  // Copyright Authors of Cilium
     3  
     4  package types
     5  
     6  import (
     7  	"os"
     8  
     9  	"github.com/cilium/cilium/pkg/defaults"
    10  	k8sConsts "github.com/cilium/cilium/pkg/k8s/constants"
    11  	"github.com/cilium/cilium/pkg/logging/logfields"
    12  	"github.com/cilium/cilium/pkg/option"
    13  )
    14  
    15  var (
    16  	nodeName = "localhost"
    17  )
    18  
    19  // SetName sets the name of the local node. This will overwrite the value that
    20  // is automatically retrieved with `os.Hostname()`.
    21  //
    22  // Note: This function is currently designed to only be called during the
    23  // bootstrapping procedure of the agent where no parallelism exists. If you
    24  // want to use this function in later stages, a mutex must be added first.
    25  func SetName(name string) {
    26  	nodeName = name
    27  }
    28  
    29  // GetName returns the name of the local node. The value returned was either
    30  // previously set with SetName(), retrieved via `os.Hostname()`, or as a last
    31  // resort is hardcoded to "localhost".
    32  func GetName() string {
    33  	return nodeName
    34  }
    35  
    36  // GetAbsoluteNodeName returns the absolute node name combined of both
    37  // (prefixed)cluster name and the local node name in case of
    38  // clustered environments otherwise returns the name of the local node.
    39  func GetAbsoluteNodeName() string {
    40  	if clusterName := GetClusterName(); clusterName != "" {
    41  		return clusterName + "/" + nodeName
    42  	} else {
    43  		return nodeName
    44  	}
    45  }
    46  
    47  func GetClusterName() string {
    48  	if option.Config.ClusterName != "" &&
    49  		option.Config.ClusterName != defaults.ClusterName {
    50  		return option.Config.ClusterName
    51  	} else {
    52  		return ""
    53  	}
    54  }
    55  
    56  func init() {
    57  	// Give priority to the environment variable available in the Cilium agent
    58  	if name := os.Getenv(k8sConsts.EnvNodeNameSpec); name != "" {
    59  		nodeName = name
    60  		return
    61  	}
    62  	if h, err := os.Hostname(); err != nil {
    63  		log.WithError(err).Warn("Unable to retrieve local hostname")
    64  	} else {
    65  		log.WithField(logfields.NodeName, h).Debug("os.Hostname() returned")
    66  		nodeName = h
    67  	}
    68  }