mirror of
https://github.com/kyverno/kyverno.git
synced 2025-03-28 02:18:15 +00:00
chore: enable gofmt and gofumpt linters (#3931)
Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com>
This commit is contained in:
parent
c12f94d6d4
commit
0099ef54ad
91 changed files with 329 additions and 304 deletions
|
@ -13,6 +13,8 @@ linters:
|
|||
- exportloopref
|
||||
- gci
|
||||
- gochecknoinits
|
||||
- gofmt
|
||||
- gofumpt
|
||||
- goprintffuncname
|
||||
- gosec
|
||||
- gosimple
|
||||
|
|
6
api/kyverno/v1/common_types.go
Executable file → Normal file
6
api/kyverno/v1/common_types.go
Executable file → Normal file
|
@ -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"`
|
||||
|
|
|
@ -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"
|
||||
)
|
||||
|
|
|
@ -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"`
|
||||
|
||||
|
|
2
api/policyreport/v1alpha2/policyreport_types.go
Executable file → Normal file
2
api/policyreport/v1alpha2/policyreport_types.go
Executable file → Normal file
|
@ -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"`
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -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{}
|
||||
|
|
|
@ -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:]
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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(),
|
||||
|
|
3
cmd/kyverno/main.go
Executable file → Normal file
3
cmd/kyverno/main.go
Executable file → Normal file
|
@ -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)
|
||||
|
|
|
@ -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{
|
||||
{
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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
|
||||
}
|
||||
|
|
|
@ -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}
|
||||
}
|
||||
|
|
|
@ -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,
|
||||
|
|
|
@ -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()
|
||||
|
|
|
@ -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{})
|
||||
}
|
||||
|
|
|
@ -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"
|
||||
)
|
||||
|
||||
|
|
|
@ -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()
|
||||
|
|
|
@ -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,
|
||||
|
|
|
@ -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"
|
||||
|
|
|
@ -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
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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())
|
||||
}
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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 := ")"
|
||||
|
|
|
@ -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 == "" {
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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}},
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
|
|
|
@ -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()
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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
|
||||
}
|
||||
|
|
|
@ -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) {
|
||||
|
|
|
@ -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:
|
||||
|
|
|
@ -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:
|
||||
|
|
|
@ -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:
|
||||
|
|
|
@ -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:
|
||||
|
|
|
@ -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
|
||||
}
|
||||
|
|
|
@ -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) {
|
||||
|
|
|
@ -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) {
|
||||
|
|
|
@ -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
|
||||
}
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -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:
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
package event
|
||||
|
||||
//Reason types of Event Reasons
|
||||
// Reason types of Event Reasons
|
||||
type Reason int
|
||||
|
||||
const (
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
package event
|
||||
|
||||
//Source of event generation
|
||||
// Source of event generation
|
||||
type Source int
|
||||
|
||||
const (
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -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() {
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -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()
|
||||
|
|
|
@ -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,
|
||||
|
|
|
@ -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{}
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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()
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -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
|
||||
|
|
10
pkg/policyreport/builder.go
Executable file → Normal file
10
pkg/policyreport/builder.go
Executable file → Normal file
|
@ -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
|
||||
|
|
|
@ -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)
|
||||
|
|
10
pkg/policyreport/reportrequest.go
Executable file → Normal file
10
pkg/policyreport/reportrequest.go
Executable file → Normal file
|
@ -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")
|
||||
}
|
||||
|
|
|
@ -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
|
||||
}
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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()...) {
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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,
|
||||
|
|
|
@ -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())
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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
|
||||
|
||||
|
|
|
@ -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")
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -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, ""
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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(`
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
|
Loading…
Add table
Reference in a new issue