-
Notifications
You must be signed in to change notification settings - Fork 78
feat(cel): Add CEL custom library for semver comparison #202
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
Merged
openshift-merge-robot
merged 2 commits into
operator-framework:master
from
dinhxuanvu:cel-pkg
Dec 10, 2021
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,146 @@ | ||
package constraints | ||
|
||
import ( | ||
"fmt" | ||
|
||
"github.com/google/cel-go/cel" | ||
"github.com/google/cel-go/checker/decls" | ||
"github.com/google/cel-go/common/types" | ||
"github.com/google/cel-go/common/types/ref" | ||
"github.com/google/cel-go/interpreter/functions" | ||
exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1" | ||
|
||
"github.com/blang/semver/v4" | ||
) | ||
|
||
// PropertiesKey is the key for bundle properties map (input data for CEL evaluation) | ||
const PropertiesKey = "properties" | ||
|
||
// Constraint is a struct representing the new generic constraint type | ||
type Constraint struct { | ||
// Constraint message that surfaces in resolution | ||
// This field is optional | ||
Message string `json:"message" yaml:"message"` | ||
|
||
// The cel struct that contraints CEL expression | ||
// This field is required | ||
Cel *Cel `json:"cel" yaml:"cel"` | ||
} | ||
|
||
// Cel is a struct representing CEL expression information | ||
type Cel struct { | ||
// The CEL expression | ||
Rule string `json:"rule" yaml:"rule"` | ||
} | ||
|
||
// NewCelEnvironment returns a CEL environment which can be used to | ||
// evaluate CEL expression and an error if occurs | ||
func NewCelEnvironment() *CelEnvironment { | ||
env, err := cel.NewEnv(cel.Declarations( | ||
decls.NewVar(PropertiesKey, decls.NewListType(decls.NewMapType(decls.String, decls.Any)))), | ||
cel.Lib(semverLib{}), | ||
) | ||
// If an error occurs here, it means the CEL enviroment is unable to load | ||
// configuration for custom libraries propertly. Hence, the CEL enviroment is | ||
// unusable. Panic here will cause the program to fail immediately to prevent | ||
// cascading failures later on when this CEL env is in use. | ||
if err != nil { | ||
panic(err) | ||
} | ||
return &CelEnvironment{ | ||
env: env, | ||
} | ||
} | ||
|
||
// CelEnvironment is a struct that encapsulates CEL custom program enviroment | ||
type CelEnvironment struct { | ||
env *cel.Env | ||
} | ||
|
||
// CelProgram is a struct that encapsulates compiled CEL program | ||
type CelProgram struct { | ||
program cel.Program | ||
} | ||
|
||
/* | ||
This section of code is for custom library for semver comparison in CEL | ||
The code is inspired by https://github.com/google/cel-go/blob/master/cel/cel_test.go#L46 | ||
|
||
The semver_compare is written based on `Compare` function in https://github.com/blang/semver | ||
particularly in https://github.com/blang/semver/blob/master/semver.go#L125 | ||
|
||
Example: | ||
`semver_compare(v1, v2)` is equivalent of `v1.Compare(v2)` in blang/semver library | ||
|
||
The result is `semver_compare` is an integer just like `Compare`. So, the CEL | ||
expression `semver_compare(v1, v2) == 0` is equivalent v1.Compare(v2) == 0. In | ||
the other words, it checks if v1 is equal to v2 in term of semver comparision. | ||
*/ | ||
type semverLib struct{} | ||
|
||
func (semverLib) CompileOptions() []cel.EnvOption { | ||
return []cel.EnvOption{ | ||
cel.Declarations( | ||
decls.NewFunction("semver_compare", | ||
decls.NewOverload("semver_compare", | ||
[]*exprpb.Type{decls.Any, decls.Any}, | ||
decls.Int))), | ||
} | ||
} | ||
|
||
func (semverLib) ProgramOptions() []cel.ProgramOption { | ||
return []cel.ProgramOption{ | ||
cel.Functions( | ||
&functions.Overload{ | ||
Operator: "semver_compare", | ||
Binary: semverCompare, | ||
}, | ||
), | ||
} | ||
} | ||
|
||
func semverCompare(val1, val2 ref.Val) ref.Val { | ||
v1, err := semver.ParseTolerant(fmt.Sprint(val1.Value())) | ||
if err != nil { | ||
return types.ValOrErr(val1, "unable to parse '%v' to semver format", val1.Value()) | ||
} | ||
|
||
v2, err := semver.ParseTolerant(fmt.Sprint(val2.Value())) | ||
if err != nil { | ||
return types.ValOrErr(val2, "unable to parse '%v' to semver format", val2.Value()) | ||
} | ||
return types.Int(v1.Compare(v2)) | ||
} | ||
|
||
// Evaluate to evaluate the compiled CEL program against input data (map) | ||
func (e CelProgram) Evaluate(data map[string]interface{}) (bool, error) { | ||
result, _, err := e.program.Eval(data) | ||
if err != nil { | ||
return false, err | ||
} | ||
|
||
// we should have already ensured that this will be types.Bool during compilation | ||
if b, ok := result.Value().(bool); ok { | ||
return b, nil | ||
} | ||
return false, fmt.Errorf("cel expression evalutated to %T, not bool", result.Value()) | ||
} | ||
|
||
// Validate to validate the CEL expression string by compiling it into CEL program | ||
func (e *CelEnvironment) Validate(rule string) (CelProgram, error) { | ||
var celProg CelProgram | ||
ast, issues := e.env.Compile(rule) | ||
if err := issues.Err(); err != nil { | ||
return celProg, err | ||
} | ||
|
||
if ast.ResultType() != decls.Bool { | ||
return celProg, fmt.Errorf("cel expressions must have type Bool") | ||
} | ||
|
||
prog, err := e.env.Program(ast) | ||
if err != nil { | ||
return celProg, err | ||
} | ||
return CelProgram{program: prog}, nil | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
package constraints | ||
|
||
import ( | ||
"testing" | ||
|
||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
func TestCelLibrary(t *testing.T) { | ||
props := make([]map[string]interface{}, 1) | ||
props[0] = map[string]interface{}{ | ||
"type": "olm.test", | ||
"value": "1.0.0", | ||
} | ||
|
||
propertiesMap := map[string]interface{}{"properties": props} | ||
|
||
tests := []struct { | ||
name string | ||
rule string | ||
out bool | ||
isErr bool | ||
}{ | ||
{ | ||
name: "ValidCelExpression/True", | ||
rule: "properties.exists(p, p.type == 'olm.test' && (semver_compare(p.value, '1.0.0') == 0))", | ||
out: true, | ||
isErr: false, | ||
}, | ||
{ | ||
name: "ValidCelExpression/NotEqual/False", | ||
rule: "properties.exists(p, p.type == 'olm.test' && (semver_compare(p.value, '1.0.1') == 0))", | ||
out: false, | ||
isErr: false, | ||
}, | ||
{ | ||
name: "ValidCelExpression/Less/False", | ||
rule: "properties.exists(p, p.type == 'olm.test' && (semver_compare(p.value, '1.0.0') < 0))", | ||
isErr: false, | ||
}, | ||
{ | ||
name: "ValidCelExpression/Larger/False", | ||
rule: "properties.exists(p, p.type == 'olm.test' && (semver_compare(p.value, '1.0.0') > 0))", | ||
isErr: false, | ||
}, | ||
{ | ||
name: "InvalidCelExpression/NotExistedFunc", | ||
rule: "properties.exists(p, p.type == 'olm.test' && (doesnt_exist(p.value, '1.0.0') == 0))", | ||
isErr: true, | ||
}, | ||
{ | ||
name: "InvalidCelExpression/NonBoolReturn", | ||
rule: "1", | ||
isErr: true, | ||
}, | ||
} | ||
|
||
validator := NewCelEnvironment() | ||
for _, tt := range tests { | ||
t.Run(tt.name, func(t *testing.T) { | ||
prog, err := validator.Validate(tt.rule) | ||
if tt.isErr { | ||
assert.Error(t, err) | ||
} else { | ||
result, err := prog.Evaluate(propertiesMap) | ||
assert.NoError(t, err) | ||
assert.Equal(t, result, tt.out) | ||
} | ||
}) | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.