1
0
Fork 0
mirror of https://github.com/kyverno/kyverno.git synced 2025-04-18 02:06:52 +00:00

Format error messages correctly ()

* Format error messages correctly

Signed-off-by: Marcel Mueller <marcel.mueller1@rwth-aachen.de>

* No punctuation at the end or errors

Signed-off-by: Marcel Mueller <marcel.mueller1@rwth-aachen.de>

* Replace loop with simple if

Signed-off-by: Marcel Mueller <marcel.mueller1@rwth-aachen.de>

* Fix more errors

Signed-off-by: Marcel Mueller <marcel.mueller1@rwth-aachen.de>
This commit is contained in:
Bricktop 2021-10-12 23:29:20 +02:00 committed by GitHub
parent 806bd184b7
commit 2d0df77963
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
17 changed files with 53 additions and 55 deletions
pkg
dclient
engine
metrics
admissionrequests
admissionreviewduration
policyexecutionduration
policyresults
policy
tls

View file

@ -157,7 +157,7 @@ func (c *Client) CreateResource(apiVersion string, kind string, namespace string
if unstructuredObj := convertToUnstructured(obj); unstructuredObj != nil {
return c.getResourceInterface(apiVersion, kind, namespace).Create(context.TODO(), unstructuredObj, options)
}
return nil, fmt.Errorf("Unable to create resource ")
return nil, fmt.Errorf("unable to create resource ")
}
// UpdateResource updates object for the specified resource/namespace
@ -170,7 +170,7 @@ func (c *Client) UpdateResource(apiVersion string, kind string, namespace string
if unstructuredObj := convertToUnstructured(obj); unstructuredObj != nil {
return c.getResourceInterface(apiVersion, kind, namespace).Update(context.TODO(), unstructuredObj, options)
}
return nil, fmt.Errorf("Unable to update resource ")
return nil, fmt.Errorf("unable to update resource ")
}
// UpdateStatusResource updates the resource "status" subresource
@ -183,7 +183,7 @@ func (c *Client) UpdateStatusResource(apiVersion string, kind string, namespace
if unstructuredObj := convertToUnstructured(obj); unstructuredObj != nil {
return c.getResourceInterface(apiVersion, kind, namespace).UpdateStatus(context.TODO(), unstructuredObj, options)
}
return nil, fmt.Errorf("Unable to update resource ")
return nil, fmt.Errorf("unable to update resource ")
}
func convertToUnstructured(obj interface{}) *unstructured.Unstructured {

View file

@ -73,7 +73,7 @@ func (c *fakeDiscoveryClient) GetGVRFromAPIVersionKind(apiVersion string, kind s
}
func (c *fakeDiscoveryClient) FindResource(apiVersion string, kind string) (*meta.APIResource, schema.GroupVersionResource, error) {
return nil, schema.GroupVersionResource{}, fmt.Errorf("Not implemented")
return nil, schema.GroupVersionResource{}, fmt.Errorf("not implemented")
}
func (c *fakeDiscoveryClient) OpenAPISchema() (*openapiv2.Document, error) {

View file

@ -223,7 +223,7 @@ func (eh ExistenceHandler) Handle(handler resourceElementHandler, resourceMap ma
case []interface{}:
typedPattern, ok := eh.pattern.([]interface{})
if !ok {
return currentPath, fmt.Errorf("Invalid pattern type %T: Pattern has to be of list to compare against resource", eh.pattern)
return currentPath, fmt.Errorf("invalid pattern type %T: Pattern has to be of list to compare against resource", eh.pattern)
}
// loop all item in the pattern array
errorPath := ""
@ -231,7 +231,7 @@ func (eh ExistenceHandler) Handle(handler resourceElementHandler, resourceMap ma
for _, patternMap := range typedPattern {
typedPatternMap, ok := patternMap.(map[string]interface{})
if !ok {
return currentPath, fmt.Errorf("Invalid pattern type %T: Pattern has to be of type map to compare against items in resource", eh.pattern)
return currentPath, fmt.Errorf("invalid pattern type %T: Pattern has to be of type map to compare against items in resource", eh.pattern)
}
errorPath, err = validateExistenceListResource(handler, typedResource, typedPatternMap, originPattern, currentPath, ac)
if err != nil {
@ -240,7 +240,7 @@ func (eh ExistenceHandler) Handle(handler resourceElementHandler, resourceMap ma
}
return errorPath, err
default:
return currentPath, fmt.Errorf("Invalid resource type %T: Existence ^ () anchor can be used only on list/array type resource", value)
return currentPath, fmt.Errorf("invalid resource type %T: Existence ^ () anchor can be used only on list/array type resource", value)
}
}
return "", nil
@ -258,7 +258,7 @@ func validateExistenceListResource(handler resourceElementHandler, resourceList
}
}
// none of the existence checks worked, so thats a failure sceanario
return path, fmt.Errorf("Existence anchor validation failed at path %s", path)
return path, fmt.Errorf("existence anchor validation failed at path %s", path)
}
//GetAnchorsResourcesFromMap returns map of anchors

View file

@ -180,7 +180,7 @@ func applyOverlayForSameTypes(resource, overlay interface{}, path string) ([][]b
}
appliedPatches = append(appliedPatches, patch)
default:
return nil, fmt.Errorf("Overlay has unsupported type: %T", overlay)
return nil, fmt.Errorf("overlay has unsupported type: %T", overlay)
}
return appliedPatches, nil
@ -228,7 +228,7 @@ func applyOverlayToArray(resource, overlay []interface{}, path string) ([][]byte
var appliedPatches [][]byte
if len(overlay) == 0 {
return nil, errors.New("Empty array detected in the overlay")
return nil, errors.New("empty array detected in the overlay")
}
if len(resource) == 0 {
@ -243,7 +243,7 @@ func applyOverlayToArray(resource, overlay []interface{}, path string) ([][]byte
}
if reflect.TypeOf(resource[0]) != reflect.TypeOf(overlay[0]) {
return nil, fmt.Errorf("Overlay array and resource array have elements of different types: %T and %T", overlay[0], resource[0])
return nil, fmt.Errorf("overlay array and resource array have elements of different types: %T and %T", overlay[0], resource[0])
}
return applyOverlayToArrayOfSameTypes(resource, overlay, path)
@ -360,7 +360,7 @@ func processSubtree(overlay interface{}, path string, op string) ([]byte, error)
// check the patch
_, err := jsonpatch.DecodePatch([]byte("[" + patchStr + "]"))
if err != nil {
return nil, fmt.Errorf("Failed to make '%s' patch from an overlay '%s' for path %s, err: %v", op, value, path, err)
return nil, fmt.Errorf("failed to make '%s' patch from an overlay '%s' for path %s, err: %v", op, value, path, err)
}
return []byte(patchStr), nil

View file

@ -60,7 +60,7 @@ func validateResourceElement(log logr.Logger, resourceElement, patternElement, o
typedResourceElement, ok := resourceElement.(map[string]interface{})
if !ok {
log.V(4).Info("Pattern and resource have different structures.", "path", path, "expected", fmt.Sprintf("%T", patternElement), "current", fmt.Sprintf("%T", resourceElement))
return path, fmt.Errorf("Pattern and resource have different structures. Path: %s. Expected %T, found %T", path, patternElement, resourceElement)
return path, fmt.Errorf("pattern and resource have different structures. Path: %s. Expected %T, found %T", path, patternElement, resourceElement)
}
// CheckAnchorInResource - check anchor key exists in resource and update the AnchorKey fields.
ac.CheckAnchorInResource(typedPatternElement, typedResourceElement)
@ -70,7 +70,7 @@ func validateResourceElement(log logr.Logger, resourceElement, patternElement, o
typedResourceElement, ok := resourceElement.([]interface{})
if !ok {
log.V(4).Info("Pattern and resource have different structures.", "path", path, "expected", fmt.Sprintf("%T", patternElement), "current", fmt.Sprintf("%T", resourceElement))
return path, fmt.Errorf("Validation rule Failed at path %s, resource does not satisfy the expected overlay pattern", path)
return path, fmt.Errorf("validation rule Failed at path %s, resource does not satisfy the expected overlay pattern", path)
}
return validateArray(log, typedResourceElement, typedPatternElement, originPattern, path, ac)
// elementary values
@ -140,7 +140,7 @@ func validateMap(log logr.Logger, resourceMap, patternMap map[string]interface{}
func validateArray(log logr.Logger, resourceArray, patternArray []interface{}, originPattern interface{}, path string, ac *common.AnchorKey) (string, error) {
if 0 == len(patternArray) {
return path, fmt.Errorf("Pattern Array empty")
return path, fmt.Errorf("pattern Array empty")
}
switch typedPatternElement := patternArray[0].(type) {
@ -170,7 +170,7 @@ func validateArray(log logr.Logger, resourceArray, patternArray []interface{}, o
}
}
} else {
return "", fmt.Errorf("Validate Array failed, array length mismatch, resource Array len is %d and pattern Array len is %d", len(resourceArray), len(patternArray))
return "", fmt.Errorf("validate Array failed, array length mismatch, resource Array len is %d and pattern Array len is %d", len(resourceArray), len(patternArray))
}
}
return "", nil
@ -190,26 +190,23 @@ func getValueFromPattern(log logr.Logger, patternMap map[string]interface{}, key
switch typedPattern := pattern.(type) {
case []interface{}:
if keys[currentKeyIndex] == rawKey {
for i, value := range typedPattern {
resourceMap, ok := value.(map[string]interface{})
if len(typedPattern) > 0 {
resourceMap, ok := typedPattern[0].(map[string]interface{})
if !ok {
log.V(4).Info("Pattern and resource have different structures.", "expected", fmt.Sprintf("%T", pattern), "current", fmt.Sprintf("%T", value))
return nil, fmt.Errorf("Validation rule failed, resource does not have expected pattern %v", patternMap)
log.V(4).Info("Pattern and resource have different structures.", "expected", fmt.Sprintf("%T", pattern), "current", fmt.Sprintf("%T", typedPattern[0]))
return nil, fmt.Errorf("validation rule failed, resource does not have expected pattern %v", patternMap)
}
if keys[currentKeyIndex+1] == strconv.Itoa(i) {
if keys[currentKeyIndex+1] == strconv.Itoa(0) {
return getValueFromPattern(log, resourceMap, keys, currentKeyIndex+2)
}
// TODO : SA4004: the surrounding loop is unconditionally terminated (staticcheck)
return nil, errors.New("Reference to non-existent place in the document")
}
return nil, nil // Just a hack to fix the lint
}
return nil, errors.New("Reference to non-existent place in the document")
return nil, errors.New("reference to non-existent place in the document")
case map[string]interface{}:
if keys[currentKeyIndex] == rawKey {
return getValueFromPattern(log, typedPattern, keys, currentKeyIndex+1)
}
return nil, errors.New("Reference to non-existent place in the document")
return nil, errors.New("reference to non-existent place in the document")
case string, float64, int, int64, bool, nil:
continue
}
@ -220,7 +217,7 @@ func getValueFromPattern(log logr.Logger, patternMap map[string]interface{}, key
for _, elem := range keys {
elemPath = "/" + elem + elemPath
}
return nil, fmt.Errorf("No value found for specified reference: %s", elemPath)
return nil, fmt.Errorf("no value found for specified reference: %s", elemPath)
}
// validateArrayOfMaps gets anchors from pattern array map element, applies anchors logic

View file

@ -71,7 +71,7 @@ func (doh DurationOperatorHandler) validateValueWithIntPattern(key int64, value
if err == nil {
return durationCompareByCondition(time.Duration(key)*time.Second, duration, doh.condition, &doh.log)
}
doh.log.Error(fmt.Errorf("Parse Error: "), "Failed to parse time duration from the string value")
doh.log.Error(fmt.Errorf("parse error: "), "Failed to parse time duration from the string value")
return false
default:
doh.log.Info("Unexpected type", "value", value, "type", fmt.Sprintf("%T", value))
@ -92,7 +92,7 @@ func (doh DurationOperatorHandler) validateValueWithFloatPattern(key float64, va
if err == nil {
return durationCompareByCondition(time.Duration(key)*time.Second, duration, doh.condition, &doh.log)
}
doh.log.Error(fmt.Errorf("Parse Error: "), "Failed to parse time duration from the string value")
doh.log.Error(fmt.Errorf("parse error: "), "Failed to parse time duration from the string value")
return false
default:
doh.log.Info("Unexpected type", "value", value, "type", fmt.Sprintf("%T", value))
@ -118,7 +118,7 @@ func (doh DurationOperatorHandler) validateValueWithStringPattern(key string, va
if err == nil {
return durationCompareByCondition(duration, durationValue, doh.condition, &doh.log)
}
doh.log.Error(fmt.Errorf("Parse Error: "), "Failed to parse time duration from the string value")
doh.log.Error(fmt.Errorf("parse error: "), "Failed to parse time duration from the string value")
return false
default:
doh.log.Info("Unexpected type", "value", value, "type", fmt.Sprintf("%T", value))

View file

@ -76,7 +76,7 @@ func (noh NumericOperatorHandler) validateValueWithIntPattern(key int64, value i
if err == nil {
return compareByCondition(float64(key), float64(int64val), noh.condition, &noh.log)
}
noh.log.Error(fmt.Errorf("Parse Error: "), "Failed to parse both float64 and int64 from the string value")
noh.log.Error(fmt.Errorf("parse error: "), "Failed to parse both float64 and int64 from the string value")
return false
default:
noh.log.Info("Expected type int", "value", value, "type", fmt.Sprintf("%T", value))
@ -101,7 +101,7 @@ func (noh NumericOperatorHandler) validateValueWithFloatPattern(key float64, val
if err == nil {
return compareByCondition(key, float64(int64val), noh.condition, &noh.log)
}
noh.log.Error(fmt.Errorf("Parse Error: "), "Failed to parse both float64 and int64 from the string value")
noh.log.Error(fmt.Errorf("parse error: "), "Failed to parse both float64 and int64 from the string value")
return false
default:
noh.log.Info("Expected type float", "value", value, "type", fmt.Sprintf("%T", value))

View file

@ -414,7 +414,7 @@ func resolveReference(log logr.Logger, fullDocument interface{}, reference, abso
path = path[len(operation):]
if len(path) == 0 {
return nil, errors.New("Expected path. Found empty reference")
return nil, errors.New("expected path, found empty reference")
}
path = formAbsolutePath(path, absolutePath)
@ -447,7 +447,7 @@ func valFromReferenceToString(value interface{}, operator string) (string, error
case float64:
return fmt.Sprintf("%f", value), nil
default:
return "", fmt.Errorf("Incorrect expression. Operator %s does not match with value: %v", operator, value)
return "", fmt.Errorf("incorrect expression: operator %s does not match with value %v", operator, value)
}
}
@ -462,7 +462,7 @@ func FindAndShiftReferences(log logr.Logger, value, shift, pivot string) string
index := strings.Index(reference, pivot)
if index == -1 {
log.Error(fmt.Errorf(`Failed to shit reference. Pivot value "%s" was not found`, pivot), "pivot search failed")
log.Error(fmt.Errorf(`failed to shift reference: pivot value "%s" was not found`, pivot), "pivot search failed")
}
// try to get rule index from the reference

View file

@ -2,6 +2,7 @@ package admissionrequests
import (
"fmt"
"github.com/kyverno/kyverno/pkg/metrics"
)
@ -24,6 +25,6 @@ func ParseResourceRequestOperation(requestOperationStr string) (metrics.Resource
case "CONNECT":
return metrics.ResourceConnected, nil
default:
return "", fmt.Errorf("Unknown request operation made by resource: %s. Allowed requests: 'CREATE', 'UPDATE', 'DELETE', 'CONNECT'", requestOperationStr)
return "", fmt.Errorf("unknown request operation made by resource: %s. Allowed requests: 'CREATE', 'UPDATE', 'DELETE', 'CONNECT'", requestOperationStr)
}
}

View file

@ -25,6 +25,6 @@ func ParseResourceRequestOperation(requestOperationStr string) (metrics.Resource
case "CONNECT":
return metrics.ResourceConnected, nil
default:
return "", fmt.Errorf("Unknown request operation made by resource: %s. Allowed requests: 'CREATE', 'UPDATE', 'DELETE', 'CONNECT'", requestOperationStr)
return "", fmt.Errorf("unknown request operation made by resource: %s. Allowed requests: 'CREATE', 'UPDATE', 'DELETE', 'CONNECT'", requestOperationStr)
}
}

View file

@ -39,6 +39,6 @@ func ParseResourceRequestOperation(requestOperationStr string) (metrics.Resource
case "CONNECT":
return metrics.ResourceConnected, nil
default:
return "", fmt.Errorf("Unknown request operation made by resource: %s. Allowed requests: 'CREATE', 'UPDATE', 'DELETE', 'CONNECT'", requestOperationStr)
return "", fmt.Errorf("unknown request operation made by resource: %s. Allowed requests: 'CREATE', 'UPDATE', 'DELETE', 'CONNECT'", requestOperationStr)
}
}

View file

@ -39,6 +39,6 @@ func ParseResourceRequestOperation(requestOperationStr string) (metrics.Resource
case "CONNECT":
return metrics.ResourceConnected, nil
default:
return "", fmt.Errorf("Unknown request operation made by resource: %s. Allowed requests: 'CREATE', 'UPDATE', 'DELETE', 'CONNECT'", requestOperationStr)
return "", fmt.Errorf("unknown request operation made by resource: %s. Allowed requests: 'CREATE', 'UPDATE', 'DELETE', 'CONNECT'", requestOperationStr)
}
}

View file

@ -31,7 +31,7 @@ func validateMap(patternMap map[string]interface{}, path string, supportedAnchor
// single char ()
re, err := regexp.Compile(`^.?\(.+\)$`)
if err != nil {
return path + "/" + key, fmt.Errorf("Unable to parse the field %s: %v", key, err)
return path + "/" + key, fmt.Errorf("unable to parse the field %s: %v", key, err)
}
matched := re.MatchString(key)
@ -40,7 +40,7 @@ func validateMap(patternMap map[string]interface{}, path string, supportedAnchor
// some type of anchor
// check if valid anchor
if !checkAnchors(key, supportedAnchors) {
return path + "/" + key, fmt.Errorf("Unsupported anchor %s", key)
return path + "/" + key, fmt.Errorf("unsupported anchor %s", key)
}
// addition check for existence anchor
@ -48,11 +48,11 @@ func validateMap(patternMap map[string]interface{}, path string, supportedAnchor
if commonAnchors.IsExistenceAnchor(key) {
typedValue, ok := value.([]interface{})
if !ok {
return path + "/" + key, fmt.Errorf("Existence anchor should have value of type list")
return path + "/" + key, fmt.Errorf("existence anchor should have value of type list")
}
// validate that there is atleast one entry in the list
if len(typedValue) == 0 {
return path + "/" + key, fmt.Errorf("Existence anchor: should have atleast one value")
return path + "/" + key, fmt.Errorf("existence anchor: should have atleast one value")
}
}
}

View file

@ -59,5 +59,5 @@ func validatePatch(pp kyverno.Patch) error {
return nil
}
return fmt.Errorf("Unsupported JSONPatch operation '%s'", pp.Operation)
return fmt.Errorf("unsupported JSONPatch operation '%s'", pp.Operation)
}

View file

@ -93,7 +93,7 @@ func Validate(policy *kyverno.ClusterPolicy, client *dclient.Client, mock bool,
}
if jsonPatchOnPod(rule) {
log.Log.V(1).Info("pods managed by workload controllers cannot be mutated using policies. Use the auto-gen feature or write policies that match pod controllers.")
log.Log.V(1).Info("pods managed by workload controllers cannot be mutated using policies, use the auto-gen feature or write policies that match pod controllers")
}
// validate resource description
if path, err := validateResources(rule); err != nil {
@ -197,7 +197,7 @@ func Validate(policy *kyverno.ClusterPolicy, client *dclient.Client, mock bool,
}
if utils.ContainsString(rule.MatchResources.Kinds, "*") || utils.ContainsString(rule.ExcludeResources.Kinds, "*") {
return fmt.Errorf("wildcards (*) are currently not supported in the match.resources.kinds field. at least one resource kind must be specified in a kind block.")
return fmt.Errorf("wildcards (*) are currently not supported in the match.resources.kinds field, at least one resource kind must be specified in a kind block")
}
// Validate Kind with match resource kinds
@ -301,7 +301,7 @@ func validateMatchKindHelper(rule kyverno.Rule) error {
return fmt.Errorf("policy can only deal with the metadata field of the resource if" +
" the rule does not match an kind")
}
return fmt.Errorf("At least one element must be specified in a kind block. The kind attribute is mandatory when working with the resources element")
return fmt.Errorf("at least one element must be specified in a kind block, the kind attribute is mandatory when working with the resources element")
}
// doMatchAndExcludeConflict checks if the resultant
@ -645,19 +645,19 @@ func validateResources(rule kyverno.Rule) (string, error) {
}
if (len(rule.MatchResources.Any) > 0 || len(rule.MatchResources.All) > 0) && !reflect.DeepEqual(rule.MatchResources.ResourceDescription, kyverno.ResourceDescription{}) {
return "match.", fmt.Errorf("Can't specify any/all together with match resources")
return "match.", fmt.Errorf("can't specify any/all together with match resources")
}
if (len(rule.ExcludeResources.Any) > 0 || len(rule.ExcludeResources.All) > 0) && !reflect.DeepEqual(rule.ExcludeResources.ResourceDescription, kyverno.ResourceDescription{}) {
return "exclude.", fmt.Errorf("Can't specify any/all together with exclude resources")
return "exclude.", fmt.Errorf("can't specify any/all together with exclude resources")
}
if len(rule.MatchResources.Any) > 0 && len(rule.MatchResources.All) > 0 {
return "match.", fmt.Errorf("Can't specify any and all together.")
return "match.", fmt.Errorf("can't specify any and all together")
}
if len(rule.ExcludeResources.Any) > 0 && len(rule.ExcludeResources.All) > 0 {
return "match.", fmt.Errorf("Can't specify any and all together.")
return "match.", fmt.Errorf("can't specify any and all together")
}
if len(rule.MatchResources.Any) > 0 {
@ -804,7 +804,7 @@ func validateConditionValuesKeyRequestOperation(c kyverno.Condition) (string, er
}
}
default:
return fmt.Sprintf("value"), fmt.Errorf("'value' field found to be of the type %v. The provided value/values are expected to be either in the form of a string or list", reflect.TypeOf(c.Value).Kind())
return "value", fmt.Errorf("'value' field found to be of the type %v. The provided value/values are expected to be either in the form of a string or list", reflect.TypeOf(c.Value).Kind())
}
return "", nil
}

View file

@ -102,7 +102,7 @@ func (v *Validate) validateForEach(foreach *kyverno.ForEachValidation) error {
}
if !strings.HasPrefix(foreach.List, "request.object") {
return fmt.Errorf("foreach.list must start with 'request.object' e.g. 'request.object.spec.containers'.")
return fmt.Errorf("foreach.list must start with 'request.object' e.g. 'request.object.spec.containers'")
}
count := foreachElemCount(foreach)

View file

@ -186,12 +186,12 @@ func generateInClusterServiceName(props CertificateProps) string {
func tlsCertificateGetExpirationDate(certData []byte) (*time.Time, error) {
block, _ := pem.Decode(certData)
if block == nil {
return nil, errors.New("Failed to decode PEM")
return nil, errors.New("failed to decode PEM")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, errors.New("Failed to parse certificate: %v" + err.Error())
return nil, errors.New("failed to parse certificate: %v" + err.Error())
}
return &cert.NotAfter, nil
}