github.com/cilium/cilium@v1.16.2/pkg/hubble/parser/common/labels.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  // Copyright Authors of Hubble
     3  
     4  package common
     5  
     6  import (
     7  	"net"
     8  	"sort"
     9  	"strings"
    10  
    11  	"github.com/sirupsen/logrus"
    12  
    13  	"github.com/cilium/cilium/pkg/identity"
    14  )
    15  
    16  func FilterCIDRLabels(log logrus.FieldLogger, labels []string) []string {
    17  	// Cilium might return a bunch of cidr labels with different prefix length. Filter out all
    18  	// but the longest prefix cidr label, which can be useful for troubleshooting. This also
    19  	// relies on the fact that when a Cilium security identity has multiple CIDR labels, longer
    20  	// prefix is always a subset of shorter prefix.
    21  	cidrPrefix := "cidr:"
    22  	var filteredLabels []string
    23  	var maxSize int
    24  	var maxStr string
    25  	for _, label := range labels {
    26  		if !strings.HasPrefix(label, cidrPrefix) {
    27  			filteredLabels = append(filteredLabels, label)
    28  			continue
    29  		}
    30  		currLabel := strings.TrimPrefix(label, cidrPrefix)
    31  		// labels for IPv6 addresses are represented with - instead of : as
    32  		// : cannot be used in labels; make sure to convert it to a valid
    33  		// IPv6 representation
    34  		currLabel = strings.Replace(currLabel, "-", ":", -1)
    35  		_, curr, err := net.ParseCIDR(currLabel)
    36  		if err != nil {
    37  			log.WithField("label", label).Warn("got an invalid cidr label")
    38  			continue
    39  		}
    40  		if currMask, _ := curr.Mask.Size(); currMask > maxSize {
    41  			maxSize, maxStr = currMask, label
    42  		}
    43  	}
    44  	if maxSize != 0 {
    45  		filteredLabels = append(filteredLabels, maxStr)
    46  	}
    47  	return filteredLabels
    48  }
    49  
    50  func SortAndFilterLabels(log logrus.FieldLogger, labels []string, securityIdentity identity.NumericIdentity) []string {
    51  	if securityIdentity.HasLocalScope() {
    52  		labels = FilterCIDRLabels(log, labels)
    53  	}
    54  	sort.Strings(labels)
    55  	return labels
    56  }