From 0099ef54ad32993b4a4e63fda34fa841fb3db79b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Charles-Edouard=20Br=C3=A9t=C3=A9ch=C3=A9?= Date: Tue, 17 May 2022 08:19:03 +0200 Subject: [PATCH] chore: enable gofmt and gofumpt linters (#3931) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Charles-Edouard Brétéché --- .golangci.yml | 2 + api/kyverno/v1/common_types.go | 6 -- api/kyverno/v1/constants.go | 2 +- api/kyverno/v1/image_verification_types.go | 7 -- .../v1alpha2/policyreport_types.go | 2 - .../kubectl-kyverno/apply/apply_command.go | 15 ++- cmd/cli/kubectl-kyverno/test/test_command.go | 9 +- .../kubectl-kyverno/utils/common/common.go | 13 +-- cmd/cli/kubectl-kyverno/utils/common/fetch.go | 6 +- cmd/cli/kubectl-kyverno/utils/store/store.go | 10 +- cmd/initContainer/main.go | 2 +- cmd/kyverno/main.go | 3 +- litmuschaos/pod_cpu_hog/config.go | 3 +- pkg/auth/auth.go | 6 +- pkg/autogen/autogen.go | 8 +- pkg/background/common/errors.go | 2 +- pkg/background/common/status.go | 4 +- pkg/background/generate/cleanup/controller.go | 7 +- pkg/background/generate/cleanup/resource.go | 4 +- pkg/background/generate/generate.go | 8 +- pkg/background/mutate/mutate.go | 2 +- pkg/background/update_request_controller.go | 2 +- pkg/config/config.go | 28 +++--- pkg/config/filter.go | 2 +- pkg/cosign/client.go | 3 +- pkg/cosign/cosign.go | 2 +- pkg/dclient/mock.go | 2 +- pkg/engine/anchor/common.go | 14 +-- pkg/engine/context/mock_context.go | 6 +- pkg/engine/imageVerify.go | 2 +- pkg/engine/imageVerifyMetadata.go | 4 +- pkg/engine/jmespath/functions.go | 98 ++++++++++++------- pkg/engine/operator/operator.go | 2 +- pkg/engine/response/response.go | 38 ++++--- pkg/engine/utils.go | 6 +- pkg/engine/utils/utils.go | 4 +- pkg/engine/validation.go | 4 +- pkg/engine/variables/evaluate.go | 8 +- pkg/engine/variables/operator/allin.go | 6 +- pkg/engine/variables/operator/allnotin.go | 6 +- pkg/engine/variables/operator/anyin.go | 6 +- pkg/engine/variables/operator/anynotin.go | 6 +- pkg/engine/variables/operator/duration.go | 6 +- pkg/engine/variables/operator/equal.go | 6 +- pkg/engine/variables/operator/notequal.go | 6 +- pkg/engine/variables/operator/numeric.go | 6 +- pkg/engine/variables/operator/operator.go | 6 +- pkg/engine/variables/vars.go | 9 +- pkg/event/controller.go | 8 +- pkg/event/reason.go | 2 +- pkg/event/source.go | 2 +- pkg/event/util.go | 2 +- pkg/leaderelection/leaderelection.go | 5 +- .../policyExecutionDuration.go | 4 +- pkg/metrics/policyresults/policyResults.go | 4 +- pkg/openapi/validation.go | 4 +- pkg/policy/actions.go | 6 +- pkg/policy/background.go | 2 +- pkg/policy/common/validate_pattern.go | 5 +- pkg/policy/existing.go | 14 +-- pkg/policy/generate/auth.go | 6 +- pkg/policy/generate/fake.go | 4 +- pkg/policy/generate/fake/auth.go | 7 +- pkg/policy/generate/validate.go | 10 +- pkg/policy/mutate/validate.go | 4 +- pkg/policy/validate.go | 10 +- pkg/policy/validate/validate.go | 4 +- pkg/policyreport/builder.go | 10 +- pkg/policyreport/policyreport.go | 6 +- pkg/policyreport/reportrequest.go | 10 +- pkg/registryclient/client.go | 2 +- pkg/signal/signal.go | 6 +- pkg/testrunner/scenario.go | 2 +- pkg/testrunner/utils.go | 2 +- pkg/userinfo/roleRef.go | 2 +- pkg/utils/annotations.go | 2 +- pkg/utils/util.go | 2 +- pkg/version/version.go | 2 +- pkg/webhookconfig/monitor.go | 2 +- pkg/webhookconfig/registration.go | 3 +- pkg/webhookconfig/status.go | 10 +- pkg/webhooks/resource/generation.go | 8 +- pkg/webhooks/resource/report.go | 2 +- pkg/webhooks/resource/utils.go | 5 +- pkg/webhooks/resource/validate_audit.go | 3 +- pkg/webhooks/resource/validation.go | 8 +- test/e2e/generate/config.go | 14 +-- test/e2e/mutate/config.go | 4 +- test/e2e/mutate/resources.go | 10 +- test/e2e/validate/config.go | 4 +- test/e2e/verifyimages/config.go | 2 +- 91 files changed, 329 insertions(+), 304 deletions(-) mode change 100755 => 100644 api/kyverno/v1/common_types.go mode change 100755 => 100644 api/policyreport/v1alpha2/policyreport_types.go mode change 100755 => 100644 cmd/kyverno/main.go mode change 100755 => 100644 pkg/policyreport/builder.go mode change 100755 => 100644 pkg/policyreport/reportrequest.go diff --git a/.golangci.yml b/.golangci.yml index c1178a924e..4c2c7b0687 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -13,6 +13,8 @@ linters: - exportloopref - gci - gochecknoinits + - gofmt + - gofumpt - goprintffuncname - gosec - gosimple diff --git a/api/kyverno/v1/common_types.go b/api/kyverno/v1/common_types.go old mode 100755 new mode 100644 index 4d5dcb31a1..2decc519de --- a/api/kyverno/v1/common_types.go +++ b/api/kyverno/v1/common_types.go @@ -40,7 +40,6 @@ type AnyAllConditions struct { // ContextEntry adds variables and data sources to a rule Context. Either a // ConfigMap reference or a APILookup must be provided. type ContextEntry struct { - // Name is the variable name. Name string `json:"name,omitempty" yaml:"name,omitempty"` @@ -92,7 +91,6 @@ type ImageRegistry struct { // ConfigMapReference refers to a ConfigMap type ConfigMapReference struct { - // Name is the ConfigMap name. Name string `json:"name" yaml:"name"` @@ -105,7 +103,6 @@ type ConfigMapReference struct { // used to perform the HTTP GET request and an optional JMESPath used to // transform the retrieved JSON data. type APICall struct { - // URLPath is the URL path to be used in the HTTP GET request to the // Kubernetes API server (e.g. "/api/v1/namespaces" or "/apis/apps/v1/deployments"). // The format required is the same format used by the `kubectl get --raw` command. @@ -213,7 +210,6 @@ type ResourceFilter struct { // Mutation defines how resource are modified. type Mutation struct { - // Targets defines the target resources to be mutated. // +optional Targets []ResourceSpec `json:"targets,omitempty" yaml:"targets,omitempty"` @@ -361,7 +357,6 @@ func (d *Deny) SetAnyAllConditions(in apiextensions.JSON) { // ForEach applies validate rules to a list of sub-elements by creating a context for each entry in the list and looping over it to apply the specified logic. type ForEachValidation struct { - // List specifies a JMESPath expression that results in one or more elements // to which the validation logic is applied. List string `json:"list,omitempty" yaml:"list,omitempty"` @@ -449,7 +444,6 @@ func (g *Generation) SetData(in apiextensions.JSON) { // CloneFrom provides the location of the source resource used to generate target resources. // The resource kind is derived from the match criteria. type CloneFrom struct { - // Namespace specifies source resource namespace. // +optional Namespace string `json:"namespace,omitempty" yaml:"namespace,omitempty"` diff --git a/api/kyverno/v1/constants.go b/api/kyverno/v1/constants.go index fcff2b165a..a5e948e741 100644 --- a/api/kyverno/v1/constants.go +++ b/api/kyverno/v1/constants.go @@ -1,6 +1,6 @@ package v1 const ( - //PodControllersAnnotation defines the annotation key for Pod-Controllers + // PodControllersAnnotation defines the annotation key for Pod-Controllers PodControllersAnnotation = "pod-policies.kyverno.io/autogen-controllers" ) diff --git a/api/kyverno/v1/image_verification_types.go b/api/kyverno/v1/image_verification_types.go index a9225e5993..531178eb7e 100644 --- a/api/kyverno/v1/image_verification_types.go +++ b/api/kyverno/v1/image_verification_types.go @@ -12,7 +12,6 @@ import ( // are signed with the supplied public key. Once the image is verified it is // mutated to include the SHA digest retrieved during the registration. type ImageVerification struct { - // Image is the image name consisting of the registry address, repository, image, and tag. // Wildcards ('*' and '?') are allowed. See: https://kubernetes.io/docs/concepts/containers/images. // Deprecated. Use ImageReferences instead. @@ -84,7 +83,6 @@ type ImageVerification struct { } type AttestorSet struct { - // Count specifies the required number of entries that must match. If the count is null, all entries must match // (a logical AND). If the count is 1, at least one entry must match (a logical OR). If the count contains a // value N, then N must be less than or equal to the size of entries, and at least N entries must match. @@ -99,7 +97,6 @@ type AttestorSet struct { } type Attestor struct { - // Keys specifies one or more public keys // +kubebuilder:validation:Optional Keys *StaticKeyAttestor `json:"keys,omitempty" yaml:"keys,omitempty"` @@ -128,7 +125,6 @@ type Attestor struct { } type StaticKeyAttestor struct { - // Keys is a set of X.509 public keys used to verify image signatures. The keys can be directly // specified or can be a variable reference to a key specified in a ConfigMap (see // https://kyverno.io/docs/writing-policies/variables/). When multiple keys are specified each @@ -144,7 +140,6 @@ type StaticKeyAttestor struct { } type CertificateAttestor struct { - // Certificate is an optional PEM encoded public certificate. // +kubebuilder:validation:Optional Certificate string `json:"cert,omitempty" yaml:"cert,omitempty"` @@ -161,7 +156,6 @@ type CertificateAttestor struct { } type KeylessAttestor struct { - // Rekor provides configuration for the Rekor transparency log service. If the value is nil, // Rekor is not checked and a root certificate chain is expected instead. If an empty object // is provided the public instance of Rekor (https://rekor.sigstore.dev) is used. @@ -197,7 +191,6 @@ type CTLog struct { // See https://github.com/in-toto/attestation. Kyverno fetches signed attestations from the // OCI registry and decodes them into a list of Statements. type Attestation struct { - // PredicateType defines the type of Predicate contained within the Statement. PredicateType string `json:"predicateType,omitempty" yaml:"predicateType,omitempty"` diff --git a/api/policyreport/v1alpha2/policyreport_types.go b/api/policyreport/v1alpha2/policyreport_types.go old mode 100755 new mode 100644 index 2fa5b4e1cc..bab99c9eac --- a/api/policyreport/v1alpha2/policyreport_types.go +++ b/api/policyreport/v1alpha2/policyreport_types.go @@ -41,7 +41,6 @@ const ( // PolicyReportSummary provides a status count summary type PolicyReportSummary struct { - // Pass provides the count of policies whose requirements were met // +optional Pass int `json:"pass"` @@ -89,7 +88,6 @@ type PolicySeverity string // PolicyReportResult provides the result for an individual policy type PolicyReportResult struct { - // Source is an identifier for the policy engine that manages this report // +optional Source string `json:"source"` diff --git a/cmd/cli/kubectl-kyverno/apply/apply_command.go b/cmd/cli/kubectl-kyverno/apply/apply_command.go index 13f28eb641..3c860424be 100644 --- a/cmd/cli/kubectl-kyverno/apply/apply_command.go +++ b/cmd/cli/kubectl-kyverno/apply/apply_command.go @@ -146,7 +146,8 @@ func Command() *cobra.Command { } func applyCommandHelper(resourcePaths []string, userInfoPath string, cluster bool, policyReport bool, mutateLogPath string, - variablesString string, valuesFile string, namespace string, policyPaths []string, stdin bool, registryAccess bool) (rc *common.ResultCounts, resources []*unstructured.Unstructured, skipInvalidPolicies SkippedInvalidPolicies, pvInfos []policyreport.Info, err error) { + variablesString string, valuesFile string, namespace string, policyPaths []string, stdin bool, registryAccess bool, +) (rc *common.ResultCounts, resources []*unstructured.Unstructured, skipInvalidPolicies SkippedInvalidPolicies, pvInfos []policyreport.Info, err error) { store.SetMock(true) store.SetRegistryAccess(registryAccess) kubernetesConfig := genericclioptions.NewConfigFlags(true) @@ -157,7 +158,6 @@ func applyCommandHelper(resourcePaths []string, userInfoPath string, cluster boo } variables, globalValMap, valuesMap, namespaceSelectorMap, err := common.GetVariable(variablesString, valuesFile, fs, false, "") - if err != nil { if !sanitizederror.IsErrorSanitized(err) { return rc, resources, skipInvalidPolicies, pvInfos, sanitizederror.NewWithError("failed to decode yaml", err) @@ -213,8 +213,7 @@ func applyCommandHelper(resourcePaths []string, userInfoPath string, cluster boo if !mutateLogPathIsDir && mutateLogPath != "" { mutateLogPath = filepath.Clean(mutateLogPath) // Necessary for us to include the file via variable as it is part of the CLI. - _, err := os.OpenFile(mutateLogPath, os.O_TRUNC|os.O_WRONLY, 0600) // #nosec G304 - + _, err := os.OpenFile(mutateLogPath, os.O_TRUNC|os.O_WRONLY, 0o600) // #nosec G304 if err != nil { if !sanitizederror.IsErrorSanitized(err) { return rc, resources, skipInvalidPolicies, pvInfos, sanitizederror.NewWithError("failed to truncate the existing file at "+mutateLogPath, err) @@ -397,7 +396,6 @@ func printReportOrViolation(policyReport bool, rc *common.ResultCounts, resource func createFileOrFolder(mutateLogPath string, mutateLogPathIsDir bool) error { mutateLogPath = filepath.Clean(mutateLogPath) _, err := os.Stat(mutateLogPath) - if err != nil { if os.IsNotExist(err) { if !mutateLogPathIsDir { @@ -409,7 +407,7 @@ func createFileOrFolder(mutateLogPath string, mutateLogPathIsDir bool) error { folderPath = mutateLogPath[:len(mutateLogPath)-len(s[len(s)-1])-1] _, err := os.Stat(folderPath) if os.IsNotExist(err) { - errDir := os.MkdirAll(folderPath, 0750) + errDir := os.MkdirAll(folderPath, 0o750) if errDir != nil { return sanitizederror.NewWithError("failed to create directory", err) } @@ -418,8 +416,7 @@ func createFileOrFolder(mutateLogPath string, mutateLogPathIsDir bool) error { mutateLogPath = filepath.Clean(mutateLogPath) // Necessary for us to create the file via variable as it is part of the CLI. - file, err := os.OpenFile(mutateLogPath, os.O_RDONLY|os.O_CREATE, 0600) // #nosec G304 - + file, err := os.OpenFile(mutateLogPath, os.O_RDONLY|os.O_CREATE, 0o600) // #nosec G304 if err != nil { return sanitizederror.NewWithError("failed to create file", err) } @@ -429,7 +426,7 @@ func createFileOrFolder(mutateLogPath string, mutateLogPathIsDir bool) error { return sanitizederror.NewWithError("failed to close file", err) } } else { - errDir := os.MkdirAll(mutateLogPath, 0750) + errDir := os.MkdirAll(mutateLogPath, 0o750) if errDir != nil { return sanitizederror.NewWithError("failed to create directory", err) } diff --git a/cmd/cli/kubectl-kyverno/test/test_command.go b/cmd/cli/kubectl-kyverno/test/test_command.go index e1e71604ae..6538061e1c 100644 --- a/cmd/cli/kubectl-kyverno/test/test_command.go +++ b/cmd/cli/kubectl-kyverno/test/test_command.go @@ -43,6 +43,7 @@ import ( var longHelp = ` The test command provides a facility to test resources against policies by comparing expected results, declared ahead of time in a test manifest file, to actual results reported by Kyverno. Users provide the path to the folder containing a kyverno-test.yaml file where the location could be on a local filesystem or a remote git repository. ` + var exampleHelp = ` # Test a git repository containing Kyverno test cases. kyverno test https://github.com/kyverno/policies/pod-security --git-branch main @@ -298,7 +299,7 @@ func testCommandExecute(dirPath []string, fileName string, gitBranch string, tes fs := memfs.New() rc = &resultCounts{} var testYamlCount int - var tf = &testFilter{ + tf := &testFilter{ enabled: true, } @@ -772,7 +773,7 @@ func applyPoliciesFromPath(fs billy.Filesystem, policyBytes []byte, isGit bool, os.Exit(1) } - var filteredPolicies = []v1.PolicyInterface{} + filteredPolicies := []v1.PolicyInterface{} for _, p := range policies { for _, res := range values.Results { if p.GetName() == res.Policy { @@ -783,7 +784,7 @@ func applyPoliciesFromPath(fs billy.Filesystem, policyBytes []byte, isGit bool, } for _, p := range filteredPolicies { - var filteredRules = []v1.Rule{} + filteredRules := []v1.Rule{} for _, rule := range autogen.ComputeRules(p) { for _, res := range values.Results { @@ -815,7 +816,7 @@ func applyPoliciesFromPath(fs billy.Filesystem, policyBytes []byte, isGit bool, os.Exit(1) } - var filteredResources = []*unstructured.Unstructured{} + filteredResources := []*unstructured.Unstructured{} for _, r := range resources { for _, res := range values.Results { if r.GetName() == res.Resource { diff --git a/cmd/cli/kubectl-kyverno/utils/common/common.go b/cmd/cli/kubectl-kyverno/utils/common/common.go index d3c6f67f1a..d7a9ab51fa 100644 --- a/cmd/cli/kubectl-kyverno/utils/common/common.go +++ b/cmd/cli/kubectl-kyverno/utils/common/common.go @@ -570,9 +570,9 @@ func PrintMutatedOutput(mutateLogPath string, mutateLogPathIsDir bool, yaml stri mutateLogPath = filepath.Clean(mutateLogPath) if !mutateLogPathIsDir { // truncation for the case when mutateLogPath is a file (not a directory) is handled under pkg/kyverno/apply/test_command.go - f, err = os.OpenFile(mutateLogPath, os.O_APPEND|os.O_WRONLY, 0600) // #nosec G304 + f, err = os.OpenFile(mutateLogPath, os.O_APPEND|os.O_WRONLY, 0o600) // #nosec G304 } else { - f, err = os.OpenFile(mutateLogPath+"/"+fileName+".yaml", os.O_CREATE|os.O_WRONLY, 0600) // #nosec G304 + f, err = os.OpenFile(mutateLogPath+"/"+fileName+".yaml", os.O_CREATE|os.O_WRONLY, 0o600) // #nosec G304 } if err != nil { @@ -654,7 +654,8 @@ func GetPoliciesFromPaths(fs billy.Filesystem, dirPath []string, isGit bool, pol // GetResourceAccordingToResourcePath - get resources according to the resource path func GetResourceAccordingToResourcePath(fs billy.Filesystem, resourcePaths []string, - cluster bool, policies []v1.PolicyInterface, dClient client.Interface, namespace string, policyReport bool, isGit bool, policyResourcePath string) (resources []*unstructured.Unstructured, err error) { + cluster bool, policies []v1.PolicyInterface, dClient client.Interface, namespace string, policyReport bool, isGit bool, policyResourcePath string, +) (resources []*unstructured.Unstructured, err error) { if isGit { resources, err = GetResourcesWithTest(fs, policies, resourcePaths, isGit, policyResourcePath) if err != nil { @@ -969,7 +970,7 @@ func CheckVariableForPolicy(valuesMap map[string]map[string]Resource, globalValM } func GetKindsFromPolicy(policy v1.PolicyInterface) map[string]struct{} { - var kindOnwhichPolicyIsApplied = make(map[string]struct{}) + kindOnwhichPolicyIsApplied := make(map[string]struct{}) for _, rule := range autogen.ComputeRules(policy) { for _, kind := range rule.MatchResources.ResourceDescription.Kinds { kindOnwhichPolicyIsApplied[kind] = struct{}{} @@ -981,7 +982,7 @@ func GetKindsFromPolicy(policy v1.PolicyInterface) map[string]struct{} { return kindOnwhichPolicyIsApplied } -//GetPatchedResourceFromPath - get patchedResource from given path +// GetPatchedResourceFromPath - get patchedResource from given path func GetPatchedResourceFromPath(fs billy.Filesystem, path string, isGit bool, policyResourcePath string) (unstructured.Unstructured, error) { var patchedResourceBytes []byte var patchedResource unstructured.Unstructured @@ -1012,7 +1013,7 @@ func GetPatchedResourceFromPath(fs billy.Filesystem, path string, isGit bool, po return patchedResource, nil } -//GetUserInfoFromPath - get the request info as user info from a given path +// GetUserInfoFromPath - get the request info as user info from a given path func GetUserInfoFromPath(fs billy.Filesystem, path string, isGit bool, policyResourcePath string) (v1beta1.RequestInfo, store.Subject, error) { userInfo := &v1beta1.RequestInfo{} subjectInfo := &store.Subject{} diff --git a/cmd/cli/kubectl-kyverno/utils/common/fetch.go b/cmd/cli/kubectl-kyverno/utils/common/fetch.go index c46b324104..4d5cde5d84 100644 --- a/cmd/cli/kubectl-kyverno/utils/common/fetch.go +++ b/cmd/cli/kubectl-kyverno/utils/common/fetch.go @@ -29,7 +29,7 @@ import ( func GetResources(policies []v1.PolicyInterface, resourcePaths []string, dClient client.Interface, cluster bool, namespace string, policyReport bool) ([]*unstructured.Unstructured, error) { resources := make([]*unstructured.Unstructured, 0) var err error - var resourceTypesMap = make(map[string]bool) + resourceTypesMap := make(map[string]bool) var resourceTypes []string for _, policy := range policies { @@ -119,7 +119,7 @@ func whenClusterIsFalse(resourcePaths []string, policyReport bool) ([]*unstructu // GetResourcesWithTest with gets matched resources by the given policies func GetResourcesWithTest(fs billy.Filesystem, policies []v1.PolicyInterface, resourcePaths []string, isGit bool, policyResourcePath string) ([]*unstructured.Unstructured, error) { resources := make([]*unstructured.Unstructured, 0) - var resourceTypesMap = make(map[string]bool) + resourceTypesMap := make(map[string]bool) for _, policy := range policies { for _, rule := range autogen.ComputeRules(policy) { for _, kind := range rule.MatchResources.Kinds { @@ -289,7 +289,7 @@ func GetPatchedResource(patchResourceBytes []byte) (unstructured.Unstructured, e // GetKindsFromRule will return the kinds from policy match block func GetKindsFromRule(rule v1.Rule) map[string]bool { - var resourceTypesMap = make(map[string]bool) + resourceTypesMap := make(map[string]bool) for _, kind := range rule.MatchResources.Kinds { if strings.Contains(kind, "/") { lastElement := kind[strings.LastIndex(kind, "/")+1:] diff --git a/cmd/cli/kubectl-kyverno/utils/store/store.go b/cmd/cli/kubectl-kyverno/utils/store/store.go index 8417d5ba50..3fe3b4f0ab 100644 --- a/cmd/cli/kubectl-kyverno/utils/store/store.go +++ b/cmd/cli/kubectl-kyverno/utils/store/store.go @@ -5,10 +5,12 @@ import ( rbacv1 "k8s.io/api/rbac/v1" ) -var Mock, RegistryAccess bool -var ContextVar Context -var ForeachElement int -var Subjects Subject +var ( + Mock, RegistryAccess bool + ContextVar Context + ForeachElement int + Subjects Subject +) func SetMock(mock bool) { Mock = mock diff --git a/cmd/initContainer/main.go b/cmd/initContainer/main.go index ff11be944a..3160809fb3 100644 --- a/cmd/initContainer/main.go +++ b/cmd/initContainer/main.go @@ -445,7 +445,7 @@ func convertGR(pclient kyvernoclient.Interface) error { } for _, gr := range grs.Items { - var ur = &urkyverno.UpdateRequest{ + ur := &urkyverno.UpdateRequest{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "ur-", Namespace: config.KyvernoNamespace(), diff --git a/cmd/kyverno/main.go b/cmd/kyverno/main.go old mode 100755 new mode 100644 index d2d4095e14..7fd63a934d --- a/cmd/kyverno/main.go +++ b/cmd/kyverno/main.go @@ -52,7 +52,7 @@ import ( const resyncPeriod = 15 * time.Minute var ( - //TODO: this has been added to backward support command line arguments + // TODO: this has been added to backward support command line arguments // will be removed in future and the configuration will be set only via configmaps serverIP string profilePort string @@ -274,7 +274,6 @@ func main() { policyControllerResyncPeriod, promConfig, ) - if err != nil { setupLog.Error(err, "Failed to create policy controller") os.Exit(1) diff --git a/litmuschaos/pod_cpu_hog/config.go b/litmuschaos/pod_cpu_hog/config.go index 33c22892e2..2f920ebe69 100644 --- a/litmuschaos/pod_cpu_hog/config.go +++ b/litmuschaos/pod_cpu_hog/config.go @@ -7,11 +7,10 @@ type testData struct { // Pod CPU hog test var PodCPUHogTest = struct { - //TestName - Name of the Test + // TestName - Name of the Test TestName string TestData []testData }{ - TestName: "test-litmus-chaos-experiment", TestData: []testData{ { diff --git a/pkg/auth/auth.go b/pkg/auth/auth.go index 889bbc03a4..89bc965473 100644 --- a/pkg/auth/auth.go +++ b/pkg/auth/auth.go @@ -10,7 +10,7 @@ import ( "k8s.io/apimachinery/pkg/runtime/schema" ) -//CanIOptions provides utility to check if user has authorization for the given operation +// CanIOptions provides utility to check if user has authorization for the given operation type CanIOptions struct { namespace string verb string @@ -18,7 +18,7 @@ type CanIOptions struct { client client.Interface } -//NewCanI returns a new instance of operation access controller evaluator +// NewCanI returns a new instance of operation access controller evaluator func NewCanI(client client.Interface, kind, namespace, verb string) *CanIOptions { return &CanIOptions{ namespace: namespace, @@ -28,7 +28,7 @@ func NewCanI(client client.Interface, kind, namespace, verb string) *CanIOptions } } -//RunAccessCheck checks if the caller can perform the operation +// RunAccessCheck checks if the caller can perform the operation // - operation is a combination of namespace, kind, verb // - can only evaluate a single verb // - group version resource is determined from the kind using the discovery client REST mapper diff --git a/pkg/autogen/autogen.go b/pkg/autogen/autogen.go index 670f8e5600..d64c466615 100644 --- a/pkg/autogen/autogen.go +++ b/pkg/autogen/autogen.go @@ -18,13 +18,11 @@ import ( const ( // PodControllerCronJob represent CronJob string PodControllerCronJob = "CronJob" - //PodControllers stores the list of Pod-controllers in csv string + // PodControllers stores the list of Pod-controllers in csv string PodControllers = "DaemonSet,Deployment,Job,StatefulSet,CronJob" ) -var ( - podControllersKindsSet = sets.NewString(append(strings.Split(PodControllers, ","), "Pod")...) -) +var podControllersKindsSet = sets.NewString(append(strings.Split(PodControllers, ","), "Pod")...) func isKindOtherthanPod(kinds []string) bool { if len(kinds) > 1 && kubeutils.ContainsKind(kinds, "Pod") { @@ -166,7 +164,7 @@ func GetControllers(meta *metav1.ObjectMeta, spec *kyverno.Spec) ([]string, []st // GenerateRulePatches generates rule for podControllers based on scenario A and C func GenerateRulePatches(spec *kyverno.Spec, controllers string) (rulePatches [][]byte, errs []error) { - var ruleIndex = make(map[string]int) + ruleIndex := make(map[string]int) for index, rule := range spec.Rules { ruleIndex[rule.Name] = index } diff --git a/pkg/background/common/errors.go b/pkg/background/common/errors.go index f8c6434190..488a39e9b1 100644 --- a/pkg/background/common/errors.go +++ b/pkg/background/common/errors.go @@ -60,7 +60,7 @@ func (e *ConfigNotFoundError) Error() string { return fmt.Sprintf("configuration %v, not present in resource %s/%s/%s", e.config, e.kind, e.namespace, e.name) } -//NewConfigNotFound returns a new NewConfigNotFound error +// NewConfigNotFound returns a new NewConfigNotFound error func NewConfigNotFound(config interface{}, kind, namespace, name string) *ConfigNotFoundError { return &ConfigNotFoundError{config: config, kind: kind, namespace: namespace, name: name} } diff --git a/pkg/background/common/status.go b/pkg/background/common/status.go index 585a059ffc..dd9e751eba 100644 --- a/pkg/background/common/status.go +++ b/pkg/background/common/status.go @@ -9,7 +9,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/log" ) -//StatusControlInterface provides interface to update status subresource +// StatusControlInterface provides interface to update status subresource type StatusControlInterface interface { Failed(ur urkyverno.UpdateRequest, message string, genResources []kyverno.ResourceSpec) error Success(ur urkyverno.UpdateRequest, genResources []kyverno.ResourceSpec) error @@ -21,7 +21,7 @@ type StatusControl struct { Client kyvernoclient.Interface } -//Failed sets ur status.state to failed with message +// Failed sets ur status.state to failed with message func (sc StatusControl) Failed(ur urkyverno.UpdateRequest, message string, genResources []kyverno.ResourceSpec) error { genR := &urkyverno.UpdateRequestStatus{ State: urkyverno.Failed, diff --git a/pkg/background/generate/cleanup/controller.go b/pkg/background/generate/cleanup/controller.go index 3a9c9ec645..c4c8ea1a4a 100644 --- a/pkg/background/generate/cleanup/controller.go +++ b/pkg/background/generate/cleanup/controller.go @@ -29,9 +29,8 @@ const ( maxRetries = 10 ) -//Controller manages life-cycle of generate-requests +// Controller manages life-cycle of generate-requests type Controller struct { - // dynamic client implementation client dclient.Interface @@ -63,7 +62,7 @@ type Controller struct { log logr.Logger } -//NewController returns a new controller instance to manage generate-requests +// NewController returns a new controller instance to manage generate-requests func NewController( kubeClient kubernetes.Interface, kyvernoclient kyvernoclient.Interface, @@ -184,7 +183,7 @@ func (c *Controller) enqueue(ur *urkyverno.UpdateRequest) { c.queue.Add(key) } -//Run starts the update-request re-conciliation loop +// Run starts the update-request re-conciliation loop func (c *Controller) Run(workers int, stopCh <-chan struct{}) { logger := c.log defer utilruntime.HandleCrash() diff --git a/pkg/background/generate/cleanup/resource.go b/pkg/background/generate/cleanup/resource.go index b0515ff698..016e21b015 100644 --- a/pkg/background/generate/cleanup/resource.go +++ b/pkg/background/generate/cleanup/resource.go @@ -13,12 +13,12 @@ type ControlInterface interface { Delete(gr string) error } -//Control provides implementation to manage resource +// Control provides implementation to manage resource type Control struct { client kyvernoclient.Interface } -//Delete deletes the specified resource +// Delete deletes the specified resource func (c Control) Delete(gr string) error { return c.client.KyvernoV1beta1().UpdateRequests(config.KyvernoNamespace()).Delete(context.TODO(), gr, metav1.DeleteOptions{}) } diff --git a/pkg/background/generate/generate.go b/pkg/background/generate/generate.go index 2cb9919be9..6e2f65926f 100644 --- a/pkg/background/generate/generate.go +++ b/pkg/background/generate/generate.go @@ -66,7 +66,7 @@ type GenerateController struct { Config config.Configuration } -//NewGenerateController returns an instance of the Generate-Request Controller +// NewGenerateController returns an instance of the Generate-Request Controller func NewGenerateController( kyvernoClient kyvernoclient.Interface, client dclient.Interface, @@ -609,11 +609,11 @@ func manageClone(log logr.Logger, apiVersion, kind, namespace, name, policy stri type ResourceMode string const ( - //Skip : failed to process rule, will not update the resource + // Skip : failed to process rule, will not update the resource Skip ResourceMode = "SKIP" - //Create : create a new resource + // Create : create a new resource Create = "CREATE" - //Update : update/overwrite the new resource + // Update : update/overwrite the new resource Update = "UPDATE" ) diff --git a/pkg/background/mutate/mutate.go b/pkg/background/mutate/mutate.go index 025aa5f364..378fbe83a8 100644 --- a/pkg/background/mutate/mutate.go +++ b/pkg/background/mutate/mutate.go @@ -216,7 +216,7 @@ func addAnnotation(policy kyvernov1.PolicyInterface, patched *unstructured.Unstr rulePatches = append(rulePatches, rp) } - var annotationContent = make(map[string]string) + annotationContent := make(map[string]string) policyName := policy.GetName() if policy.GetNamespace() != "" { policyName = policy.GetNamespace() + "/" + policy.GetName() diff --git a/pkg/background/update_request_controller.go b/pkg/background/update_request_controller.go index c59f59ce84..e012909f21 100644 --- a/pkg/background/update_request_controller.go +++ b/pkg/background/update_request_controller.go @@ -69,7 +69,7 @@ type Controller struct { Config config.Configuration } -//NewController returns an instance of the Generate-Request Controller +// NewController returns an instance of the Generate-Request Controller func NewController( kubeClient kubernetes.Interface, kyvernoClient kyvernoclient.Interface, diff --git a/pkg/config/config.go b/pkg/config/config.go index 04399d9ea1..f9b37be03b 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -28,23 +28,23 @@ const ( ValidatingWebhookConfigurationDebugName = "kyverno-resource-validating-webhook-cfg-debug" // ValidatingWebhookName ... ValidatingWebhookName = "validate.kyverno.svc" - //VerifyMutatingWebhookConfigurationName default verify mutating webhook configuration name + // VerifyMutatingWebhookConfigurationName default verify mutating webhook configuration name VerifyMutatingWebhookConfigurationName = "kyverno-verify-mutating-webhook-cfg" - //VerifyMutatingWebhookConfigurationDebugName default verify mutating webhook configuration name for debug mode + // VerifyMutatingWebhookConfigurationDebugName default verify mutating webhook configuration name for debug mode VerifyMutatingWebhookConfigurationDebugName = "kyverno-verify-mutating-webhook-cfg-debug" - //VerifyMutatingWebhookName default verify mutating webhook name + // VerifyMutatingWebhookName default verify mutating webhook name VerifyMutatingWebhookName = "monitor-webhooks.kyverno.svc" - //PolicyValidatingWebhookConfigurationName default policy validating webhook configuration name + // PolicyValidatingWebhookConfigurationName default policy validating webhook configuration name PolicyValidatingWebhookConfigurationName = "kyverno-policy-validating-webhook-cfg" - //PolicyValidatingWebhookConfigurationDebugName default policy validating webhook configuration name for debug mode + // PolicyValidatingWebhookConfigurationDebugName default policy validating webhook configuration name for debug mode PolicyValidatingWebhookConfigurationDebugName = "kyverno-policy-validating-webhook-cfg-debug" - //PolicyValidatingWebhookName default policy validating webhook name + // PolicyValidatingWebhookName default policy validating webhook name PolicyValidatingWebhookName = "validate-policy.kyverno.svc" - //PolicyMutatingWebhookConfigurationName default policy mutating webhook configuration name + // PolicyMutatingWebhookConfigurationName default policy mutating webhook configuration name PolicyMutatingWebhookConfigurationName = "kyverno-policy-mutating-webhook-cfg" - //PolicyMutatingWebhookConfigurationDebugName default policy mutating webhook configuration name for debug mode + // PolicyMutatingWebhookConfigurationDebugName default policy mutating webhook configuration name for debug mode PolicyMutatingWebhookConfigurationDebugName = "kyverno-policy-mutating-webhook-cfg-debug" - //PolicyMutatingWebhookName default policy mutating webhook name + // PolicyMutatingWebhookName default policy mutating webhook name PolicyMutatingWebhookName = "mutate-policy.kyverno.svc" // Due to kubernetes issue, we must use next literal constants instead of deployment TypeMeta fields // Issue: https://github.com/kubernetes/kubernetes/pull/63972 @@ -53,15 +53,15 @@ const ( ClusterRoleAPIVersion = "rbac.authorization.k8s.io/v1" // ClusterRoleKind define the default clusterrole resource kind ClusterRoleKind = "ClusterRole" - //MutatingWebhookServicePath is the path for mutation webhook + // MutatingWebhookServicePath is the path for mutation webhook MutatingWebhookServicePath = "/mutate" - //ValidatingWebhookServicePath is the path for validation webhook + // ValidatingWebhookServicePath is the path for validation webhook ValidatingWebhookServicePath = "/validate" - //PolicyValidatingWebhookServicePath is the path for policy validation webhook(used to validate policy resource) + // PolicyValidatingWebhookServicePath is the path for policy validation webhook(used to validate policy resource) PolicyValidatingWebhookServicePath = "/policyvalidate" - //PolicyMutatingWebhookServicePath is the path for policy mutation webhook(used to default) + // PolicyMutatingWebhookServicePath is the path for policy mutation webhook(used to default) PolicyMutatingWebhookServicePath = "/policymutate" - //VerifyMutatingWebhookServicePath is the path for verify webhook(used to veryfing if admission control is enabled and active) + // VerifyMutatingWebhookServicePath is the path for verify webhook(used to veryfing if admission control is enabled and active) VerifyMutatingWebhookServicePath = "/verifymutate" // LivenessServicePath is the path for check liveness health LivenessServicePath = "/health/liveness" diff --git a/pkg/config/filter.go b/pkg/config/filter.go index 96ec4ee50e..a3126cdc61 100644 --- a/pkg/config/filter.go +++ b/pkg/config/filter.go @@ -6,7 +6,7 @@ import ( ) type filter struct { - Kind string //TODO: as we currently only support one GVK version, we use the kind only. But if we support multiple GVK, then GV need to be added + Kind string // TODO: as we currently only support one GVK version, we use the kind only. But if we support multiple GVK, then GV need to be added Namespace string Name string } diff --git a/pkg/cosign/client.go b/pkg/cosign/client.go index 988d1db5f8..981165025f 100644 --- a/pkg/cosign/client.go +++ b/pkg/cosign/client.go @@ -16,8 +16,7 @@ type Cosign interface { VerifyImageAttestations(ctx context.Context, signedImgRef name.Reference, co *cosign.CheckOpts) (checkedAttestations []oci.Signature, bundleVerified bool, err error) } -type driver struct { -} +type driver struct{} func (d *driver) VerifyImageSignatures(ctx context.Context, signedImgRef name.Reference, co *cosign.CheckOpts) ([]oci.Signature, bool, error) { return cosign.VerifyImageSignatures(ctx, signedImgRef, co) diff --git a/pkg/cosign/cosign.go b/pkg/cosign/cosign.go index 1848af8591..52e28c4128 100644 --- a/pkg/cosign/cosign.go +++ b/pkg/cosign/cosign.go @@ -356,7 +356,7 @@ func stringToJSONMap(i interface{}) (map[string]interface{}, error) { return nil, fmt.Errorf("expected string type") } - var data = map[string]interface{}{} + data := map[string]interface{}{} if err := json.Unmarshal([]byte(s), &data); err != nil { return nil, fmt.Errorf("failed to marshal JSON: %s", err.Error()) } diff --git a/pkg/dclient/mock.go b/pkg/dclient/mock.go index c77654d40b..147cfb2fa6 100644 --- a/pkg/dclient/mock.go +++ b/pkg/dclient/mock.go @@ -7,7 +7,7 @@ import ( kubefake "k8s.io/client-go/kubernetes/fake" ) -//NewMockClient ---testing utilities +// NewMockClient ---testing utilities func NewMockClient(scheme *runtime.Scheme, gvrToListKind map[schema.GroupVersionResource]string, objects ...runtime.Object) (Interface, error) { c := fake.NewSimpleDynamicClientWithCustomListKinds(scheme, gvrToListKind, objects...) // the typed and dynamic client are initialized with similar resources diff --git a/pkg/engine/anchor/common.go b/pkg/engine/anchor/common.go index df53c78fac..5500a26d55 100644 --- a/pkg/engine/anchor/common.go +++ b/pkg/engine/anchor/common.go @@ -8,7 +8,7 @@ import ( // IsAnchor is a function handler type IsAnchor func(str string) bool -//IsConditionAnchor checks for condition anchor +// IsConditionAnchor checks for condition anchor func IsConditionAnchor(str string) bool { if len(str) < 2 { return false @@ -17,7 +17,7 @@ func IsConditionAnchor(str string) bool { return (str[0] == '(' && str[len(str)-1] == ')') } -//IsGlobalAnchor checks for global condition anchor +// IsGlobalAnchor checks for global condition anchor func IsGlobalAnchor(str string) bool { left := "<(" right := ")" @@ -30,20 +30,20 @@ func IsGlobalAnchor(str string) bool { return leftMatch && rightMatch } -//ContainsCondition returns true, if str is either condition anchor or +// ContainsCondition returns true, if str is either condition anchor or // global condition anchor func ContainsCondition(str string) bool { return IsConditionAnchor(str) || IsGlobalAnchor(str) } -//IsNegationAnchor checks for negation anchor +// IsNegationAnchor checks for negation anchor func IsNegationAnchor(str string) bool { left := "X(" right := ")" if len(str) < len(left)+len(right) { return false } - //TODO: trim spaces ? + // TODO: trim spaces ? return (str[:len(left)] == left && str[len(str)-len(right):] == right) } @@ -66,11 +66,11 @@ func IsEqualityAnchor(str string) bool { if len(str) < len(left)+len(right) { return false } - //TODO: trim spaces ? + // TODO: trim spaces ? return (str[:len(left)] == left && str[len(str)-len(right):] == right) } -//IsExistenceAnchor checks for existence anchor +// IsExistenceAnchor checks for existence anchor func IsExistenceAnchor(str string) bool { left := "^(" right := ")" diff --git a/pkg/engine/context/mock_context.go b/pkg/engine/context/mock_context.go index 2baf298df4..99d3df7442 100644 --- a/pkg/engine/context/mock_context.go +++ b/pkg/engine/context/mock_context.go @@ -10,14 +10,14 @@ import ( "github.com/kyverno/kyverno/pkg/engine/jmespath" ) -//MockContext is used for testing and validation of variables +// MockContext is used for testing and validation of variables type MockContext struct { mutex sync.RWMutex re *regexp.Regexp allowedPatterns []string } -//NewMockContext creates a new MockContext that allows variables matching the supplied list of wildcard patterns +// NewMockContext creates a new MockContext that allows variables matching the supplied list of wildcard patterns func NewMockContext(re *regexp.Regexp, vars ...string) *MockContext { return &MockContext{re: re, allowedPatterns: vars} } @@ -31,7 +31,7 @@ func (ctx *MockContext) AddVariable(wildcardPattern string) { ctx.allowedPatterns = append(builtInVarsCopy, wildcardPattern) } -//Query the JSON context with JMESPATH search path +// Query the JSON context with JMESPATH search path func (ctx *MockContext) Query(query string) (interface{}, error) { query = strings.TrimSpace(query) if query == "" { diff --git a/pkg/engine/imageVerify.go b/pkg/engine/imageVerify.go index 48b9fc43a3..5bf885535f 100644 --- a/pkg/engine/imageVerify.go +++ b/pkg/engine/imageVerify.go @@ -441,7 +441,7 @@ func (iv *imageVerifier) buildOptionsAndPath(attestor v1.Attestor, imageVerify v } func makeAddDigestPatch(imageInfo apiutils.ImageInfo, digest string) ([]byte, error) { - var patch = make(map[string]interface{}) + patch := make(map[string]interface{}) patch["op"] = "replace" patch["path"] = imageInfo.Pointer patch["value"] = imageInfo.String() + "@" + digest diff --git a/pkg/engine/imageVerifyMetadata.go b/pkg/engine/imageVerifyMetadata.go index bc8a97c19d..98c2969673 100644 --- a/pkg/engine/imageVerifyMetadata.go +++ b/pkg/engine/imageVerifyMetadata.go @@ -49,7 +49,7 @@ func parseImageMetadata(jsonData string) (*ImageVerificationMetadata, error) { func (ivm *ImageVerificationMetadata) Patches(hasAnnotations bool, log logr.Logger) ([][]byte, error) { var patches [][]byte if !hasAnnotations { - var addAnnotationsPatch = make(map[string]interface{}) + addAnnotationsPatch := make(map[string]interface{}) addAnnotationsPatch["op"] = "add" addAnnotationsPatch["path"] = "/metadata/annotations" addAnnotationsPatch["value"] = map[string]string{} @@ -67,7 +67,7 @@ func (ivm *ImageVerificationMetadata) Patches(hasAnnotations bool, log logr.Logg return nil, errors.Wrapf(err, "failed to marshal metadata value: %v", data) } - var addKeyPatch = make(map[string]interface{}) + addKeyPatch := make(map[string]interface{}) addKeyPatch["op"] = "add" addKeyPatch["path"] = makeAnnotationKeyForJSONPatch() addKeyPatch["value"] = string(data) diff --git a/pkg/engine/jmespath/functions.go b/pkg/engine/jmespath/functions.go index ecfd336eb3..d103c0ec84 100644 --- a/pkg/engine/jmespath/functions.go +++ b/pkg/engine/jmespath/functions.go @@ -67,12 +67,14 @@ var ( objectFromLists = "object_from_lists" ) -const errorPrefix = "JMESPath function '%s': " -const invalidArgumentTypeError = errorPrefix + "%d argument is expected of %s type" -const genericError = errorPrefix + "%s" -const zeroDivisionError = errorPrefix + "Zero divisor passed" -const undefinedQuoError = errorPrefix + "Undefined quotient" -const nonIntModuloError = errorPrefix + "Non-integer argument(s) passed for modulo" +const ( + errorPrefix = "JMESPath function '%s': " + invalidArgumentTypeError = errorPrefix + "%d argument is expected of %s type" + genericError = errorPrefix + "%s" + zeroDivisionError = errorPrefix + "Zero divisor passed" + undefinedQuoError = errorPrefix + "Undefined quotient" + nonIntModuloError = errorPrefix + "Non-integer argument(s) passed for modulo" +) type FunctionEntry struct { Entry *gojmespath.FunctionEntry @@ -103,7 +105,8 @@ func (f *FunctionEntry) String() string { func GetFunctions() []*FunctionEntry { return []*FunctionEntry{ { - Entry: &gojmespath.FunctionEntry{Name: compare, + Entry: &gojmespath.FunctionEntry{ + Name: compare, Arguments: []ArgSpec{ {Types: []JpType{JpString}}, {Types: []JpType{JpString}}, @@ -113,7 +116,8 @@ func GetFunctions() []*FunctionEntry { ReturnType: []JpType{JpNumber}, }, { - Entry: &gojmespath.FunctionEntry{Name: equalFold, + Entry: &gojmespath.FunctionEntry{ + Name: equalFold, Arguments: []ArgSpec{ {Types: []JpType{JpString}}, {Types: []JpType{JpString}}, @@ -123,7 +127,8 @@ func GetFunctions() []*FunctionEntry { ReturnType: []JpType{JpBool}, }, { - Entry: &gojmespath.FunctionEntry{Name: replace, + Entry: &gojmespath.FunctionEntry{ + Name: replace, Arguments: []ArgSpec{ {Types: []JpType{JpString}}, {Types: []JpType{JpString}}, @@ -135,7 +140,8 @@ func GetFunctions() []*FunctionEntry { ReturnType: []JpType{JpString}, }, { - Entry: &gojmespath.FunctionEntry{Name: replaceAll, + Entry: &gojmespath.FunctionEntry{ + Name: replaceAll, Arguments: []ArgSpec{ {Types: []JpType{JpString}}, {Types: []JpType{JpString}}, @@ -146,7 +152,8 @@ func GetFunctions() []*FunctionEntry { ReturnType: []JpType{JpString}, }, { - Entry: &gojmespath.FunctionEntry{Name: toUpper, + Entry: &gojmespath.FunctionEntry{ + Name: toUpper, Arguments: []ArgSpec{ {Types: []JpType{JpString}}, }, @@ -155,7 +162,8 @@ func GetFunctions() []*FunctionEntry { ReturnType: []JpType{JpString}, }, { - Entry: &gojmespath.FunctionEntry{Name: toLower, + Entry: &gojmespath.FunctionEntry{ + Name: toLower, Arguments: []ArgSpec{ {Types: []JpType{JpString}}, }, @@ -164,7 +172,8 @@ func GetFunctions() []*FunctionEntry { ReturnType: []JpType{JpString}, }, { - Entry: &gojmespath.FunctionEntry{Name: trim, + Entry: &gojmespath.FunctionEntry{ + Name: trim, Arguments: []ArgSpec{ {Types: []JpType{JpString}}, {Types: []JpType{JpString}}, @@ -174,7 +183,8 @@ func GetFunctions() []*FunctionEntry { ReturnType: []JpType{JpString}, }, { - Entry: &gojmespath.FunctionEntry{Name: split, + Entry: &gojmespath.FunctionEntry{ + Name: split, Arguments: []ArgSpec{ {Types: []JpType{JpString}}, {Types: []JpType{JpString}}, @@ -184,7 +194,8 @@ func GetFunctions() []*FunctionEntry { ReturnType: []JpType{JpArrayString}, }, { - Entry: &gojmespath.FunctionEntry{Name: regexReplaceAll, + Entry: &gojmespath.FunctionEntry{ + Name: regexReplaceAll, Arguments: []ArgSpec{ {Types: []JpType{JpString}}, {Types: []JpType{JpString, JpNumber}}, @@ -196,7 +207,8 @@ func GetFunctions() []*FunctionEntry { Note: "converts all parameters to string", }, { - Entry: &gojmespath.FunctionEntry{Name: regexReplaceAllLiteral, + Entry: &gojmespath.FunctionEntry{ + Name: regexReplaceAllLiteral, Arguments: []ArgSpec{ {Types: []JpType{JpString}}, {Types: []JpType{JpString, JpNumber}}, @@ -208,7 +220,8 @@ func GetFunctions() []*FunctionEntry { Note: "converts all parameters to string", }, { - Entry: &gojmespath.FunctionEntry{Name: regexMatch, + Entry: &gojmespath.FunctionEntry{ + Name: regexMatch, Arguments: []ArgSpec{ {Types: []JpType{JpString}}, {Types: []JpType{JpString, JpNumber}}, @@ -218,7 +231,8 @@ func GetFunctions() []*FunctionEntry { ReturnType: []JpType{JpBool}, }, { - Entry: &gojmespath.FunctionEntry{Name: patternMatch, + Entry: &gojmespath.FunctionEntry{ + Name: patternMatch, Arguments: []ArgSpec{ {Types: []JpType{JpString}}, {Types: []JpType{JpString, JpNumber}}, @@ -230,7 +244,8 @@ func GetFunctions() []*FunctionEntry { }, { // Validates if label (param1) would match pod/host/etc labels (param2) - Entry: &gojmespath.FunctionEntry{Name: labelMatch, + Entry: &gojmespath.FunctionEntry{ + Name: labelMatch, Arguments: []ArgSpec{ {Types: []JpType{JpObject}}, {Types: []JpType{JpObject}}, @@ -241,7 +256,8 @@ func GetFunctions() []*FunctionEntry { Note: "object arguments must be enclosed in backticks; ex. `{{request.object.spec.template.metadata.labels}}`", }, { - Entry: &gojmespath.FunctionEntry{Name: add, + Entry: &gojmespath.FunctionEntry{ + Name: add, Arguments: []ArgSpec{ {Types: []JpType{JpAny}}, {Types: []JpType{JpAny}}, @@ -251,7 +267,8 @@ func GetFunctions() []*FunctionEntry { ReturnType: []JpType{JpAny}, }, { - Entry: &gojmespath.FunctionEntry{Name: subtract, + Entry: &gojmespath.FunctionEntry{ + Name: subtract, Arguments: []ArgSpec{ {Types: []JpType{JpAny}}, {Types: []JpType{JpAny}}, @@ -261,7 +278,8 @@ func GetFunctions() []*FunctionEntry { ReturnType: []JpType{JpAny}, }, { - Entry: &gojmespath.FunctionEntry{Name: multiply, + Entry: &gojmespath.FunctionEntry{ + Name: multiply, Arguments: []ArgSpec{ {Types: []JpType{JpAny}}, {Types: []JpType{JpAny}}, @@ -271,7 +289,8 @@ func GetFunctions() []*FunctionEntry { ReturnType: []JpType{JpAny}, }, { - Entry: &gojmespath.FunctionEntry{Name: divide, + Entry: &gojmespath.FunctionEntry{ + Name: divide, Arguments: []ArgSpec{ {Types: []JpType{JpAny}}, {Types: []JpType{JpAny}}, @@ -282,7 +301,8 @@ func GetFunctions() []*FunctionEntry { Note: "divisor must be non zero", }, { - Entry: &gojmespath.FunctionEntry{Name: modulo, + Entry: &gojmespath.FunctionEntry{ + Name: modulo, Arguments: []ArgSpec{ {Types: []JpType{JpAny}}, {Types: []JpType{JpAny}}, @@ -293,7 +313,8 @@ func GetFunctions() []*FunctionEntry { Note: "divisor must be non-zero, arguments must be integers", }, { - Entry: &gojmespath.FunctionEntry{Name: base64Decode, + Entry: &gojmespath.FunctionEntry{ + Name: base64Decode, Arguments: []ArgSpec{ {Types: []JpType{JpString}}, }, @@ -302,7 +323,8 @@ func GetFunctions() []*FunctionEntry { ReturnType: []JpType{JpString}, }, { - Entry: &gojmespath.FunctionEntry{Name: base64Encode, + Entry: &gojmespath.FunctionEntry{ + Name: base64Encode, Arguments: []ArgSpec{ {Types: []JpType{JpString}}, }, @@ -311,7 +333,8 @@ func GetFunctions() []*FunctionEntry { ReturnType: []JpType{JpString}, }, { - Entry: &gojmespath.FunctionEntry{Name: timeSince, + Entry: &gojmespath.FunctionEntry{ + Name: timeSince, Arguments: []ArgSpec{ {Types: []JpType{JpString}}, {Types: []JpType{JpString}}, @@ -322,7 +345,8 @@ func GetFunctions() []*FunctionEntry { ReturnType: []JpType{JpString}, }, { - Entry: &gojmespath.FunctionEntry{Name: pathCanonicalize, + Entry: &gojmespath.FunctionEntry{ + Name: pathCanonicalize, Arguments: []ArgSpec{ {Types: []JpType{JpString}}, }, @@ -331,7 +355,8 @@ func GetFunctions() []*FunctionEntry { ReturnType: []JpType{JpString}, }, { - Entry: &gojmespath.FunctionEntry{Name: truncate, + Entry: &gojmespath.FunctionEntry{ + Name: truncate, Arguments: []ArgSpec{ {Types: []JpType{JpString}}, {Types: []JpType{JpNumber}}, @@ -342,7 +367,8 @@ func GetFunctions() []*FunctionEntry { Note: "length argument must be enclosed in backticks; ex. \"{{request.object.metadata.name | truncate(@, `9`)}}\"", }, { - Entry: &gojmespath.FunctionEntry{Name: semverCompare, + Entry: &gojmespath.FunctionEntry{ + Name: semverCompare, Arguments: []ArgSpec{ {Types: []JpType{JpString}}, {Types: []JpType{JpString}}, @@ -352,7 +378,8 @@ func GetFunctions() []*FunctionEntry { ReturnType: []JpType{JpBool}, }, { - Entry: &gojmespath.FunctionEntry{Name: parseJson, + Entry: &gojmespath.FunctionEntry{ + Name: parseJson, Arguments: []ArgSpec{ {Types: []JpType{JpString}}, }, @@ -362,7 +389,8 @@ func GetFunctions() []*FunctionEntry { Note: "decodes a valid JSON encoded string to the appropriate type. Opposite of `to_string` function", }, { - Entry: &gojmespath.FunctionEntry{Name: parseYAML, + Entry: &gojmespath.FunctionEntry{ + Name: parseYAML, Arguments: []ArgSpec{ {Types: []JpType{JpString}}, }, @@ -372,7 +400,8 @@ func GetFunctions() []*FunctionEntry { Note: "decodes a valid YAML encoded string to the appropriate type provided it can be represented as JSON", }, { - Entry: &gojmespath.FunctionEntry{Name: items, + Entry: &gojmespath.FunctionEntry{ + Name: items, Arguments: []ArgSpec{ {Types: []JpType{JpObject}}, {Types: []JpType{JpString}}, @@ -384,7 +413,8 @@ func GetFunctions() []*FunctionEntry { Note: "converts a map to an array of objects where each key:value is an item in the array", }, { - Entry: &gojmespath.FunctionEntry{Name: objectFromLists, + Entry: &gojmespath.FunctionEntry{ + Name: objectFromLists, Arguments: []ArgSpec{ {Types: []JpType{JpArray}}, {Types: []JpType{JpArray}}, diff --git a/pkg/engine/operator/operator.go b/pkg/engine/operator/operator.go index 60b3e999a3..894d659b34 100644 --- a/pkg/engine/operator/operator.go +++ b/pkg/engine/operator/operator.go @@ -26,7 +26,7 @@ const ( NotInRange Operator = "!-" ) -//ReferenceSign defines the operator for anchor reference +// ReferenceSign defines the operator for anchor reference const ReferenceSign Operator = "$()" // GetOperatorFromStringPattern parses opeartor from pattern diff --git a/pkg/engine/response/response.go b/pkg/engine/response/response.go index f84b11c189..cb3b18d3c0 100644 --- a/pkg/engine/response/response.go +++ b/pkg/engine/response/response.go @@ -9,7 +9,7 @@ import ( "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" ) -//EngineResponse engine response to the action +// EngineResponse engine response to the action type EngineResponse struct { // Resource patched with the engine action changes PatchedResource unstructured.Unstructured @@ -21,7 +21,7 @@ type EngineResponse struct { PolicyResponse PolicyResponse } -//PolicyResponse policy application response +// PolicyResponse policy application response type PolicyResponse struct { // policy details Policy PolicySpec `json:"policy"` @@ -37,13 +37,13 @@ type PolicyResponse struct { ValidationFailureActionOverrides []ValidationFailureActionOverride } -//PolicySpec policy +// PolicySpec policy type PolicySpec struct { Name string `json:"name"` Namespace string `json:"namespace"` } -//ResourceSpec resource action applied on +// ResourceSpec resource action applied on type ResourceSpec struct { Kind string `json:"kind"` APIVersion string `json:"apiVersion"` @@ -55,14 +55,13 @@ type ResourceSpec struct { UID string `json:"uid"` } -//GetKey returns the key +// GetKey returns the key func (rs ResourceSpec) GetKey() string { return rs.Kind + "/" + rs.Namespace + "/" + rs.Name } -//PolicyStats stores statistics for the single policy application +// PolicyStats stores statistics for the single policy application type PolicyStats struct { - // time required to process the policy rules on a resource ProcessingTime time.Duration `json:"processingTime"` @@ -79,19 +78,18 @@ type PolicyStats struct { type RuleType string const ( - //Mutation type for mutation rule + // Mutation type for mutation rule Mutation RuleType = "Mutation" - //Validation type for validation rule + // Validation type for validation rule Validation RuleType = "Validation" - //Generation type for generation rule + // Generation type for generation rule Generation RuleType = "Generation" // ImageVerify type for image verification ImageVerify RuleType = "ImageVerify" ) -//RuleResponse details for each rule application +// RuleResponse details for each rule application type RuleResponse struct { - // rule name specified in policy Name string `json:"name"` @@ -114,12 +112,12 @@ type RuleResponse struct { PatchedTarget *unstructured.Unstructured } -//ToString ... +// ToString ... func (rr RuleResponse) ToString() string { return fmt.Sprintf("rule %s (%s): %v", rr.Name, rr.Type, rr.Message) } -//RuleStats stores the statistics for the single rule application +// RuleStats stores the statistics for the single rule application type RuleStats struct { // time required to apply the rule on the resource ProcessingTime time.Duration `json:"processingTime"` @@ -127,7 +125,7 @@ type RuleStats struct { RuleExecutionTimestamp int64 `json:"ruleExecutionTimestamp"` } -//IsSuccessful checks if any rule has failed or produced an error during execution +// IsSuccessful checks if any rule has failed or produced an error during execution func (er EngineResponse) IsSuccessful() bool { for _, r := range er.PolicyResponse.Rules { if r.Status == RuleStatusFail || r.Status == RuleStatusError { @@ -138,7 +136,7 @@ func (er EngineResponse) IsSuccessful() bool { return true } -//IsFailed checks if any rule has succeeded or not +// IsFailed checks if any rule has succeeded or not func (er EngineResponse) IsFailed() bool { for _, r := range er.PolicyResponse.Rules { if r.Status == RuleStatusFail { @@ -149,12 +147,12 @@ func (er EngineResponse) IsFailed() bool { return false } -//IsEmpty checks if any rule results are present +// IsEmpty checks if any rule results are present func (er EngineResponse) IsEmpty() bool { return len(er.PolicyResponse.Rules) == 0 } -//GetPatches returns all the patches joined +// GetPatches returns all the patches joined func (er EngineResponse) GetPatches() [][]byte { var patches [][]byte for _, r := range er.PolicyResponse.Rules { @@ -166,12 +164,12 @@ func (er EngineResponse) GetPatches() [][]byte { return patches } -//GetFailedRules returns failed rules +// GetFailedRules returns failed rules func (er EngineResponse) GetFailedRules() []string { return er.getRules(RuleStatusFail) } -//GetSuccessRules returns success rules +// GetSuccessRules returns success rules func (er EngineResponse) GetSuccessRules() []string { return er.getRules(RuleStatusPass) } diff --git a/pkg/engine/utils.go b/pkg/engine/utils.go index e9c8e2954b..8f6a655a0a 100644 --- a/pkg/engine/utils.go +++ b/pkg/engine/utils.go @@ -28,7 +28,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/log" ) -//EngineStats stores in the statistics for a single application of resource +// EngineStats stores in the statistics for a single application of resource type EngineStats struct { // average time required to process the policy rules on a resource ExecutionTime time.Duration @@ -268,7 +268,7 @@ func matchSubjects(ruleSubjects []rbacv1.Subject, userInfo authenticationv1.User } } -//MatchesResourceDescription checks if the resource matches resource description of the rule or not +// MatchesResourceDescription checks if the resource matches resource description of the rule or not func MatchesResourceDescription(resourceRef unstructured.Unstructured, ruleRef kyverno.Rule, admissionInfoRef urkyverno.RequestInfo, dynamicConfig []string, namespaceLabels map[string]string, policyNamespace string) error { rule := ruleRef.DeepCopy() resource := *resourceRef.DeepCopy() @@ -328,7 +328,7 @@ func MatchesResourceDescription(resourceRef unstructured.Unstructured, ruleRef k } // creating final error - var errorMessage = fmt.Sprintf("rule %s not matched:", ruleRef.Name) + errorMessage := fmt.Sprintf("rule %s not matched:", ruleRef.Name) for i, reasonForFailure := range reasonsForFailure { if reasonForFailure != nil { errorMessage += "\n " + fmt.Sprint(i+1) + ". " + reasonForFailure.Error() diff --git a/pkg/engine/utils/utils.go b/pkg/engine/utils/utils.go index 9c00f7e19a..4bc11f8a2c 100644 --- a/pkg/engine/utils/utils.go +++ b/pkg/engine/utils/utils.go @@ -35,7 +35,7 @@ func ApplyPatches(resource []byte, patches [][]byte) ([]byte, error) { return patchedDocument, err } -//ApplyPatchNew patches given resource with given joined patches +// ApplyPatchNew patches given resource with given joined patches func ApplyPatchNew(resource, patch []byte) ([]byte, error) { jsonpatch, err := jsonpatch.DecodePatch(patch) if err != nil { @@ -50,7 +50,7 @@ func ApplyPatchNew(resource, patch []byte) ([]byte, error) { return patchedResource, err } -//ConvertToUnstructured converts the resource to unstructured format +// ConvertToUnstructured converts the resource to unstructured format func ConvertToUnstructured(data []byte) (*unstructured.Unstructured, error) { resource := &unstructured.Unstructured{} err := resource.UnmarshalJSON(data) diff --git a/pkg/engine/validation.go b/pkg/engine/validation.go index 378982fc6d..e4294de528 100644 --- a/pkg/engine/validation.go +++ b/pkg/engine/validation.go @@ -24,7 +24,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/log" ) -//Validate applies validation rules from policy on the resource +// Validate applies validation rules from policy on the resource func Validate(policyContext *PolicyContext) (resp *response.EngineResponse) { resp = &response.EngineResponse{} startTime := time.Now() @@ -58,7 +58,7 @@ func buildResponse(ctx *PolicyContext, resp *response.EngineResponse, startTime if reflect.DeepEqual(resp.PatchedResource, unstructured.Unstructured{}) { // for delete requests patched resource will be oldResource since newResource is empty - var resource = ctx.NewResource + resource := ctx.NewResource if reflect.DeepEqual(ctx.NewResource, unstructured.Unstructured{}) { resource = ctx.OldResource } diff --git a/pkg/engine/variables/evaluate.go b/pkg/engine/variables/evaluate.go index 51c81df696..3fa6cb66a7 100644 --- a/pkg/engine/variables/evaluate.go +++ b/pkg/engine/variables/evaluate.go @@ -7,7 +7,7 @@ import ( "github.com/kyverno/kyverno/pkg/engine/variables/operator" ) -//Evaluate evaluates the condition +// Evaluate evaluates the condition func Evaluate(log logr.Logger, ctx context.EvalInterface, condition kyverno.Condition) bool { // get handler for the operator handle := operator.CreateOperatorHandler(log, ctx, condition.Operator) @@ -17,7 +17,7 @@ func Evaluate(log logr.Logger, ctx context.EvalInterface, condition kyverno.Cond return handle.Evaluate(condition.GetKey(), condition.GetValue()) } -//EvaluateConditions evaluates all the conditions present in a slice, in a backwards compatible way +// EvaluateConditions evaluates all the conditions present in a slice, in a backwards compatible way func EvaluateConditions(log logr.Logger, ctx context.EvalInterface, conditions interface{}) bool { switch typedConditions := conditions.(type) { case kyverno.AnyAllConditions: @@ -38,7 +38,7 @@ func EvaluateAnyAllConditions(log logr.Logger, ctx context.EvalInterface, condit return true } -//evaluateAnyAllConditions evaluates multiple conditions as a logical AND (all) or OR (any) operation depending on the conditions +// evaluateAnyAllConditions evaluates multiple conditions as a logical AND (all) or OR (any) operation depending on the conditions func evaluateAnyAllConditions(log logr.Logger, ctx context.EvalInterface, conditions kyverno.AnyAllConditions) bool { anyConditions, allConditions := conditions.AnyConditions, conditions.AllConditions anyConditionsResult, allConditionsResult := true, true @@ -66,7 +66,7 @@ func evaluateAnyAllConditions(log logr.Logger, ctx context.EvalInterface, condit return finalResult } -//evaluateOldConditions evaluates multiple conditions when those conditions are provided in the old manner i.e. without 'any' or 'all' +// evaluateOldConditions evaluates multiple conditions when those conditions are provided in the old manner i.e. without 'any' or 'all' func evaluateOldConditions(log logr.Logger, ctx context.EvalInterface, conditions []kyverno.Condition) bool { for _, condition := range conditions { if !Evaluate(log, ctx, condition) { diff --git a/pkg/engine/variables/operator/allin.go b/pkg/engine/variables/operator/allin.go index 25849fc4d3..4a5258130d 100644 --- a/pkg/engine/variables/operator/allin.go +++ b/pkg/engine/variables/operator/allin.go @@ -10,7 +10,7 @@ import ( "github.com/kyverno/kyverno/pkg/engine/operator" ) -//NewAllInHandler returns handler to manage AllIn operations +// NewAllInHandler returns handler to manage AllIn operations func NewAllInHandler(log logr.Logger, ctx context.EvalInterface) OperatorHandler { return AllInHandler{ ctx: ctx, @@ -18,13 +18,13 @@ func NewAllInHandler(log logr.Logger, ctx context.EvalInterface) OperatorHandler } } -//AllInHandler provides implementation to handle AllIn Operator +// AllInHandler provides implementation to handle AllIn Operator type AllInHandler struct { ctx context.EvalInterface log logr.Logger } -//Evaluate evaluates expression with AllIn Operator +// Evaluate evaluates expression with AllIn Operator func (allin AllInHandler) Evaluate(key, value interface{}) bool { switch typedKey := key.(type) { case string: diff --git a/pkg/engine/variables/operator/allnotin.go b/pkg/engine/variables/operator/allnotin.go index 16745da354..388cb4312a 100644 --- a/pkg/engine/variables/operator/allnotin.go +++ b/pkg/engine/variables/operator/allnotin.go @@ -7,7 +7,7 @@ import ( "github.com/kyverno/kyverno/pkg/engine/context" ) -//NewAllNotInHandler returns handler to manage AllNotIn operations +// NewAllNotInHandler returns handler to manage AllNotIn operations func NewAllNotInHandler(log logr.Logger, ctx context.EvalInterface) OperatorHandler { return AllNotInHandler{ ctx: ctx, @@ -15,13 +15,13 @@ func NewAllNotInHandler(log logr.Logger, ctx context.EvalInterface) OperatorHand } } -//AllNotInHandler provides implementation to handle AllNotIn Operator +// AllNotInHandler provides implementation to handle AllNotIn Operator type AllNotInHandler struct { ctx context.EvalInterface log logr.Logger } -//Evaluate evaluates expression with AllNotIn Operator +// Evaluate evaluates expression with AllNotIn Operator func (allnin AllNotInHandler) Evaluate(key, value interface{}) bool { switch typedKey := key.(type) { case string: diff --git a/pkg/engine/variables/operator/anyin.go b/pkg/engine/variables/operator/anyin.go index de5b284b60..b99fd7f733 100644 --- a/pkg/engine/variables/operator/anyin.go +++ b/pkg/engine/variables/operator/anyin.go @@ -12,7 +12,7 @@ import ( "github.com/kyverno/kyverno/pkg/engine/operator" ) -//NewAnyInHandler returns handler to manage AnyIn operations +// NewAnyInHandler returns handler to manage AnyIn operations func NewAnyInHandler(log logr.Logger, ctx context.EvalInterface) OperatorHandler { return AnyInHandler{ ctx: ctx, @@ -20,13 +20,13 @@ func NewAnyInHandler(log logr.Logger, ctx context.EvalInterface) OperatorHandler } } -//AnyInHandler provides implementation to handle AnyIn Operator +// AnyInHandler provides implementation to handle AnyIn Operator type AnyInHandler struct { ctx context.EvalInterface log logr.Logger } -//Evaluate evaluates expression with AnyIn Operator +// Evaluate evaluates expression with AnyIn Operator func (anyin AnyInHandler) Evaluate(key, value interface{}) bool { switch typedKey := key.(type) { case string: diff --git a/pkg/engine/variables/operator/anynotin.go b/pkg/engine/variables/operator/anynotin.go index 257b71f8e3..a0992c3962 100644 --- a/pkg/engine/variables/operator/anynotin.go +++ b/pkg/engine/variables/operator/anynotin.go @@ -7,7 +7,7 @@ import ( "github.com/kyverno/kyverno/pkg/engine/context" ) -//NewAnyNotInHandler returns handler to manage AnyNotIn operations +// NewAnyNotInHandler returns handler to manage AnyNotIn operations func NewAnyNotInHandler(log logr.Logger, ctx context.EvalInterface) OperatorHandler { return AnyNotInHandler{ ctx: ctx, @@ -15,13 +15,13 @@ func NewAnyNotInHandler(log logr.Logger, ctx context.EvalInterface) OperatorHand } } -//AnyNotInHandler provides implementation to handle AnyNotIn Operator +// AnyNotInHandler provides implementation to handle AnyNotIn Operator type AnyNotInHandler struct { ctx context.EvalInterface log logr.Logger } -//Evaluate evaluates expression with AnyNotIn Operator +// Evaluate evaluates expression with AnyNotIn Operator func (anynin AnyNotInHandler) Evaluate(key, value interface{}) bool { switch typedKey := key.(type) { case string: diff --git a/pkg/engine/variables/operator/duration.go b/pkg/engine/variables/operator/duration.go index 0021aedd9e..115b6549aa 100644 --- a/pkg/engine/variables/operator/duration.go +++ b/pkg/engine/variables/operator/duration.go @@ -9,7 +9,7 @@ import ( "github.com/kyverno/kyverno/pkg/engine/context" ) -//NewDurationOperatorHandler returns handler to manage the provided duration operations (>, >=, <=, <) +// NewDurationOperatorHandler returns handler to manage the provided duration operations (>, >=, <=, <) func NewDurationOperatorHandler(log logr.Logger, ctx context.EvalInterface, op kyverno.ConditionOperator) OperatorHandler { return DurationOperatorHandler{ ctx: ctx, @@ -18,7 +18,7 @@ func NewDurationOperatorHandler(log logr.Logger, ctx context.EvalInterface, op k } } -//DurationOperatorHandler provides implementation to handle Duration Operations associated with policies +// DurationOperatorHandler provides implementation to handle Duration Operations associated with policies type DurationOperatorHandler struct { ctx context.EvalInterface log logr.Logger @@ -131,9 +131,11 @@ func (doh DurationOperatorHandler) validateValueWithStringPattern(key string, va func (doh DurationOperatorHandler) validateValueWithBoolPattern(key bool, value interface{}) bool { return false } + func (doh DurationOperatorHandler) validateValueWithMapPattern(key map[string]interface{}, value interface{}) bool { return false } + func (doh DurationOperatorHandler) validateValueWithSlicePattern(key []interface{}, value interface{}) bool { return false } diff --git a/pkg/engine/variables/operator/equal.go b/pkg/engine/variables/operator/equal.go index bd41df644a..cfa7552fed 100644 --- a/pkg/engine/variables/operator/equal.go +++ b/pkg/engine/variables/operator/equal.go @@ -12,7 +12,7 @@ import ( "k8s.io/apimachinery/pkg/api/resource" ) -//NewEqualHandler returns handler to manage Equal operations +// NewEqualHandler returns handler to manage Equal operations func NewEqualHandler(log logr.Logger, ctx context.EvalInterface) OperatorHandler { return EqualHandler{ ctx: ctx, @@ -20,13 +20,13 @@ func NewEqualHandler(log logr.Logger, ctx context.EvalInterface) OperatorHandler } } -//EqualHandler provides implementation to handle NotEqual Operator +// EqualHandler provides implementation to handle NotEqual Operator type EqualHandler struct { ctx context.EvalInterface log logr.Logger } -//Evaluate evaluates expression with Equal Operator +// Evaluate evaluates expression with Equal Operator func (eh EqualHandler) Evaluate(key, value interface{}) bool { // key and value need to be of same type switch typedKey := key.(type) { diff --git a/pkg/engine/variables/operator/notequal.go b/pkg/engine/variables/operator/notequal.go index 9ca7552054..14e4058151 100644 --- a/pkg/engine/variables/operator/notequal.go +++ b/pkg/engine/variables/operator/notequal.go @@ -12,7 +12,7 @@ import ( "k8s.io/apimachinery/pkg/api/resource" ) -//NewNotEqualHandler returns handler to manage NotEqual operations +// NewNotEqualHandler returns handler to manage NotEqual operations func NewNotEqualHandler(log logr.Logger, ctx context.EvalInterface) OperatorHandler { return NotEqualHandler{ ctx: ctx, @@ -20,13 +20,13 @@ func NewNotEqualHandler(log logr.Logger, ctx context.EvalInterface) OperatorHand } } -//NotEqualHandler provides implementation to handle NotEqual Operator +// NotEqualHandler provides implementation to handle NotEqual Operator type NotEqualHandler struct { ctx context.EvalInterface log logr.Logger } -//Evaluate evaluates expression with NotEqual Operator +// Evaluate evaluates expression with NotEqual Operator func (neh NotEqualHandler) Evaluate(key, value interface{}) bool { // key and value need to be of same type switch typedKey := key.(type) { diff --git a/pkg/engine/variables/operator/numeric.go b/pkg/engine/variables/operator/numeric.go index 0d1dd22407..2f58a01586 100644 --- a/pkg/engine/variables/operator/numeric.go +++ b/pkg/engine/variables/operator/numeric.go @@ -11,7 +11,7 @@ import ( "k8s.io/apimachinery/pkg/api/resource" ) -//NewNumericOperatorHandler returns handler to manage the provided numeric operations (>, >=, <=, <) +// NewNumericOperatorHandler returns handler to manage the provided numeric operations (>, >=, <=, <) func NewNumericOperatorHandler(log logr.Logger, ctx context.EvalInterface, op kyverno.ConditionOperator) OperatorHandler { return NumericOperatorHandler{ ctx: ctx, @@ -20,7 +20,7 @@ func NewNumericOperatorHandler(log logr.Logger, ctx context.EvalInterface, op ky } } -//NumericOperatorHandler provides implementation to handle Numeric Operations associated with policies +// NumericOperatorHandler provides implementation to handle Numeric Operations associated with policies type NumericOperatorHandler struct { ctx context.EvalInterface log logr.Logger @@ -210,9 +210,11 @@ func parseQuantity(key, value interface{}) (parsedKey, parsedValue resource.Quan func (noh NumericOperatorHandler) validateValueWithBoolPattern(key bool, value interface{}) bool { return false } + func (noh NumericOperatorHandler) validateValueWithMapPattern(key map[string]interface{}, value interface{}) bool { return false } + func (noh NumericOperatorHandler) validateValueWithSlicePattern(key []interface{}, value interface{}) bool { return false } diff --git a/pkg/engine/variables/operator/operator.go b/pkg/engine/variables/operator/operator.go index d29caca085..1ff289406b 100644 --- a/pkg/engine/variables/operator/operator.go +++ b/pkg/engine/variables/operator/operator.go @@ -10,7 +10,7 @@ import ( "github.com/kyverno/kyverno/pkg/engine/context" ) -//OperatorHandler provides interface to manage types +// OperatorHandler provides interface to manage types type OperatorHandler interface { Evaluate(key, value interface{}) bool validateValueWithStringPattern(key string, value interface{}) bool @@ -21,10 +21,10 @@ type OperatorHandler interface { validateValueWithSlicePattern(key []interface{}, value interface{}) bool } -//VariableSubstitutionHandler defines the handler function for variable substitution +// VariableSubstitutionHandler defines the handler function for variable substitution type VariableSubstitutionHandler = func(log logr.Logger, ctx context.EvalInterface, pattern interface{}) (interface{}, error) -//CreateOperatorHandler returns the operator handler based on the operator used in condition +// CreateOperatorHandler returns the operator handler based on the operator used in condition func CreateOperatorHandler(log logr.Logger, ctx context.EvalInterface, op kyverno.ConditionOperator) OperatorHandler { str := strings.ToLower(string(op)) switch str { diff --git a/pkg/engine/variables/vars.go b/pkg/engine/variables/vars.go index 756aeda99a..3f6d313ec4 100644 --- a/pkg/engine/variables/vars.go +++ b/pkg/engine/variables/vars.go @@ -157,7 +157,7 @@ func ConditionsToJSONObject(conditions []kyverno.AnyAllConditions) ([]map[string return nil, err } - var m = []map[string]interface{}{} + m := []map[string]interface{}{} if err := json.Unmarshal(bytes, &m); err != nil { return nil, err } @@ -317,7 +317,7 @@ func substituteReferencesIfAny(log logr.Logger) jsonUtils.Action { }) } -//VariableResolver defines the handler function for variable substitution +// VariableResolver defines the handler function for variable substitution type VariableResolver = func(ctx context.EvalInterface, variable string) (interface{}, error) // DefaultVariableResolver is used in all variable substitutions except preconditions @@ -364,7 +364,6 @@ func substituteVariablesIfAny(log logr.Logger, ctx context.EvalInterface, vr Var } substitutedVar, err := vr(ctx, variable) - if err != nil { switch err.(type) { case context.InvalidVariableError, gojmespath.NotFoundError: @@ -477,7 +476,7 @@ func resolveReference(log logr.Logger, fullDocument interface{}, reference, abso return err, nil } - if operation == operator.Equal { //if operator does not exist return raw value + if operation == operator.Equal { // if operator does not exist return raw value return valFromReference, nil } @@ -489,7 +488,7 @@ func resolveReference(log logr.Logger, fullDocument interface{}, reference, abso return string(operation) + foundValue.(string), nil } -//Parse value to string +// Parse value to string func valFromReferenceToString(value interface{}, operator string) (string, error) { switch typed := value.(type) { case string: diff --git a/pkg/event/controller.go b/pkg/event/controller.go index a53637ff29..3c0aa880f7 100644 --- a/pkg/event/controller.go +++ b/pkg/event/controller.go @@ -19,7 +19,7 @@ import ( "k8s.io/klog/v2" ) -//Generator generate events +// Generator generate events type Generator struct { client client.Interface // list/get cluster policy @@ -40,12 +40,12 @@ type Generator struct { log logr.Logger } -//Interface to generate event +// Interface to generate event type Interface interface { Add(infoList ...Info) } -//NewEventGenerator to generate a new event controller +// NewEventGenerator to generate a new event controller func NewEventGenerator(client client.Interface, cpInformer kyvernoinformer.ClusterPolicyInformer, pInformer kyvernoinformer.PolicyInformer, log logr.Logger) *Generator { gen := Generator{ client: client, @@ -93,7 +93,7 @@ func initRecorder(client client.Interface, eventSource Source, log logr.Logger) return recorder } -//Add queues an event for generation +// Add queues an event for generation func (gen *Generator) Add(infos ...Info) { logger := gen.log for _, info := range infos { diff --git a/pkg/event/reason.go b/pkg/event/reason.go index d4a6fc349d..8926a163df 100644 --- a/pkg/event/reason.go +++ b/pkg/event/reason.go @@ -1,6 +1,6 @@ package event -//Reason types of Event Reasons +// Reason types of Event Reasons type Reason int const ( diff --git a/pkg/event/source.go b/pkg/event/source.go index a91a3e8212..3e1dc5f447 100644 --- a/pkg/event/source.go +++ b/pkg/event/source.go @@ -1,6 +1,6 @@ package event -//Source of event generation +// Source of event generation type Source int const ( diff --git a/pkg/event/util.go b/pkg/event/util.go index a4268ba3a6..4e2ec4342a 100644 --- a/pkg/event/util.go +++ b/pkg/event/util.go @@ -4,7 +4,7 @@ const eventWorkQueueName = "kyverno-events" const workQueueRetryLimit = 10 -//Info defines the event details +// Info defines the event details type Info struct { Kind string Name string diff --git a/pkg/leaderelection/leaderelection.go b/pkg/leaderelection/leaderelection.go index 19ddcaebeb..cf0ddab586 100644 --- a/pkg/leaderelection/leaderelection.go +++ b/pkg/leaderelection/leaderelection.go @@ -15,7 +15,6 @@ import ( ) type Interface interface { - // Run is a blocking call that runs a leader election Run(ctx context.Context) @@ -66,7 +65,6 @@ func New(name, namespace string, kubeClient kubernetes.Interface, startWork, sto Identity: id, }, ) - if err != nil { return nil, errors.Wrapf(err, "error initializing resource lock: %s/%s", namespace, name) } @@ -111,7 +109,8 @@ func New(name, namespace string, kubeClient kubernetes.Interface, startWork, sto } e.log.WithValues("current id", e.lock.Identity(), "leader", identity).Info("another instance has been elected as leader") }, - }} + }, + } e.leaderElector, err = leaderelection.NewLeaderElector(e.leaderElectionCfg) if err != nil { diff --git a/pkg/metrics/policyexecutionduration/policyExecutionDuration.go b/pkg/metrics/policyexecutionduration/policyExecutionDuration.go index 04020fa979..ea542bffc3 100644 --- a/pkg/metrics/policyexecutionduration/policyExecutionDuration.go +++ b/pkg/metrics/policyexecutionduration/policyExecutionDuration.go @@ -58,8 +58,8 @@ func registerPolicyExecutionDurationMetric( return nil } -//policy - policy related data -//engineResponse - resource and rule related data +// policy - policy related data +// engineResponse - resource and rule related data func ProcessEngineResponse(pc *metrics.PromConfig, policy kyverno.PolicyInterface, engineResponse response.EngineResponse, executionCause metrics.RuleExecutionCause, generateRuleLatencyType string, resourceRequestOperation metrics.ResourceRequestOperation) error { name, namespace, policyType, backgroundMode, validationMode, err := metrics.GetPolicyInfos(policy) if err != nil { diff --git a/pkg/metrics/policyresults/policyResults.go b/pkg/metrics/policyresults/policyResults.go index 42bb592108..71ca6b24c4 100644 --- a/pkg/metrics/policyresults/policyResults.go +++ b/pkg/metrics/policyresults/policyResults.go @@ -52,8 +52,8 @@ func registerPolicyResultsMetric( return nil } -//policy - policy related data -//engineResponse - resource and rule related data +// policy - policy related data +// engineResponse - resource and rule related data func ProcessEngineResponse(pc *metrics.PromConfig, policy kyverno.PolicyInterface, engineResponse response.EngineResponse, executionCause metrics.RuleExecutionCause, resourceRequestOperation metrics.ResourceRequestOperation) error { name, namespace, policyType, backgroundMode, validationMode, err := metrics.GetPolicyInfos(policy) if err != nil { diff --git a/pkg/openapi/validation.go b/pkg/openapi/validation.go index ce84098212..89febffad5 100644 --- a/pkg/openapi/validation.go +++ b/pkg/openapi/validation.go @@ -136,7 +136,7 @@ func (o *Controller) ValidateResource(patchedResource unstructured.Unstructured, // ValidatePolicyMutation ... func (o *Controller) ValidatePolicyMutation(policy v1.PolicyInterface) error { - var kindToRules = make(map[string][]v1.Rule) + kindToRules := make(map[string][]v1.Rule) for _, rule := range autogen.ComputeRules(policy) { if rule.HasMutate() { for _, kind := range rule.MatchResources.Kinds { @@ -378,7 +378,7 @@ func getArrayValue(kindSchema *openapiv2.Schema, o *Controller) interface{} { } func getObjectValue(kindSchema *openapiv2.Schema, o *Controller) interface{} { - var props = make(map[string]interface{}) + props := make(map[string]interface{}) properties := kindSchema.GetProperties().GetAdditionalProperties() if len(properties) == 0 { return props diff --git a/pkg/policy/actions.go b/pkg/policy/actions.go index f180bed5bf..05a5c031bd 100644 --- a/pkg/policy/actions.go +++ b/pkg/policy/actions.go @@ -12,12 +12,12 @@ import ( "sigs.k8s.io/controller-runtime/pkg/log" ) -//Validation provides methods to validate a rule +// Validation provides methods to validate a rule type Validation interface { Validate() (string, error) } -//validateAction performs validation on the rule actions +// validateAction performs validation on the rule actions // - Mutate // - Validation // - Generate @@ -46,7 +46,7 @@ func validateActions(idx int, rule *kyverno.Rule, client dclient.Interface, mock // Generate if rule.HasGenerate() { - //TODO: this check is there to support offline validations + // TODO: this check is there to support offline validations // generate uses selfSubjectReviews to verify actions // this need to modified to use different implementation for online and offline mode if mock { diff --git a/pkg/policy/background.go b/pkg/policy/background.go index 46efd19589..a93976a297 100644 --- a/pkg/policy/background.go +++ b/pkg/policy/background.go @@ -8,7 +8,7 @@ import ( "github.com/kyverno/kyverno/pkg/autogen" ) -//ContainsUserVariables returns error if variable that does not start from request.object +// ContainsUserVariables returns error if variable that does not start from request.object func containsUserVariables(policy kyverno.PolicyInterface, vars [][]string) error { for _, rule := range policy.GetSpec().Rules { if rule.IsMutateExisting() { diff --git a/pkg/policy/common/validate_pattern.go b/pkg/policy/common/validate_pattern.go index affbca2133..de34838830 100644 --- a/pkg/policy/common/validate_pattern.go +++ b/pkg/policy/common/validate_pattern.go @@ -8,7 +8,7 @@ import ( commonAnchors "github.com/kyverno/kyverno/pkg/engine/anchor" ) -//ValidatePattern validates the pattern +// ValidatePattern validates the pattern func ValidatePattern(patternElement interface{}, path string, supportedAnchors []commonAnchors.IsAnchor) (string, error) { switch typedPatternElement := patternElement.(type) { case map[string]interface{}: @@ -16,12 +16,13 @@ func ValidatePattern(patternElement interface{}, path string, supportedAnchors [ case []interface{}: return validateArray(typedPatternElement, path, supportedAnchors) case string, float64, int, int64, bool, nil: - //TODO? check operator + // TODO: check operator return "", nil default: return path, fmt.Errorf("error at '%s', pattern contains unknown type", path) } } + func validateMap(patternMap map[string]interface{}, path string, supportedAnchors []commonAnchors.IsAnchor) (string, error) { // check if anchors are defined for key, value := range patternMap { diff --git a/pkg/policy/existing.go b/pkg/policy/existing.go index d80ca2b3d5..af617eab0b 100644 --- a/pkg/policy/existing.go +++ b/pkg/policy/existing.go @@ -99,11 +99,11 @@ func excludeAutoGenResources(policy kyverno.PolicyInterface, resourceMap map[str } } -//Condition defines condition type +// Condition defines condition type type Condition int const ( - //NotEvaluate to not evaluate condition + // NotEvaluate to not evaluate condition NotEvaluate Condition = 0 // Process to evaluate condition Process Condition = 1 @@ -111,7 +111,7 @@ const ( Skip Condition = 2 ) -//NewResourceManager returns a new ResourceManager +// NewResourceManager returns a new ResourceManager func NewResourceManager(rebuildTime int64) *ResourceManager { rm := ResourceManager{ scope: make(map[string]bool), @@ -136,14 +136,14 @@ type ResourceManager struct { type resourceManager interface { ProcessResource(policy, pv, kind, ns, name, rv string) bool - //TODO removeResource(kind, ns, name string) error + // TODO removeResource(kind, ns, name string) error RegisterResource(policy, pv, kind, ns, name, rv string) RegisterScope(kind string, namespaced bool) GetScope(kind string) (bool, error) Drop() } -//Drop drop the cache after every rebuild interval mins +// Drop drop the cache after every rebuild interval mins func (rm *ResourceManager) Drop() { timeSince := time.Since(rm.time) if timeSince > time.Duration(rm.rebuildTime)*time.Second { @@ -156,7 +156,7 @@ func (rm *ResourceManager) Drop() { var empty struct{} -//RegisterResource stores if the policy is processed on this resource version +// RegisterResource stores if the policy is processed on this resource version func (rm *ResourceManager) RegisterResource(policy, pv, kind, ns, name, rv string) { rm.mux.Lock() defer rm.mux.Unlock() @@ -165,7 +165,7 @@ func (rm *ResourceManager) RegisterResource(policy, pv, kind, ns, name, rv strin rm.data[key] = empty } -//ProcessResource returns true if the policy was not applied on the resource +// ProcessResource returns true if the policy was not applied on the resource func (rm *ResourceManager) ProcessResource(policy, pv, kind, ns, name, rv string) bool { rm.mux.RLock() defer rm.mux.RUnlock() diff --git a/pkg/policy/generate/auth.go b/pkg/policy/generate/auth.go index 65125a19d8..8fb9f9373e 100644 --- a/pkg/policy/generate/auth.go +++ b/pkg/policy/generate/auth.go @@ -6,7 +6,7 @@ import ( dclient "github.com/kyverno/kyverno/pkg/dclient" ) -//Operations provides methods to performing operations on resource +// Operations provides methods to performing operations on resource type Operations interface { // CanICreate returns 'true' if self can 'create' resource CanICreate(kind, namespace string) (bool, error) @@ -18,13 +18,13 @@ type Operations interface { CanIGet(kind, namespace string) (bool, error) } -//Auth provides implementation to check if caller/self/kyverno has access to perofrm operations +// Auth provides implementation to check if caller/self/kyverno has access to perofrm operations type Auth struct { client dclient.Interface log logr.Logger } -//NewAuth returns a new instance of Auth for operations +// NewAuth returns a new instance of Auth for operations func NewAuth(client dclient.Interface, log logr.Logger) *Auth { a := Auth{ client: client, diff --git a/pkg/policy/generate/fake.go b/pkg/policy/generate/fake.go index c767af671a..d0602d719a 100644 --- a/pkg/policy/generate/fake.go +++ b/pkg/policy/generate/fake.go @@ -6,13 +6,13 @@ import ( "sigs.k8s.io/controller-runtime/pkg/log" ) -//FakeGenerate provides implementation for generate rule processing +// FakeGenerate provides implementation for generate rule processing // with mocks/fakes for cluster interactions type FakeGenerate struct { Generate } -//NewFakeGenerate returns a new instance of generatecheck that uses +// NewFakeGenerate returns a new instance of generatecheck that uses // fake/mock implementation for operation access(always returns true) func NewFakeGenerate(rule kyverno.Generation) *FakeGenerate { g := FakeGenerate{} diff --git a/pkg/policy/generate/fake/auth.go b/pkg/policy/generate/fake/auth.go index 3e7467bf06..6e4bb39548 100644 --- a/pkg/policy/generate/fake/auth.go +++ b/pkg/policy/generate/fake/auth.go @@ -1,10 +1,9 @@ package fake -//FakeAuth providers implementation for testing, retuning true for all operations -type FakeAuth struct { -} +// FakeAuth providers implementation for testing, retuning true for all operations +type FakeAuth struct{} -//NewFakeAuth returns a new instance of Fake Auth that returns true for each operation +// NewFakeAuth returns a new instance of Fake Auth that returns true for each operation func NewFakeAuth() *FakeAuth { a := FakeAuth{} return &a diff --git a/pkg/policy/generate/validate.go b/pkg/policy/generate/validate.go index a1ad39119a..14ed7245a6 100644 --- a/pkg/policy/generate/validate.go +++ b/pkg/policy/generate/validate.go @@ -18,11 +18,11 @@ type Generate struct { rule kyverno.Generation // authCheck to check access for operations authCheck Operations - //logger + // logger log logr.Logger } -//NewGenerateFactory returns a new instance of Generate validation checker +// NewGenerateFactory returns a new instance of Generate validation checker func NewGenerateFactory(client dclient.Interface, rule kyverno.Generation, log logr.Logger) *Generate { g := Generate{ rule: rule, @@ -33,7 +33,7 @@ func NewGenerateFactory(client dclient.Interface, rule kyverno.Generation, log l return &g } -//Validate validates the 'generate' rule +// Validate validates the 'generate' rule func (g *Generate) Validate() (string, error) { rule := g.rule if rule.GetData() != nil && rule.Clone != (kyverno.CloneFrom{}) { @@ -56,7 +56,7 @@ func (g *Generate) Validate() (string, error) { } } if target := rule.GetData(); target != nil { - //TODO: is this required ?? as anchors can only be on pattern and not resource + // TODO: is this required ?? as anchors can only be on pattern and not resource // we can add this check by not sure if its needed here if path, err := common.ValidatePattern(target, "/", []commonAnchors.IsAnchor{}); err != nil { return fmt.Sprintf("data.%s", path), fmt.Errorf("anchors not supported on generate resources: %v", err) @@ -96,7 +96,7 @@ func (g *Generate) validateClone(c kyverno.CloneFrom, kind string) (string, erro return "", nil } -//canIGenerate returns a error if kyverno cannot perform operations +// canIGenerate returns a error if kyverno cannot perform operations func (g *Generate) canIGenerate(kind, namespace string) error { // Skip if there is variable defined authCheck := g.authCheck diff --git a/pkg/policy/mutate/validate.go b/pkg/policy/mutate/validate.go index 5fbc6b78d8..5e318957e4 100644 --- a/pkg/policy/mutate/validate.go +++ b/pkg/policy/mutate/validate.go @@ -11,14 +11,14 @@ type Mutate struct { mutation kyverno.Mutation } -//NewMutateFactory returns a new instance of Mutate validation checker +// NewMutateFactory returns a new instance of Mutate validation checker func NewMutateFactory(m kyverno.Mutation) *Mutate { return &Mutate{ mutation: m, } } -//Validate validates the 'mutate' rule +// Validate validates the 'mutate' rule func (m *Mutate) Validate() (string, error) { if m.hasForEach() { return m.validateForEach() diff --git a/pkg/policy/validate.go b/pkg/policy/validate.go index 68fd42e66f..a8cf3f98a0 100644 --- a/pkg/policy/validate.go +++ b/pkg/policy/validate.go @@ -122,7 +122,7 @@ func Validate(policy kyverno.PolicyInterface, client dclient.Interface, mock boo rulesPath := specPath.Child("rules") for i, rule := range rules { rulePath := rulesPath.Index(i) - //check for forward slash + // check for forward slash if err := validateJSONPatchPathForForwardSlash(rule.Mutation.PatchesJSON6902); err != nil { return nil, fmt.Errorf("path must begin with a forward slash: spec.rules[%d]: %s", i, err) } @@ -240,7 +240,7 @@ func Validate(policy kyverno.PolicyInterface, client dclient.Interface, mock boo } } - var podOnlyMap = make(map[string]bool) //Validate that Kind is only Pod + podOnlyMap := make(map[string]bool) // Validate that Kind is only Pod podOnlyMap["Pod"] = true if reflect.DeepEqual(common.GetKindsFromRule(rule), podOnlyMap) && podControllerAutoGenExclusion(policy) { msg := "Policies that match Pods apply to all Pods including those created and managed by controllers " + @@ -253,7 +253,7 @@ func Validate(policy kyverno.PolicyInterface, client dclient.Interface, mock boo }, nil } - //Validate Kind with match resource kinds + // Validate Kind with match resource kinds match := rule.MatchResources exclude := rule.ExcludeResources for _, value := range match.Any { @@ -704,13 +704,13 @@ func validateResources(path *field.Path, rule kyverno.Rule) (string, error) { } } - //validating the values present under validate.preconditions, if they exist + // validating the values present under validate.preconditions, if they exist if target := rule.GetAnyAllConditions(); target != nil { if path, err := validateConditions(target, "preconditions"); err != nil { return fmt.Sprintf("validate.%s", path), err } } - //validating the values present under validate.conditions, if they exist + // validating the values present under validate.conditions, if they exist if rule.Validation.Deny != nil { if target := rule.Validation.Deny.GetAnyAllConditions(); target != nil { if path, err := validateConditions(target, "conditions"); err != nil { diff --git a/pkg/policy/validate/validate.go b/pkg/policy/validate/validate.go index ed6229da85..d9c1e5df53 100644 --- a/pkg/policy/validate/validate.go +++ b/pkg/policy/validate/validate.go @@ -15,7 +15,7 @@ type Validate struct { rule *kyverno.Validation } -//NewValidateFactory returns a new instance of Mutate validation checker +// NewValidateFactory returns a new instance of Mutate validation checker func NewValidateFactory(rule *kyverno.Validation) *Validate { m := Validate{ rule: rule, @@ -24,7 +24,7 @@ func NewValidateFactory(rule *kyverno.Validation) *Validate { return &m } -//Validate validates the 'validate' rule +// Validate validates the 'validate' rule func (v *Validate) Validate() (string, error) { if err := v.validateElements(); err != nil { return "", err diff --git a/pkg/policyreport/builder.go b/pkg/policyreport/builder.go old mode 100755 new mode 100644 index cf6c844978..d0eba9892d --- a/pkg/policyreport/builder.go +++ b/pkg/policyreport/builder.go @@ -53,7 +53,7 @@ func GeneratePolicyReportName(ns string) string { return name } -//GeneratePRsFromEngineResponse generate Violations from engine responses +// GeneratePRsFromEngineResponse generate Violations from engine responses func GeneratePRsFromEngineResponse(ers []*response.EngineResponse, log logr.Logger) (pvInfos []Info) { for _, er := range ers { // ignore creation of PV for resources that are yet to be assigned a name @@ -311,9 +311,11 @@ func toPolicyResult(status response.RuleStatus) string { return "" } -const categoryLabel string = "policies.kyverno.io/category" -const severityLabel string = "policies.kyverno.io/severity" -const ScoredLabel string = "policies.kyverno.io/scored" +const ( + categoryLabel string = "policies.kyverno.io/category" + severityLabel string = "policies.kyverno.io/severity" + ScoredLabel string = "policies.kyverno.io/scored" +) type annotationValues struct { category string diff --git a/pkg/policyreport/policyreport.go b/pkg/policyreport/policyreport.go index b4b73ce885..417467a5a0 100644 --- a/pkg/policyreport/policyreport.go +++ b/pkg/policyreport/policyreport.go @@ -20,8 +20,10 @@ type PolicyReportEraser interface { EraseResultsEntries(erase EraseResultsEntries) error } -type CleanupReportChangeRequests = func(pclient kyvernoclient.Interface, rcrLister changerequestlister.ReportChangeRequestLister, crcrLister changerequestlister.ClusterReportChangeRequestLister) error -type EraseResultsEntries = func(pclient kyvernoclient.Interface, reportLister policyreportlister.PolicyReportLister, clusterReportLister policyreportlister.ClusterPolicyReportLister) error +type ( + CleanupReportChangeRequests = func(pclient kyvernoclient.Interface, rcrLister changerequestlister.ReportChangeRequestLister, crcrLister changerequestlister.ClusterReportChangeRequestLister) error + EraseResultsEntries = func(pclient kyvernoclient.Interface, reportLister policyreportlister.PolicyReportLister, clusterReportLister policyreportlister.ClusterPolicyReportLister) error +) func (g *ReportGenerator) CleanupReportChangeRequests(cleanup CleanupReportChangeRequests) error { return cleanup(g.pclient, g.reportChangeRequestLister, g.clusterReportChangeRequestLister) diff --git a/pkg/policyreport/reportrequest.go b/pkg/policyreport/reportrequest.go old mode 100755 new mode 100644 index 1fe7d031df..a857d218cd --- a/pkg/policyreport/reportrequest.go +++ b/pkg/policyreport/reportrequest.go @@ -22,8 +22,10 @@ import ( "k8s.io/client-go/util/workqueue" ) -const workQueueName = "report-request-controller" -const workQueueRetryLimit = 10 +const ( + workQueueName = "report-request-controller" + workQueueRetryLimit = 10 +) // Generator creates report request type Generator struct { @@ -54,7 +56,8 @@ func NewReportChangeRequestGenerator(client policyreportclient.Interface, clusterReportReqInformer requestinformer.ClusterReportChangeRequestInformer, cpolInformer kyvernoinformer.ClusterPolicyInformer, polInformer kyvernoinformer.PolicyInformer, - log logr.Logger) *Generator { + log logr.Logger, +) *Generator { gen := Generator{ dclient: dclient, clusterReportChangeRequestLister: clusterReportReqInformer.Lister(), @@ -230,7 +233,6 @@ func (gen *Generator) processNextWorkItem() bool { gen.handleErr(err, obj) return nil }(obj) - if err != nil { logger.Error(err, "failed to process item") } diff --git a/pkg/registryclient/client.go b/pkg/registryclient/client.go index 8b44a99461..5e06b7beee 100644 --- a/pkg/registryclient/client.go +++ b/pkg/registryclient/client.go @@ -66,7 +66,7 @@ func Initialize(client kubernetes.Interface, ns, sa string, imagePullSecrets []s // UpdateKeychain reinitializes the image pull secrets and default auth method for container registry API calls func UpdateKeychain() error { - var err = Initialize(kubeClient, namespace, serviceAccount, Secrets) + err := Initialize(kubeClient, namespace, serviceAccount, Secrets) if err != nil { return err } diff --git a/pkg/signal/signal.go b/pkg/signal/signal.go index efc4345fb2..45e5fdb9c1 100644 --- a/pkg/signal/signal.go +++ b/pkg/signal/signal.go @@ -5,8 +5,10 @@ import ( "os/signal" ) -var onlyOneSignalHandler = make(chan struct{}) -var shutdownHandler chan os.Signal +var ( + onlyOneSignalHandler = make(chan struct{}) + shutdownHandler chan os.Signal +) // SetupSignalHandler registered for SIGTERM and SIGINT. A stop channel is returned // which is closed on one of these signals. If a second signal is caught, the program diff --git a/pkg/testrunner/scenario.go b/pkg/testrunner/scenario.go index a3b96f2ccc..6058479795 100644 --- a/pkg/testrunner/scenario.go +++ b/pkg/testrunner/scenario.go @@ -77,7 +77,7 @@ func RootDir() string { return filepath.Dir(d) } -//getRelativePath expects a path relative to project and builds the complete path +// getRelativePath expects a path relative to project and builds the complete path func getRelativePath(path string) string { root := RootDir() return ospath.Join(root, path) diff --git a/pkg/testrunner/utils.go b/pkg/testrunner/utils.go index 6ab1910094..e60c4c3013 100644 --- a/pkg/testrunner/utils.go +++ b/pkg/testrunner/utils.go @@ -36,7 +36,7 @@ func getResourceFromKind(kind string) string { return "" } -//ConvertToUnstructured converts a resource to unstructured format +// ConvertToUnstructured converts a resource to unstructured format func ConvertToUnstructured(data []byte) (*unstructured.Unstructured, error) { resource := &unstructured.Unstructured{} err := resource.UnmarshalJSON(data) diff --git a/pkg/userinfo/roleRef.go b/pkg/userinfo/roleRef.go index b3d63abfc5..cd6b531a5f 100644 --- a/pkg/userinfo/roleRef.go +++ b/pkg/userinfo/roleRef.go @@ -21,7 +21,7 @@ const ( saPrefix = "system:serviceaccount:" ) -//GetRoleRef gets the list of roles and cluster roles for the incoming api-request +// GetRoleRef gets the list of roles and cluster roles for the incoming api-request func GetRoleRef(rbLister rbaclister.RoleBindingLister, crbLister rbaclister.ClusterRoleBindingLister, request *admissionv1.AdmissionRequest, dynamicConfig config.Configuration) ([]string, []string, error) { keys := append(request.UserInfo.Groups, request.UserInfo.Username) if utils.SliceContains(keys, dynamicConfig.GetExcludeGroupRole()...) { diff --git a/pkg/utils/annotations.go b/pkg/utils/annotations.go index e89eda1224..14d0662c82 100644 --- a/pkg/utils/annotations.go +++ b/pkg/utils/annotations.go @@ -90,7 +90,7 @@ func GenerateAnnotationPatches(engineResponses []*response.EngineResponse, log l } func annotationFromEngineResponses(engineResponses []*response.EngineResponse, log logr.Logger) []byte { - var annotationContent = make(map[string]string) + annotationContent := make(map[string]string) for _, engineResponse := range engineResponses { if !engineResponse.IsSuccessful() { log.V(3).Info("skip building annotation; policy failed to apply", "policy", engineResponse.PolicyResponse.Policy.Name) diff --git a/pkg/utils/util.go b/pkg/utils/util.go index c4af01235c..d98e77c7ef 100644 --- a/pkg/utils/util.go +++ b/pkg/utils/util.go @@ -264,7 +264,7 @@ func isVersionHigher(version string, major int, minor int, patch int) (bool, err // SliceContains checks whether values are contained in slice func SliceContains(slice []string, values ...string) bool { - var sliceElementsMap = make(map[string]bool, len(slice)) + sliceElementsMap := make(map[string]bool, len(slice)) for _, sliceElement := range slice { sliceElementsMap[sliceElement] = true } diff --git a/pkg/version/version.go b/pkg/version/version.go index 8d9303d204..d272daa578 100644 --- a/pkg/version/version.go +++ b/pkg/version/version.go @@ -12,7 +12,7 @@ var ( BuildTime = "--" ) -//PrintVersionInfo displays the kyverno version - git version +// PrintVersionInfo displays the kyverno version - git version func PrintVersionInfo(log logr.Logger) { log.Info("Kyverno", "Version", BuildVersion) log.Info("Kyverno", "BuildHash", BuildHash) diff --git a/pkg/webhookconfig/monitor.go b/pkg/webhookconfig/monitor.go index d3fc230f51..fa058eccad 100644 --- a/pkg/webhookconfig/monitor.go +++ b/pkg/webhookconfig/monitor.go @@ -16,7 +16,7 @@ import ( coordinationv1 "k8s.io/client-go/kubernetes/typed/coordination/v1" ) -//maxRetryCount defines the max deadline count +// maxRetryCount defines the max deadline count const ( tickerInterval time.Duration = 30 * time.Second idleCheckInterval time.Duration = 60 * time.Second diff --git a/pkg/webhookconfig/registration.go b/pkg/webhookconfig/registration.go index a69e15b4cb..c49c4e1214 100644 --- a/pkg/webhookconfig/registration.go +++ b/pkg/webhookconfig/registration.go @@ -79,7 +79,8 @@ func NewRegister( debug bool, autoUpdateWebhooks bool, stopCh <-chan struct{}, - log logr.Logger) *Register { + log logr.Logger, +) *Register { register := &Register{ clientConfig: clientConfig, kubeClient: kubeClient, diff --git a/pkg/webhookconfig/status.go b/pkg/webhookconfig/status.go index d34c1e4a32..9cf82b55ad 100644 --- a/pkg/webhookconfig/status.go +++ b/pkg/webhookconfig/status.go @@ -19,19 +19,19 @@ const ( annLastRequestTime string = "kyverno.io/last-request-time" ) -//statusControl controls the webhook status +// statusControl controls the webhook status type statusControl struct { eventGen event.Interface log logr.Logger leaseClient coordinationv1.LeaseInterface } -//success ... +// success ... func (vc statusControl) success() error { return vc.setStatus("true") } -//failure ... +// failure ... func (vc statusControl) failure() error { return vc.setStatus("false") } @@ -102,7 +102,7 @@ func (vc statusControl) UpdateLastRequestTimestmap(new time.Time) error { return err } - //add label to lease + // add label to lease label := lease.GetLabels() if len(label) == 0 { label = make(map[string]string) @@ -123,7 +123,7 @@ func (vc statusControl) UpdateLastRequestTimestmap(new time.Time) error { annotation[annLastRequestTime] = string(t) lease.SetAnnotations(annotation) - //update annotations in lease + // update annotations in lease _, err = vc.leaseClient.Update(context.TODO(), lease, metav1.UpdateOptions{}) if err != nil { return errors.Wrapf(err, "failed to update annotation %s for deployment %s in namespace %s", annLastRequestTime, lease.GetName(), lease.GetNamespace()) diff --git a/pkg/webhooks/resource/generation.go b/pkg/webhooks/resource/generation.go index 2ad2daa707..af7e16d566 100644 --- a/pkg/webhooks/resource/generation.go +++ b/pkg/webhooks/resource/generation.go @@ -24,7 +24,7 @@ import ( "k8s.io/apimachinery/pkg/labels" ) -//handleGenerate handles admission-requests for policies with generate rules +// handleGenerate handles admission-requests for policies with generate rules func (h *handlers) handleGenerate( logger logr.Logger, request *admissionv1.AdmissionRequest, @@ -87,7 +87,7 @@ func (h *handlers) handleGenerate( *generateEngineResponsesSenderForAdmissionRequestsCountMetric <- engineResponses } -//handleUpdatesForGenerateRules handles admission-requests for update +// handleUpdatesForGenerateRules handles admission-requests for update func (h *handlers) handleUpdatesForGenerateRules(logger logr.Logger, request *admissionv1.AdmissionRequest, policies []kyverno.PolicyInterface) { if request.Operation != admissionv1.Update { return @@ -108,7 +108,7 @@ func (h *handlers) handleUpdatesForGenerateRules(logger logr.Logger, request *ad } } -//handleUpdateGenerateSourceResource - handles update of clone source for generate policy +// handleUpdateGenerateSourceResource - handles update of clone source for generate policy func (h *handlers) handleUpdateGenerateSourceResource(resLabels map[string]string, logger logr.Logger) { policyNames := strings.Split(resLabels["generate.kyverno.io/clone-policy-name"], ",") for _, policyName := range policyNames { @@ -167,7 +167,7 @@ func (h *handlers) updateAnnotationInUR(ur *urkyverno.UpdateRequest, logger logr } } -//handleUpdateGenerateTargetResource - handles update of target resource for generate policy +// handleUpdateGenerateTargetResource - handles update of target resource for generate policy func (h *handlers) handleUpdateGenerateTargetResource(request *admissionv1.AdmissionRequest, policies []kyverno.PolicyInterface, resLabels map[string]string, logger logr.Logger) { enqueueBool := false newRes, err := enginutils.ConvertToUnstructured(request.Object.Raw) diff --git a/pkg/webhooks/resource/report.go b/pkg/webhooks/resource/report.go index 2a3486b095..c15b0bc74c 100644 --- a/pkg/webhooks/resource/report.go +++ b/pkg/webhooks/resource/report.go @@ -6,7 +6,7 @@ import ( "github.com/kyverno/kyverno/pkg/event" ) -//generateEvents generates event info for the engine responses +// generateEvents generates event info for the engine responses func generateEvents(engineResponses []*response.EngineResponse, blocked bool, log logr.Logger) []event.Info { var events []event.Info diff --git a/pkg/webhooks/resource/utils.go b/pkg/webhooks/resource/utils.go index c964d26b97..a805ab6621 100644 --- a/pkg/webhooks/resource/utils.go +++ b/pkg/webhooks/resource/utils.go @@ -254,7 +254,7 @@ func getGeneratedByResource(newRes *unstructured.Unstructured, resLabels map[str return rule, nil } -//stripNonPolicyFields - remove feilds which get updated with each request by kyverno and are non policy fields +// stripNonPolicyFields - remove feilds which get updated with each request by kyverno and are non policy fields func stripNonPolicyFields(obj, newRes map[string]interface{}, logger logr.Logger) (map[string]interface{}, map[string]interface{}) { if metadata, found := obj["metadata"]; found { requiredMetadataInObj := make(map[string]interface{}) @@ -316,7 +316,8 @@ func stripNonPolicyFields(obj, newRes map[string]interface{}, logger logr.Logger } func applyUpdateRequest(request *admissionv1.AdmissionRequest, ruleType kyvernov1beta1.RequestType, grGenerator updaterequest.Interface, userRequestInfo kyvernov1beta1.RequestInfo, - action admissionv1.Operation, engineResponses ...*response.EngineResponse) (failedUpdateRequest []updateRequestResponse) { + action admissionv1.Operation, engineResponses ...*response.EngineResponse, +) (failedUpdateRequest []updateRequestResponse) { requestBytes, err := json.Marshal(request) if err != nil { logger.Error(err, "error loading request into context") diff --git a/pkg/webhooks/resource/validate_audit.go b/pkg/webhooks/resource/validate_audit.go index 0074913a0b..0a35eee5f3 100644 --- a/pkg/webhooks/resource/validate_audit.go +++ b/pkg/webhooks/resource/validate_audit.go @@ -150,7 +150,8 @@ func (h *auditHandler) process(request *admissionv1.AdmissionRequest) error { userRequestInfo := v1beta1.RequestInfo{ Roles: roles, ClusterRoles: clusterRoles, - AdmissionUserInfo: request.UserInfo} + AdmissionUserInfo: request.UserInfo, + } ctx, err := newVariablesContext(request, &userRequestInfo) if err != nil { diff --git a/pkg/webhooks/resource/validation.go b/pkg/webhooks/resource/validation.go index 7bef9e59d5..c10680b05b 100644 --- a/pkg/webhooks/resource/validation.go +++ b/pkg/webhooks/resource/validation.go @@ -99,10 +99,10 @@ func (v *validationHandler) handleValidation( if blocked { logger.V(4).Info("resource blocked") - //registering the kyverno_admission_review_duration_seconds metric concurrently + // registering the kyverno_admission_review_duration_seconds metric concurrently admissionReviewLatencyDuration := int64(time.Since(time.Unix(admissionRequestTimestamp, 0))) go registerAdmissionReviewDurationMetricValidate(logger, promConfig, string(request.Operation), engineResponses, admissionReviewLatencyDuration) - //registering the kyverno_admission_requests_total metric concurrently + // registering the kyverno_admission_requests_total metric concurrently go registerAdmissionRequestsMetricValidate(logger, promConfig, string(request.Operation), engineResponses) return false, getEnforceFailureErrorMsg(engineResponses) } @@ -128,10 +128,10 @@ func (v *validationHandler) handleValidation( prInfos := policyreport.GeneratePRsFromEngineResponse(engineResponses, logger) v.prGenerator.Add(prInfos...) - //registering the kyverno_admission_review_duration_seconds metric concurrently + // registering the kyverno_admission_review_duration_seconds metric concurrently admissionReviewLatencyDuration := int64(time.Since(time.Unix(admissionRequestTimestamp, 0))) go registerAdmissionReviewDurationMetricValidate(logger, promConfig, string(request.Operation), engineResponses, admissionReviewLatencyDuration) - //registering the kyverno_admission_requests_total metric concurrently + // registering the kyverno_admission_requests_total metric concurrently go registerAdmissionRequestsMetricValidate(logger, promConfig, string(request.Operation), engineResponses) return true, "" diff --git a/test/e2e/generate/config.go b/test/e2e/generate/config.go index bf4915a949..6167a2beeb 100644 --- a/test/e2e/generate/config.go +++ b/test/e2e/generate/config.go @@ -3,7 +3,7 @@ package generate // RoleTests is E2E Test Config for Role and RoleBinding // TODO:- Clone for Role and RoleBinding var RoleTests = []struct { - //TestName - Name of the Test + // TestName - Name of the Test TestName string // RoleName - Name of the Role to be Created RoleName string @@ -63,7 +63,7 @@ var RoleTests = []struct { // ClusterRoleTests - E2E Test Config for ClusterRole and ClusterRoleBinding var ClusterRoleTests = []struct { - //TestName - Name of the Test + // TestName - Name of the Test TestName string // ClusterRoleName - Name of the ClusterRole to be Created ClusterRoleName string @@ -128,7 +128,7 @@ var ClusterRoleTests = []struct { // NetworkPolicyGenerateTests - E2E Test Config for NetworkPolicyGenerateTests var NetworkPolicyGenerateTests = []struct { - //TestName - Name of the Test + // TestName - Name of the Test TestName string // NetworkPolicyName - Name of the NetworkPolicy to be Created NetworkPolicyName string @@ -166,7 +166,7 @@ var NetworkPolicyGenerateTests = []struct { // NetworkPolicyGenerateTests - E2E Test Config for NetworkPolicyGenerateTests var GenerateNetworkPolicyOnNamespaceWithoutLabelTests = []struct { - //TestName - Name of the Test + // TestName - Name of the Test TestName string // NetworkPolicyName - Name of the NetworkPolicy to be Created NetworkPolicyName string @@ -207,7 +207,7 @@ var GenerateNetworkPolicyOnNamespaceWithoutLabelTests = []struct { // NetworkPolicyGenerateTests - E2E Test Config for NetworkPolicyGenerateTests var GenerateSynchronizeFlagTests = []struct { - //TestName - Name of the Test + // TestName - Name of the Test TestName string // NetworkPolicyName - Name of the NetworkPolicy to be Created NetworkPolicyName string @@ -248,7 +248,7 @@ var GenerateSynchronizeFlagTests = []struct { // ClusterRoleTests - E2E Test Config for ClusterRole and ClusterRoleBinding var SourceResourceUpdateReplicationTests = []struct { - //TestName - Name of the Test + // TestName - Name of the Test TestName string // ClusterRoleName - Name of the ClusterRole to be Created ResourceNamespace string @@ -281,7 +281,7 @@ var SourceResourceUpdateReplicationTests = []struct { } var GeneratePolicyDeletionforCloneTests = []struct { - //TestName - Name of the Test + // TestName - Name of the Test TestName string // ClusterRoleName - Name of the ClusterRole to be Created ResourceNamespace string diff --git a/test/e2e/mutate/config.go b/test/e2e/mutate/config.go index c08883d9b1..1824523f8e 100644 --- a/test/e2e/mutate/config.go +++ b/test/e2e/mutate/config.go @@ -8,7 +8,7 @@ import ( // MutateTests is E2E Test Config for mutation var MutateTests = []struct { - //TestName - Name of the Test + // TestName - Name of the Test TestName string // Data - The Yaml file of the ClusterPolicy Data []byte @@ -40,7 +40,7 @@ var MutateTests = []struct { // Note: sometimes deleting namespaces takes time. // Using different names for namespaces prevents collisions. var tests = []struct { - //TestDescription - Description of the Test + // TestDescription - Description of the Test TestDescription string // PolicyName - Name of the Policy PolicyName string diff --git a/test/e2e/mutate/resources.go b/test/e2e/mutate/resources.go index 73bacd8eba..c8816d5db3 100644 --- a/test/e2e/mutate/resources.go +++ b/test/e2e/mutate/resources.go @@ -6,10 +6,12 @@ import ( "github.com/kyverno/kyverno/test/e2e" ) -var podGVR = e2e.GetGVR("", "v1", "pods") -var deploymentGVR = e2e.GetGVR("apps", "v1", "deployments") -var configmGVR = e2e.GetGVR("", "v1", "configmaps") -var secretGVR = e2e.GetGVR("", "v1", "secrets") +var ( + podGVR = e2e.GetGVR("", "v1", "pods") + deploymentGVR = e2e.GetGVR("apps", "v1", "deployments") + configmGVR = e2e.GetGVR("", "v1", "configmaps") + secretGVR = e2e.GetGVR("", "v1", "secrets") +) func newNamespaceYaml(name string) []byte { ns := fmt.Sprintf(` diff --git a/test/e2e/validate/config.go b/test/e2e/validate/config.go index 14984d1889..328f8fc93e 100644 --- a/test/e2e/validate/config.go +++ b/test/e2e/validate/config.go @@ -7,7 +7,7 @@ import ( // FluxValidateTests is E2E Test Config for validation var FluxValidateTests = []struct { - //TestName - Name of the Test + // TestName - Name of the Test TestName string // PolicyRaw - The Yaml file of the ClusterPolicy PolicyRaw []byte @@ -37,7 +37,7 @@ var FluxValidateTests = []struct { var podGVR = e2e.GetGVR("", "v1", "pods") var ValidateTests = []struct { - //TestDescription - Description of the Test + // TestDescription - Description of the Test TestDescription string // PolicyName - Name of the Policy PolicyName string diff --git a/test/e2e/verifyimages/config.go b/test/e2e/verifyimages/config.go index b72badac67..a468b07a96 100644 --- a/test/e2e/verifyimages/config.go +++ b/test/e2e/verifyimages/config.go @@ -8,7 +8,7 @@ import ( var taskGVR = e2e.GetGVR("tekton.dev", "v1beta1", "tasks") var VerifyImagesTests = []struct { - //TestName - Name of the Test + // TestName - Name of the Test TestName string // PolicyName - Name of the Policy PolicyName string