github.com/cilium/cilium@v1.16.2/pkg/endpointmanager/host.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  // Copyright Authors of Cilium
     3  
     4  package endpointmanager
     5  
     6  import (
     7  	"context"
     8  	"maps"
     9  
    10  	"github.com/cilium/cilium/pkg/endpoint"
    11  	"github.com/cilium/cilium/pkg/labels"
    12  	"github.com/cilium/cilium/pkg/labelsfilter"
    13  	"github.com/cilium/cilium/pkg/node"
    14  )
    15  
    16  // GetHostEndpoint returns the host endpoint.
    17  func (mgr *endpointManager) GetHostEndpoint() *endpoint.Endpoint {
    18  	mgr.mutex.RLock()
    19  	defer mgr.mutex.RUnlock()
    20  	for _, ep := range mgr.endpoints {
    21  		if ep.IsHost() {
    22  			return ep
    23  		}
    24  	}
    25  	return nil
    26  }
    27  
    28  // HostEndpointExists returns true if the host endpoint exists.
    29  func (mgr *endpointManager) HostEndpointExists() bool {
    30  	return mgr.GetHostEndpoint() != nil
    31  }
    32  
    33  func (mgr *endpointManager) startNodeLabelsObserver(old map[string]string) {
    34  	mgr.localNodeStore.Observe(context.Background(), func(ln node.LocalNode) {
    35  		oldIdtyLabels, _ := labelsfilter.Filter(labels.Map2Labels(old, labels.LabelSourceK8s))
    36  		newIdtyLabels, _ := labelsfilter.Filter(labels.Map2Labels(ln.Labels, labels.LabelSourceK8s))
    37  		if maps.Equal(oldIdtyLabels.K8sStringMap(), newIdtyLabels.K8sStringMap()) {
    38  			log.Debug("Host endpoint identity labels unchanged, skipping labels update")
    39  			return
    40  		}
    41  
    42  		if mgr.updateHostEndpointLabels(old, ln.Labels) {
    43  			// Endpoint's label update logic rejects a request if any of the old labels are
    44  			// not present in the endpoint manager's state. So, overwrite old labels only if
    45  			// the update is successful to avoid node labels being outdated indefinitely (GH-29649).
    46  			old = ln.Labels
    47  		}
    48  
    49  	}, func(error) { /* Executed only when we are shutting down */ })
    50  }
    51  
    52  // updateHostEndpointLabels updates the local node labels in the endpoint manager.
    53  // Returns true if the update is successful.
    54  func (mgr *endpointManager) updateHostEndpointLabels(oldNodeLabels, newNodeLabels map[string]string) bool {
    55  	nodeEP := mgr.GetHostEndpoint()
    56  	if nodeEP == nil {
    57  		log.Error("Host endpoint not found")
    58  		return false
    59  	}
    60  
    61  	if err := nodeEP.UpdateLabelsFrom(oldNodeLabels, newNodeLabels, labels.LabelSourceK8s); err != nil {
    62  		// An error can only occur if either the endpoint is terminating, or the
    63  		// old labels are not found. Both are impossible, hence there's no point
    64  		// in retrying.
    65  		log.WithError(err).Error("Unable to update host endpoint labels")
    66  		return false
    67  	}
    68  	return true
    69  }