github.com/cilium/cilium@v1.16.2/pkg/identity/reserved.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  // Copyright Authors of Cilium
     3  
     4  package identity
     5  
     6  import (
     7  	"github.com/cilium/cilium/pkg/labels"
     8  	"github.com/cilium/cilium/pkg/lock"
     9  )
    10  
    11  var (
    12  	// cacheMU protects the following map.
    13  	cacheMU lock.RWMutex
    14  	// ReservedIdentityCache that maps all reserved identities from their
    15  	// numeric identity to their corresponding identity.
    16  	reservedIdentityCache = map[NumericIdentity]*Identity{}
    17  )
    18  
    19  // AddReservedIdentity adds the reserved numeric identity with the respective
    20  // label into the map of reserved identity cache, and returns the resulting Identity.
    21  // This identity must not be mutated!
    22  func AddReservedIdentity(ni NumericIdentity, lbl string) *Identity {
    23  	identity := NewIdentity(ni, labels.Labels{lbl: labels.NewLabel(lbl, "", labels.LabelSourceReserved)})
    24  	cacheMU.Lock()
    25  	reservedIdentityCache[ni] = identity
    26  	cacheMU.Unlock()
    27  	return identity
    28  }
    29  
    30  // AddReservedIdentityWithLabels is the same as AddReservedIdentity but accepts
    31  // multiple labels. Returns the resulting Identity.
    32  // This identity must not be mutated!
    33  func AddReservedIdentityWithLabels(ni NumericIdentity, lbls labels.Labels) *Identity {
    34  	identity := NewIdentity(ni, lbls)
    35  	cacheMU.Lock()
    36  	reservedIdentityCache[ni] = identity
    37  	cacheMU.Unlock()
    38  	return identity
    39  }
    40  
    41  // LookupReservedIdentity looks up a reserved identity by its NumericIdentity
    42  // and returns it if found. Returns nil if not found.
    43  // This identity must not be mutated!
    44  func LookupReservedIdentity(ni NumericIdentity) *Identity {
    45  	cacheMU.RLock()
    46  	defer cacheMU.RUnlock()
    47  	return reservedIdentityCache[ni]
    48  }
    49  
    50  func init() {
    51  	iterateReservedIdentityLabels(func(ni NumericIdentity, lbls labels.Labels) {
    52  		AddReservedIdentityWithLabels(ni, lbls)
    53  	})
    54  }
    55  
    56  // IterateReservedIdentities iterates over all reserved identities and
    57  // executes the given function for each identity.
    58  func IterateReservedIdentities(f func(_ NumericIdentity, _ *Identity)) {
    59  	cacheMU.RLock()
    60  	defer cacheMU.RUnlock()
    61  	for ni, identity := range reservedIdentityCache {
    62  		f(ni, identity)
    63  	}
    64  }
    65  
    66  func ListReservedIdentities() IdentityMap {
    67  	cacheMU.RLock()
    68  	defer cacheMU.RUnlock()
    69  	out := make(IdentityMap, len(reservedIdentityCache))
    70  	for ni, identity := range reservedIdentityCache {
    71  		out[ni] = identity.LabelArray
    72  	}
    73  	return out
    74  }