Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: matchLabels #122

Merged
merged 2 commits into from
Jan 28, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions coll/coll.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"sort"
"strings"

"github.com/flanksource/commons/collections"
"github.com/flanksource/gomplate/v3/conv"
iconv "github.com/flanksource/gomplate/v3/internal/conv"
)
Expand Down Expand Up @@ -370,3 +371,19 @@ func KeyValToMap(s string) (map[string]string, error) {
}
return m, nil
}

// MatchLabel returns true if the given map has a key that matches any of the given patterns.
// If all patterns are exclusions and the key doesn't exist, it's treated as a match.
func MatchLabel(labels map[string]any, key string, valuePatterns ...string) bool {
value, exists := labels[key]
if !exists {
return collections.IsExclusionOnlyPatterns(valuePatterns)
}

vStr, ok := value.(string)
if !ok {
return false
}

return collections.MatchItems(vStr, valuePatterns...)
}
1 change: 1 addition & 0 deletions funcs/cel_exports.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

27 changes: 27 additions & 0 deletions funcs/coll.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@ package funcs

import (
"context"
"strings"

"github.com/flanksource/gomplate/v3/conv"
"github.com/google/cel-go/cel"
"github.com/google/cel-go/common/types"
"github.com/google/cel-go/common/types/ref"

"github.com/flanksource/gomplate/v3/coll"
"github.com/pkg/errors"
Expand Down Expand Up @@ -43,6 +47,8 @@ func CreateCollFuncs(ctx context.Context) map[string]interface{} {
f["sort"] = ns.Sort
f["jq"] = ns.JQ
f["flatten"] = ns.Flatten

f["matchLabel"] = coll.MatchLabel
f["mapToKeyVal"] = coll.MapToKeyVal[any]
f["keyValToMap"] = coll.KeyValToMap
f["jsonpath"] = coll.JSONPath
Expand Down Expand Up @@ -189,3 +195,24 @@ func (CollFuncs) Omit(args ...interface{}) (map[string]interface{}, error) {
}
return coll.Omit(m, keys...), nil
}

var celLabelsMatch = cel.Function("matchLabel",
cel.Overload("matchLabel_map_string_string",
[]*cel.Type{
cel.MapType(cel.StringType, cel.DynType), cel.StringType, cel.StringType,
},
cel.BoolType,
cel.FunctionBinding(func(args ...ref.Val) ref.Val {
key := conv.ToString(args[1])
valuePatterns := strings.Split(conv.ToString(args[2]), ",")

labels, err := convertMap(args[0])
if err != nil {
return types.WrapErr(errors.New("matchLabel expects the first argument to be a map[string]any"))
}

result := coll.MatchLabel(labels, key, valuePatterns...)
return types.DefaultTypeAdapter.NativeToValue(result)
}),
),
)
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ toolchain go1.23.4
require (
github.com/Masterminds/goutils v1.1.1
github.com/Masterminds/semver/v3 v3.3.1
github.com/flanksource/commons v1.35.3
github.com/flanksource/commons v1.36.1
github.com/flanksource/is-healthy v1.0.59
github.com/flanksource/kubectl-neat v1.0.4
github.com/google/cel-go v0.22.1
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ github.com/emirpasic/gods/v2 v2.0.0-alpha h1:dwFlh8pBg1VMOXWGipNMRt8v96dKAIvBeht
github.com/emirpasic/gods/v2 v2.0.0-alpha/go.mod h1:W0y4M2dtBB9U5z3YlghmpuUhiaZT2h6yoeE+C1sCp6A=
github.com/fatih/color v1.16.0 h1:zmkK9Ngbjj+K0yRhTVONQh1p/HknKYSlNT+vZCzyokM=
github.com/fatih/color v1.16.0/go.mod h1:fL2Sau1YI5c0pdGEVCbKQbLXB6edEj1ZgiY4NijnWvE=
github.com/flanksource/commons v1.35.3 h1:EG46iWodmSQQbXywjvEAgK56ZH26jYtMv0RiPM3eKDE=
github.com/flanksource/commons v1.35.3/go.mod h1:cLZURmvF0dw3wR5VyPuibRl/7h+NEiyMdo70WhJFB9Y=
github.com/flanksource/commons v1.36.1 h1:SDppXOYO6vk06d12SPOYVZJX+8gV72FmK1l9ar5fkjc=
github.com/flanksource/commons v1.36.1/go.mod h1:nsYCn6JOhENXNLR5pz4zNco70DQV+bGObQ8NbOrUeuQ=
github.com/flanksource/is-healthy v1.0.59 h1:/dObdgBEouYMX7eF2R4l20G8I+Equ0YGDrXOtRpar/s=
github.com/flanksource/is-healthy v1.0.59/go.mod h1:5MUvkRbq78aPVIpwGjpn+k89n5+1thBLIRdhfcozUcQ=
github.com/flanksource/kubectl-neat v1.0.4 h1:t5/9CqgE84oEtB0KitgJ2+WIeLfD+RhXSxYrqb4X8yI=
Expand Down
6 changes: 0 additions & 6 deletions metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,3 @@ type MetricsType struct {
TemplatesProcessed int
Errors int
}

func newMetrics() *MetricsType {
return &MetricsType{
RenderDuration: make(map[string]time.Duration),
}
}
2 changes: 1 addition & 1 deletion template.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ func RunExpressionContext(ctx commonsContext.Context, _environment map[string]an

ast, issues := env.Compile(strings.ReplaceAll(template.Expression, "\n", " "))
if issues != nil && issues.Err() != nil {
return "", oops.With("template", template.Expression).Errorf(issues.String())
return "", oops.With("template", template.Expression).Errorf("issues: %s", issues.String())
}

prg, err = env.Program(ast, cel.Globals(data))
Expand Down
25 changes: 25 additions & 0 deletions tests/cel_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -608,6 +608,31 @@ func TestCelK8sMemoryResourceUnits(t *testing.T) {
}
}

func TestMatchLabel(t *testing.T) {
config := map[string]any{
"labels": map[string]string{
"environment": "production",
"region": "us-east-1",
},
"tags": map[string]string{
"cluster": "aws-prod",
},
}

runTests(t, []Test{
{map[string]any{"config": config}, "matchLabel(config.labels, 'region', 'us-*')", "true"},
{map[string]any{"config": config}, "matchLabel(config.labels, 'region', 'eu-*')", "false"},
{map[string]any{"config": config}, "matchLabel(config.labels, 'environment', 'production')", "true"},
{map[string]any{"config": config}, "matchLabel(config.tags, 'cluster', 'aws-*')", "true"},
{map[string]any{"config": config}, "matchLabel(config.tags, 'cluster', '*-prod')", "true"},
{map[string]any{"config": config}, "matchLabel(config.tags, 'cluster', '!aws-prod')", "false"},
{map[string]any{"config": config}, "matchLabel(config.tags, 'cluster', '!aws-demo')", "true"},
{map[string]any{"config": config}, "matchLabel(config.tags, 'nonExistingKey', 'aws-demo')", "false"},
{map[string]any{"config": config}, "matchLabel(config.tags, 'nonExistingKey', '!aws-demo')", "true"},
{map[string]any{"config": config}, "matchLabel(config.tags, 'nonExistingKey', '!*')", "true"},
})
}

func TestCelYAML(t *testing.T) {
person := Person{
Name: "Aditya",
Expand Down
Loading