...

Source file src/edge-infra.dev/pkg/f8n/warehouse/lift/pack/internal/capability.go

Documentation: edge-infra.dev/pkg/f8n/warehouse/lift/pack/internal

     1  package internal
     2  
     3  import (
     4  	"fmt"
     5  	"regexp"
     6  	"strings"
     7  
     8  	"sigs.k8s.io/kustomize/kyaml/yaml"
     9  
    10  	"edge-infra.dev/pkg/f8n/warehouse/capability"
    11  	"edge-infra.dev/pkg/f8n/warehouse/lift"
    12  )
    13  
    14  // capability is a CapabilityConfig that has been processed (eg regexp compiled)
    15  // and used to sort manifests into distinct layers during packing
    16  type Capability struct {
    17  	Name capability.Capability
    18  
    19  	// regexps are the compiled regexp from the list of APIGroup expressions that
    20  	// control which K8s objects go into the capability's layer
    21  	regexps []*regexp.Regexp
    22  	// maps of kinds and api groups to explicitly ignore
    23  	ignoreKinds     map[string]bool
    24  	ignoreAPIGroups map[string]bool
    25  }
    26  
    27  func (c Capability) Matches(y *yaml.RNode) bool {
    28  	apiVersion := y.GetApiVersion()
    29  	if apiVersion == "" {
    30  		return false
    31  	}
    32  
    33  	apiGroup := strings.ToLower(strings.Split(apiVersion, "/")[0])
    34  	if !matchesAny(c.regexps, apiGroup) {
    35  		return false
    36  	}
    37  
    38  	// check if object is explicitly ignored / excluded from match
    39  	kind := strings.ToLower(y.GetKind())
    40  	// return false if the object is explicitly ignored
    41  	return !(c.ignoreKinds[kind] || c.ignoreAPIGroups[apiGroup])
    42  }
    43  
    44  func NewCapability(name capability.Capability, cfg lift.CapabilityConfig) (Capability, error) {
    45  	c := Capability{
    46  		Name:            name,
    47  		regexps:         make([]*regexp.Regexp, len(cfg.ResourceMatcher.APIGroups)),
    48  		ignoreKinds:     make(map[string]bool, len(cfg.ResourceMatcher.Ignore.Kinds)),
    49  		ignoreAPIGroups: make(map[string]bool, len(cfg.ResourceMatcher.Ignore.APIGroups)),
    50  	}
    51  
    52  	for _, i := range cfg.ResourceMatcher.Ignore.Kinds {
    53  		c.ignoreKinds[strings.ToLower(i)] = true
    54  	}
    55  
    56  	for _, i := range cfg.ResourceMatcher.Ignore.APIGroups {
    57  		c.ignoreAPIGroups[strings.ToLower(i)] = true
    58  	}
    59  
    60  	for i, a := range cfg.ResourceMatcher.APIGroups {
    61  		r, err := regexp.Compile(strings.ToLower(a))
    62  		if err != nil {
    63  			return Capability{}, fmt.Errorf("invalid capability provider: invalid APIGroup "+
    64  				"regular expression %s: %w", a, err)
    65  		}
    66  		c.regexps[i] = r
    67  	}
    68  
    69  	return c, nil
    70  }
    71  
    72  func matchesAny(rr []*regexp.Regexp, s string) bool {
    73  	for _, r := range rr {
    74  		if r.MatchString(strings.ToLower(s)) {
    75  			return true
    76  		}
    77  	}
    78  	return false
    79  }
    80  

View as plain text