From 3f15ec5a1e77fdd8079078f57c32af38ce51c866 Mon Sep 17 00:00:00 2001 From: Bricktop Date: Wed, 13 Oct 2021 22:45:23 +0200 Subject: [PATCH] Remove dead code and unused variables (#2537) * Remove dead code and unused variables Signed-off-by: Marcel Mueller * Remove unnecessary definitions Signed-off-by: Marcel Mueller --- pkg/common/common.go | 3 + pkg/engine/context/evaluate_test.go | 5 +- .../mutate/strategicPreprocessing_test.go | 3 +- pkg/engine/validate/validate.go | 45 -------------- pkg/engine/variables/vars_test.go | 7 +-- pkg/policyreport/common.go | 58 ------------------- pkg/utils/util.go | 3 + test/e2e/generate/resources.go | 39 ------------- 8 files changed, 13 insertions(+), 150 deletions(-) delete mode 100755 pkg/policyreport/common.go diff --git a/pkg/common/common.go b/pkg/common/common.go index 317c48cfdc..011e79aa59 100644 --- a/pkg/common/common.go +++ b/pkg/common/common.go @@ -66,6 +66,9 @@ func GetNamespaceSelectorsFromNamespaceLister(kind, namespaceOfResource string, func GetNamespaceLabels(namespaceObj *v1.Namespace, logger logr.Logger) map[string]string { namespaceObj.Kind = "Namespace" namespaceRaw, err := json.Marshal(namespaceObj) + if err != nil { + logger.Error(err, "failed to marshal namespace") + } namespaceUnstructured, err := enginutils.ConvertToUnstructured(namespaceRaw) if err != nil { logger.Error(err, "failed to convert object resource to unstructured format") diff --git a/pkg/engine/context/evaluate_test.go b/pkg/engine/context/evaluate_test.go index 1892895cf9..996f963111 100644 --- a/pkg/engine/context/evaluate_test.go +++ b/pkg/engine/context/evaluate_test.go @@ -1,9 +1,10 @@ package context import ( + "testing" + "github.com/stretchr/testify/assert" "k8s.io/api/admission/v1beta1" - "testing" ) func TestHasChanged(t *testing.T) { @@ -21,7 +22,7 @@ func TestHasChanged(t *testing.T) { assert.NoError(t, err) assert.True(t, val) - val, err = ctx.HasChanged("a.x.y") + _, err = ctx.HasChanged("a.x.y") assert.Error(t, err) } diff --git a/pkg/engine/mutate/strategicPreprocessing_test.go b/pkg/engine/mutate/strategicPreprocessing_test.go index fc2a1af8ef..890ab3abd1 100644 --- a/pkg/engine/mutate/strategicPreprocessing_test.go +++ b/pkg/engine/mutate/strategicPreprocessing_test.go @@ -870,7 +870,7 @@ func Test_preProcessStrategicMergePatch_multipleAnchors(t *testing.T) { func Test_FilterKeys_NoConditions(t *testing.T) { patternRaw := []byte(`{ "key1": "value1", - "key2": "value2" + "key2": "value2" }`) pattern := yaml.MustParse(string(patternRaw)) @@ -1024,6 +1024,7 @@ func Test_deleteRNode(t *testing.T) { deleteListElement(list, 0) elements, err = list.Elements() + assert.NilError(t, err) assert.Equal(t, len(elements), 2) } diff --git a/pkg/engine/validate/validate.go b/pkg/engine/validate/validate.go index 7c5496b150..cffe2aca6c 100644 --- a/pkg/engine/validate/validate.go +++ b/pkg/engine/validate/validate.go @@ -1,7 +1,6 @@ package validate import ( - "errors" "fmt" "strconv" @@ -176,50 +175,6 @@ func validateArray(log logr.Logger, resourceArray, patternArray []interface{}, o return "", nil } -func getValueFromPattern(log logr.Logger, patternMap map[string]interface{}, keys []string, currentKeyIndex int) (interface{}, error) { - - for key, pattern := range patternMap { - rawKey := common.GetRawKeyIfWrappedWithAttributes(key) - - if rawKey == keys[len(keys)-1] && currentKeyIndex == len(keys)-1 { - return pattern, nil - } else if rawKey != keys[currentKeyIndex] && currentKeyIndex != len(keys)-1 { - continue - } - - switch typedPattern := pattern.(type) { - case []interface{}: - if keys[currentKeyIndex] == rawKey { - 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", typedPattern[0])) - return nil, fmt.Errorf("validation rule failed, resource does not have expected pattern %v", patternMap) - } - if keys[currentKeyIndex+1] == strconv.Itoa(0) { - return getValueFromPattern(log, resourceMap, keys, currentKeyIndex+2) - } - } - } - 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") - case string, float64, int, int64, bool, nil: - continue - } - } - - elemPath := "" - - for _, elem := range keys { - elemPath = "/" + elem + elemPath - } - return nil, fmt.Errorf("no value found for specified reference: %s", elemPath) -} - // validateArrayOfMaps gets anchors from pattern array map element, applies anchors logic // and then validates each map due to the pattern func validateArrayOfMaps(log logr.Logger, resourceMapArray []interface{}, patternMap map[string]interface{}, originPattern interface{}, path string, ac *common.AnchorKey) (string, error) { diff --git a/pkg/engine/variables/vars_test.go b/pkg/engine/variables/vars_test.go index b86b95ae31..e6da8e4b4d 100644 --- a/pkg/engine/variables/vars_test.go +++ b/pkg/engine/variables/vars_test.go @@ -658,7 +658,6 @@ func Test_SubstituteNull(t *testing.T) { content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"] var expected interface{} - expected = nil assert.DeepEqual(t, expected, content) } @@ -890,8 +889,7 @@ func Test_SubstituteString(t *testing.T) { assert.NilError(t, err) content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"] - var expected interface{} - expected = "example" + expected := "example" assert.DeepEqual(t, expected, content) } @@ -920,8 +918,7 @@ func Test_SubstituteStringInString(t *testing.T) { assert.NilError(t, err) content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"] - var expected interface{} - expected = "content = example" + expected := "content = example" assert.DeepEqual(t, expected, content) } diff --git a/pkg/policyreport/common.go b/pkg/policyreport/common.go deleted file mode 100755 index e570ce8c25..0000000000 --- a/pkg/policyreport/common.go +++ /dev/null @@ -1,58 +0,0 @@ -package policyreport - -import ( - "fmt" - "time" - - backoff "github.com/cenkalti/backoff" - kyverno "github.com/kyverno/kyverno/pkg/api/kyverno/v1" - client "github.com/kyverno/kyverno/pkg/dclient" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - unstructured "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/labels" - "sigs.k8s.io/controller-runtime/pkg/log" -) - -func retryGetResource(client *client.Client, rspec kyverno.ResourceSpec) (*unstructured.Unstructured, error) { - var i int - var obj *unstructured.Unstructured - var err error - getResource := func() error { - obj, err = client.GetResource("", rspec.Kind, rspec.Namespace, rspec.Name) - log.Log.V(4).Info(fmt.Sprintf("retry %v getting %s/%s/%s", i, rspec.Kind, rspec.Namespace, rspec.Name)) - i++ - return err - } - - exbackoff := &backoff.ExponentialBackOff{ - InitialInterval: 500 * time.Millisecond, - RandomizationFactor: 0.5, - Multiplier: 1.5, - MaxInterval: time.Second, - MaxElapsedTime: 3 * time.Second, - Clock: backoff.SystemClock, - } - - exbackoff.Reset() - err = backoff.Retry(getResource, exbackoff) - if err != nil { - return nil, err - } - - return obj, nil -} - -func converLabelToSelector(labelMap map[string]string) (labels.Selector, error) { - ls := &metav1.LabelSelector{} - err := metav1.Convert_Map_string_To_string_To_v1_LabelSelector(&labelMap, ls, nil) - if err != nil { - return nil, err - } - - policyViolationSelector, err := metav1.LabelSelectorAsSelector(ls) - if err != nil { - return nil, fmt.Errorf("invalid label selector: %v", err) - } - - return policyViolationSelector, nil -} diff --git a/pkg/utils/util.go b/pkg/utils/util.go index 5725d51397..b38c4b7e95 100644 --- a/pkg/utils/util.go +++ b/pkg/utils/util.go @@ -238,6 +238,9 @@ func ApiextensionsJsonToKyvernoConditions(original apiextensions.JSON) (interfac // marshalling the abstract apiextensions.JSON back to JSON form jsonByte, err := json.Marshal(original) + if err != nil { + return nil, fmt.Errorf("error occurred while marshalling %s: %+v", path, err) + } var kyvernoOldConditions []kyverno.Condition if err = json.Unmarshal(jsonByte, &kyvernoOldConditions); err == nil { diff --git a/test/e2e/generate/resources.go b/test/e2e/generate/resources.go index 30a06a644b..b6c65662d3 100644 --- a/test/e2e/generate/resources.go +++ b/test/e2e/generate/resources.go @@ -176,45 +176,6 @@ spec: namespace: "{{request.object.metadata.name}}" `) -// ClusterPolicy to generate ClusterRole and ClusterRoleBinding with clone = true -var genClusterRoleYamlWithClone = []byte(` -apiVersion: kyverno.io/v1 -kind: ClusterPolicy -metadata: - name: "gen-cluster-policy" -spec: - background: false - rules: - - name: "gen-cluster-role" - match: - resources: - kinds: - - Namespace - generate: - kind: ClusterRole - name: ns-cluster-role - namespace: "{{request.object.metadata.name}}" - synchronize: true - clone: - kind: ClusterRole - name: base-cluster-role - namespace: default - - name: "gen-cluster-role-binding" - match: - resources: - kinds: - - Namespace - generate: - kind: ClusterRoleBinding - name: ns-cluster-role-binding - namespace: "{{request.object.metadata.name}}" - synchronize: true - clone: - kind: ClusterRole - name: base-cluster-role-binding - namespace: default -`) - var baseClusterRoleData = []byte(` apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole