mirror of
https://github.com/kyverno/kyverno.git
synced 2024-12-14 11:57:48 +00:00
chore: make kyverno api import aliases consistent (#3939)
Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com>
This commit is contained in:
parent
a4348fd455
commit
5aaf2d8770
81 changed files with 772 additions and 766 deletions
|
@ -43,3 +43,9 @@ run:
|
|||
skip-files:
|
||||
- ".+_test.go"
|
||||
- ".+_test_.+.go"
|
||||
|
||||
linters-settings:
|
||||
importas:
|
||||
alias:
|
||||
- pkg: github.com/kyverno/kyverno/api/(\w+)/(v[\w\d]+)
|
||||
alias: $1$2
|
||||
|
|
|
@ -17,7 +17,7 @@ limitations under the License.
|
|||
package v1alpha2
|
||||
|
||||
import (
|
||||
report "github.com/kyverno/kyverno/api/policyreport/v1alpha2"
|
||||
policyreportv1alpha2 "github.com/kyverno/kyverno/api/policyreport/v1alpha2"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
)
|
||||
|
@ -53,11 +53,11 @@ type ClusterReportChangeRequest struct {
|
|||
|
||||
// PolicyReportSummary provides a summary of results
|
||||
// +optional
|
||||
Summary report.PolicyReportSummary `json:"summary,omitempty"`
|
||||
Summary policyreportv1alpha2.PolicyReportSummary `json:"summary,omitempty"`
|
||||
|
||||
// PolicyReportResult provides result details
|
||||
// +optional
|
||||
Results []report.PolicyReportResult `json:"results,omitempty"`
|
||||
Results []policyreportv1alpha2.PolicyReportResult `json:"results,omitempty"`
|
||||
}
|
||||
|
||||
// +kubebuilder:object:root=true
|
||||
|
|
|
@ -17,7 +17,7 @@ limitations under the License.
|
|||
package v1alpha2
|
||||
|
||||
import (
|
||||
report "github.com/kyverno/kyverno/api/policyreport/v1alpha2"
|
||||
policyreportv1alpha2 "github.com/kyverno/kyverno/api/policyreport/v1alpha2"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
)
|
||||
|
@ -55,11 +55,11 @@ type ReportChangeRequest struct {
|
|||
|
||||
// PolicyReportSummary provides a summary of results
|
||||
// +optional
|
||||
Summary report.PolicyReportSummary `json:"summary,omitempty"`
|
||||
Summary policyreportv1alpha2.PolicyReportSummary `json:"summary,omitempty"`
|
||||
|
||||
// PolicyReportResult provides result details
|
||||
// +optional
|
||||
Results []report.PolicyReportResult `json:"results,omitempty"`
|
||||
Results []policyreportv1alpha2.PolicyReportResult `json:"results,omitempty"`
|
||||
}
|
||||
|
||||
// +kubebuilder:object:root=true
|
||||
|
|
|
@ -17,7 +17,7 @@ limitations under the License.
|
|||
package v1beta1
|
||||
|
||||
import (
|
||||
v1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
admissionv1 "k8s.io/api/admission/v1"
|
||||
authenticationv1 "k8s.io/api/authentication/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
|
@ -37,7 +37,7 @@ type UpdateRequestStatus struct {
|
|||
|
||||
// This will track the resources that are updated by the generate Policy.
|
||||
// Will be used during clean up resources.
|
||||
GeneratedResources []v1.ResourceSpec `json:"generatedResources,omitempty" yaml:"generatedResources,omitempty"`
|
||||
GeneratedResources []kyvernov1.ResourceSpec `json:"generatedResources,omitempty" yaml:"generatedResources,omitempty"`
|
||||
}
|
||||
|
||||
// +genclient
|
||||
|
@ -83,7 +83,7 @@ type UpdateRequestSpec struct {
|
|||
Policy string `json:"policy" yaml:"policy"`
|
||||
|
||||
// ResourceSpec is the information to identify the update request.
|
||||
Resource v1.ResourceSpec `json:"resource" yaml:"resource"`
|
||||
Resource kyvernov1.ResourceSpec `json:"resource" yaml:"resource"`
|
||||
|
||||
// Context ...
|
||||
Context UpdateRequestSpecContext `json:"context" yaml:"context"`
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
package apply
|
||||
|
||||
import (
|
||||
report "github.com/kyverno/kyverno/api/policyreport/v1alpha2"
|
||||
policyreportv1alpha2 "github.com/kyverno/kyverno/api/policyreport/v1alpha2"
|
||||
sanitizederror "github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/utils/sanitizedError"
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
"sigs.k8s.io/controller-runtime/pkg/log"
|
||||
|
@ -23,7 +23,7 @@ func mergeClusterReport(reports []*unstructured.Unstructured) (*unstructured.Uns
|
|||
res := &unstructured.Unstructured{}
|
||||
res.SetName(clusterpolicyreport)
|
||||
res.SetKind("ClusterPolicyReport")
|
||||
res.SetAPIVersion(report.SchemeGroupVersion.String())
|
||||
res.SetAPIVersion(policyreportv1alpha2.SchemeGroupVersion.String())
|
||||
|
||||
for _, report := range reports {
|
||||
if report.GetNamespace() != "" {
|
||||
|
@ -59,7 +59,7 @@ func mergeResults(report *unstructured.Unstructured, results *[]interface{}) {
|
|||
|
||||
func updateSummary(results []interface{}) map[string]interface{} {
|
||||
summary := make(map[string]interface{})
|
||||
status := []string{report.StatusPass, report.StatusFail, report.StatusError, report.StatusSkip, report.StatusWarn}
|
||||
status := []string{policyreportv1alpha2.StatusPass, policyreportv1alpha2.StatusFail, policyreportv1alpha2.StatusError, policyreportv1alpha2.StatusSkip, policyreportv1alpha2.StatusWarn}
|
||||
for i := 0; i < 5; i++ {
|
||||
if _, ok := summary[status[i]].(int64); !ok {
|
||||
summary[status[i]] = int64(0)
|
||||
|
@ -72,26 +72,26 @@ func updateSummary(results []interface{}) map[string]interface{} {
|
|||
}
|
||||
|
||||
switch typedResult["result"].(string) {
|
||||
case report.StatusPass:
|
||||
pass, _ := summary[report.StatusPass].(int64)
|
||||
case policyreportv1alpha2.StatusPass:
|
||||
pass, _ := summary[policyreportv1alpha2.StatusPass].(int64)
|
||||
pass++
|
||||
summary[report.StatusPass] = pass
|
||||
case report.StatusFail:
|
||||
fail, _ := summary[report.StatusFail].(int64)
|
||||
summary[policyreportv1alpha2.StatusPass] = pass
|
||||
case policyreportv1alpha2.StatusFail:
|
||||
fail, _ := summary[policyreportv1alpha2.StatusFail].(int64)
|
||||
fail++
|
||||
summary[report.StatusFail] = fail
|
||||
case report.StatusWarn:
|
||||
warn, _ := summary[report.StatusWarn].(int64)
|
||||
summary[policyreportv1alpha2.StatusFail] = fail
|
||||
case policyreportv1alpha2.StatusWarn:
|
||||
warn, _ := summary[policyreportv1alpha2.StatusWarn].(int64)
|
||||
warn++
|
||||
summary[report.StatusWarn] = warn
|
||||
case report.StatusError:
|
||||
e, _ := summary[report.StatusError].(int64)
|
||||
summary[policyreportv1alpha2.StatusWarn] = warn
|
||||
case policyreportv1alpha2.StatusError:
|
||||
e, _ := summary[policyreportv1alpha2.StatusError].(int64)
|
||||
e++
|
||||
summary[report.StatusError] = e
|
||||
case report.StatusSkip:
|
||||
skip, _ := summary[report.StatusSkip].(int64)
|
||||
summary[policyreportv1alpha2.StatusError] = e
|
||||
case policyreportv1alpha2.StatusSkip:
|
||||
skip, _ := summary[policyreportv1alpha2.StatusSkip].(int64)
|
||||
skip++
|
||||
summary[report.StatusSkip] = skip
|
||||
summary[policyreportv1alpha2.StatusSkip] = skip
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -6,7 +6,7 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
report "github.com/kyverno/kyverno/api/policyreport/v1alpha2"
|
||||
policyreportv1alpha2 "github.com/kyverno/kyverno/api/policyreport/v1alpha2"
|
||||
"github.com/kyverno/kyverno/pkg/engine/response"
|
||||
engineutils "github.com/kyverno/kyverno/pkg/engine/utils"
|
||||
"github.com/kyverno/kyverno/pkg/policyreport"
|
||||
|
@ -27,9 +27,9 @@ func buildPolicyReports(pvInfos []policyreport.Info) (res []*unstructured.Unstru
|
|||
resultsMap := buildPolicyResults(pvInfos)
|
||||
for scope, result := range resultsMap {
|
||||
if scope == clusterpolicyreport {
|
||||
report := &report.ClusterPolicyReport{
|
||||
report := &policyreportv1alpha2.ClusterPolicyReport{
|
||||
TypeMeta: metav1.TypeMeta{
|
||||
APIVersion: report.SchemeGroupVersion.String(),
|
||||
APIVersion: policyreportv1alpha2.SchemeGroupVersion.String(),
|
||||
Kind: "ClusterPolicyReport",
|
||||
},
|
||||
Results: result,
|
||||
|
@ -41,9 +41,9 @@ func buildPolicyReports(pvInfos []policyreport.Info) (res []*unstructured.Unstru
|
|||
log.Log.V(3).Info("failed to serialize policy report", "name", report.Name, "scope", scope, "error", err)
|
||||
}
|
||||
} else {
|
||||
report := &report.PolicyReport{
|
||||
report := &policyreportv1alpha2.PolicyReport{
|
||||
TypeMeta: metav1.TypeMeta{
|
||||
APIVersion: report.SchemeGroupVersion.String(),
|
||||
APIVersion: policyreportv1alpha2.SchemeGroupVersion.String(),
|
||||
Kind: "PolicyReport",
|
||||
},
|
||||
Results: result,
|
||||
|
@ -73,8 +73,8 @@ func buildPolicyReports(pvInfos []policyreport.Info) (res []*unstructured.Unstru
|
|||
|
||||
// buildPolicyResults returns a string-PolicyReportResult map
|
||||
// the key of the map is one of "clusterpolicyreport", "policyreport-ns-<namespace>"
|
||||
func buildPolicyResults(infos []policyreport.Info) map[string][]report.PolicyReportResult {
|
||||
results := make(map[string][]report.PolicyReportResult)
|
||||
func buildPolicyResults(infos []policyreport.Info) map[string][]policyreportv1alpha2.PolicyReportResult {
|
||||
results := make(map[string][]policyreportv1alpha2.PolicyReportResult)
|
||||
now := metav1.Timestamp{Seconds: time.Now().Unix()}
|
||||
|
||||
for _, info := range infos {
|
||||
|
@ -92,7 +92,7 @@ func buildPolicyResults(infos []policyreport.Info) map[string][]report.PolicyRep
|
|||
continue
|
||||
}
|
||||
|
||||
result := report.PolicyReportResult{
|
||||
result := policyreportv1alpha2.PolicyReportResult{
|
||||
Policy: info.PolicyName,
|
||||
Resources: []corev1.ObjectReference{
|
||||
{
|
||||
|
@ -108,7 +108,7 @@ func buildPolicyResults(infos []policyreport.Info) map[string][]report.PolicyRep
|
|||
|
||||
result.Rule = rule.Name
|
||||
result.Message = rule.Message
|
||||
result.Result = report.PolicyResult(rule.Status)
|
||||
result.Result = policyreportv1alpha2.PolicyResult(rule.Status)
|
||||
result.Source = policyreport.SourceValue
|
||||
result.Timestamp = now
|
||||
results[appname] = append(results[appname], result)
|
||||
|
@ -119,12 +119,12 @@ func buildPolicyResults(infos []policyreport.Info) map[string][]report.PolicyRep
|
|||
return results
|
||||
}
|
||||
|
||||
func calculateSummary(results []report.PolicyReportResult) (summary report.PolicyReportSummary) {
|
||||
func calculateSummary(results []policyreportv1alpha2.PolicyReportResult) (summary policyreportv1alpha2.PolicyReportSummary) {
|
||||
for _, res := range results {
|
||||
switch string(res.Result) {
|
||||
case report.StatusPass:
|
||||
case policyreportv1alpha2.StatusPass:
|
||||
summary.Pass++
|
||||
case report.StatusFail:
|
||||
case policyreportv1alpha2.StatusFail:
|
||||
summary.Fail++
|
||||
case "warn":
|
||||
summary.Warn++
|
||||
|
|
|
@ -17,9 +17,9 @@ import (
|
|||
"github.com/go-git/go-billy/v5"
|
||||
"github.com/go-git/go-billy/v5/memfs"
|
||||
"github.com/kataras/tablewriter"
|
||||
v1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
report "github.com/kyverno/kyverno/api/policyreport/v1alpha2"
|
||||
policyreportv1alpha2 "github.com/kyverno/kyverno/api/policyreport/v1alpha2"
|
||||
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/utils/common"
|
||||
sanitizederror "github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/utils/sanitizedError"
|
||||
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/utils/store"
|
||||
|
@ -244,15 +244,15 @@ type Test struct {
|
|||
}
|
||||
|
||||
type TestResults struct {
|
||||
Policy string `json:"policy"`
|
||||
Rule string `json:"rule"`
|
||||
Result report.PolicyResult `json:"result"`
|
||||
Status report.PolicyResult `json:"status"`
|
||||
Resource string `json:"resource"`
|
||||
Kind string `json:"kind"`
|
||||
Namespace string `json:"namespace"`
|
||||
PatchedResource string `json:"patchedResource"`
|
||||
AutoGeneratedRule string `json:"auto_generated_rule"`
|
||||
Policy string `json:"policy"`
|
||||
Rule string `json:"rule"`
|
||||
Result policyreportv1alpha2.PolicyResult `json:"result"`
|
||||
Status policyreportv1alpha2.PolicyResult `json:"status"`
|
||||
Resource string `json:"resource"`
|
||||
Kind string `json:"kind"`
|
||||
Namespace string `json:"namespace"`
|
||||
PatchedResource string `json:"patchedResource"`
|
||||
AutoGeneratedRule string `json:"auto_generated_rule"`
|
||||
}
|
||||
|
||||
type ReportResult struct {
|
||||
|
@ -483,8 +483,8 @@ func getLocalDirTestFiles(fs billy.Filesystem, path, fileName string, rc *result
|
|||
return errors
|
||||
}
|
||||
|
||||
func buildPolicyResults(engineResponses []*response.EngineResponse, testResults []TestResults, infos []policyreport.Info, policyResourcePath string, fs billy.Filesystem, isGit bool) (map[string]report.PolicyReportResult, []TestResults) {
|
||||
results := make(map[string]report.PolicyReportResult)
|
||||
func buildPolicyResults(engineResponses []*response.EngineResponse, testResults []TestResults, infos []policyreport.Info, policyResourcePath string, fs billy.Filesystem, isGit bool) (map[string]policyreportv1alpha2.PolicyReportResult, []TestResults) {
|
||||
results := make(map[string]policyreportv1alpha2.PolicyReportResult)
|
||||
now := metav1.Timestamp{Seconds: time.Now().Unix()}
|
||||
|
||||
for _, resp := range engineResponses {
|
||||
|
@ -499,7 +499,7 @@ func buildPolicyResults(engineResponses []*response.EngineResponse, testResults
|
|||
rules = append(rules, rule.Name)
|
||||
}
|
||||
|
||||
result := report.PolicyReportResult{
|
||||
result := policyreportv1alpha2.PolicyReportResult{
|
||||
Policy: policyName,
|
||||
Resources: []corev1.ObjectReference{
|
||||
{
|
||||
|
@ -530,7 +530,7 @@ func buildPolicyResults(engineResponses []*response.EngineResponse, testResults
|
|||
if !util.ContainsString(rules, test.Rule) {
|
||||
if !util.ContainsString(rules, "autogen-"+test.Rule) {
|
||||
if !util.ContainsString(rules, "autogen-cronjob-"+test.Rule) {
|
||||
result.Result = report.StatusSkip
|
||||
result.Result = policyreportv1alpha2.StatusSkip
|
||||
} else {
|
||||
testResults[i].AutoGeneratedRule = "autogen-cronjob"
|
||||
test.Rule = "autogen-cronjob-" + test.Rule
|
||||
|
@ -543,7 +543,7 @@ func buildPolicyResults(engineResponses []*response.EngineResponse, testResults
|
|||
}
|
||||
|
||||
if results[resultsKey].Result == "" {
|
||||
result.Result = report.StatusSkip
|
||||
result.Result = policyreportv1alpha2.StatusSkip
|
||||
results[resultsKey] = result
|
||||
}
|
||||
}
|
||||
|
@ -562,7 +562,7 @@ func buildPolicyResults(engineResponses []*response.EngineResponse, testResults
|
|||
|
||||
var resultsKey []string
|
||||
var resultKey string
|
||||
var result report.PolicyReportResult
|
||||
var result policyreportv1alpha2.PolicyReportResult
|
||||
resultsKey = GetAllPossibleResultsKey(policyNamespace, policyName, rule.Name, resourceNamespace, resourceKind, resourceName)
|
||||
for _, key := range resultsKey {
|
||||
if val, ok := results[key]; ok {
|
||||
|
@ -573,16 +573,16 @@ func buildPolicyResults(engineResponses []*response.EngineResponse, testResults
|
|||
}
|
||||
|
||||
if rule.Status == response.RuleStatusSkip {
|
||||
result.Result = report.StatusSkip
|
||||
result.Result = policyreportv1alpha2.StatusSkip
|
||||
} else if rule.Status == response.RuleStatusError {
|
||||
result.Result = report.StatusError
|
||||
result.Result = policyreportv1alpha2.StatusError
|
||||
} else {
|
||||
var x string
|
||||
for _, path := range patchedResourcePath {
|
||||
result.Result = report.StatusFail
|
||||
result.Result = policyreportv1alpha2.StatusFail
|
||||
x = getAndComparePatchedResource(path, resp.PatchedResource, isGit, policyResourcePath, fs)
|
||||
if x == "pass" {
|
||||
result.Result = report.StatusPass
|
||||
result.Result = policyreportv1alpha2.StatusPass
|
||||
break
|
||||
}
|
||||
}
|
||||
|
@ -600,7 +600,7 @@ func buildPolicyResults(engineResponses []*response.EngineResponse, testResults
|
|||
continue
|
||||
}
|
||||
|
||||
var result report.PolicyReportResult
|
||||
var result policyreportv1alpha2.PolicyReportResult
|
||||
var resultsKeys []string
|
||||
var resultKey string
|
||||
resultsKeys = GetAllPossibleResultsKey("", info.PolicyName, rule.Name, infoResult.Resource.Namespace, infoResult.Resource.Kind, infoResult.Resource.Name)
|
||||
|
@ -614,7 +614,7 @@ func buildPolicyResults(engineResponses []*response.EngineResponse, testResults
|
|||
}
|
||||
|
||||
result.Rule = rule.Name
|
||||
result.Result = report.PolicyResult(rule.Status)
|
||||
result.Result = policyreportv1alpha2.PolicyResult(rule.Status)
|
||||
result.Source = policyreport.SourceValue
|
||||
result.Timestamp = now
|
||||
results[resultKey] = result
|
||||
|
@ -773,7 +773,7 @@ func applyPoliciesFromPath(fs billy.Filesystem, policyBytes []byte, isGit bool,
|
|||
os.Exit(1)
|
||||
}
|
||||
|
||||
filteredPolicies := []v1.PolicyInterface{}
|
||||
filteredPolicies := []kyvernov1.PolicyInterface{}
|
||||
for _, p := range policies {
|
||||
for _, res := range values.Results {
|
||||
if p.GetName() == res.Policy {
|
||||
|
@ -784,7 +784,7 @@ func applyPoliciesFromPath(fs billy.Filesystem, policyBytes []byte, isGit bool,
|
|||
}
|
||||
|
||||
for _, p := range filteredPolicies {
|
||||
filteredRules := []v1.Rule{}
|
||||
filteredRules := []kyvernov1.Rule{}
|
||||
|
||||
for _, rule := range autogen.ComputeRules(p) {
|
||||
for _, res := range values.Results {
|
||||
|
@ -886,7 +886,7 @@ func applyPoliciesFromPath(fs billy.Filesystem, policyBytes []byte, isGit bool,
|
|||
return
|
||||
}
|
||||
|
||||
func printTestResult(resps map[string]report.PolicyReportResult, testResults []TestResults, rc *resultCounts) error {
|
||||
func printTestResult(resps map[string]policyreportv1alpha2.PolicyReportResult, testResults []TestResults, rc *resultCounts) error {
|
||||
printer := tableprinter.New(os.Stdout)
|
||||
table := []*Table{}
|
||||
boldGreen := color.New(color.FgGreen).Add(color.Bold)
|
||||
|
@ -928,7 +928,7 @@ func printTestResult(resps map[string]report.PolicyReportResult, testResults []T
|
|||
resultKey = fmt.Sprintf("%s-%s-%s-%s-%s", v.Policy, ruleNameInResultKey, v.Namespace, v.Kind, v.Resource)
|
||||
}
|
||||
|
||||
var testRes report.PolicyReportResult
|
||||
var testRes policyreportv1alpha2.PolicyReportResult
|
||||
if val, ok := resps[resultKey]; ok {
|
||||
testRes = val
|
||||
} else {
|
||||
|
@ -945,7 +945,7 @@ func printTestResult(resps map[string]report.PolicyReportResult, testResults []T
|
|||
|
||||
if testRes.Result == v.Result {
|
||||
res.Result = boldGreen.Sprintf("Pass")
|
||||
if testRes.Result == report.StatusSkip {
|
||||
if testRes.Result == policyreportv1alpha2.StatusSkip {
|
||||
res.Result = boldGreen.Sprintf("Pass")
|
||||
rc.Skip++
|
||||
} else {
|
||||
|
|
|
@ -15,9 +15,9 @@ import (
|
|||
jsonpatch "github.com/evanphx/json-patch/v5"
|
||||
"github.com/go-git/go-billy/v5"
|
||||
"github.com/go-logr/logr"
|
||||
v1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
v1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
report "github.com/kyverno/kyverno/api/policyreport/v1alpha2"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
policyreportv1alpha2 "github.com/kyverno/kyverno/api/policyreport/v1alpha2"
|
||||
sanitizederror "github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/utils/sanitizedError"
|
||||
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/utils/store"
|
||||
"github.com/kyverno/kyverno/pkg/autogen"
|
||||
|
@ -72,14 +72,14 @@ type NamespaceSelector struct {
|
|||
}
|
||||
|
||||
// HasVariables - check for variables in the policy
|
||||
func HasVariables(policy v1.PolicyInterface) [][]string {
|
||||
func HasVariables(policy kyvernov1.PolicyInterface) [][]string {
|
||||
policyRaw, _ := json.Marshal(policy)
|
||||
matches := variables.RegexVariables.FindAllStringSubmatch(string(policyRaw), -1)
|
||||
return matches
|
||||
}
|
||||
|
||||
// GetPolicies - Extracting the policies from multiple YAML
|
||||
func GetPolicies(paths []string) (policies []v1.PolicyInterface, errors []error) {
|
||||
func GetPolicies(paths []string) (policies []kyvernov1.PolicyInterface, errors []error) {
|
||||
for _, path := range paths {
|
||||
log.Log.V(5).Info("reading policies", "path", path)
|
||||
|
||||
|
@ -178,7 +178,7 @@ func GetPolicies(paths []string) (policies []v1.PolicyInterface, errors []error)
|
|||
}
|
||||
|
||||
// MutatePolicy - applies mutation to a policy
|
||||
func MutatePolicy(policy v1.PolicyInterface, logger logr.Logger) (v1.PolicyInterface, error) {
|
||||
func MutatePolicy(policy kyvernov1.PolicyInterface, logger logr.Logger) (kyvernov1.PolicyInterface, error) {
|
||||
patches, _ := policymutation.GenerateJSONPatchesForDefaults(policy, logger)
|
||||
if len(patches) == 0 {
|
||||
return policy, nil
|
||||
|
@ -196,14 +196,14 @@ func MutatePolicy(policy v1.PolicyInterface, logger logr.Logger) (v1.PolicyInter
|
|||
return nil, sanitizederror.NewWithError(fmt.Sprintf("failed to apply %s policy", policy.GetName()), err)
|
||||
}
|
||||
if policy.IsNamespaced() {
|
||||
var p v1.Policy
|
||||
var p kyvernov1.Policy
|
||||
err = json.Unmarshal(modifiedPolicy, &p)
|
||||
if err != nil {
|
||||
return nil, sanitizederror.NewWithError(fmt.Sprintf("failed to unmarshal %s policy", policy.GetName()), err)
|
||||
}
|
||||
return &p, nil
|
||||
} else {
|
||||
var p v1.ClusterPolicy
|
||||
var p kyvernov1.ClusterPolicy
|
||||
err = json.Unmarshal(modifiedPolicy, &p)
|
||||
if err != nil {
|
||||
return nil, sanitizederror.NewWithError(fmt.Sprintf("failed to unmarshal %s policy", policy.GetName()), err)
|
||||
|
@ -363,8 +363,8 @@ func GetVariable(variablesString, valuesFile string, fs billy.Filesystem, isGit
|
|||
}
|
||||
|
||||
// MutatePolicies - function to apply mutation on policies
|
||||
func MutatePolicies(policies []v1.PolicyInterface) ([]v1.PolicyInterface, error) {
|
||||
newPolicies := make([]v1.PolicyInterface, 0)
|
||||
func MutatePolicies(policies []kyvernov1.PolicyInterface) ([]kyvernov1.PolicyInterface, error) {
|
||||
newPolicies := make([]kyvernov1.PolicyInterface, 0)
|
||||
logger := log.Log.WithName("apply")
|
||||
|
||||
for _, policy := range policies {
|
||||
|
@ -381,8 +381,8 @@ func MutatePolicies(policies []v1.PolicyInterface) ([]v1.PolicyInterface, error)
|
|||
}
|
||||
|
||||
// ApplyPolicyOnResource - function to apply policy on resource
|
||||
func ApplyPolicyOnResource(policy v1.PolicyInterface, resource *unstructured.Unstructured,
|
||||
mutateLogPath string, mutateLogPathIsDir bool, variables map[string]interface{}, userInfo v1beta1.RequestInfo, policyReport bool,
|
||||
func ApplyPolicyOnResource(policy kyvernov1.PolicyInterface, resource *unstructured.Unstructured,
|
||||
mutateLogPath string, mutateLogPathIsDir bool, variables map[string]interface{}, userInfo kyvernov1beta1.RequestInfo, policyReport bool,
|
||||
namespaceSelectorMap map[string]map[string]string, stdin bool, rc *ResultCounts,
|
||||
printPatchResource bool,
|
||||
) ([]*response.EngineResponse, policyreport.Info, error) {
|
||||
|
@ -500,8 +500,8 @@ OuterLoop:
|
|||
if resource.GetKind() == "Pod" && len(resource.GetOwnerReferences()) > 0 {
|
||||
if policy.HasAutoGenAnnotation() {
|
||||
annotations := policy.GetAnnotations()
|
||||
if _, ok := annotations[v1.PodControllersAnnotation]; ok {
|
||||
delete(annotations, v1.PodControllersAnnotation)
|
||||
if _, ok := annotations[kyvernov1.PodControllersAnnotation]; ok {
|
||||
delete(annotations, kyvernov1.PodControllersAnnotation)
|
||||
policy.SetAnnotations(annotations)
|
||||
}
|
||||
}
|
||||
|
@ -593,7 +593,7 @@ func PrintMutatedOutput(mutateLogPath string, mutateLogPathIsDir bool, yaml stri
|
|||
}
|
||||
|
||||
// GetPoliciesFromPaths - get policies according to the resource path
|
||||
func GetPoliciesFromPaths(fs billy.Filesystem, dirPath []string, isGit bool, policyResourcePath string) (policies []v1.PolicyInterface, err error) {
|
||||
func GetPoliciesFromPaths(fs billy.Filesystem, dirPath []string, isGit bool, policyResourcePath string) (policies []kyvernov1.PolicyInterface, err error) {
|
||||
if isGit {
|
||||
for _, pp := range dirPath {
|
||||
filep, err := fs.Open(filepath.Join(policyResourcePath, pp))
|
||||
|
@ -654,7 +654,7 @@ 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,
|
||||
cluster bool, policies []kyvernov1.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)
|
||||
|
@ -707,8 +707,8 @@ func GetResourceAccordingToResourcePath(fs billy.Filesystem, resourcePaths []str
|
|||
return resources, err
|
||||
}
|
||||
|
||||
func ProcessValidateEngineResponse(policy v1.PolicyInterface, validateResponse *response.EngineResponse, resPath string, rc *ResultCounts, policyReport bool) policyreport.Info {
|
||||
var violatedRules []v1.ViolatedRule
|
||||
func ProcessValidateEngineResponse(policy kyvernov1.PolicyInterface, validateResponse *response.EngineResponse, resPath string, rc *ResultCounts, policyReport bool) policyreport.Info {
|
||||
var violatedRules []kyvernov1.ViolatedRule
|
||||
|
||||
printCount := 0
|
||||
for _, policyRule := range autogen.ComputeRules(policy) {
|
||||
|
@ -720,7 +720,7 @@ func ProcessValidateEngineResponse(policy v1.PolicyInterface, validateResponse *
|
|||
for i, valResponseRule := range validateResponse.PolicyResponse.Rules {
|
||||
if policyRule.Name == valResponseRule.Name {
|
||||
ruleFoundInEngineResponse = true
|
||||
vrule := v1.ViolatedRule{
|
||||
vrule := kyvernov1.ViolatedRule{
|
||||
Name: valResponseRule.Name,
|
||||
Type: string(valResponseRule.Type),
|
||||
Message: valResponseRule.Message,
|
||||
|
@ -729,17 +729,17 @@ func ProcessValidateEngineResponse(policy v1.PolicyInterface, validateResponse *
|
|||
switch valResponseRule.Status {
|
||||
case response.RuleStatusPass:
|
||||
rc.Pass++
|
||||
vrule.Status = report.StatusPass
|
||||
vrule.Status = policyreportv1alpha2.StatusPass
|
||||
|
||||
case response.RuleStatusFail:
|
||||
ann := policy.GetAnnotations()
|
||||
if scored, ok := ann[policyreport.ScoredLabel]; ok && scored == "false" {
|
||||
rc.Warn++
|
||||
vrule.Status = report.StatusWarn
|
||||
vrule.Status = policyreportv1alpha2.StatusWarn
|
||||
break
|
||||
} else {
|
||||
rc.Fail++
|
||||
vrule.Status = report.StatusFail
|
||||
vrule.Status = policyreportv1alpha2.StatusFail
|
||||
}
|
||||
|
||||
if !policyReport {
|
||||
|
@ -753,15 +753,15 @@ func ProcessValidateEngineResponse(policy v1.PolicyInterface, validateResponse *
|
|||
|
||||
case response.RuleStatusError:
|
||||
rc.Error++
|
||||
vrule.Status = report.StatusError
|
||||
vrule.Status = policyreportv1alpha2.StatusError
|
||||
|
||||
case response.RuleStatusWarn:
|
||||
rc.Warn++
|
||||
vrule.Status = report.StatusWarn
|
||||
vrule.Status = policyreportv1alpha2.StatusWarn
|
||||
|
||||
case response.RuleStatusSkip:
|
||||
rc.Skip++
|
||||
vrule.Status = report.StatusSkip
|
||||
vrule.Status = policyreportv1alpha2.StatusSkip
|
||||
}
|
||||
|
||||
violatedRules = append(violatedRules, vrule)
|
||||
|
@ -771,11 +771,11 @@ func ProcessValidateEngineResponse(policy v1.PolicyInterface, validateResponse *
|
|||
|
||||
if !ruleFoundInEngineResponse {
|
||||
rc.Skip++
|
||||
vruleSkip := v1.ViolatedRule{
|
||||
vruleSkip := kyvernov1.ViolatedRule{
|
||||
Name: policyRule.Name,
|
||||
Type: "Validation",
|
||||
Message: policyRule.Validation.Message,
|
||||
Status: report.StatusSkip,
|
||||
Status: policyreportv1alpha2.StatusSkip,
|
||||
}
|
||||
violatedRules = append(violatedRules, vruleSkip)
|
||||
}
|
||||
|
@ -783,7 +783,7 @@ func ProcessValidateEngineResponse(policy v1.PolicyInterface, validateResponse *
|
|||
return buildPVInfo(validateResponse, violatedRules)
|
||||
}
|
||||
|
||||
func buildPVInfo(er *response.EngineResponse, violatedRules []v1.ViolatedRule) policyreport.Info {
|
||||
func buildPVInfo(er *response.EngineResponse, violatedRules []kyvernov1.ViolatedRule) policyreport.Info {
|
||||
info := policyreport.Info{
|
||||
PolicyName: er.PolicyResponse.Policy.Name,
|
||||
Namespace: er.PatchedResource.GetNamespace(),
|
||||
|
@ -797,7 +797,7 @@ func buildPVInfo(er *response.EngineResponse, violatedRules []v1.ViolatedRule) p
|
|||
return info
|
||||
}
|
||||
|
||||
func updateResultCounts(policy v1.PolicyInterface, engineResponse *response.EngineResponse, resPath string, rc *ResultCounts) {
|
||||
func updateResultCounts(policy kyvernov1.PolicyInterface, engineResponse *response.EngineResponse, resPath string, rc *ResultCounts) {
|
||||
printCount := 0
|
||||
for _, policyRule := range autogen.ComputeRules(policy) {
|
||||
ruleFoundInEngineResponse := false
|
||||
|
@ -825,7 +825,7 @@ func updateResultCounts(policy v1.PolicyInterface, engineResponse *response.Engi
|
|||
}
|
||||
}
|
||||
|
||||
func SetInStoreContext(mutatedPolicies []v1.PolicyInterface, variables map[string]string) map[string]string {
|
||||
func SetInStoreContext(mutatedPolicies []kyvernov1.PolicyInterface, variables map[string]string) map[string]string {
|
||||
storePolicies := make([]store.Policy, 0)
|
||||
for _, policy := range mutatedPolicies {
|
||||
storeRules := make([]store.Rule, 0)
|
||||
|
@ -859,7 +859,7 @@ func SetInStoreContext(mutatedPolicies []v1.PolicyInterface, variables map[strin
|
|||
return variables
|
||||
}
|
||||
|
||||
func processMutateEngineResponse(policy v1.PolicyInterface, mutateResponse *response.EngineResponse, resPath string, rc *ResultCounts, mutateLogPath string, stdin bool, mutateLogPathIsDir bool, resourceName string, printPatchResource bool) error {
|
||||
func processMutateEngineResponse(policy kyvernov1.PolicyInterface, mutateResponse *response.EngineResponse, resPath string, rc *ResultCounts, mutateLogPath string, stdin bool, mutateLogPathIsDir bool, resourceName string, printPatchResource bool) error {
|
||||
var policyHasMutate bool
|
||||
for _, rule := range autogen.ComputeRules(policy) {
|
||||
if rule.HasMutate() {
|
||||
|
@ -928,7 +928,7 @@ func processMutateEngineResponse(policy v1.PolicyInterface, mutateResponse *resp
|
|||
return nil
|
||||
}
|
||||
|
||||
func PrintMutatedPolicy(mutatedPolicies []v1.PolicyInterface) error {
|
||||
func PrintMutatedPolicy(mutatedPolicies []kyvernov1.PolicyInterface) error {
|
||||
for _, policy := range mutatedPolicies {
|
||||
p, err := json.Marshal(policy)
|
||||
if err != nil {
|
||||
|
@ -969,7 +969,7 @@ func CheckVariableForPolicy(valuesMap map[string]map[string]Resource, globalValM
|
|||
return thisPolicyResourceValues, nil
|
||||
}
|
||||
|
||||
func GetKindsFromPolicy(policy v1.PolicyInterface) map[string]struct{} {
|
||||
func GetKindsFromPolicy(policy kyvernov1.PolicyInterface) map[string]struct{} {
|
||||
kindOnwhichPolicyIsApplied := make(map[string]struct{})
|
||||
for _, rule := range autogen.ComputeRules(policy) {
|
||||
for _, kind := range rule.MatchResources.ResourceDescription.Kinds {
|
||||
|
@ -1014,8 +1014,8 @@ func GetPatchedResourceFromPath(fs billy.Filesystem, path string, isGit bool, po
|
|||
}
|
||||
|
||||
// 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{}
|
||||
func GetUserInfoFromPath(fs billy.Filesystem, path string, isGit bool, policyResourcePath string) (kyvernov1beta1.RequestInfo, store.Subject, error) {
|
||||
userInfo := &kyvernov1beta1.RequestInfo{}
|
||||
subjectInfo := &store.Subject{}
|
||||
if isGit {
|
||||
filep, err := fs.Open(filepath.Join(policyResourcePath, path))
|
||||
|
|
|
@ -10,7 +10,7 @@ import (
|
|||
"strings"
|
||||
|
||||
"github.com/go-git/go-billy/v5"
|
||||
v1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/autogen"
|
||||
client "github.com/kyverno/kyverno/pkg/dclient"
|
||||
engineutils "github.com/kyverno/kyverno/pkg/engine/utils"
|
||||
|
@ -26,7 +26,7 @@ import (
|
|||
// the resources are fetched from
|
||||
// - local paths to resources, if given
|
||||
// - the k8s cluster, if given
|
||||
func GetResources(policies []v1.PolicyInterface, resourcePaths []string, dClient client.Interface, cluster bool, namespace string, policyReport bool) ([]*unstructured.Unstructured, error) {
|
||||
func GetResources(policies []kyvernov1.PolicyInterface, resourcePaths []string, dClient client.Interface, cluster bool, namespace string, policyReport bool) ([]*unstructured.Unstructured, error) {
|
||||
resources := make([]*unstructured.Unstructured, 0)
|
||||
var err error
|
||||
resourceTypesMap := make(map[string]bool)
|
||||
|
@ -117,7 +117,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) {
|
||||
func GetResourcesWithTest(fs billy.Filesystem, policies []kyvernov1.PolicyInterface, resourcePaths []string, isGit bool, policyResourcePath string) ([]*unstructured.Unstructured, error) {
|
||||
resources := make([]*unstructured.Unstructured, 0)
|
||||
resourceTypesMap := make(map[string]bool)
|
||||
for _, policy := range policies {
|
||||
|
@ -288,7 +288,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 {
|
||||
func GetKindsFromRule(rule kyvernov1.Rule) map[string]bool {
|
||||
resourceTypesMap := make(map[string]bool)
|
||||
for _, kind := range rule.MatchResources.Kinds {
|
||||
if strings.Contains(kind, "/") {
|
||||
|
|
|
@ -10,7 +10,7 @@ import (
|
|||
"sync"
|
||||
"time"
|
||||
|
||||
urkyverno "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
kyvernoclient "github.com/kyverno/kyverno/pkg/client/clientset/versioned"
|
||||
"github.com/kyverno/kyverno/pkg/config"
|
||||
client "github.com/kyverno/kyverno/pkg/dclient"
|
||||
|
@ -445,24 +445,24 @@ func convertGR(pclient kyvernoclient.Interface) error {
|
|||
}
|
||||
|
||||
for _, gr := range grs.Items {
|
||||
ur := &urkyverno.UpdateRequest{
|
||||
ur := &kyvernov1beta1.UpdateRequest{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
GenerateName: "ur-",
|
||||
Namespace: config.KyvernoNamespace(),
|
||||
Labels: gr.GetLabels(),
|
||||
},
|
||||
Spec: urkyverno.UpdateRequestSpec{
|
||||
Type: urkyverno.Generate,
|
||||
Spec: kyvernov1beta1.UpdateRequestSpec{
|
||||
Type: kyvernov1beta1.Generate,
|
||||
Policy: gr.Spec.Policy,
|
||||
Resource: *gr.Spec.Resource.DeepCopy(),
|
||||
Context: urkyverno.UpdateRequestSpecContext{
|
||||
UserRequestInfo: urkyverno.RequestInfo{
|
||||
Context: kyvernov1beta1.UpdateRequestSpecContext{
|
||||
UserRequestInfo: kyvernov1beta1.RequestInfo{
|
||||
Roles: gr.Spec.Context.UserRequestInfo.DeepCopy().Roles,
|
||||
ClusterRoles: gr.Spec.Context.UserRequestInfo.DeepCopy().ClusterRoles,
|
||||
AdmissionUserInfo: *gr.Spec.Context.UserRequestInfo.AdmissionUserInfo.DeepCopy(),
|
||||
},
|
||||
|
||||
AdmissionRequestInfo: urkyverno.AdmissionRequestInfoObject{
|
||||
AdmissionRequestInfo: kyvernov1beta1.AdmissionRequestInfoObject{
|
||||
AdmissionRequest: gr.Spec.Context.AdmissionRequestInfo.DeepCopy().AdmissionRequest,
|
||||
Operation: gr.Spec.Context.AdmissionRequestInfo.DeepCopy().Operation,
|
||||
},
|
||||
|
@ -479,7 +479,7 @@ func convertGR(pclient kyvernoclient.Interface) error {
|
|||
logger.Info("successfully created UpdateRequest", "GR namespace", gr.GetNamespace(), "GR name", gr.GetName())
|
||||
}
|
||||
|
||||
new.Status.State = urkyverno.Pending
|
||||
new.Status.State = kyvernov1beta1.Pending
|
||||
if _, err := pclient.KyvernoV1beta1().UpdateRequests(config.KyvernoNamespace()).UpdateStatus(context.TODO(), new, metav1.UpdateOptions{}); err != nil {
|
||||
logger.Error(err, "failed to set UpdateRequest state to Pending")
|
||||
errors = append(errors, err)
|
||||
|
|
|
@ -6,7 +6,7 @@ import (
|
|||
"strconv"
|
||||
"strings"
|
||||
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/toggle"
|
||||
"github.com/kyverno/kyverno/pkg/utils"
|
||||
jsonutils "github.com/kyverno/kyverno/pkg/utils/json"
|
||||
|
@ -31,7 +31,7 @@ func isKindOtherthanPod(kinds []string) bool {
|
|||
return false
|
||||
}
|
||||
|
||||
func checkAutogenSupport(needed *bool, subjects ...kyverno.ResourceDescription) bool {
|
||||
func checkAutogenSupport(needed *bool, subjects ...kyvernov1.ResourceDescription) bool {
|
||||
for _, subject := range subjects {
|
||||
if subject.Name != "" || subject.Selector != nil || subject.Annotations != nil || isKindOtherthanPod(subject.Kinds) {
|
||||
return false
|
||||
|
@ -67,7 +67,7 @@ func stripCronJob(controllers string) string {
|
|||
// - Pod and PodControllers are not defined
|
||||
// - mutate.Patches/mutate.PatchesJSON6902/validate.deny/generate rule is defined
|
||||
// - otherwise it returns all pod controllers
|
||||
func CanAutoGen(spec *kyverno.Spec) (applyAutoGen bool, controllers string) {
|
||||
func CanAutoGen(spec *kyvernov1.Spec) (applyAutoGen bool, controllers string) {
|
||||
needed := false
|
||||
for _, rule := range spec.Rules {
|
||||
if rule.Mutation.PatchesJSON6902 != "" || rule.HasGenerate() {
|
||||
|
@ -110,7 +110,7 @@ func CanAutoGen(spec *kyverno.Spec) (applyAutoGen bool, controllers string) {
|
|||
}
|
||||
|
||||
// GetSupportedControllers returns the supported autogen controllers for a given spec.
|
||||
func GetSupportedControllers(spec *kyverno.Spec) []string {
|
||||
func GetSupportedControllers(spec *kyvernov1.Spec) []string {
|
||||
apply, controllers := CanAutoGen(spec)
|
||||
if !apply || controllers == "none" {
|
||||
return nil
|
||||
|
@ -124,7 +124,7 @@ func GetRequestedControllers(meta *metav1.ObjectMeta) []string {
|
|||
if annotations == nil {
|
||||
return nil
|
||||
}
|
||||
controllers, ok := annotations[kyverno.PodControllersAnnotation]
|
||||
controllers, ok := annotations[kyvernov1.PodControllersAnnotation]
|
||||
if !ok || controllers == "" {
|
||||
return nil
|
||||
}
|
||||
|
@ -136,7 +136,7 @@ func GetRequestedControllers(meta *metav1.ObjectMeta) []string {
|
|||
|
||||
// GetControllers computes the autogen controllers that should be applied to a policy.
|
||||
// It returns the requested, supported and effective controllers (intersection of requested and supported ones).
|
||||
func GetControllers(meta *metav1.ObjectMeta, spec *kyverno.Spec) ([]string, []string, []string) {
|
||||
func GetControllers(meta *metav1.ObjectMeta, spec *kyvernov1.Spec) ([]string, []string, []string) {
|
||||
// compute supported and requested controllers
|
||||
supported, requested := GetSupportedControllers(spec), GetRequestedControllers(meta)
|
||||
// no specific request, we can return supported controllers without further filtering
|
||||
|
@ -163,7 +163,7 @@ func GetControllers(meta *metav1.ObjectMeta, spec *kyverno.Spec) ([]string, []st
|
|||
// make sure all fields are applicable to pod controllers
|
||||
|
||||
// GenerateRulePatches generates rule for podControllers based on scenario A and C
|
||||
func GenerateRulePatches(spec *kyverno.Spec, controllers string) (rulePatches [][]byte, errs []error) {
|
||||
func GenerateRulePatches(spec *kyvernov1.Spec, controllers string) (rulePatches [][]byte, errs []error) {
|
||||
ruleIndex := make(map[string]int)
|
||||
for index, rule := range spec.Rules {
|
||||
ruleIndex[rule.Name] = index
|
||||
|
@ -212,8 +212,8 @@ func GenerateRulePatches(spec *kyverno.Spec, controllers string) (rulePatches []
|
|||
// make sure all fields are applicable to pod controllers
|
||||
|
||||
// generateRules generates rule for podControllers based on scenario A and C
|
||||
func generateRules(spec *kyverno.Spec, controllers string) []kyverno.Rule {
|
||||
var rules []kyverno.Rule
|
||||
func generateRules(spec *kyvernov1.Spec, controllers string) []kyvernov1.Rule {
|
||||
var rules []kyvernov1.Rule
|
||||
for i := range spec.Rules {
|
||||
// handle all other controllers other than CronJob
|
||||
if genRule := createRule(generateRuleForControllers(&spec.Rules[i], stripCronJob(controllers))); genRule != nil {
|
||||
|
@ -231,7 +231,7 @@ func generateRules(spec *kyverno.Spec, controllers string) []kyverno.Rule {
|
|||
return rules
|
||||
}
|
||||
|
||||
func convertRule(rule kyvernoRule, kind string) (*kyverno.Rule, error) {
|
||||
func convertRule(rule kyvernoRule, kind string) (*kyvernov1.Rule, error) {
|
||||
if bytes, err := json.Marshal(rule); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
|
@ -240,7 +240,7 @@ func convertRule(rule kyvernoRule, kind string) (*kyverno.Rule, error) {
|
|||
return nil, err
|
||||
}
|
||||
}
|
||||
out := kyverno.Rule{
|
||||
out := kyvernov1.Rule{
|
||||
Name: rule.Name,
|
||||
VerifyImages: rule.VerifyImages,
|
||||
}
|
||||
|
@ -265,7 +265,7 @@ func convertRule(rule kyvernoRule, kind string) (*kyverno.Rule, error) {
|
|||
return &out, nil
|
||||
}
|
||||
|
||||
func ComputeRules(p kyverno.PolicyInterface) []kyverno.Rule {
|
||||
func ComputeRules(p kyvernov1.PolicyInterface) []kyvernov1.Rule {
|
||||
if !toggle.AutogenInternals() {
|
||||
spec := p.GetSpec()
|
||||
return spec.Rules
|
||||
|
@ -273,14 +273,14 @@ func ComputeRules(p kyverno.PolicyInterface) []kyverno.Rule {
|
|||
return computeRules(p)
|
||||
}
|
||||
|
||||
func computeRules(p kyverno.PolicyInterface) []kyverno.Rule {
|
||||
func computeRules(p kyvernov1.PolicyInterface) []kyvernov1.Rule {
|
||||
spec := p.GetSpec()
|
||||
applyAutoGen, desiredControllers := CanAutoGen(spec)
|
||||
if !applyAutoGen {
|
||||
desiredControllers = "none"
|
||||
}
|
||||
ann := p.GetAnnotations()
|
||||
actualControllers, ok := ann[kyverno.PodControllersAnnotation]
|
||||
actualControllers, ok := ann[kyvernov1.PodControllersAnnotation]
|
||||
if !ok || !applyAutoGen {
|
||||
actualControllers = desiredControllers
|
||||
} else {
|
||||
|
@ -295,7 +295,7 @@ func computeRules(p kyverno.PolicyInterface) []kyverno.Rule {
|
|||
if len(genRules) == 0 {
|
||||
return spec.Rules
|
||||
}
|
||||
var out []kyverno.Rule
|
||||
var out []kyvernov1.Rule
|
||||
out = append(out, spec.Rules...)
|
||||
out = append(out, genRules...)
|
||||
return out
|
||||
|
|
|
@ -4,7 +4,7 @@ import (
|
|||
"reflect"
|
||||
"strings"
|
||||
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/engine/variables"
|
||||
"github.com/kyverno/kyverno/pkg/utils"
|
||||
kubeutils "github.com/kyverno/kyverno/pkg/utils/kube"
|
||||
|
@ -21,17 +21,17 @@ import (
|
|||
// https://github.com/kyverno/kyverno/issues/568
|
||||
|
||||
type kyvernoRule struct {
|
||||
Name string `json:"name"`
|
||||
MatchResources *kyverno.MatchResources `json:"match"`
|
||||
ExcludeResources *kyverno.MatchResources `json:"exclude,omitempty"`
|
||||
Context *[]kyverno.ContextEntry `json:"context,omitempty"`
|
||||
AnyAllConditions *apiextensions.JSON `json:"preconditions,omitempty"`
|
||||
Mutation *kyverno.Mutation `json:"mutate,omitempty"`
|
||||
Validation *kyverno.Validation `json:"validate,omitempty"`
|
||||
VerifyImages []kyverno.ImageVerification `json:"verifyImages,omitempty" yaml:"verifyImages,omitempty"`
|
||||
Name string `json:"name"`
|
||||
MatchResources *kyvernov1.MatchResources `json:"match"`
|
||||
ExcludeResources *kyvernov1.MatchResources `json:"exclude,omitempty"`
|
||||
Context *[]kyvernov1.ContextEntry `json:"context,omitempty"`
|
||||
AnyAllConditions *apiextensions.JSON `json:"preconditions,omitempty"`
|
||||
Mutation *kyvernov1.Mutation `json:"mutate,omitempty"`
|
||||
Validation *kyvernov1.Validation `json:"validate,omitempty"`
|
||||
VerifyImages []kyvernov1.ImageVerification `json:"verifyImages,omitempty" yaml:"verifyImages,omitempty"`
|
||||
}
|
||||
|
||||
func createRule(rule *kyverno.Rule) *kyvernoRule {
|
||||
func createRule(rule *kyvernov1.Rule) *kyvernoRule {
|
||||
if rule == nil {
|
||||
return nil
|
||||
}
|
||||
|
@ -39,25 +39,25 @@ func createRule(rule *kyverno.Rule) *kyvernoRule {
|
|||
Name: rule.Name,
|
||||
VerifyImages: rule.VerifyImages,
|
||||
}
|
||||
if !reflect.DeepEqual(rule.MatchResources, kyverno.MatchResources{}) {
|
||||
if !reflect.DeepEqual(rule.MatchResources, kyvernov1.MatchResources{}) {
|
||||
jsonFriendlyStruct.MatchResources = rule.MatchResources.DeepCopy()
|
||||
}
|
||||
if !reflect.DeepEqual(rule.ExcludeResources, kyverno.MatchResources{}) {
|
||||
if !reflect.DeepEqual(rule.ExcludeResources, kyvernov1.MatchResources{}) {
|
||||
jsonFriendlyStruct.ExcludeResources = rule.ExcludeResources.DeepCopy()
|
||||
}
|
||||
if !reflect.DeepEqual(rule.Mutation, kyverno.Mutation{}) {
|
||||
if !reflect.DeepEqual(rule.Mutation, kyvernov1.Mutation{}) {
|
||||
jsonFriendlyStruct.Mutation = rule.Mutation.DeepCopy()
|
||||
}
|
||||
if !reflect.DeepEqual(rule.Validation, kyverno.Validation{}) {
|
||||
if !reflect.DeepEqual(rule.Validation, kyvernov1.Validation{}) {
|
||||
jsonFriendlyStruct.Validation = rule.Validation.DeepCopy()
|
||||
}
|
||||
kyvernoAnyAllConditions, _ := utils.ApiextensionsJsonToKyvernoConditions(rule.GetAnyAllConditions())
|
||||
switch typedAnyAllConditions := kyvernoAnyAllConditions.(type) {
|
||||
case kyverno.AnyAllConditions:
|
||||
if !reflect.DeepEqual(typedAnyAllConditions, kyverno.AnyAllConditions{}) {
|
||||
case kyvernov1.AnyAllConditions:
|
||||
if !reflect.DeepEqual(typedAnyAllConditions, kyvernov1.AnyAllConditions{}) {
|
||||
jsonFriendlyStruct.AnyAllConditions = rule.DeepCopy().RawAnyAllConditions
|
||||
}
|
||||
case []kyverno.Condition:
|
||||
case []kyvernov1.Condition:
|
||||
if len(typedAnyAllConditions) > 0 {
|
||||
jsonFriendlyStruct.AnyAllConditions = rule.DeepCopy().RawAnyAllConditions
|
||||
}
|
||||
|
@ -68,9 +68,9 @@ func createRule(rule *kyverno.Rule) *kyvernoRule {
|
|||
return &jsonFriendlyStruct
|
||||
}
|
||||
|
||||
type generateResourceFilters func(kyverno.ResourceFilters, []string) kyverno.ResourceFilters
|
||||
type generateResourceFilters func(kyvernov1.ResourceFilters, []string) kyvernov1.ResourceFilters
|
||||
|
||||
func generateRule(name string, rule *kyverno.Rule, tplKey, shift string, kinds []string, grf generateResourceFilters) *kyverno.Rule {
|
||||
func generateRule(name string, rule *kyvernov1.Rule, tplKey, shift string, kinds []string, grf generateResourceFilters) *kyvernov1.Rule {
|
||||
if rule == nil {
|
||||
return nil
|
||||
}
|
||||
|
@ -94,7 +94,7 @@ func generateRule(name string, rule *kyverno.Rule, tplKey, shift string, kinds [
|
|||
}
|
||||
}
|
||||
if target := rule.Mutation.GetPatchStrategicMerge(); target != nil {
|
||||
newMutation := kyverno.Mutation{}
|
||||
newMutation := kyvernov1.Mutation{}
|
||||
newMutation.SetPatchStrategicMerge(
|
||||
map[string]interface{}{
|
||||
"spec": map[string]interface{}{
|
||||
|
@ -106,9 +106,9 @@ func generateRule(name string, rule *kyverno.Rule, tplKey, shift string, kinds [
|
|||
return rule
|
||||
}
|
||||
if len(rule.Mutation.ForEachMutation) > 0 && rule.Mutation.ForEachMutation != nil {
|
||||
var newForeachMutation []kyverno.ForEachMutation
|
||||
var newForeachMutation []kyvernov1.ForEachMutation
|
||||
for _, foreach := range rule.Mutation.ForEachMutation {
|
||||
temp := kyverno.ForEachMutation{
|
||||
temp := kyvernov1.ForEachMutation{
|
||||
List: foreach.List,
|
||||
Context: foreach.Context,
|
||||
AnyAllConditions: foreach.AnyAllConditions,
|
||||
|
@ -122,13 +122,13 @@ func generateRule(name string, rule *kyverno.Rule, tplKey, shift string, kinds [
|
|||
)
|
||||
newForeachMutation = append(newForeachMutation, temp)
|
||||
}
|
||||
rule.Mutation = kyverno.Mutation{
|
||||
rule.Mutation = kyvernov1.Mutation{
|
||||
ForEachMutation: newForeachMutation,
|
||||
}
|
||||
return rule
|
||||
}
|
||||
if target := rule.Validation.GetPattern(); target != nil {
|
||||
newValidate := kyverno.Validation{
|
||||
newValidate := kyvernov1.Validation{
|
||||
Message: variables.FindAndShiftReferences(logger, rule.Validation.Message, shift, "pattern"),
|
||||
}
|
||||
newValidate.SetPattern(
|
||||
|
@ -142,7 +142,7 @@ func generateRule(name string, rule *kyverno.Rule, tplKey, shift string, kinds [
|
|||
return rule
|
||||
}
|
||||
if rule.Validation.Deny != nil {
|
||||
deny := kyverno.Validation{
|
||||
deny := kyvernov1.Validation{
|
||||
Message: variables.FindAndShiftReferences(logger, rule.Validation.Message, shift, "deny"),
|
||||
Deny: rule.Validation.Deny,
|
||||
}
|
||||
|
@ -163,25 +163,25 @@ func generateRule(name string, rule *kyverno.Rule, tplKey, shift string, kinds [
|
|||
}
|
||||
patterns = append(patterns, newPattern)
|
||||
}
|
||||
rule.Validation = kyverno.Validation{
|
||||
rule.Validation = kyvernov1.Validation{
|
||||
Message: variables.FindAndShiftReferences(logger, rule.Validation.Message, shift, "anyPattern"),
|
||||
}
|
||||
rule.Validation.SetAnyPattern(patterns)
|
||||
return rule
|
||||
}
|
||||
if len(rule.Validation.ForEachValidation) > 0 && rule.Validation.ForEachValidation != nil {
|
||||
newForeachValidate := make([]kyverno.ForEachValidation, len(rule.Validation.ForEachValidation))
|
||||
newForeachValidate := make([]kyvernov1.ForEachValidation, len(rule.Validation.ForEachValidation))
|
||||
for i, foreach := range rule.Validation.ForEachValidation {
|
||||
newForeachValidate[i] = foreach
|
||||
}
|
||||
rule.Validation = kyverno.Validation{
|
||||
rule.Validation = kyvernov1.Validation{
|
||||
Message: variables.FindAndShiftReferences(logger, rule.Validation.Message, shift, "pattern"),
|
||||
ForEachValidation: newForeachValidate,
|
||||
}
|
||||
return rule
|
||||
}
|
||||
if rule.VerifyImages != nil {
|
||||
newVerifyImages := make([]kyverno.ImageVerification, len(rule.VerifyImages))
|
||||
newVerifyImages := make([]kyvernov1.ImageVerification, len(rule.VerifyImages))
|
||||
for i, vi := range rule.VerifyImages {
|
||||
newVerifyImages[i] = *vi.DeepCopy()
|
||||
}
|
||||
|
@ -203,7 +203,7 @@ func isAutogenRuleName(name string) bool {
|
|||
return strings.HasPrefix(name, "autogen-")
|
||||
}
|
||||
|
||||
func getAnyAllAutogenRule(v kyverno.ResourceFilters, match string, kinds []string) kyverno.ResourceFilters {
|
||||
func getAnyAllAutogenRule(v kyvernov1.ResourceFilters, match string, kinds []string) kyvernov1.ResourceFilters {
|
||||
anyKind := v.DeepCopy()
|
||||
for i, value := range v {
|
||||
if kubeutils.ContainsKind(value.Kinds, match) {
|
||||
|
@ -213,7 +213,7 @@ func getAnyAllAutogenRule(v kyverno.ResourceFilters, match string, kinds []strin
|
|||
return anyKind
|
||||
}
|
||||
|
||||
func generateRuleForControllers(rule *kyverno.Rule, controllers string) *kyverno.Rule {
|
||||
func generateRuleForControllers(rule *kyvernov1.Rule, controllers string) *kyvernov1.Rule {
|
||||
if isAutogenRuleName(rule.Name) || controllers == "" {
|
||||
logger.V(5).Info("skip generateRuleForControllers")
|
||||
return nil
|
||||
|
@ -253,13 +253,13 @@ func generateRuleForControllers(rule *kyverno.Rule, controllers string) *kyverno
|
|||
"template",
|
||||
"spec/template",
|
||||
strings.Split(controllers, ","),
|
||||
func(r kyverno.ResourceFilters, kinds []string) kyverno.ResourceFilters {
|
||||
func(r kyvernov1.ResourceFilters, kinds []string) kyvernov1.ResourceFilters {
|
||||
return getAnyAllAutogenRule(r, "Pod", kinds)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func generateCronJobRule(rule *kyverno.Rule, controllers string) *kyverno.Rule {
|
||||
func generateCronJobRule(rule *kyvernov1.Rule, controllers string) *kyvernov1.Rule {
|
||||
hasCronJob := strings.Contains(controllers, PodControllerCronJob) || strings.Contains(controllers, "all")
|
||||
if !hasCronJob {
|
||||
return nil
|
||||
|
@ -271,7 +271,7 @@ func generateCronJobRule(rule *kyverno.Rule, controllers string) *kyverno.Rule {
|
|||
"jobTemplate",
|
||||
"spec/jobTemplate/spec/template",
|
||||
[]string{PodControllerCronJob},
|
||||
func(r kyverno.ResourceFilters, kinds []string) kyverno.ResourceFilters {
|
||||
func(r kyvernov1.ResourceFilters, kinds []string) kyvernov1.ResourceFilters {
|
||||
return getAnyAllAutogenRule(r, "Job", kinds)
|
||||
},
|
||||
)
|
||||
|
|
|
@ -6,8 +6,8 @@ import (
|
|||
"reflect"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
urkyverno "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
"github.com/kyverno/kyverno/pkg/config"
|
||||
dclient "github.com/kyverno/kyverno/pkg/dclient"
|
||||
"github.com/kyverno/kyverno/pkg/engine"
|
||||
|
@ -18,8 +18,8 @@ import (
|
|||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
)
|
||||
|
||||
func NewBackgroundContext(dclient dclient.Interface, ur *urkyverno.UpdateRequest,
|
||||
policy kyverno.PolicyInterface,
|
||||
func NewBackgroundContext(dclient dclient.Interface, ur *kyvernov1beta1.UpdateRequest,
|
||||
policy kyvernov1.PolicyInterface,
|
||||
trigger *unstructured.Unstructured,
|
||||
cfg config.Configuration,
|
||||
namespaceLabels map[string]string,
|
||||
|
|
|
@ -5,7 +5,7 @@ import (
|
|||
"time"
|
||||
|
||||
logr "github.com/go-logr/logr"
|
||||
urkyverno "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
"github.com/kyverno/kyverno/pkg/common"
|
||||
dclient "github.com/kyverno/kyverno/pkg/dclient"
|
||||
v1 "k8s.io/api/admission/v1"
|
||||
|
@ -13,7 +13,7 @@ import (
|
|||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
)
|
||||
|
||||
func GetResource(client dclient.Interface, urSpec urkyverno.UpdateRequestSpec, log logr.Logger) (*unstructured.Unstructured, error) {
|
||||
func GetResource(client dclient.Interface, urSpec kyvernov1beta1.UpdateRequestSpec, log logr.Logger) (*unstructured.Unstructured, error) {
|
||||
resourceSpec := urSpec.Resource
|
||||
|
||||
get := func() (*unstructured.Unstructured, error) {
|
||||
|
@ -22,7 +22,7 @@ func GetResource(client dclient.Interface, urSpec urkyverno.UpdateRequestSpec, l
|
|||
}
|
||||
resource, err := client.GetResource(resourceSpec.APIVersion, resourceSpec.Kind, resourceSpec.Namespace, resourceSpec.Name)
|
||||
if err != nil {
|
||||
if urSpec.Type == urkyverno.Mutate && errors.IsNotFound(err) && urSpec.Context.AdmissionRequestInfo.Operation == v1.Delete {
|
||||
if urSpec.Type == kyvernov1beta1.Mutate && errors.IsNotFound(err) && urSpec.Context.AdmissionRequestInfo.Operation == v1.Delete {
|
||||
log.V(4).Info("trigger resource does not exist for mutateExisting rule", "operation", urSpec.Context.AdmissionRequestInfo.Operation)
|
||||
return nil, nil
|
||||
}
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
package common
|
||||
|
||||
import (
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
urkyverno "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
kyvernoclient "github.com/kyverno/kyverno/pkg/client/clientset/versioned"
|
||||
jsonutils "github.com/kyverno/kyverno/pkg/utils/json"
|
||||
"k8s.io/apimachinery/pkg/api/errors"
|
||||
|
@ -11,9 +11,9 @@ import (
|
|||
|
||||
// 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
|
||||
Skip(ur urkyverno.UpdateRequest, genResources []kyverno.ResourceSpec) error
|
||||
Failed(ur kyvernov1beta1.UpdateRequest, message string, genResources []kyvernov1.ResourceSpec) error
|
||||
Success(ur kyvernov1beta1.UpdateRequest, genResources []kyvernov1.ResourceSpec) error
|
||||
Skip(ur kyvernov1beta1.UpdateRequest, genResources []kyvernov1.ResourceSpec) error
|
||||
}
|
||||
|
||||
// StatusControl is default implementaation of GRStatusControlInterface
|
||||
|
@ -22,9 +22,9 @@ type StatusControl struct {
|
|||
}
|
||||
|
||||
// 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,
|
||||
func (sc StatusControl) Failed(ur kyvernov1beta1.UpdateRequest, message string, genResources []kyvernov1.ResourceSpec) error {
|
||||
genR := &kyvernov1beta1.UpdateRequestStatus{
|
||||
State: kyvernov1beta1.Failed,
|
||||
Message: message,
|
||||
}
|
||||
if genResources != nil {
|
||||
|
@ -41,14 +41,14 @@ func (sc StatusControl) Failed(ur urkyverno.UpdateRequest, message string, genRe
|
|||
log.Log.Error(err, "failed to patch update request status", "name", ur.Name)
|
||||
return err
|
||||
}
|
||||
log.Log.V(3).Info("updated update request status", "name", ur.Name, "status", string(kyverno.Failed))
|
||||
log.Log.V(3).Info("updated update request status", "name", ur.Name, "status", string(kyvernov1.Failed))
|
||||
return nil
|
||||
}
|
||||
|
||||
// Success sets the ur status.state to completed and clears message
|
||||
func (sc StatusControl) Success(ur urkyverno.UpdateRequest, genResources []kyverno.ResourceSpec) error {
|
||||
genR := &urkyverno.UpdateRequestStatus{
|
||||
State: urkyverno.Completed,
|
||||
func (sc StatusControl) Success(ur kyvernov1beta1.UpdateRequest, genResources []kyvernov1.ResourceSpec) error {
|
||||
genR := &kyvernov1beta1.UpdateRequestStatus{
|
||||
State: kyvernov1beta1.Completed,
|
||||
Message: "",
|
||||
}
|
||||
|
||||
|
@ -66,14 +66,14 @@ func (sc StatusControl) Success(ur urkyverno.UpdateRequest, genResources []kyver
|
|||
log.Log.Error(err, "failed to patch update request status", "name", ur.Name)
|
||||
return err
|
||||
}
|
||||
log.Log.V(3).Info("updated update request status", "name", ur.Name, "status", string(urkyverno.Completed))
|
||||
log.Log.V(3).Info("updated update request status", "name", ur.Name, "status", string(kyvernov1beta1.Completed))
|
||||
return nil
|
||||
}
|
||||
|
||||
// Success sets the ur status.state to completed and clears message
|
||||
func (sc StatusControl) Skip(ur urkyverno.UpdateRequest, genResources []kyverno.ResourceSpec) error {
|
||||
genR := &urkyverno.UpdateRequestStatus{
|
||||
State: urkyverno.Skip,
|
||||
func (sc StatusControl) Skip(ur kyvernov1beta1.UpdateRequest, genResources []kyvernov1.ResourceSpec) error {
|
||||
genR := &kyvernov1beta1.UpdateRequestStatus{
|
||||
State: kyvernov1beta1.Skip,
|
||||
Message: "",
|
||||
}
|
||||
|
||||
|
@ -91,6 +91,6 @@ func (sc StatusControl) Skip(ur urkyverno.UpdateRequest, genResources []kyverno.
|
|||
log.Log.Error(err, "failed to update UR status", "name", ur.Name)
|
||||
return err
|
||||
}
|
||||
log.Log.V(3).Info("updated UR status", "name", ur.Name, "status", string(kyverno.Skip))
|
||||
log.Log.V(3).Info("updated UR status", "name", ur.Name, "status", string(kyvernov1.Skip))
|
||||
return nil
|
||||
}
|
||||
|
|
|
@ -4,7 +4,7 @@ import (
|
|||
"context"
|
||||
"time"
|
||||
|
||||
urkyverno "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
kyvernoclient "github.com/kyverno/kyverno/pkg/client/clientset/versioned"
|
||||
"github.com/kyverno/kyverno/pkg/config"
|
||||
jsonutils "github.com/kyverno/kyverno/pkg/utils/json"
|
||||
|
@ -21,7 +21,7 @@ var DefaultRetry = wait.Backoff{
|
|||
}
|
||||
|
||||
// PatchUpdateRequest patches a update request object
|
||||
func PatchUpdateRequest(ur *urkyverno.UpdateRequest, patch jsonutils.Patch, client kyvernoclient.Interface, subresources ...string) (*urkyverno.UpdateRequest, error) {
|
||||
func PatchUpdateRequest(ur *kyvernov1beta1.UpdateRequest, patch jsonutils.Patch, client kyvernoclient.Interface, subresources ...string) (*kyvernov1beta1.UpdateRequest, error) {
|
||||
data, err := patch.ToPatchBytes()
|
||||
if nil != err {
|
||||
return ur, err
|
||||
|
|
|
@ -4,12 +4,12 @@ import (
|
|||
"strconv"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
urkyverno "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
dclient "github.com/kyverno/kyverno/pkg/dclient"
|
||||
apierrors "k8s.io/apimachinery/pkg/api/errors"
|
||||
)
|
||||
|
||||
func (c *Controller) processUR(ur urkyverno.UpdateRequest) error {
|
||||
func (c *Controller) processUR(ur kyvernov1beta1.UpdateRequest) error {
|
||||
logger := c.log.WithValues("kind", ur.Kind, "namespace", ur.Namespace, "name", ur.Name)
|
||||
// 1- Corresponding policy has been deleted
|
||||
// then we don't delete the generated resources
|
||||
|
@ -44,7 +44,7 @@ func (c *Controller) processUR(ur urkyverno.UpdateRequest) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func ownerResourceExists(log logr.Logger, client dclient.Interface, ur urkyverno.UpdateRequest) bool {
|
||||
func ownerResourceExists(log logr.Logger, client dclient.Interface, ur kyvernov1beta1.UpdateRequest) bool {
|
||||
_, err := client.GetResource("", ur.Spec.Resource.Kind, ur.Spec.Resource.Namespace, ur.Spec.Resource.Name)
|
||||
// trigger resources has been deleted
|
||||
if apierrors.IsNotFound(err) {
|
||||
|
@ -58,7 +58,7 @@ func ownerResourceExists(log logr.Logger, client dclient.Interface, ur urkyverno
|
|||
return true
|
||||
}
|
||||
|
||||
func deleteGeneratedResources(log logr.Logger, client dclient.Interface, ur urkyverno.UpdateRequest) error {
|
||||
func deleteGeneratedResources(log logr.Logger, client dclient.Interface, ur kyvernov1beta1.UpdateRequest) error {
|
||||
for _, genResource := range ur.Status.GeneratedResources {
|
||||
err := client.DeleteResource("", genResource.Kind, genResource.Namespace, genResource.Name, false)
|
||||
if err != nil && !apierrors.IsNotFound(err) {
|
||||
|
|
|
@ -4,8 +4,8 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
urkyverno "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
kyvernoclient "github.com/kyverno/kyverno/pkg/client/clientset/versioned"
|
||||
kyvernoinformer "github.com/kyverno/kyverno/pkg/client/informers/externalversions/kyverno/v1"
|
||||
urkyvernoinformer "github.com/kyverno/kyverno/pkg/client/informers/externalversions/kyverno/v1beta1"
|
||||
|
@ -94,14 +94,14 @@ func NewController(
|
|||
|
||||
func (c *Controller) deletePolicy(obj interface{}) {
|
||||
logger := c.log
|
||||
p, ok := obj.(*kyverno.ClusterPolicy)
|
||||
p, ok := obj.(*kyvernov1.ClusterPolicy)
|
||||
if !ok {
|
||||
tombstone, ok := obj.(cache.DeletedFinalStateUnknown)
|
||||
if !ok {
|
||||
logger.Info("couldn't get object from tombstone", "obj", obj)
|
||||
return
|
||||
}
|
||||
p, ok = tombstone.Obj.(*kyverno.ClusterPolicy)
|
||||
p, ok = tombstone.Obj.(*kyvernov1.ClusterPolicy)
|
||||
if !ok {
|
||||
logger.Info("Tombstone contained object that is not a Update Request", "obj", obj)
|
||||
return
|
||||
|
@ -114,12 +114,12 @@ func (c *Controller) deletePolicy(obj interface{}) {
|
|||
|
||||
// get the generated resource name from update request for log
|
||||
selector := labels.SelectorFromSet(labels.Set(map[string]string{
|
||||
urkyverno.URGeneratePolicyLabel: p.Name,
|
||||
kyvernov1beta1.URGeneratePolicyLabel: p.Name,
|
||||
}))
|
||||
|
||||
urList, err := c.urLister.List(selector)
|
||||
if err != nil {
|
||||
logger.Error(err, "failed to get update request for the resource", "label", urkyverno.URGeneratePolicyLabel)
|
||||
logger.Error(err, "failed to get update request for the resource", "label", kyvernov1beta1.URGeneratePolicyLabel)
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -145,14 +145,14 @@ func (c *Controller) deletePolicy(obj interface{}) {
|
|||
|
||||
func (c *Controller) deleteUR(obj interface{}) {
|
||||
logger := c.log
|
||||
ur, ok := obj.(*urkyverno.UpdateRequest)
|
||||
ur, ok := obj.(*kyvernov1beta1.UpdateRequest)
|
||||
if !ok {
|
||||
tombstone, ok := obj.(cache.DeletedFinalStateUnknown)
|
||||
if !ok {
|
||||
logger.Info("Couldn't get object from tombstone", "obj", obj)
|
||||
return
|
||||
}
|
||||
ur, ok = tombstone.Obj.(*urkyverno.UpdateRequest)
|
||||
ur, ok = tombstone.Obj.(*kyvernov1beta1.UpdateRequest)
|
||||
if !ok {
|
||||
logger.Info("ombstone contained object that is not a Update Request", "obj", obj)
|
||||
return
|
||||
|
@ -166,9 +166,9 @@ func (c *Controller) deleteUR(obj interface{}) {
|
|||
c.enqueue(ur)
|
||||
}
|
||||
|
||||
func (c *Controller) enqueue(ur *urkyverno.UpdateRequest) {
|
||||
func (c *Controller) enqueue(ur *kyvernov1beta1.UpdateRequest) {
|
||||
// skip enqueueing Pending requests
|
||||
if ur.Status.State == urkyverno.Pending {
|
||||
if ur.Status.State == kyvernov1beta1.Pending {
|
||||
return
|
||||
}
|
||||
|
||||
|
|
|
@ -11,8 +11,8 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
urkyverno "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
"github.com/kyverno/kyverno/pkg/autogen"
|
||||
"github.com/kyverno/kyverno/pkg/background/common"
|
||||
kyvernoclient "github.com/kyverno/kyverno/pkg/client/clientset/versioned"
|
||||
|
@ -95,11 +95,11 @@ func NewGenerateController(
|
|||
return &c, nil
|
||||
}
|
||||
|
||||
func (c *GenerateController) ProcessUR(ur *urkyverno.UpdateRequest) error {
|
||||
func (c *GenerateController) ProcessUR(ur *kyvernov1beta1.UpdateRequest) error {
|
||||
logger := c.log.WithValues("name", ur.Name, "policy", ur.Spec.Policy, "kind", ur.Spec.Resource.Kind, "apiVersion", ur.Spec.Resource.APIVersion, "namespace", ur.Spec.Resource.Namespace, "name", ur.Spec.Resource.Name)
|
||||
var err error
|
||||
var resource *unstructured.Unstructured
|
||||
var genResources []kyverno.ResourceSpec
|
||||
var genResources []kyvernov1.ResourceSpec
|
||||
var precreatedResource bool
|
||||
logger.Info("start processing UR", "ur", ur.Name, "resourceVersion", ur.GetResourceVersion())
|
||||
|
||||
|
@ -177,7 +177,7 @@ func (c *GenerateController) ProcessUR(ur *urkyverno.UpdateRequest) error {
|
|||
|
||||
const doesNotApply = "policy does not apply to resource"
|
||||
|
||||
func (c *GenerateController) applyGenerate(resource unstructured.Unstructured, ur urkyverno.UpdateRequest, namespaceLabels map[string]string) ([]kyverno.ResourceSpec, bool, error) {
|
||||
func (c *GenerateController) applyGenerate(resource unstructured.Unstructured, ur kyvernov1beta1.UpdateRequest, namespaceLabels map[string]string) ([]kyvernov1.ResourceSpec, bool, error) {
|
||||
logger := c.log.WithValues("name", ur.GetName(), "policy", ur.Spec.Policy, "kind", ur.Spec.Resource.Kind, "apiVersion", ur.Spec.Resource.APIVersion, "namespace", ur.Spec.Resource.Namespace, "name", ur.Spec.Resource.Name)
|
||||
logger.V(3).Info("applying generate policy rule")
|
||||
|
||||
|
@ -214,7 +214,7 @@ func (c *GenerateController) applyGenerate(resource unstructured.Unstructured, u
|
|||
if r.Status != response.RuleStatusPass {
|
||||
logger.V(4).Info("querying all update requests")
|
||||
selector := labels.SelectorFromSet(labels.Set(map[string]string{
|
||||
urkyverno.URGeneratePolicyLabel: engineResponse.PolicyResponse.Policy.Name,
|
||||
kyvernov1beta1.URGeneratePolicyLabel: engineResponse.PolicyResponse.Policy.Name,
|
||||
"generate.kyverno.io/resource-name": engineResponse.PolicyResponse.Resource.Name,
|
||||
"generate.kyverno.io/resource-kind": engineResponse.PolicyResponse.Resource.Kind,
|
||||
"generate.kyverno.io/resource-namespace": engineResponse.PolicyResponse.Resource.Namespace,
|
||||
|
@ -241,7 +241,7 @@ func (c *GenerateController) applyGenerate(resource unstructured.Unstructured, u
|
|||
}
|
||||
|
||||
// cleanupClonedResource deletes cloned resource if sync is not enabled for the clone policy
|
||||
func (c *GenerateController) cleanupClonedResource(targetSpec kyverno.ResourceSpec) error {
|
||||
func (c *GenerateController) cleanupClonedResource(targetSpec kyvernov1.ResourceSpec) error {
|
||||
target, err := c.client.GetResource(targetSpec.APIVersion, targetSpec.Kind, targetSpec.Namespace, targetSpec.Name)
|
||||
if err != nil {
|
||||
if !apierrors.IsNotFound(err) {
|
||||
|
@ -266,8 +266,8 @@ func (c *GenerateController) cleanupClonedResource(targetSpec kyverno.ResourceSp
|
|||
}
|
||||
|
||||
// getPolicySpec gets the policy spec from the ClusterPolicy/Policy
|
||||
func (c *GenerateController) getPolicySpec(ur urkyverno.UpdateRequest) (kyverno.ClusterPolicy, error) {
|
||||
var policy kyverno.ClusterPolicy
|
||||
func (c *GenerateController) getPolicySpec(ur kyvernov1beta1.UpdateRequest) (kyvernov1.ClusterPolicy, error) {
|
||||
var policy kyvernov1.ClusterPolicy
|
||||
|
||||
pNamespace, pName, err := cache.SplitMetaNamespaceKey(ur.Spec.Policy)
|
||||
if err != nil {
|
||||
|
@ -285,7 +285,7 @@ func (c *GenerateController) getPolicySpec(ur urkyverno.UpdateRequest) (kyverno.
|
|||
if err != nil {
|
||||
return policy, err
|
||||
}
|
||||
return kyverno.ClusterPolicy{
|
||||
return kyvernov1.ClusterPolicy{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: pName,
|
||||
},
|
||||
|
@ -294,7 +294,7 @@ func (c *GenerateController) getPolicySpec(ur urkyverno.UpdateRequest) (kyverno.
|
|||
}
|
||||
}
|
||||
|
||||
func updateStatus(statusControl common.StatusControlInterface, ur urkyverno.UpdateRequest, err error, genResources []kyverno.ResourceSpec, precreatedResource bool) error {
|
||||
func updateStatus(statusControl common.StatusControlInterface, ur kyvernov1beta1.UpdateRequest, err error, genResources []kyvernov1.ResourceSpec, precreatedResource bool) error {
|
||||
if err != nil {
|
||||
return statusControl.Failed(ur, err.Error(), genResources)
|
||||
} else if precreatedResource {
|
||||
|
@ -304,7 +304,7 @@ func updateStatus(statusControl common.StatusControlInterface, ur urkyverno.Upda
|
|||
return statusControl.Success(ur, genResources)
|
||||
}
|
||||
|
||||
func (c *GenerateController) applyGeneratePolicy(log logr.Logger, policyContext *engine.PolicyContext, ur urkyverno.UpdateRequest, applicableRules []string) (genResources []kyverno.ResourceSpec, processExisting bool, err error) {
|
||||
func (c *GenerateController) applyGeneratePolicy(log logr.Logger, policyContext *engine.PolicyContext, ur kyvernov1beta1.UpdateRequest, applicableRules []string) (genResources []kyvernov1.ResourceSpec, processExisting bool, err error) {
|
||||
// Get the response as the actions to be performed on the resource
|
||||
// - - substitute values
|
||||
policy := policyContext.Policy
|
||||
|
@ -326,7 +326,7 @@ func (c *GenerateController) applyGeneratePolicy(log logr.Logger, policyContext
|
|||
|
||||
startTime := time.Now()
|
||||
processExisting = false
|
||||
var genResource kyverno.ResourceSpec
|
||||
var genResource kyvernov1.ResourceSpec
|
||||
|
||||
if len(rule.MatchResources.Kinds) > 0 {
|
||||
if len(rule.MatchResources.Annotations) == 0 && rule.MatchResources.Selector == nil {
|
||||
|
@ -386,11 +386,11 @@ func getResourceInfo(object map[string]interface{}) (kind, name, namespace, apiv
|
|||
return
|
||||
}
|
||||
|
||||
func applyRule(log logr.Logger, client dclient.Interface, rule kyverno.Rule, resource unstructured.Unstructured, ctx context.EvalInterface, policy kyverno.PolicyInterface, ur urkyverno.UpdateRequest) (kyverno.ResourceSpec, error) {
|
||||
func applyRule(log logr.Logger, client dclient.Interface, rule kyvernov1.Rule, resource unstructured.Unstructured, ctx context.EvalInterface, policy kyvernov1.PolicyInterface, ur kyvernov1beta1.UpdateRequest) (kyvernov1.ResourceSpec, error) {
|
||||
var rdata map[string]interface{}
|
||||
var err error
|
||||
var mode ResourceMode
|
||||
var noGenResource kyverno.ResourceSpec
|
||||
var noGenResource kyvernov1.ResourceSpec
|
||||
genUnst, err := getUnstrRule(rule.Generation.DeepCopy())
|
||||
if err != nil {
|
||||
return noGenResource, err
|
||||
|
@ -404,7 +404,7 @@ func applyRule(log logr.Logger, client dclient.Interface, rule kyverno.Rule, res
|
|||
logger := log.WithValues("genKind", genKind, "genAPIVersion", genAPIVersion, "genNamespace", genNamespace, "genName", genName)
|
||||
|
||||
// Resource to be generated
|
||||
newGenResource := kyverno.ResourceSpec{
|
||||
newGenResource := kyvernov1.ResourceSpec{
|
||||
APIVersion: genAPIVersion,
|
||||
Kind: genKind,
|
||||
Namespace: genNamespace,
|
||||
|
@ -617,7 +617,7 @@ const (
|
|||
Update = "UPDATE"
|
||||
)
|
||||
|
||||
func getUnstrRule(rule *kyverno.Generation) (*unstructured.Unstructured, error) {
|
||||
func getUnstrRule(rule *kyvernov1.Generation) (*unstructured.Unstructured, error) {
|
||||
ruleData, err := json.Marshal(rule)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
|
|
@ -6,7 +6,7 @@ import (
|
|||
|
||||
"github.com/go-logr/logr"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
urkyverno "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
"github.com/kyverno/kyverno/pkg/background/common"
|
||||
kyvernoclient "github.com/kyverno/kyverno/pkg/client/clientset/versioned"
|
||||
kyvernolister "github.com/kyverno/kyverno/pkg/client/listers/kyverno/v1"
|
||||
|
@ -77,7 +77,7 @@ func NewMutateExistingController(
|
|||
return &c, nil
|
||||
}
|
||||
|
||||
func (c *MutateExistingController) ProcessUR(ur *urkyverno.UpdateRequest) error {
|
||||
func (c *MutateExistingController) ProcessUR(ur *kyvernov1beta1.UpdateRequest) error {
|
||||
logger := c.log.WithValues("name", ur.Name, "policy", ur.Spec.Policy, "kind", ur.Spec.Resource.Kind, "apiVersion", ur.Spec.Resource.APIVersion, "namespace", ur.Spec.Resource.Namespace, "name", ur.Spec.Resource.Name)
|
||||
var errs []error
|
||||
|
||||
|
@ -181,7 +181,7 @@ func (c *MutateExistingController) report(err error, policy, rule string, target
|
|||
c.eventGen.Add(events...)
|
||||
}
|
||||
|
||||
func updateURStatus(statusControl common.StatusControlInterface, ur urkyverno.UpdateRequest, err error) error {
|
||||
func updateURStatus(statusControl common.StatusControlInterface, ur kyvernov1beta1.UpdateRequest, err error) error {
|
||||
if err != nil {
|
||||
return statusControl.Failed(ur, err.Error(), nil)
|
||||
}
|
||||
|
|
|
@ -5,7 +5,7 @@ import (
|
|||
"strconv"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
urkyverno "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
"github.com/kyverno/kyverno/pkg/background/common"
|
||||
"github.com/kyverno/kyverno/pkg/background/generate"
|
||||
"github.com/kyverno/kyverno/pkg/background/mutate"
|
||||
|
@ -18,14 +18,14 @@ import (
|
|||
"k8s.io/client-go/util/retry"
|
||||
)
|
||||
|
||||
func (c *Controller) ProcessUR(ur *urkyverno.UpdateRequest) error {
|
||||
func (c *Controller) ProcessUR(ur *kyvernov1beta1.UpdateRequest) error {
|
||||
switch ur.Spec.Type {
|
||||
case urkyverno.Mutate:
|
||||
case kyvernov1beta1.Mutate:
|
||||
ctrl, _ := mutate.NewMutateExistingController(c.kyvernoClient, c.client,
|
||||
c.policyLister, c.npolicyLister, c.urLister, c.eventGen, c.log, c.Config)
|
||||
return ctrl.ProcessUR(ur)
|
||||
|
||||
case urkyverno.Generate:
|
||||
case kyvernov1beta1.Generate:
|
||||
ctrl, _ := generate.NewGenerateController(c.kyvernoClient, c.client,
|
||||
c.policyLister, c.npolicyLister, c.urLister, c.eventGen, c.nsLister, c.log, c.Config,
|
||||
)
|
||||
|
@ -34,7 +34,7 @@ func (c *Controller) ProcessUR(ur *urkyverno.UpdateRequest) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func (c *Controller) MarkUR(ur *urkyverno.UpdateRequest) (*urkyverno.UpdateRequest, bool, error) {
|
||||
func (c *Controller) MarkUR(ur *kyvernov1beta1.UpdateRequest) (*kyvernov1beta1.UpdateRequest, bool, error) {
|
||||
handler := ur.Status.Handler
|
||||
if handler != "" {
|
||||
if handler != config.KyvernoPodName() {
|
||||
|
@ -44,7 +44,7 @@ func (c *Controller) MarkUR(ur *urkyverno.UpdateRequest) (*urkyverno.UpdateReque
|
|||
}
|
||||
handler = config.KyvernoPodName()
|
||||
ur.Status.Handler = handler
|
||||
var updateRequest *urkyverno.UpdateRequest
|
||||
var updateRequest *kyvernov1beta1.UpdateRequest
|
||||
|
||||
err := retry.RetryOnConflict(common.DefaultRetry, func() error {
|
||||
var retryError error
|
||||
|
@ -55,19 +55,19 @@ func (c *Controller) MarkUR(ur *urkyverno.UpdateRequest) (*urkyverno.UpdateReque
|
|||
return updateRequest, true, err
|
||||
}
|
||||
|
||||
func (c *Controller) UnmarkUR(ur *urkyverno.UpdateRequest) error {
|
||||
func (c *Controller) UnmarkUR(ur *kyvernov1beta1.UpdateRequest) error {
|
||||
_, err := c.PatchHandler(ur, "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if ur.Spec.Type == urkyverno.Mutate && ur.Status.State == urkyverno.Completed {
|
||||
if ur.Spec.Type == kyvernov1beta1.Mutate && ur.Status.State == kyvernov1beta1.Completed {
|
||||
return c.kyvernoClient.KyvernoV1beta1().UpdateRequests(config.KyvernoNamespace()).Delete(context.TODO(), ur.GetName(), metav1.DeleteOptions{})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Controller) PatchHandler(ur *urkyverno.UpdateRequest, val string) (*urkyverno.UpdateRequest, error) {
|
||||
func (c *Controller) PatchHandler(ur *kyvernov1beta1.UpdateRequest, val string) (*kyvernov1beta1.UpdateRequest, error) {
|
||||
patch := jsonutils.NewPatch(
|
||||
"/status/handler",
|
||||
"replace",
|
||||
|
@ -85,7 +85,7 @@ func (c *Controller) PatchHandler(ur *urkyverno.UpdateRequest, val string) (*urk
|
|||
return updateUR, nil
|
||||
}
|
||||
|
||||
func (c *Controller) HandleDeleteUR(ur urkyverno.UpdateRequest) error {
|
||||
func (c *Controller) HandleDeleteUR(ur kyvernov1beta1.UpdateRequest) error {
|
||||
logger := c.log.WithValues("kind", ur.Kind, "namespace", ur.Namespace, "name", ur.Name)
|
||||
// 1- Corresponding policy has been deleted
|
||||
// then we don't delete the generated resources
|
||||
|
@ -120,7 +120,7 @@ func (c *Controller) HandleDeleteUR(ur urkyverno.UpdateRequest) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func ownerResourceExists(log logr.Logger, client dclient.Interface, ur urkyverno.UpdateRequest) bool {
|
||||
func ownerResourceExists(log logr.Logger, client dclient.Interface, ur kyvernov1beta1.UpdateRequest) bool {
|
||||
_, err := client.GetResource("", ur.Spec.Resource.Kind, ur.Spec.Resource.Namespace, ur.Spec.Resource.Name)
|
||||
// trigger resources has been deleted
|
||||
if apierrors.IsNotFound(err) {
|
||||
|
@ -134,7 +134,7 @@ func ownerResourceExists(log logr.Logger, client dclient.Interface, ur urkyverno
|
|||
return true
|
||||
}
|
||||
|
||||
func deleteGeneratedResources(log logr.Logger, client dclient.Interface, ur urkyverno.UpdateRequest) error {
|
||||
func deleteGeneratedResources(log logr.Logger, client dclient.Interface, ur kyvernov1beta1.UpdateRequest) error {
|
||||
for _, genResource := range ur.Status.GeneratedResources {
|
||||
err := client.DeleteResource("", genResource.Kind, genResource.Namespace, genResource.Name, false)
|
||||
if err != nil && !apierrors.IsNotFound(err) {
|
||||
|
|
|
@ -6,8 +6,8 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
urkyverno "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
"github.com/kyverno/kyverno/pkg/autogen"
|
||||
common "github.com/kyverno/kyverno/pkg/background/common"
|
||||
kyvernoclient "github.com/kyverno/kyverno/pkg/client/clientset/versioned"
|
||||
|
@ -229,8 +229,8 @@ func (c *Controller) enqueueUpdateRequest(obj interface{}) {
|
|||
|
||||
func (c *Controller) updatePolicy(old, cur interface{}) {
|
||||
logger := c.log
|
||||
oldP := old.(*kyverno.ClusterPolicy)
|
||||
curP := cur.(*kyverno.ClusterPolicy)
|
||||
oldP := old.(*kyvernov1.ClusterPolicy)
|
||||
curP := cur.(*kyvernov1.ClusterPolicy)
|
||||
if oldP.ResourceVersion == curP.ResourceVersion {
|
||||
// Periodic resync will send update events for all known Namespace.
|
||||
// Two different versions of the same replica set will always have different RVs.
|
||||
|
@ -268,7 +268,7 @@ func (c *Controller) updatePolicy(old, cur interface{}) {
|
|||
}
|
||||
|
||||
func (c *Controller) addUR(obj interface{}) {
|
||||
ur := obj.(*urkyverno.UpdateRequest)
|
||||
ur := obj.(*kyvernov1beta1.UpdateRequest)
|
||||
if ur.Status.Handler != "" {
|
||||
return
|
||||
}
|
||||
|
@ -276,8 +276,8 @@ func (c *Controller) addUR(obj interface{}) {
|
|||
}
|
||||
|
||||
func (c *Controller) updateUR(old, cur interface{}) {
|
||||
oldUr := old.(*urkyverno.UpdateRequest)
|
||||
curUr := cur.(*urkyverno.UpdateRequest)
|
||||
oldUr := old.(*kyvernov1beta1.UpdateRequest)
|
||||
curUr := cur.(*kyvernov1beta1.UpdateRequest)
|
||||
if oldUr.ResourceVersion == curUr.ResourceVersion {
|
||||
// Periodic resync will send update events for all known Namespace.
|
||||
// Two different versions of the same replica set will always have different RVs.
|
||||
|
@ -285,7 +285,7 @@ func (c *Controller) updateUR(old, cur interface{}) {
|
|||
}
|
||||
// only process the ones that are in "Pending"/"Completed" state
|
||||
// if the UPDATE Request fails due to incorrect policy, it will be requeued during policy update
|
||||
if curUr.Status.State != urkyverno.Pending {
|
||||
if curUr.Status.State != kyvernov1beta1.Pending {
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -297,14 +297,14 @@ func (c *Controller) updateUR(old, cur interface{}) {
|
|||
|
||||
func (c *Controller) deleteUR(obj interface{}) {
|
||||
logger := c.log
|
||||
ur, ok := obj.(*urkyverno.UpdateRequest)
|
||||
ur, ok := obj.(*kyvernov1beta1.UpdateRequest)
|
||||
if !ok {
|
||||
tombstone, ok := obj.(cache.DeletedFinalStateUnknown)
|
||||
if !ok {
|
||||
logger.Info("Couldn't get object from tombstone", "obj", obj)
|
||||
return
|
||||
}
|
||||
ur, ok = tombstone.Obj.(*urkyverno.UpdateRequest)
|
||||
ur, ok = tombstone.Obj.(*kyvernov1beta1.UpdateRequest)
|
||||
if !ok {
|
||||
logger.Info("tombstone contained object that is not a Update Request CR", "obj", obj)
|
||||
return
|
||||
|
|
|
@ -6,7 +6,7 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernoclient "github.com/kyverno/kyverno/pkg/client/clientset/versioned"
|
||||
urkyvernolister "github.com/kyverno/kyverno/pkg/client/listers/kyverno/v1beta1"
|
||||
dclient "github.com/kyverno/kyverno/pkg/dclient"
|
||||
|
@ -79,7 +79,7 @@ func RetryFunc(retryInterval, timeout time.Duration, run func() error, msg strin
|
|||
}
|
||||
}
|
||||
|
||||
func ProcessDeletePolicyForCloneGenerateRule(policy kyverno.PolicyInterface, client dclient.Interface, kyvernoClient kyvernoclient.Interface, urlister urkyvernolister.UpdateRequestNamespaceLister, pName string, logger logr.Logger) bool {
|
||||
func ProcessDeletePolicyForCloneGenerateRule(policy kyvernov1.PolicyInterface, client dclient.Interface, kyvernoClient kyvernoclient.Interface, urlister urkyvernolister.UpdateRequestNamespaceLister, pName string, logger logr.Logger) bool {
|
||||
generatePolicyWithClone := false
|
||||
for _, rule := range policy.GetSpec().Rules {
|
||||
clone, sync := rule.GetCloneSyncForGenerate()
|
||||
|
@ -108,7 +108,7 @@ func ProcessDeletePolicyForCloneGenerateRule(policy kyverno.PolicyInterface, cli
|
|||
return generatePolicyWithClone
|
||||
}
|
||||
|
||||
func updateSourceResource(pName string, rule kyverno.Rule, client dclient.Interface, log logr.Logger) error {
|
||||
func updateSourceResource(pName string, rule kyvernov1.Rule, client dclient.Interface, log logr.Logger) error {
|
||||
obj, err := client.GetResource("", rule.Generation.Kind, rule.Generation.Clone.Namespace, rule.Generation.Clone.Name)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "source resource %s/%s/%s not found", rule.Generation.Kind, rule.Generation.Clone.Namespace, rule.Generation.Clone.Name)
|
||||
|
|
|
@ -14,7 +14,7 @@ import (
|
|||
gcrremote "github.com/google/go-containerregistry/pkg/v1/remote"
|
||||
"github.com/in-toto/in-toto-golang/in_toto"
|
||||
wildcard "github.com/kyverno/go-wildcard"
|
||||
v1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/registryclient"
|
||||
"github.com/kyverno/kyverno/pkg/utils"
|
||||
"github.com/pkg/errors"
|
||||
|
@ -219,7 +219,7 @@ func loadCertChain(pem []byte) ([]*x509.Certificate, error) {
|
|||
|
||||
// FetchAttestations retrieves signed attestations and decodes them into in-toto statements
|
||||
// https://github.com/in-toto/attestation/blob/main/spec/README.md#statement
|
||||
func FetchAttestations(imageRef string, imageVerify v1.ImageVerification) ([]map[string]interface{}, error) {
|
||||
func FetchAttestations(imageRef string, imageVerify kyvernov1.ImageVerification) ([]map[string]interface{}, error) {
|
||||
ctx := context.Background()
|
||||
var err error
|
||||
|
||||
|
|
|
@ -3,7 +3,7 @@ package engine
|
|||
import (
|
||||
"time"
|
||||
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/autogen"
|
||||
"github.com/kyverno/kyverno/pkg/engine/common"
|
||||
"github.com/kyverno/kyverno/pkg/engine/response"
|
||||
|
@ -57,7 +57,7 @@ func filterRules(policyContext *PolicyContext, startTime time.Time) *response.En
|
|||
return resp
|
||||
}
|
||||
|
||||
func filterRule(rule kyverno.Rule, policyContext *PolicyContext) *response.RuleResponse {
|
||||
func filterRule(rule kyvernov1.Rule, policyContext *PolicyContext) *response.RuleResponse {
|
||||
if !rule.HasGenerate() && !rule.IsMutateExisting() {
|
||||
return nil
|
||||
}
|
||||
|
|
|
@ -3,7 +3,7 @@ package common
|
|||
import (
|
||||
"fmt"
|
||||
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/utils"
|
||||
"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
|
||||
)
|
||||
|
@ -28,10 +28,10 @@ func TransformConditions(original apiextensions.JSON) (interface{}, error) {
|
|||
return nil, err
|
||||
}
|
||||
switch typedValue := oldConditions.(type) {
|
||||
case kyverno.AnyAllConditions:
|
||||
case kyvernov1.AnyAllConditions:
|
||||
return *typedValue.DeepCopy(), nil
|
||||
case []kyverno.Condition: // backwards compatibility
|
||||
var copies []kyverno.Condition
|
||||
case []kyvernov1.Condition: // backwards compatibility
|
||||
var copies []kyvernov1.Condition
|
||||
for _, condition := range typedValue {
|
||||
copies = append(copies, *condition.DeepCopy())
|
||||
}
|
||||
|
|
|
@ -3,7 +3,7 @@ package engine
|
|||
import (
|
||||
"fmt"
|
||||
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/engine/context"
|
||||
"github.com/kyverno/kyverno/pkg/engine/mutate"
|
||||
"github.com/kyverno/kyverno/pkg/engine/response"
|
||||
|
@ -14,7 +14,7 @@ import (
|
|||
|
||||
// ForceMutate does not check any conditions, it simply mutates the given resource
|
||||
// It is used to validate mutation logic, and for tests.
|
||||
func ForceMutate(ctx context.Interface, policy kyverno.PolicyInterface, resource unstructured.Unstructured) (unstructured.Unstructured, error) {
|
||||
func ForceMutate(ctx context.Interface, policy kyvernov1.PolicyInterface, resource unstructured.Unstructured) (unstructured.Unstructured, error) {
|
||||
logger := log.Log.WithName("EngineForceMutate").WithValues("policy", policy.GetName(), "kind", resource.GetKind(),
|
||||
"namespace", resource.GetNamespace(), "name", resource.GetName())
|
||||
|
||||
|
@ -59,7 +59,7 @@ func ForceMutate(ctx context.Interface, policy kyverno.PolicyInterface, resource
|
|||
}
|
||||
|
||||
// removeConditions mutates the rule to remove AnyAllConditions
|
||||
func removeConditions(rule *kyverno.Rule) {
|
||||
func removeConditions(rule *kyvernov1.Rule) {
|
||||
if rule.GetAnyAllConditions() != nil {
|
||||
rule.SetAnyAllConditions(nil)
|
||||
}
|
||||
|
|
|
@ -3,7 +3,7 @@ package engine
|
|||
import (
|
||||
"time"
|
||||
|
||||
urkyverno "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
"github.com/kyverno/kyverno/pkg/autogen"
|
||||
"github.com/kyverno/kyverno/pkg/engine/response"
|
||||
"k8s.io/client-go/tools/cache"
|
||||
|
@ -11,7 +11,7 @@ import (
|
|||
)
|
||||
|
||||
// GenerateResponse checks for validity of generate rule on the resource
|
||||
func GenerateResponse(policyContext *PolicyContext, gr urkyverno.UpdateRequest) (resp *response.EngineResponse) {
|
||||
func GenerateResponse(policyContext *PolicyContext, gr kyvernov1beta1.UpdateRequest) (resp *response.EngineResponse) {
|
||||
policyStartTime := time.Now()
|
||||
return filterGenerateRules(policyContext, gr.Spec.Policy, policyStartTime)
|
||||
}
|
||||
|
|
|
@ -11,7 +11,7 @@ import (
|
|||
"github.com/google/go-containerregistry/pkg/name"
|
||||
"github.com/google/go-containerregistry/pkg/v1/remote"
|
||||
"github.com/kyverno/go-wildcard"
|
||||
v1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/autogen"
|
||||
"github.com/kyverno/kyverno/pkg/cosign"
|
||||
"github.com/kyverno/kyverno/pkg/engine/context"
|
||||
|
@ -107,13 +107,13 @@ func VerifyAndPatchImages(policyContext *PolicyContext) (*response.EngineRespons
|
|||
return resp, ivm
|
||||
}
|
||||
|
||||
func appendError(resp *response.EngineResponse, rule *v1.Rule, msg string, status response.RuleStatus) {
|
||||
func appendError(resp *response.EngineResponse, rule *kyvernov1.Rule, msg string, status response.RuleStatus) {
|
||||
rr := ruleResponse(*rule, response.ImageVerify, msg, status, nil)
|
||||
resp.PolicyResponse.Rules = append(resp.PolicyResponse.Rules, *rr)
|
||||
incrementErrorCount(resp)
|
||||
}
|
||||
|
||||
func substituteVariables(rule *v1.Rule, ctx context.EvalInterface, logger logr.Logger) (*v1.Rule, error) {
|
||||
func substituteVariables(rule *kyvernov1.Rule, ctx context.EvalInterface, logger logr.Logger) (*kyvernov1.Rule, error) {
|
||||
// remove attestations as variables are not substituted in them
|
||||
ruleCopy := *rule.DeepCopy()
|
||||
for i := range ruleCopy.VerifyImages {
|
||||
|
@ -137,14 +137,14 @@ func substituteVariables(rule *v1.Rule, ctx context.EvalInterface, logger logr.L
|
|||
type imageVerifier struct {
|
||||
logger logr.Logger
|
||||
policyContext *PolicyContext
|
||||
rule *v1.Rule
|
||||
rule *kyvernov1.Rule
|
||||
resp *response.EngineResponse
|
||||
ivm *ImageVerificationMetadata
|
||||
}
|
||||
|
||||
// verify applies policy rules to each matching image. The policy rule results and annotation patches are
|
||||
// added to tme imageVerifier `resp` and `ivm` fields.
|
||||
func (iv *imageVerifier) verify(imageVerify v1.ImageVerification, images map[string]map[string]apiutils.ImageInfo) {
|
||||
func (iv *imageVerifier) verify(imageVerify kyvernov1.ImageVerification, images map[string]map[string]apiutils.ImageInfo) {
|
||||
// for backward compatibility
|
||||
imageVerify = *imageVerify.Convert()
|
||||
|
||||
|
@ -277,7 +277,7 @@ func imageMatches(image string, imagePatterns []string) bool {
|
|||
return false
|
||||
}
|
||||
|
||||
func (iv *imageVerifier) verifySignatures(imageVerify v1.ImageVerification, imageInfo apiutils.ImageInfo) (*response.RuleResponse, string) {
|
||||
func (iv *imageVerifier) verifySignatures(imageVerify kyvernov1.ImageVerification, imageInfo apiutils.ImageInfo) (*response.RuleResponse, string) {
|
||||
image := imageInfo.String()
|
||||
iv.logger.V(2).Info("verifying image signatures", "image", image, "attestors", len(imageVerify.Attestors), "attestations", len(imageVerify.Attestations))
|
||||
|
||||
|
@ -297,7 +297,7 @@ func (iv *imageVerifier) verifySignatures(imageVerify v1.ImageVerification, imag
|
|||
return ruleResponse(*iv.rule, response.ImageVerify, msg, response.RuleStatusPass, nil), digest
|
||||
}
|
||||
|
||||
func (iv *imageVerifier) verifyAttestorSet(attestorSet v1.AttestorSet, imageVerify v1.ImageVerification, image, path string) (string, error) {
|
||||
func (iv *imageVerifier) verifyAttestorSet(attestorSet kyvernov1.AttestorSet, imageVerify kyvernov1.ImageVerification, image, path string) (string, error) {
|
||||
var errorList []error
|
||||
verifiedCount := 0
|
||||
attestorSet = expandStaticKeys(attestorSet)
|
||||
|
@ -309,7 +309,7 @@ func (iv *imageVerifier) verifyAttestorSet(attestorSet v1.AttestorSet, imageVeri
|
|||
attestorPath := fmt.Sprintf("%s.entries[%d]", path, i)
|
||||
|
||||
if a.Attestor != nil {
|
||||
nestedAttestorSet, err := v1.AttestorSetUnmarshal(a.Attestor)
|
||||
nestedAttestorSet, err := kyvernov1.AttestorSetUnmarshal(a.Attestor)
|
||||
if err != nil {
|
||||
entryError = errors.Wrapf(err, "failed to unmarshal nested attestor %s", attestorPath)
|
||||
} else {
|
||||
|
@ -340,8 +340,8 @@ func (iv *imageVerifier) verifyAttestorSet(attestorSet v1.AttestorSet, imageVeri
|
|||
return "", err
|
||||
}
|
||||
|
||||
func expandStaticKeys(attestorSet v1.AttestorSet) v1.AttestorSet {
|
||||
var entries []v1.Attestor
|
||||
func expandStaticKeys(attestorSet kyvernov1.AttestorSet) kyvernov1.AttestorSet {
|
||||
var entries []kyvernov1.Attestor
|
||||
for _, e := range attestorSet.Entries {
|
||||
if e.Keys != nil {
|
||||
keys := splitPEM(e.Keys.PublicKeys)
|
||||
|
@ -355,7 +355,7 @@ func expandStaticKeys(attestorSet v1.AttestorSet) v1.AttestorSet {
|
|||
entries = append(entries, e)
|
||||
}
|
||||
|
||||
return v1.AttestorSet{
|
||||
return kyvernov1.AttestorSet{
|
||||
Count: attestorSet.Count,
|
||||
Entries: entries,
|
||||
}
|
||||
|
@ -370,11 +370,11 @@ func splitPEM(pem string) []string {
|
|||
return keys[0 : len(keys)-1]
|
||||
}
|
||||
|
||||
func createStaticKeyAttestors(keys []string) []v1.Attestor {
|
||||
var attestors []v1.Attestor
|
||||
func createStaticKeyAttestors(keys []string) []kyvernov1.Attestor {
|
||||
var attestors []kyvernov1.Attestor
|
||||
for _, k := range keys {
|
||||
a := v1.Attestor{
|
||||
Keys: &v1.StaticKeyAttestor{
|
||||
a := kyvernov1.Attestor{
|
||||
Keys: &kyvernov1.StaticKeyAttestor{
|
||||
PublicKeys: k,
|
||||
},
|
||||
}
|
||||
|
@ -384,7 +384,7 @@ func createStaticKeyAttestors(keys []string) []v1.Attestor {
|
|||
return attestors
|
||||
}
|
||||
|
||||
func getRequiredCount(as v1.AttestorSet) int {
|
||||
func getRequiredCount(as kyvernov1.AttestorSet) int {
|
||||
if as.Count == nil || *as.Count == 0 {
|
||||
return len(as.Entries)
|
||||
}
|
||||
|
@ -392,7 +392,7 @@ func getRequiredCount(as v1.AttestorSet) int {
|
|||
return *as.Count
|
||||
}
|
||||
|
||||
func (iv *imageVerifier) buildOptionsAndPath(attestor v1.Attestor, imageVerify v1.ImageVerification, image string) (*cosign.Options, string) {
|
||||
func (iv *imageVerifier) buildOptionsAndPath(attestor kyvernov1.Attestor, imageVerify kyvernov1.ImageVerification, image string) (*cosign.Options, string) {
|
||||
path := ""
|
||||
opts := &cosign.Options{
|
||||
ImageRef: image,
|
||||
|
@ -448,7 +448,7 @@ func makeAddDigestPatch(imageInfo apiutils.ImageInfo, digest string) ([]byte, er
|
|||
return json.Marshal(patch)
|
||||
}
|
||||
|
||||
func (iv *imageVerifier) verifyAttestations(imageVerify v1.ImageVerification, imageInfo apiutils.ImageInfo) *response.RuleResponse {
|
||||
func (iv *imageVerifier) verifyAttestations(imageVerify kyvernov1.ImageVerification, imageInfo apiutils.ImageInfo) *response.RuleResponse {
|
||||
image := imageInfo.String()
|
||||
start := time.Now()
|
||||
|
||||
|
@ -500,7 +500,7 @@ func buildStatementMap(statements []map[string]interface{}) map[string][]map[str
|
|||
return results
|
||||
}
|
||||
|
||||
func (iv *imageVerifier) checkAttestations(a v1.Attestation, s map[string]interface{}, img apiutils.ImageInfo) (bool, error) {
|
||||
func (iv *imageVerifier) checkAttestations(a kyvernov1.Attestation, s map[string]interface{}, img apiutils.ImageInfo) (bool, error) {
|
||||
if len(a.Conditions) == 0 {
|
||||
return true, nil
|
||||
}
|
||||
|
|
|
@ -6,14 +6,14 @@ import (
|
|||
|
||||
"github.com/go-logr/logr"
|
||||
gojmespath "github.com/jmespath/go-jmespath"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/engine/response"
|
||||
apiutils "github.com/kyverno/kyverno/pkg/utils/api"
|
||||
"github.com/pkg/errors"
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
)
|
||||
|
||||
func processImageValidationRule(log logr.Logger, ctx *PolicyContext, rule *kyverno.Rule) *response.RuleResponse {
|
||||
func processImageValidationRule(log logr.Logger, ctx *PolicyContext, rule *kyvernov1.Rule) *response.RuleResponse {
|
||||
if isDeleteRequest(ctx) {
|
||||
return nil
|
||||
}
|
||||
|
@ -35,7 +35,7 @@ func processImageValidationRule(log logr.Logger, ctx *PolicyContext, rule *kyver
|
|||
}
|
||||
|
||||
if !preconditionsPassed {
|
||||
if ctx.Policy.GetSpec().ValidationFailureAction == kyverno.Audit {
|
||||
if ctx.Policy.GetSpec().ValidationFailureAction == kyvernov1.Audit {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
@ -66,7 +66,7 @@ func processImageValidationRule(log logr.Logger, ctx *PolicyContext, rule *kyver
|
|||
return ruleResponse(*rule, response.Validation, "image verified", response.RuleStatusPass, nil)
|
||||
}
|
||||
|
||||
func validateImage(ctx *PolicyContext, imageVerify *kyverno.ImageVerification, name string, imageInfo apiutils.ImageInfo, log logr.Logger) error {
|
||||
func validateImage(ctx *PolicyContext, imageVerify *kyvernov1.ImageVerification, name string, imageInfo apiutils.ImageInfo, log logr.Logger) error {
|
||||
image := imageInfo.String()
|
||||
if imageVerify.VerifyDigest && imageInfo.Digest == "" {
|
||||
log.Info("missing digest", "image", imageInfo.String())
|
||||
|
|
|
@ -7,7 +7,7 @@ import (
|
|||
"github.com/go-logr/logr"
|
||||
"github.com/google/go-containerregistry/pkg/name"
|
||||
"github.com/google/go-containerregistry/pkg/v1/remote"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/utils/store"
|
||||
jmespath "github.com/kyverno/kyverno/pkg/engine/jmespath"
|
||||
"github.com/kyverno/kyverno/pkg/engine/variables"
|
||||
|
@ -15,7 +15,7 @@ import (
|
|||
)
|
||||
|
||||
// LoadContext - Fetches and adds external data to the Context.
|
||||
func LoadContext(logger logr.Logger, contextEntries []kyverno.ContextEntry, ctx *PolicyContext, ruleName string) error {
|
||||
func LoadContext(logger logr.Logger, contextEntries []kyvernov1.ContextEntry, ctx *PolicyContext, ruleName string) error {
|
||||
if len(contextEntries) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
@ -75,7 +75,7 @@ func LoadContext(logger logr.Logger, contextEntries []kyverno.ContextEntry, ctx
|
|||
return nil
|
||||
}
|
||||
|
||||
func loadVariable(logger logr.Logger, entry kyverno.ContextEntry, ctx *PolicyContext) (err error) {
|
||||
func loadVariable(logger logr.Logger, entry kyvernov1.ContextEntry, ctx *PolicyContext) (err error) {
|
||||
path := ""
|
||||
if entry.Variable.JMESPath != "" {
|
||||
jp, err := variables.SubstituteAll(logger, ctx.JSONContext, entry.Variable.JMESPath)
|
||||
|
@ -134,7 +134,7 @@ func loadVariable(logger logr.Logger, entry kyverno.ContextEntry, ctx *PolicyCon
|
|||
}
|
||||
}
|
||||
|
||||
func loadImageData(logger logr.Logger, entry kyverno.ContextEntry, ctx *PolicyContext) error {
|
||||
func loadImageData(logger logr.Logger, entry kyvernov1.ContextEntry, ctx *PolicyContext) error {
|
||||
if len(registryclient.Secrets) > 0 {
|
||||
if err := registryclient.UpdateKeychain(); err != nil {
|
||||
return fmt.Errorf("unable to load image registry credentials, %w", err)
|
||||
|
@ -154,7 +154,7 @@ func loadImageData(logger logr.Logger, entry kyverno.ContextEntry, ctx *PolicyCo
|
|||
return nil
|
||||
}
|
||||
|
||||
func fetchImageData(logger logr.Logger, entry kyverno.ContextEntry, ctx *PolicyContext) (interface{}, error) {
|
||||
func fetchImageData(logger logr.Logger, entry kyvernov1.ContextEntry, ctx *PolicyContext) (interface{}, error) {
|
||||
ref, err := variables.SubstituteAll(logger, ctx.JSONContext, entry.ImageRegistry.Reference)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ailed to substitute variables in context entry %s %s: %v", entry.Name, entry.ImageRegistry.Reference, err)
|
||||
|
@ -238,7 +238,7 @@ func fetchImageDataMap(ref string) (interface{}, error) {
|
|||
return untyped, nil
|
||||
}
|
||||
|
||||
func loadAPIData(logger logr.Logger, entry kyverno.ContextEntry, ctx *PolicyContext) error {
|
||||
func loadAPIData(logger logr.Logger, entry kyvernov1.ContextEntry, ctx *PolicyContext) error {
|
||||
jsonData, err := fetchAPIData(logger, entry, ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
|
@ -295,7 +295,7 @@ func applyJMESPathJSON(jmesPath string, jsonData []byte) (interface{}, error) {
|
|||
return applyJMESPath(jmesPath, data)
|
||||
}
|
||||
|
||||
func fetchAPIData(log logr.Logger, entry kyverno.ContextEntry, ctx *PolicyContext) ([]byte, error) {
|
||||
func fetchAPIData(log logr.Logger, entry kyvernov1.ContextEntry, ctx *PolicyContext) ([]byte, error) {
|
||||
if entry.APICall == nil {
|
||||
return nil, fmt.Errorf("missing APICall in context entry %s %v", entry.Name, entry.APICall)
|
||||
}
|
||||
|
@ -353,7 +353,7 @@ func loadResource(ctx *PolicyContext, p *APIPath) ([]byte, error) {
|
|||
return r.MarshalJSON()
|
||||
}
|
||||
|
||||
func loadConfigMap(logger logr.Logger, entry kyverno.ContextEntry, ctx *PolicyContext) error {
|
||||
func loadConfigMap(logger logr.Logger, entry kyvernov1.ContextEntry, ctx *PolicyContext) error {
|
||||
data, err := fetchConfigMap(logger, entry, ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to retrieve config map for context entry %s: %v", entry.Name, err)
|
||||
|
@ -367,7 +367,7 @@ func loadConfigMap(logger logr.Logger, entry kyverno.ContextEntry, ctx *PolicyCo
|
|||
return nil
|
||||
}
|
||||
|
||||
func fetchConfigMap(logger logr.Logger, entry kyverno.ContextEntry, ctx *PolicyContext) ([]byte, error) {
|
||||
func fetchConfigMap(logger logr.Logger, entry kyvernov1.ContextEntry, ctx *PolicyContext) ([]byte, error) {
|
||||
contextData := make(map[string]interface{})
|
||||
|
||||
name, err := variables.SubstituteAll(logger, ctx.JSONContext, entry.ConfigMap.Name)
|
||||
|
|
|
@ -5,14 +5,14 @@ import (
|
|||
|
||||
"github.com/go-logr/logr"
|
||||
"github.com/kyverno/go-wildcard"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
engineUtils "github.com/kyverno/kyverno/pkg/engine/utils"
|
||||
"github.com/kyverno/kyverno/pkg/engine/variables"
|
||||
stringutils "github.com/kyverno/kyverno/pkg/utils/string"
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
)
|
||||
|
||||
func loadTargets(targets []kyverno.ResourceSpec, ctx *PolicyContext, logger logr.Logger) ([]unstructured.Unstructured, error) {
|
||||
func loadTargets(targets []kyvernov1.ResourceSpec, ctx *PolicyContext, logger logr.Logger) ([]unstructured.Unstructured, error) {
|
||||
targetObjects := []unstructured.Unstructured{}
|
||||
var errors []error
|
||||
|
||||
|
@ -35,28 +35,28 @@ func loadTargets(targets []kyverno.ResourceSpec, ctx *PolicyContext, logger logr
|
|||
return targetObjects, engineUtils.CombineErrors(errors)
|
||||
}
|
||||
|
||||
func resolveSpec(i int, target kyverno.ResourceSpec, ctx *PolicyContext, logger logr.Logger) (kyverno.ResourceSpec, error) {
|
||||
func resolveSpec(i int, target kyvernov1.ResourceSpec, ctx *PolicyContext, logger logr.Logger) (kyvernov1.ResourceSpec, error) {
|
||||
kind, err := variables.SubstituteAll(logger, ctx.JSONContext, target.Kind)
|
||||
if err != nil {
|
||||
return kyverno.ResourceSpec{}, fmt.Errorf("failed to substitute variables in target[%d].Kind %s: %v", i, target.Kind, err)
|
||||
return kyvernov1.ResourceSpec{}, fmt.Errorf("failed to substitute variables in target[%d].Kind %s: %v", i, target.Kind, err)
|
||||
}
|
||||
|
||||
apiversion, err := variables.SubstituteAll(logger, ctx.JSONContext, target.APIVersion)
|
||||
if err != nil {
|
||||
return kyverno.ResourceSpec{}, fmt.Errorf("failed to substitute variables in target[%d].APIVersion %s: %v", i, target.APIVersion, err)
|
||||
return kyvernov1.ResourceSpec{}, fmt.Errorf("failed to substitute variables in target[%d].APIVersion %s: %v", i, target.APIVersion, err)
|
||||
}
|
||||
|
||||
namespace, err := variables.SubstituteAll(logger, ctx.JSONContext, target.Namespace)
|
||||
if err != nil {
|
||||
return kyverno.ResourceSpec{}, fmt.Errorf("failed to substitute variables in target[%d].Namespace %s: %v", i, target.Namespace, err)
|
||||
return kyvernov1.ResourceSpec{}, fmt.Errorf("failed to substitute variables in target[%d].Namespace %s: %v", i, target.Namespace, err)
|
||||
}
|
||||
|
||||
name, err := variables.SubstituteAll(logger, ctx.JSONContext, target.Name)
|
||||
if err != nil {
|
||||
return kyverno.ResourceSpec{}, fmt.Errorf("failed to substitute variables in target[%d].Name %s: %v", i, target.Name, err)
|
||||
return kyvernov1.ResourceSpec{}, fmt.Errorf("failed to substitute variables in target[%d].Name %s: %v", i, target.Name, err)
|
||||
}
|
||||
|
||||
return kyverno.ResourceSpec{
|
||||
return kyvernov1.ResourceSpec{
|
||||
APIVersion: apiversion.(string),
|
||||
Kind: kind.(string),
|
||||
Namespace: namespace.(string),
|
||||
|
@ -64,7 +64,7 @@ func resolveSpec(i int, target kyverno.ResourceSpec, ctx *PolicyContext, logger
|
|||
}, nil
|
||||
}
|
||||
|
||||
func getTargets(target kyverno.ResourceSpec, ctx *PolicyContext, logger logr.Logger) ([]unstructured.Unstructured, error) {
|
||||
func getTargets(target kyvernov1.ResourceSpec, ctx *PolicyContext, logger logr.Logger) ([]unstructured.Unstructured, error) {
|
||||
var targetObjects []unstructured.Unstructured
|
||||
namespace := target.Namespace
|
||||
name := target.Name
|
||||
|
|
|
@ -5,7 +5,7 @@ import (
|
|||
"fmt"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/engine/context"
|
||||
"github.com/kyverno/kyverno/pkg/engine/mutate/patch"
|
||||
"github.com/kyverno/kyverno/pkg/engine/response"
|
||||
|
@ -35,7 +35,7 @@ func newResponse(status response.RuleStatus, resource unstructured.Unstructured,
|
|||
}
|
||||
}
|
||||
|
||||
func Mutate(rule *kyverno.Rule, ctx context.Interface, resource unstructured.Unstructured, logger logr.Logger) *Response {
|
||||
func Mutate(rule *kyvernov1.Rule, ctx context.Interface, resource unstructured.Unstructured, logger logr.Logger) *Response {
|
||||
updatedRule, err := variables.SubstituteAllInRule(logger, ctx, *rule)
|
||||
if err != nil {
|
||||
return newErrorResponse("variable substitution failed", err)
|
||||
|
@ -63,7 +63,7 @@ func Mutate(rule *kyverno.Rule, ctx context.Interface, resource unstructured.Uns
|
|||
return newResponse(response.RuleStatusPass, patchedResource, resp.Patches, resp.Message)
|
||||
}
|
||||
|
||||
func ForEach(name string, foreach kyverno.ForEachMutation, ctx context.Interface, resource unstructured.Unstructured, logger logr.Logger) *Response {
|
||||
func ForEach(name string, foreach kyvernov1.ForEachMutation, ctx context.Interface, resource unstructured.Unstructured, logger logr.Logger) *Response {
|
||||
fe, err := substituteAllInForEach(foreach, ctx, logger)
|
||||
if err != nil {
|
||||
return newErrorResponse("variable substitution failed", err)
|
||||
|
@ -90,7 +90,7 @@ func ForEach(name string, foreach kyverno.ForEachMutation, ctx context.Interface
|
|||
return newResponse(response.RuleStatusPass, patchedResource, resp.Patches, resp.Message)
|
||||
}
|
||||
|
||||
func substituteAllInForEach(fe kyverno.ForEachMutation, ctx context.Interface, logger logr.Logger) (*kyverno.ForEachMutation, error) {
|
||||
func substituteAllInForEach(fe kyvernov1.ForEachMutation, ctx context.Interface, logger logr.Logger) (*kyvernov1.ForEachMutation, error) {
|
||||
jsonObj, err := utils.ToMap(fe)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
@ -106,7 +106,7 @@ func substituteAllInForEach(fe kyverno.ForEachMutation, ctx context.Interface, l
|
|||
return nil, err
|
||||
}
|
||||
|
||||
var updatedForEach kyverno.ForEachMutation
|
||||
var updatedForEach kyvernov1.ForEachMutation
|
||||
if err := json.Unmarshal(bytes, &updatedForEach); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
|
@ -7,7 +7,7 @@ import (
|
|||
|
||||
"github.com/go-logr/logr"
|
||||
gojmespath "github.com/jmespath/go-jmespath"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/utils/store"
|
||||
"github.com/kyverno/kyverno/pkg/autogen"
|
||||
"github.com/kyverno/kyverno/pkg/engine/mutate"
|
||||
|
@ -131,7 +131,7 @@ func Mutate(policyContext *PolicyContext) (resp *response.EngineResponse) {
|
|||
return resp
|
||||
}
|
||||
|
||||
func mutateResource(rule *kyverno.Rule, ctx *PolicyContext, resource unstructured.Unstructured, logger logr.Logger) (*response.RuleResponse, unstructured.Unstructured) {
|
||||
func mutateResource(rule *kyvernov1.Rule, ctx *PolicyContext, resource unstructured.Unstructured, logger logr.Logger) (*response.RuleResponse, unstructured.Unstructured) {
|
||||
preconditionsPassed, err := checkPreconditions(logger, ctx, rule.GetAnyAllConditions())
|
||||
if err != nil {
|
||||
return ruleError(rule, response.Mutation, "failed to evaluate preconditions", err), resource
|
||||
|
@ -146,7 +146,7 @@ func mutateResource(rule *kyverno.Rule, ctx *PolicyContext, resource unstructure
|
|||
return ruleResp, mutateResp.PatchedResource
|
||||
}
|
||||
|
||||
func mutateForEach(rule *kyverno.Rule, ctx *PolicyContext, resource unstructured.Unstructured, logger logr.Logger) (*response.RuleResponse, unstructured.Unstructured) {
|
||||
func mutateForEach(rule *kyvernov1.Rule, ctx *PolicyContext, resource unstructured.Unstructured, logger logr.Logger) (*response.RuleResponse, unstructured.Unstructured) {
|
||||
foreachList := rule.Mutation.ForEachMutation
|
||||
if foreachList == nil {
|
||||
return nil, resource
|
||||
|
@ -201,7 +201,7 @@ func mutateForEach(rule *kyverno.Rule, ctx *PolicyContext, resource unstructured
|
|||
return r, patchedResource
|
||||
}
|
||||
|
||||
func mutateElements(name string, foreach kyverno.ForEachMutation, ctx *PolicyContext, elements []interface{}, resource unstructured.Unstructured, logger logr.Logger) *mutate.Response {
|
||||
func mutateElements(name string, foreach kyvernov1.ForEachMutation, ctx *PolicyContext, elements []interface{}, resource unstructured.Unstructured, logger logr.Logger) *mutate.Response {
|
||||
ctx.JSONContext.Checkpoint()
|
||||
defer ctx.JSONContext.Restore()
|
||||
|
||||
|
@ -262,7 +262,7 @@ func mutateError(err error, message string) *mutate.Response {
|
|||
}
|
||||
}
|
||||
|
||||
func buildRuleResponse(rule *kyverno.Rule, mutateResp *mutate.Response, patchedResource *unstructured.Unstructured) *response.RuleResponse {
|
||||
func buildRuleResponse(rule *kyvernov1.Rule, mutateResp *mutate.Response, patchedResource *unstructured.Unstructured) *response.RuleResponse {
|
||||
resp := ruleResponse(*rule, response.Mutation, mutateResp.Message, mutateResp.Status, patchedResource)
|
||||
if resp.Status == response.RuleStatusPass {
|
||||
resp.Patches = mutateResp.Patches
|
||||
|
@ -285,7 +285,7 @@ func buildSuccessMessage(r unstructured.Unstructured) string {
|
|||
return fmt.Sprintf("mutated %s/%s in namespace %s", r.GetKind(), r.GetName(), r.GetNamespace())
|
||||
}
|
||||
|
||||
func startMutateResultResponse(resp *response.EngineResponse, policy kyverno.PolicyInterface, resource unstructured.Unstructured) {
|
||||
func startMutateResultResponse(resp *response.EngineResponse, policy kyvernov1.PolicyInterface, resource unstructured.Unstructured) {
|
||||
if resp == nil {
|
||||
return
|
||||
}
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
package engine
|
||||
|
||||
import (
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
urkyverno "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
client "github.com/kyverno/kyverno/pkg/dclient"
|
||||
"github.com/kyverno/kyverno/pkg/engine/context"
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
|
@ -11,7 +11,7 @@ import (
|
|||
// PolicyContext contains the contexts for engine to process
|
||||
type PolicyContext struct {
|
||||
// Policy is the policy to be processed
|
||||
Policy kyverno.PolicyInterface
|
||||
Policy kyvernov1.PolicyInterface
|
||||
|
||||
// NewResource is the resource to be processed
|
||||
NewResource unstructured.Unstructured
|
||||
|
@ -23,7 +23,7 @@ type PolicyContext struct {
|
|||
Element unstructured.Unstructured
|
||||
|
||||
// AdmissionInfo contains the admission request information
|
||||
AdmissionInfo urkyverno.RequestInfo
|
||||
AdmissionInfo kyvernov1beta1.RequestInfo
|
||||
|
||||
// Dynamic client - used for api lookups
|
||||
Client client.Interface
|
||||
|
|
|
@ -5,7 +5,7 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/kyverno/go-wildcard"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
)
|
||||
|
||||
|
@ -15,7 +15,7 @@ type EngineResponse struct {
|
|||
PatchedResource unstructured.Unstructured
|
||||
|
||||
// Original policy
|
||||
Policy kyverno.PolicyInterface
|
||||
Policy kyvernov1.PolicyInterface
|
||||
|
||||
// Policy Response
|
||||
PolicyResponse PolicyResponse
|
||||
|
@ -32,7 +32,7 @@ type PolicyResponse struct {
|
|||
// rule response
|
||||
Rules []RuleResponse `json:"rules"`
|
||||
// ValidationFailureAction: audit (default) or enforce
|
||||
ValidationFailureAction kyverno.ValidationFailureAction
|
||||
ValidationFailureAction kyvernov1.ValidationFailureAction
|
||||
|
||||
ValidationFailureActionOverrides []ValidationFailureActionOverride
|
||||
}
|
||||
|
@ -196,9 +196,9 @@ func (er EngineResponse) getRules(status RuleStatus) []string {
|
|||
return rules
|
||||
}
|
||||
|
||||
func (er *EngineResponse) GetValidationFailureAction() kyverno.ValidationFailureAction {
|
||||
func (er *EngineResponse) GetValidationFailureAction() kyvernov1.ValidationFailureAction {
|
||||
for _, v := range er.PolicyResponse.ValidationFailureActionOverrides {
|
||||
if v.Action != kyverno.Enforce && v.Action != kyverno.Audit {
|
||||
if v.Action != kyvernov1.Enforce && v.Action != kyvernov1.Audit {
|
||||
continue
|
||||
}
|
||||
for _, ns := range v.Namespaces {
|
||||
|
@ -211,6 +211,6 @@ func (er *EngineResponse) GetValidationFailureAction() kyverno.ValidationFailure
|
|||
}
|
||||
|
||||
type ValidationFailureActionOverride struct {
|
||||
Action kyverno.ValidationFailureAction `json:"action"`
|
||||
Namespaces []string `json:"namespaces"`
|
||||
Action kyvernov1.ValidationFailureAction `json:"action"`
|
||||
Namespaces []string `json:"namespaces"`
|
||||
}
|
||||
|
|
|
@ -8,8 +8,8 @@ import (
|
|||
|
||||
"github.com/go-logr/logr"
|
||||
wildcard "github.com/kyverno/go-wildcard"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
urkyverno "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/utils/store"
|
||||
"github.com/kyverno/kyverno/pkg/engine/common"
|
||||
"github.com/kyverno/kyverno/pkg/engine/context"
|
||||
|
@ -134,7 +134,7 @@ func checkSelector(labelSelector *metav1.LabelSelector, resourceLabels map[strin
|
|||
// should be: AND across attributes but an OR inside attributes that of type list
|
||||
// To filter out the targeted resources with UserInfo, the check
|
||||
// should be: OR (across & inside) attributes
|
||||
func doesResourceMatchConditionBlock(conditionBlock kyverno.ResourceDescription, userInfo kyverno.UserInfo, admissionInfo urkyverno.RequestInfo, resource unstructured.Unstructured, dynamicConfig []string, namespaceLabels map[string]string) []error {
|
||||
func doesResourceMatchConditionBlock(conditionBlock kyvernov1.ResourceDescription, userInfo kyvernov1.UserInfo, admissionInfo kyvernov1beta1.RequestInfo, resource unstructured.Unstructured, dynamicConfig []string, namespaceLabels map[string]string) []error {
|
||||
var errs []error
|
||||
|
||||
if len(conditionBlock.Kinds) > 0 {
|
||||
|
@ -269,7 +269,7 @@ func matchSubjects(ruleSubjects []rbacv1.Subject, userInfo authenticationv1.User
|
|||
}
|
||||
|
||||
// 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 {
|
||||
func MatchesResourceDescription(resourceRef unstructured.Unstructured, ruleRef kyvernov1.Rule, admissionInfoRef kyvernov1beta1.RequestInfo, dynamicConfig []string, namespaceLabels map[string]string, policyNamespace string) error {
|
||||
rule := ruleRef.DeepCopy()
|
||||
resource := *resourceRef.DeepCopy()
|
||||
admissionInfo := *admissionInfoRef.DeepCopy()
|
||||
|
@ -299,7 +299,7 @@ func MatchesResourceDescription(resourceRef unstructured.Unstructured, ruleRef k
|
|||
reasonsForFailure = append(reasonsForFailure, matchesResourceDescriptionMatchHelper(rmr, admissionInfo, resource, dynamicConfig, namespaceLabels)...)
|
||||
}
|
||||
} else {
|
||||
rmr := kyverno.ResourceFilter{UserInfo: rule.MatchResources.UserInfo, ResourceDescription: rule.MatchResources.ResourceDescription}
|
||||
rmr := kyvernov1.ResourceFilter{UserInfo: rule.MatchResources.UserInfo, ResourceDescription: rule.MatchResources.ResourceDescription}
|
||||
reasonsForFailure = append(reasonsForFailure, matchesResourceDescriptionMatchHelper(rmr, admissionInfo, resource, dynamicConfig, namespaceLabels)...)
|
||||
}
|
||||
|
||||
|
@ -323,7 +323,7 @@ func MatchesResourceDescription(resourceRef unstructured.Unstructured, ruleRef k
|
|||
reasonsForFailure = append(reasonsForFailure, fmt.Errorf("resource excluded since the combination of all criteria exclude it"))
|
||||
}
|
||||
} else {
|
||||
rer := kyverno.ResourceFilter{UserInfo: rule.ExcludeResources.UserInfo, ResourceDescription: rule.ExcludeResources.ResourceDescription}
|
||||
rer := kyvernov1.ResourceFilter{UserInfo: rule.ExcludeResources.UserInfo, ResourceDescription: rule.ExcludeResources.ResourceDescription}
|
||||
reasonsForFailure = append(reasonsForFailure, matchesResourceDescriptionExcludeHelper(rer, admissionInfo, resource, dynamicConfig, namespaceLabels)...)
|
||||
}
|
||||
|
||||
|
@ -342,15 +342,15 @@ func MatchesResourceDescription(resourceRef unstructured.Unstructured, ruleRef k
|
|||
return nil
|
||||
}
|
||||
|
||||
func matchesResourceDescriptionMatchHelper(rmr kyverno.ResourceFilter, admissionInfo urkyverno.RequestInfo, resource unstructured.Unstructured, dynamicConfig []string, namespaceLabels map[string]string) []error {
|
||||
func matchesResourceDescriptionMatchHelper(rmr kyvernov1.ResourceFilter, admissionInfo kyvernov1beta1.RequestInfo, resource unstructured.Unstructured, dynamicConfig []string, namespaceLabels map[string]string) []error {
|
||||
var errs []error
|
||||
if reflect.DeepEqual(admissionInfo, kyverno.RequestInfo{}) {
|
||||
rmr.UserInfo = kyverno.UserInfo{}
|
||||
if reflect.DeepEqual(admissionInfo, kyvernov1.RequestInfo{}) {
|
||||
rmr.UserInfo = kyvernov1.UserInfo{}
|
||||
}
|
||||
|
||||
// checking if resource matches the rule
|
||||
if !reflect.DeepEqual(rmr.ResourceDescription, kyverno.ResourceDescription{}) ||
|
||||
!reflect.DeepEqual(rmr.UserInfo, kyverno.UserInfo{}) {
|
||||
if !reflect.DeepEqual(rmr.ResourceDescription, kyvernov1.ResourceDescription{}) ||
|
||||
!reflect.DeepEqual(rmr.UserInfo, kyvernov1.UserInfo{}) {
|
||||
matchErrs := doesResourceMatchConditionBlock(rmr.ResourceDescription, rmr.UserInfo, admissionInfo, resource, dynamicConfig, namespaceLabels)
|
||||
errs = append(errs, matchErrs...)
|
||||
} else {
|
||||
|
@ -359,11 +359,11 @@ func matchesResourceDescriptionMatchHelper(rmr kyverno.ResourceFilter, admission
|
|||
return errs
|
||||
}
|
||||
|
||||
func matchesResourceDescriptionExcludeHelper(rer kyverno.ResourceFilter, admissionInfo urkyverno.RequestInfo, resource unstructured.Unstructured, dynamicConfig []string, namespaceLabels map[string]string) []error {
|
||||
func matchesResourceDescriptionExcludeHelper(rer kyvernov1.ResourceFilter, admissionInfo kyvernov1beta1.RequestInfo, resource unstructured.Unstructured, dynamicConfig []string, namespaceLabels map[string]string) []error {
|
||||
var errs []error
|
||||
// checking if resource matches the rule
|
||||
if !reflect.DeepEqual(rer.ResourceDescription, kyverno.ResourceDescription{}) ||
|
||||
!reflect.DeepEqual(rer.UserInfo, kyverno.UserInfo{}) {
|
||||
if !reflect.DeepEqual(rer.ResourceDescription, kyvernov1.ResourceDescription{}) ||
|
||||
!reflect.DeepEqual(rer.UserInfo, kyvernov1.UserInfo{}) {
|
||||
excludeErrs := doesResourceMatchConditionBlock(rer.ResourceDescription, rer.UserInfo, admissionInfo, resource, dynamicConfig, namespaceLabels)
|
||||
// it was a match so we want to exclude it
|
||||
if len(excludeErrs) == 0 {
|
||||
|
@ -395,8 +395,8 @@ func excludeResource(podControllers string, resource unstructured.Unstructured)
|
|||
// ManagedPodResource returns true:
|
||||
// - if the policy has auto-gen annotation && resource == Pod
|
||||
// - if the auto-gen contains cronJob && resource == Job
|
||||
func ManagedPodResource(policy kyverno.PolicyInterface, resource unstructured.Unstructured) bool {
|
||||
podControllers, ok := policy.GetAnnotations()[kyverno.PodControllersAnnotation]
|
||||
func ManagedPodResource(policy kyvernov1.PolicyInterface, resource unstructured.Unstructured) bool {
|
||||
podControllers, ok := policy.GetAnnotations()[kyvernov1.PodControllersAnnotation]
|
||||
if !ok || strings.ToLower(podControllers) == "none" {
|
||||
return false
|
||||
}
|
||||
|
@ -441,12 +441,12 @@ func evaluateList(jmesPath string, ctx context.EvalInterface) ([]interface{}, er
|
|||
return l, nil
|
||||
}
|
||||
|
||||
func ruleError(rule *kyverno.Rule, ruleType response.RuleType, msg string, err error) *response.RuleResponse {
|
||||
func ruleError(rule *kyvernov1.Rule, ruleType response.RuleType, msg string, err error) *response.RuleResponse {
|
||||
msg = fmt.Sprintf("%s: %s", msg, err.Error())
|
||||
return ruleResponse(*rule, ruleType, msg, response.RuleStatusError, nil)
|
||||
}
|
||||
|
||||
func ruleResponse(rule kyverno.Rule, ruleType response.RuleType, msg string, status response.RuleStatus, patchedResource *unstructured.Unstructured) *response.RuleResponse {
|
||||
func ruleResponse(rule kyvernov1.Rule, ruleType response.RuleType, msg string, status response.RuleStatus, patchedResource *unstructured.Unstructured) *response.RuleResponse {
|
||||
resp := &response.RuleResponse{
|
||||
Name: rule.Name,
|
||||
Type: ruleType,
|
||||
|
|
|
@ -9,7 +9,7 @@ import (
|
|||
|
||||
"github.com/go-logr/logr"
|
||||
gojmespath "github.com/jmespath/go-jmespath"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/utils/store"
|
||||
"github.com/kyverno/kyverno/pkg/autogen"
|
||||
"github.com/kyverno/kyverno/pkg/engine/common"
|
||||
|
@ -122,7 +122,7 @@ func validateResource(log logr.Logger, ctx *PolicyContext) *response.EngineRespo
|
|||
return resp
|
||||
}
|
||||
|
||||
func validateOldObject(log logr.Logger, ctx *PolicyContext, rule *kyverno.Rule) (*response.RuleResponse, error) {
|
||||
func validateOldObject(log logr.Logger, ctx *PolicyContext, rule *kyvernov1.Rule) (*response.RuleResponse, error) {
|
||||
ctxCopy := ctx.Copy()
|
||||
ctxCopy.NewResource = *ctxCopy.OldResource.DeepCopy()
|
||||
ctxCopy.OldResource = unstructured.Unstructured{}
|
||||
|
@ -138,7 +138,7 @@ func validateOldObject(log logr.Logger, ctx *PolicyContext, rule *kyverno.Rule)
|
|||
return processValidationRule(log, ctxCopy, rule), nil
|
||||
}
|
||||
|
||||
func processValidationRule(log logr.Logger, ctx *PolicyContext, rule *kyverno.Rule) *response.RuleResponse {
|
||||
func processValidationRule(log logr.Logger, ctx *PolicyContext, rule *kyvernov1.Rule) *response.RuleResponse {
|
||||
v := newValidator(log, ctx, rule)
|
||||
if rule.Validation.ForEachValidation != nil {
|
||||
return v.validateForEach()
|
||||
|
@ -164,15 +164,15 @@ func addRuleResponse(log logr.Logger, resp *response.EngineResponse, ruleResp *r
|
|||
type validator struct {
|
||||
log logr.Logger
|
||||
ctx *PolicyContext
|
||||
rule *kyverno.Rule
|
||||
contextEntries []kyverno.ContextEntry
|
||||
rule *kyvernov1.Rule
|
||||
contextEntries []kyvernov1.ContextEntry
|
||||
anyAllConditions apiextensions.JSON
|
||||
pattern apiextensions.JSON
|
||||
anyPattern apiextensions.JSON
|
||||
deny *kyverno.Deny
|
||||
deny *kyvernov1.Deny
|
||||
}
|
||||
|
||||
func newValidator(log logr.Logger, ctx *PolicyContext, rule *kyverno.Rule) *validator {
|
||||
func newValidator(log logr.Logger, ctx *PolicyContext, rule *kyvernov1.Rule) *validator {
|
||||
ruleCopy := rule.DeepCopy()
|
||||
return &validator{
|
||||
log: log,
|
||||
|
@ -186,7 +186,7 @@ func newValidator(log logr.Logger, ctx *PolicyContext, rule *kyverno.Rule) *vali
|
|||
}
|
||||
}
|
||||
|
||||
func newForeachValidator(foreach kyverno.ForEachValidation, rule *kyverno.Rule, ctx *PolicyContext, log logr.Logger) *validator {
|
||||
func newForeachValidator(foreach kyvernov1.ForEachValidation, rule *kyvernov1.Rule, ctx *PolicyContext, log logr.Logger) *validator {
|
||||
ruleCopy := rule.DeepCopy()
|
||||
anyAllConditions, err := utils.ToMap(foreach.AnyAllConditions)
|
||||
if err != nil {
|
||||
|
@ -215,7 +215,7 @@ func (v *validator) validate() *response.RuleResponse {
|
|||
return ruleError(v.rule, response.Validation, "failed to evaluate preconditions", err)
|
||||
}
|
||||
|
||||
if !preconditionsPassed && (v.ctx.Policy.GetSpec().ValidationFailureAction != kyverno.Audit || store.GetMock()) {
|
||||
if !preconditionsPassed && (v.ctx.Policy.GetSpec().ValidationFailureAction != kyvernov1.Audit || store.GetMock()) {
|
||||
return ruleResponse(*v.rule, response.Validation, "preconditions not met", response.RuleStatusSkip, nil)
|
||||
}
|
||||
|
||||
|
@ -256,7 +256,7 @@ func (v *validator) validateForEach() *response.RuleResponse {
|
|||
preconditionsPassed, err := checkPreconditions(v.log, v.ctx, v.anyAllConditions)
|
||||
if err != nil {
|
||||
return ruleError(v.rule, response.Validation, "failed to evaluate preconditions", err)
|
||||
} else if !preconditionsPassed && (v.ctx.Policy.GetSpec().ValidationFailureAction != kyverno.Audit || store.GetMock()) {
|
||||
} else if !preconditionsPassed && (v.ctx.Policy.GetSpec().ValidationFailureAction != kyvernov1.Audit || store.GetMock()) {
|
||||
return ruleResponse(*v.rule, response.Validation, "preconditions not met", response.RuleStatusSkip, nil)
|
||||
}
|
||||
|
||||
|
@ -288,7 +288,7 @@ func (v *validator) validateForEach() *response.RuleResponse {
|
|||
return ruleResponse(*v.rule, response.Validation, "rule passed", response.RuleStatusPass, nil)
|
||||
}
|
||||
|
||||
func (v *validator) validateElements(foreach kyverno.ForEachValidation, elements []interface{}, elementScope *bool) (*response.RuleResponse, int) {
|
||||
func (v *validator) validateElements(foreach kyvernov1.ForEachValidation, elements []interface{}, elementScope *bool) (*response.RuleResponse, int) {
|
||||
v.ctx.JSONContext.Checkpoint()
|
||||
defer v.ctx.JSONContext.Restore()
|
||||
applyCount := 0
|
||||
|
@ -448,7 +448,7 @@ func isEmptyUnstructured(u *unstructured.Unstructured) bool {
|
|||
}
|
||||
|
||||
// matches checks if either the new or old resource satisfies the filter conditions defined in the rule
|
||||
func matches(logger logr.Logger, rule *kyverno.Rule, ctx *PolicyContext) bool {
|
||||
func matches(logger logr.Logger, rule *kyvernov1.Rule, ctx *PolicyContext) bool {
|
||||
err := MatchesResourceDescription(ctx.NewResource, *rule, ctx.AdmissionInfo, ctx.ExcludeGroupRole, ctx.NamespaceLabels, "")
|
||||
if err == nil {
|
||||
return true
|
||||
|
@ -601,7 +601,7 @@ func (v *validator) buildErrorMessage(err error, path string) string {
|
|||
return fmt.Sprintf("validation error: %s rule %s execution error: %s", msg, v.rule.Name, err.Error())
|
||||
}
|
||||
|
||||
func buildAnyPatternErrorMessage(rule *kyverno.Rule, errors []string) string {
|
||||
func buildAnyPatternErrorMessage(rule *kyvernov1.Rule, errors []string) string {
|
||||
errStr := strings.Join(errors, " ")
|
||||
if rule.Validation.Message == "" {
|
||||
return fmt.Sprintf("validation error: %s", errStr)
|
||||
|
@ -648,6 +648,6 @@ func (v *validator) substituteDeny() error {
|
|||
return err
|
||||
}
|
||||
|
||||
v.deny = i.(*kyverno.Deny)
|
||||
v.deny = i.(*kyvernov1.Deny)
|
||||
return nil
|
||||
}
|
||||
|
|
|
@ -2,13 +2,13 @@ package variables
|
|||
|
||||
import (
|
||||
"github.com/go-logr/logr"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/engine/context"
|
||||
"github.com/kyverno/kyverno/pkg/engine/variables/operator"
|
||||
)
|
||||
|
||||
// Evaluate evaluates the condition
|
||||
func Evaluate(log logr.Logger, ctx context.EvalInterface, condition kyverno.Condition) bool {
|
||||
func Evaluate(log logr.Logger, ctx context.EvalInterface, condition kyvernov1.Condition) bool {
|
||||
// get handler for the operator
|
||||
handle := operator.CreateOperatorHandler(log, ctx, condition.Operator)
|
||||
if handle == nil {
|
||||
|
@ -20,15 +20,15 @@ func Evaluate(log logr.Logger, ctx context.EvalInterface, condition kyverno.Cond
|
|||
// 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:
|
||||
case kyvernov1.AnyAllConditions:
|
||||
return evaluateAnyAllConditions(log, ctx, typedConditions)
|
||||
case []kyverno.Condition: // backwards compatibility
|
||||
case []kyvernov1.Condition: // backwards compatibility
|
||||
return evaluateOldConditions(log, ctx, typedConditions)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func EvaluateAnyAllConditions(log logr.Logger, ctx context.EvalInterface, conditions []kyverno.AnyAllConditions) bool {
|
||||
func EvaluateAnyAllConditions(log logr.Logger, ctx context.EvalInterface, conditions []kyvernov1.AnyAllConditions) bool {
|
||||
for _, c := range conditions {
|
||||
if !evaluateAnyAllConditions(log, ctx, c) {
|
||||
return false
|
||||
|
@ -39,7 +39,7 @@ func EvaluateAnyAllConditions(log logr.Logger, ctx context.EvalInterface, condit
|
|||
}
|
||||
|
||||
// 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 {
|
||||
func evaluateAnyAllConditions(log logr.Logger, ctx context.EvalInterface, conditions kyvernov1.AnyAllConditions) bool {
|
||||
anyConditions, allConditions := conditions.AnyConditions, conditions.AllConditions
|
||||
anyConditionsResult, allConditionsResult := true, true
|
||||
|
||||
|
@ -67,7 +67,7 @@ func evaluateAnyAllConditions(log logr.Logger, ctx context.EvalInterface, condit
|
|||
}
|
||||
|
||||
// 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 {
|
||||
func evaluateOldConditions(log logr.Logger, ctx context.EvalInterface, conditions []kyvernov1.Condition) bool {
|
||||
for _, condition := range conditions {
|
||||
if !Evaluate(log, ctx, condition) {
|
||||
return false
|
||||
|
|
|
@ -5,12 +5,12 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/engine/context"
|
||||
)
|
||||
|
||||
// NewDurationOperatorHandler returns handler to manage the provided duration operations (>, >=, <=, <)
|
||||
func NewDurationOperatorHandler(log logr.Logger, ctx context.EvalInterface, op kyverno.ConditionOperator) OperatorHandler {
|
||||
func NewDurationOperatorHandler(log logr.Logger, ctx context.EvalInterface, op kyvernov1.ConditionOperator) OperatorHandler {
|
||||
return DurationOperatorHandler{
|
||||
ctx: ctx,
|
||||
log: log,
|
||||
|
@ -22,19 +22,19 @@ func NewDurationOperatorHandler(log logr.Logger, ctx context.EvalInterface, op k
|
|||
type DurationOperatorHandler struct {
|
||||
ctx context.EvalInterface
|
||||
log logr.Logger
|
||||
condition kyverno.ConditionOperator
|
||||
condition kyvernov1.ConditionOperator
|
||||
}
|
||||
|
||||
// durationCompareByCondition compares a time.Duration key with a time.Duration value on the basis of the provided operator
|
||||
func durationCompareByCondition(key time.Duration, value time.Duration, op kyverno.ConditionOperator, log logr.Logger) bool {
|
||||
func durationCompareByCondition(key time.Duration, value time.Duration, op kyvernov1.ConditionOperator, log logr.Logger) bool {
|
||||
switch op {
|
||||
case kyverno.ConditionOperators["DurationGreaterThanOrEquals"]:
|
||||
case kyvernov1.ConditionOperators["DurationGreaterThanOrEquals"]:
|
||||
return key >= value
|
||||
case kyverno.ConditionOperators["DurationGreaterThan"]:
|
||||
case kyvernov1.ConditionOperators["DurationGreaterThan"]:
|
||||
return key > value
|
||||
case kyverno.ConditionOperators["DurationLessThanOrEquals"]:
|
||||
case kyvernov1.ConditionOperators["DurationLessThanOrEquals"]:
|
||||
return key <= value
|
||||
case kyverno.ConditionOperators["DurationLessThan"]:
|
||||
case kyvernov1.ConditionOperators["DurationLessThan"]:
|
||||
return key < value
|
||||
default:
|
||||
log.Info(fmt.Sprintf("Expected operator, one of [DurationGreaterThanOrEquals, DurationGreaterThan, DurationLessThanOrEquals, DurationLessThan], found %s", op))
|
||||
|
|
|
@ -6,13 +6,13 @@ import (
|
|||
|
||||
"github.com/blang/semver/v4"
|
||||
"github.com/go-logr/logr"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/engine/context"
|
||||
"k8s.io/apimachinery/pkg/api/resource"
|
||||
)
|
||||
|
||||
// NewNumericOperatorHandler returns handler to manage the provided numeric operations (>, >=, <=, <)
|
||||
func NewNumericOperatorHandler(log logr.Logger, ctx context.EvalInterface, op kyverno.ConditionOperator) OperatorHandler {
|
||||
func NewNumericOperatorHandler(log logr.Logger, ctx context.EvalInterface, op kyvernov1.ConditionOperator) OperatorHandler {
|
||||
return NumericOperatorHandler{
|
||||
ctx: ctx,
|
||||
log: log,
|
||||
|
@ -24,19 +24,19 @@ func NewNumericOperatorHandler(log logr.Logger, ctx context.EvalInterface, op ky
|
|||
type NumericOperatorHandler struct {
|
||||
ctx context.EvalInterface
|
||||
log logr.Logger
|
||||
condition kyverno.ConditionOperator
|
||||
condition kyvernov1.ConditionOperator
|
||||
}
|
||||
|
||||
// compareByCondition compares a float64 key with a float64 value on the basis of the provided operator
|
||||
func compareByCondition(key float64, value float64, op kyverno.ConditionOperator, log logr.Logger) bool {
|
||||
func compareByCondition(key float64, value float64, op kyvernov1.ConditionOperator, log logr.Logger) bool {
|
||||
switch op {
|
||||
case kyverno.ConditionOperators["GreaterThanOrEquals"]:
|
||||
case kyvernov1.ConditionOperators["GreaterThanOrEquals"]:
|
||||
return key >= value
|
||||
case kyverno.ConditionOperators["GreaterThan"]:
|
||||
case kyvernov1.ConditionOperators["GreaterThan"]:
|
||||
return key > value
|
||||
case kyverno.ConditionOperators["LessThanOrEquals"]:
|
||||
case kyvernov1.ConditionOperators["LessThanOrEquals"]:
|
||||
return key <= value
|
||||
case kyverno.ConditionOperators["LessThan"]:
|
||||
case kyvernov1.ConditionOperators["LessThan"]:
|
||||
return key < value
|
||||
default:
|
||||
log.Info(fmt.Sprintf("Expected operator, one of [GreaterThanOrEquals, GreaterThan, LessThanOrEquals, LessThan, Equals, NotEquals], found %s", op))
|
||||
|
@ -44,15 +44,15 @@ func compareByCondition(key float64, value float64, op kyverno.ConditionOperator
|
|||
}
|
||||
}
|
||||
|
||||
func compareVersionByCondition(key semver.Version, value semver.Version, op kyverno.ConditionOperator, log logr.Logger) bool {
|
||||
func compareVersionByCondition(key semver.Version, value semver.Version, op kyvernov1.ConditionOperator, log logr.Logger) bool {
|
||||
switch op {
|
||||
case kyverno.ConditionOperators["GreaterThanOrEquals"]:
|
||||
case kyvernov1.ConditionOperators["GreaterThanOrEquals"]:
|
||||
return key.GTE(value)
|
||||
case kyverno.ConditionOperators["GreaterThan"]:
|
||||
case kyvernov1.ConditionOperators["GreaterThan"]:
|
||||
return key.GT(value)
|
||||
case kyverno.ConditionOperators["LessThanOrEquals"]:
|
||||
case kyvernov1.ConditionOperators["LessThanOrEquals"]:
|
||||
return key.LTE(value)
|
||||
case kyverno.ConditionOperators["LessThan"]:
|
||||
case kyvernov1.ConditionOperators["LessThan"]:
|
||||
return key.LT(value)
|
||||
default:
|
||||
log.Info(fmt.Sprintf("Expected operator, one of [GreaterThanOrEquals, GreaterThan, LessThanOrEquals, LessThan, Equals, NotEquals], found %s", op))
|
||||
|
|
|
@ -6,7 +6,7 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/engine/context"
|
||||
)
|
||||
|
||||
|
@ -25,47 +25,47 @@ type OperatorHandler interface {
|
|||
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
|
||||
func CreateOperatorHandler(log logr.Logger, ctx context.EvalInterface, op kyverno.ConditionOperator) OperatorHandler {
|
||||
func CreateOperatorHandler(log logr.Logger, ctx context.EvalInterface, op kyvernov1.ConditionOperator) OperatorHandler {
|
||||
str := strings.ToLower(string(op))
|
||||
switch str {
|
||||
case strings.ToLower(string(kyverno.ConditionOperators["Equal"])),
|
||||
strings.ToLower(string(kyverno.ConditionOperators["Equals"])):
|
||||
case strings.ToLower(string(kyvernov1.ConditionOperators["Equal"])),
|
||||
strings.ToLower(string(kyvernov1.ConditionOperators["Equals"])):
|
||||
return NewEqualHandler(log, ctx)
|
||||
|
||||
case strings.ToLower(string(kyverno.ConditionOperators["NotEqual"])),
|
||||
strings.ToLower(string(kyverno.ConditionOperators["NotEquals"])):
|
||||
case strings.ToLower(string(kyvernov1.ConditionOperators["NotEqual"])),
|
||||
strings.ToLower(string(kyvernov1.ConditionOperators["NotEquals"])):
|
||||
return NewNotEqualHandler(log, ctx)
|
||||
|
||||
// deprecated
|
||||
case strings.ToLower(string(kyverno.ConditionOperators["In"])):
|
||||
case strings.ToLower(string(kyvernov1.ConditionOperators["In"])):
|
||||
return NewInHandler(log, ctx)
|
||||
|
||||
case strings.ToLower(string(kyverno.ConditionOperators["AnyIn"])):
|
||||
case strings.ToLower(string(kyvernov1.ConditionOperators["AnyIn"])):
|
||||
return NewAnyInHandler(log, ctx)
|
||||
|
||||
case strings.ToLower(string(kyverno.ConditionOperators["AllIn"])):
|
||||
case strings.ToLower(string(kyvernov1.ConditionOperators["AllIn"])):
|
||||
return NewAllInHandler(log, ctx)
|
||||
|
||||
// deprecated
|
||||
case strings.ToLower(string(kyverno.ConditionOperators["NotIn"])):
|
||||
case strings.ToLower(string(kyvernov1.ConditionOperators["NotIn"])):
|
||||
return NewNotInHandler(log, ctx)
|
||||
|
||||
case strings.ToLower(string(kyverno.ConditionOperators["AnyNotIn"])):
|
||||
case strings.ToLower(string(kyvernov1.ConditionOperators["AnyNotIn"])):
|
||||
return NewAnyNotInHandler(log, ctx)
|
||||
|
||||
case strings.ToLower(string(kyverno.ConditionOperators["AllNotIn"])):
|
||||
case strings.ToLower(string(kyvernov1.ConditionOperators["AllNotIn"])):
|
||||
return NewAllNotInHandler(log, ctx)
|
||||
|
||||
case strings.ToLower(string(kyverno.ConditionOperators["GreaterThanOrEquals"])),
|
||||
strings.ToLower(string(kyverno.ConditionOperators["GreaterThan"])),
|
||||
strings.ToLower(string(kyverno.ConditionOperators["LessThanOrEquals"])),
|
||||
strings.ToLower(string(kyverno.ConditionOperators["LessThan"])):
|
||||
case strings.ToLower(string(kyvernov1.ConditionOperators["GreaterThanOrEquals"])),
|
||||
strings.ToLower(string(kyvernov1.ConditionOperators["GreaterThan"])),
|
||||
strings.ToLower(string(kyvernov1.ConditionOperators["LessThanOrEquals"])),
|
||||
strings.ToLower(string(kyvernov1.ConditionOperators["LessThan"])):
|
||||
return NewNumericOperatorHandler(log, ctx, op)
|
||||
|
||||
case strings.ToLower(string(kyverno.ConditionOperators["DurationGreaterThanOrEquals"])),
|
||||
strings.ToLower(string(kyverno.ConditionOperators["DurationGreaterThan"])),
|
||||
strings.ToLower(string(kyverno.ConditionOperators["DurationLessThanOrEquals"])),
|
||||
strings.ToLower(string(kyverno.ConditionOperators["DurationLessThan"])):
|
||||
case strings.ToLower(string(kyvernov1.ConditionOperators["DurationGreaterThanOrEquals"])),
|
||||
strings.ToLower(string(kyvernov1.ConditionOperators["DurationGreaterThan"])),
|
||||
strings.ToLower(string(kyvernov1.ConditionOperators["DurationLessThanOrEquals"])),
|
||||
strings.ToLower(string(kyvernov1.ConditionOperators["DurationLessThan"])):
|
||||
log.Info("DEPRECATED: The Duration* operators have been replaced with the other existing operators that now also support duration values", "operator", str)
|
||||
return NewDurationOperatorHandler(log, ctx, op)
|
||||
|
||||
|
|
|
@ -10,7 +10,7 @@ import (
|
|||
|
||||
"github.com/go-logr/logr"
|
||||
gojmespath "github.com/jmespath/go-jmespath"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/engine/anchor"
|
||||
"github.com/kyverno/kyverno/pkg/engine/context"
|
||||
jsonUtils "github.com/kyverno/kyverno/pkg/engine/jsonutils"
|
||||
|
@ -92,7 +92,7 @@ func SubstituteAllInPreconditions(log logr.Logger, ctx context.EvalInterface, do
|
|||
return substituteAll(log, ctx, untypedDoc, newPreconditionsVariableResolver(log))
|
||||
}
|
||||
|
||||
func SubstituteAllInRule(log logr.Logger, ctx context.EvalInterface, typedRule kyverno.Rule) (_ kyverno.Rule, err error) {
|
||||
func SubstituteAllInRule(log logr.Logger, ctx context.EvalInterface, typedRule kyvernov1.Rule) (_ kyvernov1.Rule, err error) {
|
||||
var rule interface{}
|
||||
rule, err = DocumentToUntyped(typedRule)
|
||||
if err != nil {
|
||||
|
@ -122,22 +122,22 @@ func DocumentToUntyped(doc interface{}) (interface{}, error) {
|
|||
return untyped, nil
|
||||
}
|
||||
|
||||
func UntypedToRule(untyped interface{}) (kyverno.Rule, error) {
|
||||
func UntypedToRule(untyped interface{}) (kyvernov1.Rule, error) {
|
||||
jsonRule, err := json.Marshal(untyped)
|
||||
if err != nil {
|
||||
return kyverno.Rule{}, err
|
||||
return kyvernov1.Rule{}, err
|
||||
}
|
||||
|
||||
var rule kyverno.Rule
|
||||
var rule kyvernov1.Rule
|
||||
err = json.Unmarshal(jsonRule, &rule)
|
||||
if err != nil {
|
||||
return kyverno.Rule{}, err
|
||||
return kyvernov1.Rule{}, err
|
||||
}
|
||||
|
||||
return rule, nil
|
||||
}
|
||||
|
||||
func SubstituteAllInConditions(log logr.Logger, ctx context.EvalInterface, conditions []kyverno.AnyAllConditions) ([]kyverno.AnyAllConditions, error) {
|
||||
func SubstituteAllInConditions(log logr.Logger, ctx context.EvalInterface, conditions []kyvernov1.AnyAllConditions) ([]kyvernov1.AnyAllConditions, error) {
|
||||
c, err := ConditionsToJSONObject(conditions)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
@ -151,7 +151,7 @@ func SubstituteAllInConditions(log logr.Logger, ctx context.EvalInterface, condi
|
|||
return JSONObjectToConditions(i)
|
||||
}
|
||||
|
||||
func ConditionsToJSONObject(conditions []kyverno.AnyAllConditions) ([]map[string]interface{}, error) {
|
||||
func ConditionsToJSONObject(conditions []kyvernov1.AnyAllConditions) ([]map[string]interface{}, error) {
|
||||
bytes, err := json.Marshal(conditions)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
@ -165,13 +165,13 @@ func ConditionsToJSONObject(conditions []kyverno.AnyAllConditions) ([]map[string
|
|||
return m, nil
|
||||
}
|
||||
|
||||
func JSONObjectToConditions(data interface{}) ([]kyverno.AnyAllConditions, error) {
|
||||
func JSONObjectToConditions(data interface{}) ([]kyvernov1.AnyAllConditions, error) {
|
||||
bytes, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var c []kyverno.AnyAllConditions
|
||||
var c []kyvernov1.AnyAllConditions
|
||||
if err := json.Unmarshal(bytes, &c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
@ -188,17 +188,17 @@ func substituteAll(log logr.Logger, ctx context.EvalInterface, document interfac
|
|||
return substituteVars(log, ctx, document, resolver)
|
||||
}
|
||||
|
||||
func SubstituteAllForceMutate(log logr.Logger, ctx context.Interface, typedRule kyverno.Rule) (_ kyverno.Rule, err error) {
|
||||
func SubstituteAllForceMutate(log logr.Logger, ctx context.Interface, typedRule kyvernov1.Rule) (_ kyvernov1.Rule, err error) {
|
||||
var rule interface{}
|
||||
|
||||
rule, err = DocumentToUntyped(typedRule)
|
||||
if err != nil {
|
||||
return kyverno.Rule{}, err
|
||||
return kyvernov1.Rule{}, err
|
||||
}
|
||||
|
||||
rule, err = substituteReferences(log, rule)
|
||||
if err != nil {
|
||||
return kyverno.Rule{}, err
|
||||
return kyvernov1.Rule{}, err
|
||||
}
|
||||
|
||||
if ctx == nil {
|
||||
|
@ -206,7 +206,7 @@ func SubstituteAllForceMutate(log logr.Logger, ctx context.Interface, typedRule
|
|||
} else {
|
||||
rule, err = substituteVars(log, ctx, rule, DefaultVariableResolver)
|
||||
if err != nil {
|
||||
return kyverno.Rule{}, err
|
||||
return kyvernov1.Rule{}, err
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -4,7 +4,7 @@ import (
|
|||
"fmt"
|
||||
"strings"
|
||||
|
||||
v1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/engine/response"
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
)
|
||||
|
@ -42,7 +42,7 @@ func buildPolicyEventMessage(resp *response.RuleResponse, resource response.Reso
|
|||
return b.String()
|
||||
}
|
||||
|
||||
func getPolicyKind(policy v1.PolicyInterface) string {
|
||||
func getPolicyKind(policy kyvernov1.PolicyInterface) string {
|
||||
if policy.IsNamespaced() {
|
||||
return "Policy"
|
||||
}
|
||||
|
|
|
@ -4,36 +4,36 @@ import (
|
|||
"fmt"
|
||||
"reflect"
|
||||
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/engine/response"
|
||||
)
|
||||
|
||||
func ParsePolicyValidationMode(validationFailureAction kyverno.ValidationFailureAction) (PolicyValidationMode, error) {
|
||||
func ParsePolicyValidationMode(validationFailureAction kyvernov1.ValidationFailureAction) (PolicyValidationMode, error) {
|
||||
switch validationFailureAction {
|
||||
case kyverno.Enforce:
|
||||
case kyvernov1.Enforce:
|
||||
return Enforce, nil
|
||||
case kyverno.Audit:
|
||||
case kyvernov1.Audit:
|
||||
return Audit, nil
|
||||
default:
|
||||
return "", fmt.Errorf("wrong validation failure action found %s. Allowed: '%s', '%s'", validationFailureAction, "enforce", "audit")
|
||||
}
|
||||
}
|
||||
|
||||
func ParsePolicyBackgroundMode(policy kyverno.PolicyInterface) PolicyBackgroundMode {
|
||||
func ParsePolicyBackgroundMode(policy kyvernov1.PolicyInterface) PolicyBackgroundMode {
|
||||
if policy.BackgroundProcessingEnabled() {
|
||||
return BackgroundTrue
|
||||
}
|
||||
return BackgroundFalse
|
||||
}
|
||||
|
||||
func ParseRuleType(rule kyverno.Rule) RuleType {
|
||||
if !reflect.DeepEqual(rule.Validation, kyverno.Validation{}) {
|
||||
func ParseRuleType(rule kyvernov1.Rule) RuleType {
|
||||
if !reflect.DeepEqual(rule.Validation, kyvernov1.Validation{}) {
|
||||
return Validate
|
||||
}
|
||||
if !reflect.DeepEqual(rule.Mutation, kyverno.Mutation{}) {
|
||||
if !reflect.DeepEqual(rule.Mutation, kyvernov1.Mutation{}) {
|
||||
return Mutate
|
||||
}
|
||||
if !reflect.DeepEqual(rule.Generation, kyverno.Generation{}) {
|
||||
if !reflect.DeepEqual(rule.Generation, kyvernov1.Generation{}) {
|
||||
return Generate
|
||||
}
|
||||
return EmptyRuleType
|
||||
|
@ -67,7 +67,7 @@ func ParseRuleTypeFromEngineRuleResponse(rule response.RuleResponse) RuleType {
|
|||
}
|
||||
}
|
||||
|
||||
func GetPolicyInfos(policy kyverno.PolicyInterface) (string, string, PolicyType, PolicyBackgroundMode, PolicyValidationMode, error) {
|
||||
func GetPolicyInfos(policy kyvernov1.PolicyInterface) (string, string, PolicyType, PolicyBackgroundMode, PolicyValidationMode, error) {
|
||||
name := policy.GetName()
|
||||
namespace := ""
|
||||
policyType := Cluster
|
||||
|
|
|
@ -3,7 +3,7 @@ package policychanges
|
|||
import (
|
||||
"fmt"
|
||||
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/metrics"
|
||||
"github.com/kyverno/kyverno/pkg/utils"
|
||||
prom "github.com/prometheus/client_golang/prometheus"
|
||||
|
@ -40,7 +40,7 @@ func registerPolicyChangesMetric(
|
|||
return nil
|
||||
}
|
||||
|
||||
func RegisterPolicy(pc *metrics.PromConfig, policy kyverno.PolicyInterface, policyChangeType PolicyChangeType) error {
|
||||
func RegisterPolicy(pc *metrics.PromConfig, policy kyvernov1.PolicyInterface, policyChangeType PolicyChangeType) error {
|
||||
name, namespace, policyType, backgroundMode, validationMode, err := metrics.GetPolicyInfos(policy)
|
||||
if err != nil {
|
||||
return err
|
||||
|
|
|
@ -3,7 +3,7 @@ package policyexecutionduration
|
|||
import (
|
||||
"fmt"
|
||||
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/engine/response"
|
||||
"github.com/kyverno/kyverno/pkg/metrics"
|
||||
"github.com/kyverno/kyverno/pkg/utils"
|
||||
|
@ -60,7 +60,7 @@ func registerPolicyExecutionDurationMetric(
|
|||
|
||||
// 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 {
|
||||
func ProcessEngineResponse(pc *metrics.PromConfig, policy kyvernov1.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 {
|
||||
return err
|
||||
|
|
|
@ -3,7 +3,7 @@ package policyresults
|
|||
import (
|
||||
"fmt"
|
||||
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/engine/response"
|
||||
"github.com/kyverno/kyverno/pkg/metrics"
|
||||
"github.com/kyverno/kyverno/pkg/utils"
|
||||
|
@ -54,7 +54,7 @@ func registerPolicyResultsMetric(
|
|||
|
||||
// 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 {
|
||||
func ProcessEngineResponse(pc *metrics.PromConfig, policy kyvernov1.PolicyInterface, engineResponse response.EngineResponse, executionCause metrics.RuleExecutionCause, resourceRequestOperation metrics.ResourceRequestOperation) error {
|
||||
name, namespace, policyType, backgroundMode, validationMode, err := metrics.GetPolicyInfos(policy)
|
||||
if err != nil {
|
||||
return err
|
||||
|
|
|
@ -3,7 +3,7 @@ package policyruleinfo
|
|||
import (
|
||||
"fmt"
|
||||
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/autogen"
|
||||
"github.com/kyverno/kyverno/pkg/metrics"
|
||||
"github.com/kyverno/kyverno/pkg/utils"
|
||||
|
@ -58,7 +58,7 @@ func registerPolicyRuleInfoMetric(
|
|||
return nil
|
||||
}
|
||||
|
||||
func AddPolicy(pc *metrics.PromConfig, policy kyverno.PolicyInterface) error {
|
||||
func AddPolicy(pc *metrics.PromConfig, policy kyvernov1.PolicyInterface) error {
|
||||
name, namespace, policyType, backgroundMode, validationMode, err := metrics.GetPolicyInfos(policy)
|
||||
if err != nil {
|
||||
return err
|
||||
|
@ -74,7 +74,7 @@ func AddPolicy(pc *metrics.PromConfig, policy kyverno.PolicyInterface) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func RemovePolicy(pc *metrics.PromConfig, policy kyverno.PolicyInterface) error {
|
||||
func RemovePolicy(pc *metrics.PromConfig, policy kyvernov1.PolicyInterface) error {
|
||||
name, namespace, policyType, backgroundMode, validationMode, err := metrics.GetPolicyInfos(policy)
|
||||
if err != nil {
|
||||
return err
|
||||
|
|
|
@ -9,7 +9,7 @@ import (
|
|||
|
||||
"github.com/googleapis/gnostic/compiler"
|
||||
openapiv2 "github.com/googleapis/gnostic/openapiv2"
|
||||
v1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/data"
|
||||
"github.com/kyverno/kyverno/pkg/autogen"
|
||||
"github.com/kyverno/kyverno/pkg/engine"
|
||||
|
@ -135,8 +135,8 @@ func (o *Controller) ValidateResource(patchedResource unstructured.Unstructured,
|
|||
}
|
||||
|
||||
// ValidatePolicyMutation ...
|
||||
func (o *Controller) ValidatePolicyMutation(policy v1.PolicyInterface) error {
|
||||
kindToRules := make(map[string][]v1.Rule)
|
||||
func (o *Controller) ValidatePolicyMutation(policy kyvernov1.PolicyInterface) error {
|
||||
kindToRules := make(map[string][]kyvernov1.Rule)
|
||||
for _, rule := range autogen.ComputeRules(policy) {
|
||||
if rule.HasMutate() {
|
||||
for _, kind := range rule.MatchResources.Kinds {
|
||||
|
|
|
@ -3,7 +3,7 @@ package policy
|
|||
import (
|
||||
"fmt"
|
||||
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
dclient "github.com/kyverno/kyverno/pkg/dclient"
|
||||
"github.com/kyverno/kyverno/pkg/policy/generate"
|
||||
"github.com/kyverno/kyverno/pkg/policy/mutate"
|
||||
|
@ -21,7 +21,7 @@ type Validation interface {
|
|||
// - Mutate
|
||||
// - Validation
|
||||
// - Generate
|
||||
func validateActions(idx int, rule *kyverno.Rule, client dclient.Interface, mock bool) error {
|
||||
func validateActions(idx int, rule *kyvernov1.Rule, client dclient.Interface, mock bool) error {
|
||||
if rule == nil {
|
||||
return nil
|
||||
}
|
||||
|
|
|
@ -8,7 +8,7 @@ import (
|
|||
|
||||
jsonpatch "github.com/evanphx/json-patch/v5"
|
||||
"github.com/go-logr/logr"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
client "github.com/kyverno/kyverno/pkg/dclient"
|
||||
"github.com/kyverno/kyverno/pkg/engine"
|
||||
"github.com/kyverno/kyverno/pkg/engine/context"
|
||||
|
@ -18,7 +18,7 @@ import (
|
|||
)
|
||||
|
||||
// applyPolicy applies policy on a resource
|
||||
func applyPolicy(policy kyverno.PolicyInterface, resource unstructured.Unstructured,
|
||||
func applyPolicy(policy kyvernov1.PolicyInterface, resource unstructured.Unstructured,
|
||||
logger logr.Logger, excludeGroupRole []string,
|
||||
client client.Interface, namespaceLabels map[string]string,
|
||||
) (responses []*response.EngineResponse) {
|
||||
|
@ -72,7 +72,7 @@ func applyPolicy(policy kyverno.PolicyInterface, resource unstructured.Unstructu
|
|||
return engineResponses
|
||||
}
|
||||
|
||||
func mutation(policy kyverno.PolicyInterface, resource unstructured.Unstructured, log logr.Logger, jsonContext context.Interface, namespaceLabels map[string]string) (*response.EngineResponse, error) {
|
||||
func mutation(policy kyvernov1.PolicyInterface, resource unstructured.Unstructured, log logr.Logger, jsonContext context.Interface, namespaceLabels map[string]string) (*response.EngineResponse, error) {
|
||||
policyContext := &engine.PolicyContext{
|
||||
Policy: policy,
|
||||
NewResource: resource,
|
||||
|
|
|
@ -4,12 +4,12 @@ import (
|
|||
"fmt"
|
||||
"strings"
|
||||
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/autogen"
|
||||
)
|
||||
|
||||
// ContainsUserVariables returns error if variable that does not start from request.object
|
||||
func containsUserVariables(policy kyverno.PolicyInterface, vars [][]string) error {
|
||||
func containsUserVariables(policy kyvernov1.PolicyInterface, vars [][]string) error {
|
||||
for _, rule := range policy.GetSpec().Rules {
|
||||
if rule.IsMutateExisting() {
|
||||
return nil
|
||||
|
@ -31,7 +31,7 @@ func containsUserVariables(policy kyverno.PolicyInterface, vars [][]string) erro
|
|||
return nil
|
||||
}
|
||||
|
||||
func hasUserMatchExclude(idx int, rule *kyverno.Rule) error {
|
||||
func hasUserMatchExclude(idx int, rule *kyvernov1.Rule) error {
|
||||
if path := userInfoDefined(rule.MatchResources.UserInfo); path != "" {
|
||||
return fmt.Errorf("invalid variable used at path: spec/rules[%d]/match/%s", idx, path)
|
||||
}
|
||||
|
@ -75,7 +75,7 @@ func hasUserMatchExclude(idx int, rule *kyverno.Rule) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func userInfoDefined(ui kyverno.UserInfo) string {
|
||||
func userInfoDefined(ui kyvernov1.UserInfo) string {
|
||||
if len(ui.Roles) > 0 {
|
||||
return "roles"
|
||||
}
|
||||
|
|
|
@ -6,7 +6,7 @@ import (
|
|||
|
||||
"github.com/go-logr/logr"
|
||||
wildcard "github.com/kyverno/go-wildcard"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/config"
|
||||
"github.com/kyverno/kyverno/pkg/utils"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
|
@ -56,7 +56,7 @@ func (pc *PolicyController) getResourceList(kind, namespace string, labelSelecto
|
|||
// - Namespaced resources across all namespaces if namespace is set to empty "", for Namespaced Kind
|
||||
// - Namespaced resources in the given namespace
|
||||
// - Cluster-wide resources for Cluster-wide Kind
|
||||
func (pc *PolicyController) getResourcesPerNamespace(kind string, namespace string, rule kyverno.Rule, log logr.Logger) map[string]unstructured.Unstructured {
|
||||
func (pc *PolicyController) getResourcesPerNamespace(kind string, namespace string, rule kyvernov1.Rule, log logr.Logger) map[string]unstructured.Unstructured {
|
||||
resourceMap := map[string]unstructured.Unstructured{}
|
||||
|
||||
if kind == "Namespace" {
|
||||
|
@ -84,7 +84,7 @@ func (pc *PolicyController) getResourcesPerNamespace(kind string, namespace stri
|
|||
return resourceMap
|
||||
}
|
||||
|
||||
func (pc *PolicyController) match(r unstructured.Unstructured, rule kyverno.Rule) bool {
|
||||
func (pc *PolicyController) match(r unstructured.Unstructured, rule kyvernov1.Rule) bool {
|
||||
if r.GetDeletionTimestamp() != nil {
|
||||
return false
|
||||
}
|
||||
|
@ -110,8 +110,8 @@ func (pc *PolicyController) match(r unstructured.Unstructured, rule kyverno.Rule
|
|||
}
|
||||
|
||||
// ExcludeResources ...
|
||||
func excludeResources(included map[string]unstructured.Unstructured, exclude kyverno.ResourceDescription, configHandler config.Configuration, log logr.Logger) {
|
||||
if reflect.DeepEqual(exclude, (kyverno.ResourceDescription{})) {
|
||||
func excludeResources(included map[string]unstructured.Unstructured, exclude kyvernov1.ResourceDescription, configHandler config.Configuration, log logr.Logger) {
|
||||
if reflect.DeepEqual(exclude, (kyvernov1.ResourceDescription{})) {
|
||||
return
|
||||
}
|
||||
excludeName := func(name string) Condition {
|
||||
|
|
|
@ -7,7 +7,7 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/autogen"
|
||||
"github.com/kyverno/kyverno/pkg/common"
|
||||
"github.com/kyverno/kyverno/pkg/engine"
|
||||
|
@ -19,7 +19,7 @@ import (
|
|||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
)
|
||||
|
||||
func (pc *PolicyController) processExistingResources(policy kyverno.PolicyInterface) {
|
||||
func (pc *PolicyController) processExistingResources(policy kyvernov1.PolicyInterface) {
|
||||
logger := pc.log.WithValues("policy", policy.GetName())
|
||||
logger.V(4).Info("applying policy to existing resources")
|
||||
|
||||
|
@ -35,7 +35,7 @@ func (pc *PolicyController) processExistingResources(policy kyverno.PolicyInterf
|
|||
}
|
||||
}
|
||||
|
||||
func (pc *PolicyController) applyAndReportPerNamespace(policy kyverno.PolicyInterface, kind string, ns string, rule kyverno.Rule, logger logr.Logger, metricAlreadyRegistered *bool) {
|
||||
func (pc *PolicyController) applyAndReportPerNamespace(policy kyvernov1.PolicyInterface, kind string, ns string, rule kyvernov1.Rule, logger logr.Logger, metricAlreadyRegistered *bool) {
|
||||
rMap := pc.getResourcesPerNamespace(kind, ns, rule, logger)
|
||||
excludeAutoGenResources(policy, rMap, logger)
|
||||
if len(rMap) == 0 {
|
||||
|
@ -61,19 +61,19 @@ func (pc *PolicyController) applyAndReportPerNamespace(policy kyverno.PolicyInte
|
|||
pc.report(engineResponses, logger)
|
||||
}
|
||||
|
||||
func (pc *PolicyController) registerPolicyResultsMetricValidation(logger logr.Logger, policy kyverno.PolicyInterface, engineResponse response.EngineResponse) {
|
||||
func (pc *PolicyController) registerPolicyResultsMetricValidation(logger logr.Logger, policy kyvernov1.PolicyInterface, engineResponse response.EngineResponse) {
|
||||
if err := policyResults.ProcessEngineResponse(pc.promConfig, policy, engineResponse, metrics.BackgroundScan, metrics.ResourceCreated); err != nil {
|
||||
logger.Error(err, "error occurred while registering kyverno_policy_results_total metrics for the above policy", "name", policy.GetName())
|
||||
}
|
||||
}
|
||||
|
||||
func (pc *PolicyController) registerPolicyExecutionDurationMetricValidate(logger logr.Logger, policy kyverno.PolicyInterface, engineResponse response.EngineResponse) {
|
||||
func (pc *PolicyController) registerPolicyExecutionDurationMetricValidate(logger logr.Logger, policy kyvernov1.PolicyInterface, engineResponse response.EngineResponse) {
|
||||
if err := policyExecutionDuration.ProcessEngineResponse(pc.promConfig, policy, engineResponse, metrics.BackgroundScan, "", metrics.ResourceCreated); err != nil {
|
||||
logger.Error(err, "error occurred while registering kyverno_policy_execution_duration_seconds metrics for the above policy", "name", policy.GetName())
|
||||
}
|
||||
}
|
||||
|
||||
func (pc *PolicyController) applyPolicy(policy kyverno.PolicyInterface, resource unstructured.Unstructured, logger logr.Logger) (engineResponses []*response.EngineResponse) {
|
||||
func (pc *PolicyController) applyPolicy(policy kyvernov1.PolicyInterface, resource unstructured.Unstructured, logger logr.Logger) (engineResponses []*response.EngineResponse) {
|
||||
// pre-processing, check if the policy and resource version has been processed before
|
||||
if !pc.rm.ProcessResource(policy.GetName(), policy.GetResourceVersion(), resource.GetKind(), resource.GetNamespace(), resource.GetName(), resource.GetResourceVersion()) {
|
||||
logger.V(4).Info("policy and resource already processed", "policyResourceVersion", policy.GetResourceVersion(), "resourceResourceVersion", resource.GetResourceVersion(), "kind", resource.GetKind(), "namespace", resource.GetNamespace(), "name", resource.GetName())
|
||||
|
@ -90,7 +90,7 @@ func (pc *PolicyController) applyPolicy(policy kyverno.PolicyInterface, resource
|
|||
}
|
||||
|
||||
// excludeAutoGenResources filter out the pods / jobs with ownerReference
|
||||
func excludeAutoGenResources(policy kyverno.PolicyInterface, resourceMap map[string]unstructured.Unstructured, log logr.Logger) {
|
||||
func excludeAutoGenResources(policy kyvernov1.PolicyInterface, resourceMap map[string]unstructured.Unstructured, log logr.Logger) {
|
||||
for uid, r := range resourceMap {
|
||||
if engine.ManagedPodResource(policy, r) {
|
||||
log.V(4).Info("exclude resource", "namespace", r.GetNamespace(), "kind", r.GetKind(), "name", r.GetName())
|
||||
|
@ -201,7 +201,7 @@ func buildKey(policy, pv, kind, ns, name, rv string) string {
|
|||
return policy + "/" + pv + "/" + kind + "/" + ns + "/" + name + "/" + rv
|
||||
}
|
||||
|
||||
func (pc *PolicyController) processExistingKinds(kinds []string, policy kyverno.PolicyInterface, rule kyverno.Rule, logger logr.Logger) {
|
||||
func (pc *PolicyController) processExistingKinds(kinds []string, policy kyvernov1.PolicyInterface, rule kyvernov1.Rule, logger logr.Logger) {
|
||||
for _, kind := range kinds {
|
||||
logger = logger.WithValues("rule", rule.Name, "kind", kind)
|
||||
_, err := pc.rm.GetScope(kind)
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
package generate
|
||||
|
||||
import (
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/policy/generate/fake"
|
||||
"sigs.k8s.io/controller-runtime/pkg/log"
|
||||
)
|
||||
|
@ -14,7 +14,7 @@ type FakeGenerate struct {
|
|||
|
||||
// NewFakeGenerate returns a new instance of generatecheck that uses
|
||||
// fake/mock implementation for operation access(always returns true)
|
||||
func NewFakeGenerate(rule kyverno.Generation) *FakeGenerate {
|
||||
func NewFakeGenerate(rule kyvernov1.Generation) *FakeGenerate {
|
||||
g := FakeGenerate{}
|
||||
g.rule = rule
|
||||
g.authCheck = fake.NewFakeAuth()
|
||||
|
|
|
@ -5,7 +5,7 @@ import (
|
|||
"reflect"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
dclient "github.com/kyverno/kyverno/pkg/dclient"
|
||||
commonAnchors "github.com/kyverno/kyverno/pkg/engine/anchor"
|
||||
"github.com/kyverno/kyverno/pkg/engine/variables"
|
||||
|
@ -15,7 +15,7 @@ import (
|
|||
// Generate provides implementation to validate 'generate' rule
|
||||
type Generate struct {
|
||||
// rule to hold 'generate' rule specifications
|
||||
rule kyverno.Generation
|
||||
rule kyvernov1.Generation
|
||||
// authCheck to check access for operations
|
||||
authCheck Operations
|
||||
// logger
|
||||
|
@ -23,7 +23,7 @@ type Generate struct {
|
|||
}
|
||||
|
||||
// NewGenerateFactory returns a new instance of Generate validation checker
|
||||
func NewGenerateFactory(client dclient.Interface, rule kyverno.Generation, log logr.Logger) *Generate {
|
||||
func NewGenerateFactory(client dclient.Interface, rule kyvernov1.Generation, log logr.Logger) *Generate {
|
||||
g := Generate{
|
||||
rule: rule,
|
||||
authCheck: NewAuth(client, log),
|
||||
|
@ -36,7 +36,7 @@ func NewGenerateFactory(client dclient.Interface, rule kyverno.Generation, log l
|
|||
// Validate validates the 'generate' rule
|
||||
func (g *Generate) Validate() (string, error) {
|
||||
rule := g.rule
|
||||
if rule.GetData() != nil && rule.Clone != (kyverno.CloneFrom{}) {
|
||||
if rule.GetData() != nil && rule.Clone != (kyvernov1.CloneFrom{}) {
|
||||
return "", fmt.Errorf("only one of data or clone can be specified")
|
||||
}
|
||||
|
||||
|
@ -50,7 +50,7 @@ func (g *Generate) Validate() (string, error) {
|
|||
}
|
||||
// Can I generate resource
|
||||
|
||||
if !reflect.DeepEqual(rule.Clone, kyverno.CloneFrom{}) {
|
||||
if !reflect.DeepEqual(rule.Clone, kyvernov1.CloneFrom{}) {
|
||||
if path, err := g.validateClone(rule.Clone, kind); err != nil {
|
||||
return fmt.Sprintf("clone.%s", path), err
|
||||
}
|
||||
|
@ -74,7 +74,7 @@ func (g *Generate) Validate() (string, error) {
|
|||
return "", nil
|
||||
}
|
||||
|
||||
func (g *Generate) validateClone(c kyverno.CloneFrom, kind string) (string, error) {
|
||||
func (g *Generate) validateClone(c kyvernov1.CloneFrom, kind string) (string, error) {
|
||||
if c.Name == "" {
|
||||
return "name", fmt.Errorf("name cannot be empty")
|
||||
}
|
||||
|
|
|
@ -4,19 +4,19 @@ import (
|
|||
"reflect"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
policyChangesMetric "github.com/kyverno/kyverno/pkg/metrics/policychanges"
|
||||
policyRuleInfoMetric "github.com/kyverno/kyverno/pkg/metrics/policyruleinfo"
|
||||
)
|
||||
|
||||
func (pc *PolicyController) registerPolicyRuleInfoMetricAddPolicy(logger logr.Logger, p kyverno.PolicyInterface) {
|
||||
func (pc *PolicyController) registerPolicyRuleInfoMetricAddPolicy(logger logr.Logger, p kyvernov1.PolicyInterface) {
|
||||
err := policyRuleInfoMetric.AddPolicy(pc.promConfig, p)
|
||||
if err != nil {
|
||||
logger.Error(err, "error occurred while registering kyverno_policy_rule_info_total metrics for the above policy's creation", "name", p.GetName())
|
||||
}
|
||||
}
|
||||
|
||||
func (pc *PolicyController) registerPolicyRuleInfoMetricUpdatePolicy(logger logr.Logger, oldP, curP kyverno.PolicyInterface) {
|
||||
func (pc *PolicyController) registerPolicyRuleInfoMetricUpdatePolicy(logger logr.Logger, oldP, curP kyvernov1.PolicyInterface) {
|
||||
// removing the old rules associated metrics
|
||||
err := policyRuleInfoMetric.RemovePolicy(pc.promConfig, oldP)
|
||||
if err != nil {
|
||||
|
@ -29,21 +29,21 @@ func (pc *PolicyController) registerPolicyRuleInfoMetricUpdatePolicy(logger logr
|
|||
}
|
||||
}
|
||||
|
||||
func (pc *PolicyController) registerPolicyRuleInfoMetricDeletePolicy(logger logr.Logger, p kyverno.PolicyInterface) {
|
||||
func (pc *PolicyController) registerPolicyRuleInfoMetricDeletePolicy(logger logr.Logger, p kyvernov1.PolicyInterface) {
|
||||
err := policyRuleInfoMetric.RemovePolicy(pc.promConfig, p)
|
||||
if err != nil {
|
||||
logger.Error(err, "error occurred while registering kyverno_policy_rule_info_total metrics for the above policy's deletion", "name", p.GetName())
|
||||
}
|
||||
}
|
||||
|
||||
func (pc *PolicyController) registerPolicyChangesMetricAddPolicy(logger logr.Logger, p kyverno.PolicyInterface) {
|
||||
func (pc *PolicyController) registerPolicyChangesMetricAddPolicy(logger logr.Logger, p kyvernov1.PolicyInterface) {
|
||||
err := policyChangesMetric.RegisterPolicy(pc.promConfig, p, policyChangesMetric.PolicyCreated)
|
||||
if err != nil {
|
||||
logger.Error(err, "error occurred while registering kyverno_policy_changes_total metrics for the above policy's creation", "name", p.GetName())
|
||||
}
|
||||
}
|
||||
|
||||
func (pc *PolicyController) registerPolicyChangesMetricUpdatePolicy(logger logr.Logger, oldP, curP kyverno.PolicyInterface) {
|
||||
func (pc *PolicyController) registerPolicyChangesMetricUpdatePolicy(logger logr.Logger, oldP, curP kyvernov1.PolicyInterface) {
|
||||
oldSpec := oldP.GetSpec()
|
||||
curSpec := curP.GetSpec()
|
||||
if reflect.DeepEqual(oldSpec, curSpec) {
|
||||
|
@ -62,7 +62,7 @@ func (pc *PolicyController) registerPolicyChangesMetricUpdatePolicy(logger logr.
|
|||
}
|
||||
}
|
||||
|
||||
func (pc *PolicyController) registerPolicyChangesMetricDeletePolicy(logger logr.Logger, p kyverno.PolicyInterface) {
|
||||
func (pc *PolicyController) registerPolicyChangesMetricDeletePolicy(logger logr.Logger, p kyvernov1.PolicyInterface) {
|
||||
err := policyChangesMetric.RegisterPolicy(pc.promConfig, p, policyChangesMetric.PolicyDeleted)
|
||||
if err != nil {
|
||||
logger.Error(err, "error occurred while registering kyverno_policy_changes_total metrics for the above policy's deletion", "name", p.GetName())
|
||||
|
|
|
@ -3,16 +3,16 @@ package mutate
|
|||
import (
|
||||
"fmt"
|
||||
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
)
|
||||
|
||||
// Mutate provides implementation to validate 'mutate' rule
|
||||
type Mutate struct {
|
||||
mutation kyverno.Mutation
|
||||
mutation kyvernov1.Mutation
|
||||
}
|
||||
|
||||
// NewMutateFactory returns a new instance of Mutate validation checker
|
||||
func NewMutateFactory(m kyverno.Mutation) *Mutate {
|
||||
func NewMutateFactory(m kyvernov1.Mutation) *Mutate {
|
||||
return &Mutate{
|
||||
mutation: m,
|
||||
}
|
||||
|
|
|
@ -10,8 +10,8 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
urkyverno "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
utilscommon "github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/utils/common"
|
||||
"github.com/kyverno/kyverno/pkg/autogen"
|
||||
kyvernoclient "github.com/kyverno/kyverno/pkg/client/clientset/versioned"
|
||||
|
@ -149,7 +149,7 @@ func NewPolicyController(
|
|||
return &pc, nil
|
||||
}
|
||||
|
||||
func (pc *PolicyController) canBackgroundProcess(p kyverno.PolicyInterface) bool {
|
||||
func (pc *PolicyController) canBackgroundProcess(p kyvernov1.PolicyInterface) bool {
|
||||
logger := pc.log.WithValues("policy", p.GetName())
|
||||
if !p.BackgroundProcessingEnabled() {
|
||||
logger.V(4).Info("background processed is disabled")
|
||||
|
@ -166,7 +166,7 @@ func (pc *PolicyController) canBackgroundProcess(p kyverno.PolicyInterface) bool
|
|||
|
||||
func (pc *PolicyController) addPolicy(obj interface{}) {
|
||||
logger := pc.log
|
||||
p := obj.(*kyverno.ClusterPolicy)
|
||||
p := obj.(*kyvernov1.ClusterPolicy)
|
||||
|
||||
logger.Info("policy created", "uid", p.UID, "kind", "ClusterPolicy", "name", p.Name)
|
||||
|
||||
|
@ -177,7 +177,7 @@ func (pc *PolicyController) addPolicy(obj interface{}) {
|
|||
|
||||
if p.Spec.Background == nil || p.Spec.ValidationFailureAction == "" || missingAutoGenRules(p, logger) {
|
||||
pol, _ := utilscommon.MutatePolicy(p, logger)
|
||||
_, err := pc.kyvernoClient.KyvernoV1().ClusterPolicies().Update(context.TODO(), pol.(*kyverno.ClusterPolicy), metav1.UpdateOptions{})
|
||||
_, err := pc.kyvernoClient.KyvernoV1().ClusterPolicies().Update(context.TODO(), pol.(*kyvernov1.ClusterPolicy), metav1.UpdateOptions{})
|
||||
if err != nil {
|
||||
logger.Error(err, "failed to add policy ")
|
||||
}
|
||||
|
@ -193,8 +193,8 @@ func (pc *PolicyController) addPolicy(obj interface{}) {
|
|||
|
||||
func (pc *PolicyController) updatePolicy(old, cur interface{}) {
|
||||
logger := pc.log
|
||||
oldP := old.(*kyverno.ClusterPolicy)
|
||||
curP := cur.(*kyverno.ClusterPolicy)
|
||||
oldP := old.(*kyvernov1.ClusterPolicy)
|
||||
curP := cur.(*kyvernov1.ClusterPolicy)
|
||||
|
||||
// register kyverno_policy_rule_info_total metric concurrently
|
||||
go pc.registerPolicyRuleInfoMetricUpdatePolicy(logger, oldP, curP)
|
||||
|
@ -203,7 +203,7 @@ func (pc *PolicyController) updatePolicy(old, cur interface{}) {
|
|||
|
||||
if curP.Spec.Background == nil || curP.Spec.ValidationFailureAction == "" || missingAutoGenRules(curP, logger) {
|
||||
pol, _ := utilscommon.MutatePolicy(curP, logger)
|
||||
_, err := pc.kyvernoClient.KyvernoV1().ClusterPolicies().Update(context.TODO(), pol.(*kyverno.ClusterPolicy), metav1.UpdateOptions{})
|
||||
_, err := pc.kyvernoClient.KyvernoV1().ClusterPolicies().Update(context.TODO(), pol.(*kyvernov1.ClusterPolicy), metav1.UpdateOptions{})
|
||||
if err != nil {
|
||||
logger.Error(err, "failed to update policy ")
|
||||
}
|
||||
|
@ -225,14 +225,14 @@ func (pc *PolicyController) updatePolicy(old, cur interface{}) {
|
|||
|
||||
func (pc *PolicyController) deletePolicy(obj interface{}) {
|
||||
logger := pc.log
|
||||
p, ok := obj.(*kyverno.ClusterPolicy)
|
||||
p, ok := obj.(*kyvernov1.ClusterPolicy)
|
||||
if !ok {
|
||||
tombstone, ok := obj.(cache.DeletedFinalStateUnknown)
|
||||
if !ok {
|
||||
logger.Info("couldn't get object from tombstone", "obj", obj)
|
||||
return
|
||||
}
|
||||
p, ok = tombstone.Obj.(*kyverno.ClusterPolicy)
|
||||
p, ok = tombstone.Obj.(*kyvernov1.ClusterPolicy)
|
||||
if !ok {
|
||||
logger.Info("tombstone container object that is not a policy", "obj", obj)
|
||||
return
|
||||
|
@ -261,7 +261,7 @@ func (pc *PolicyController) deletePolicy(obj interface{}) {
|
|||
|
||||
func (pc *PolicyController) addNsPolicy(obj interface{}) {
|
||||
logger := pc.log
|
||||
p := obj.(*kyverno.Policy)
|
||||
p := obj.(*kyvernov1.Policy)
|
||||
|
||||
// register kyverno_policy_rule_info_total metric concurrently
|
||||
go pc.registerPolicyRuleInfoMetricAddPolicy(logger, p)
|
||||
|
@ -273,7 +273,7 @@ func (pc *PolicyController) addNsPolicy(obj interface{}) {
|
|||
spec := p.GetSpec()
|
||||
if spec.Background == nil || spec.ValidationFailureAction == "" || missingAutoGenRules(p, logger) {
|
||||
nsPol, _ := utilscommon.MutatePolicy(p, logger)
|
||||
_, err := pc.kyvernoClient.KyvernoV1().Policies(p.Namespace).Update(context.TODO(), nsPol.(*kyverno.Policy), metav1.UpdateOptions{})
|
||||
_, err := pc.kyvernoClient.KyvernoV1().Policies(p.Namespace).Update(context.TODO(), nsPol.(*kyvernov1.Policy), metav1.UpdateOptions{})
|
||||
if err != nil {
|
||||
logger.Error(err, "failed to add namespace policy")
|
||||
}
|
||||
|
@ -287,8 +287,8 @@ func (pc *PolicyController) addNsPolicy(obj interface{}) {
|
|||
|
||||
func (pc *PolicyController) updateNsPolicy(old, cur interface{}) {
|
||||
logger := pc.log
|
||||
oldP := old.(*kyverno.Policy)
|
||||
curP := cur.(*kyverno.Policy)
|
||||
oldP := old.(*kyvernov1.Policy)
|
||||
curP := cur.(*kyvernov1.Policy)
|
||||
|
||||
// register kyverno_policy_rule_info_total metric concurrently
|
||||
go pc.registerPolicyRuleInfoMetricUpdatePolicy(logger, oldP, curP)
|
||||
|
@ -297,7 +297,7 @@ func (pc *PolicyController) updateNsPolicy(old, cur interface{}) {
|
|||
|
||||
if curP.Spec.Background == nil || curP.Spec.ValidationFailureAction == "" || missingAutoGenRules(curP, logger) {
|
||||
nsPol, _ := utilscommon.MutatePolicy(curP, logger)
|
||||
_, err := pc.kyvernoClient.KyvernoV1().Policies(curP.GetNamespace()).Update(context.TODO(), nsPol.(*kyverno.Policy), metav1.UpdateOptions{})
|
||||
_, err := pc.kyvernoClient.KyvernoV1().Policies(curP.GetNamespace()).Update(context.TODO(), nsPol.(*kyvernov1.Policy), metav1.UpdateOptions{})
|
||||
if err != nil {
|
||||
logger.Error(err, "failed to update namespace policy ")
|
||||
}
|
||||
|
@ -319,14 +319,14 @@ func (pc *PolicyController) updateNsPolicy(old, cur interface{}) {
|
|||
|
||||
func (pc *PolicyController) deleteNsPolicy(obj interface{}) {
|
||||
logger := pc.log
|
||||
p, ok := obj.(*kyverno.Policy)
|
||||
p, ok := obj.(*kyvernov1.Policy)
|
||||
if !ok {
|
||||
tombstone, ok := obj.(cache.DeletedFinalStateUnknown)
|
||||
if !ok {
|
||||
logger.Info("couldn't get object from tombstone", "obj", obj)
|
||||
return
|
||||
}
|
||||
p, ok = tombstone.Obj.(*kyverno.Policy)
|
||||
p, ok = tombstone.Obj.(*kyvernov1.Policy)
|
||||
if !ok {
|
||||
logger.Info("tombstone container object that is not a policy", "obj", obj)
|
||||
return
|
||||
|
@ -355,7 +355,7 @@ func (pc *PolicyController) deleteNsPolicy(obj interface{}) {
|
|||
pc.enqueuePolicy(pol)
|
||||
}
|
||||
|
||||
func (pc *PolicyController) enqueueRCRDeletedRule(old, cur kyverno.PolicyInterface) {
|
||||
func (pc *PolicyController) enqueueRCRDeletedRule(old, cur kyvernov1.PolicyInterface) {
|
||||
curRule := make(map[string]bool)
|
||||
for _, rule := range autogen.ComputeRules(cur) {
|
||||
curRule[rule.Name] = true
|
||||
|
@ -367,7 +367,7 @@ func (pc *PolicyController) enqueueRCRDeletedRule(old, cur kyverno.PolicyInterfa
|
|||
PolicyName: cur.GetName(),
|
||||
Results: []policyreport.EngineResponseResult{
|
||||
{
|
||||
Rules: []kyverno.ViolatedRule{
|
||||
Rules: []kyvernov1.ViolatedRule{
|
||||
{Name: rule.Name},
|
||||
},
|
||||
},
|
||||
|
@ -383,7 +383,7 @@ func (pc *PolicyController) enqueueRCRDeletedPolicy(policyName string) {
|
|||
})
|
||||
}
|
||||
|
||||
func (pc *PolicyController) enqueuePolicy(policy kyverno.PolicyInterface) {
|
||||
func (pc *PolicyController) enqueuePolicy(policy kyvernov1.PolicyInterface) {
|
||||
logger := pc.log
|
||||
key, err := cache.MetaNamespaceKeyFunc(policy)
|
||||
if err != nil {
|
||||
|
@ -490,7 +490,7 @@ func (pc *PolicyController) syncPolicy(key string) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func (pc *PolicyController) getPolicy(key string) (policy kyverno.PolicyInterface, err error) {
|
||||
func (pc *PolicyController) getPolicy(key string) (policy kyvernov1.PolicyInterface, err error) {
|
||||
namespace, key, isNamespacedPolicy := ParseNamespacedPolicy(key)
|
||||
if !isNamespacedPolicy {
|
||||
return pc.pLister.Get(key)
|
||||
|
@ -504,7 +504,7 @@ func (pc *PolicyController) getPolicy(key string) (policy kyverno.PolicyInterfac
|
|||
return
|
||||
}
|
||||
|
||||
func generateTriggers(client client.Interface, rule kyverno.Rule, log logr.Logger) []*unstructured.Unstructured {
|
||||
func generateTriggers(client client.Interface, rule kyvernov1.Rule, log logr.Logger) []*unstructured.Unstructured {
|
||||
list := &unstructured.UnstructuredList{}
|
||||
|
||||
kinds := fetchUniqueKinds(rule)
|
||||
|
@ -519,7 +519,7 @@ func generateTriggers(client client.Interface, rule kyverno.Rule, log logr.Logge
|
|||
return convertlist(list.Items)
|
||||
}
|
||||
|
||||
func deleteUR(kyvernoClient kyvernoclient.Interface, policyKey string, grList []*urkyverno.UpdateRequest, logger logr.Logger) {
|
||||
func deleteUR(kyvernoClient kyvernoclient.Interface, policyKey string, grList []*kyvernov1beta1.UpdateRequest, logger logr.Logger) {
|
||||
for _, v := range grList {
|
||||
if policyKey == v.Spec.Policy {
|
||||
err := kyvernoClient.KyvernoV1beta1().UpdateRequests(config.KyvernoNamespace()).Delete(context.TODO(), v.GetName(), metav1.DeleteOptions{})
|
||||
|
@ -530,7 +530,7 @@ func deleteUR(kyvernoClient kyvernoclient.Interface, policyKey string, grList []
|
|||
}
|
||||
}
|
||||
|
||||
func updateUR(kyvernoClient kyvernoclient.Interface, policyKey string, urList []*urkyverno.UpdateRequest, logger logr.Logger) {
|
||||
func updateUR(kyvernoClient kyvernoclient.Interface, policyKey string, urList []*kyvernov1beta1.UpdateRequest, logger logr.Logger) {
|
||||
for _, ur := range urList {
|
||||
if policyKey == ur.Spec.Policy {
|
||||
urLabels := ur.Labels
|
||||
|
@ -551,7 +551,7 @@ func updateUR(kyvernoClient kyvernoclient.Interface, policyKey string, urList []
|
|||
continue
|
||||
}
|
||||
|
||||
new.Status.State = urkyverno.Pending
|
||||
new.Status.State = kyvernov1beta1.Pending
|
||||
if _, err := kyvernoClient.KyvernoV1beta1().UpdateRequests(config.KyvernoNamespace()).UpdateStatus(context.TODO(), new, metav1.UpdateOptions{}); err != nil {
|
||||
logger.Error(err, "failed to set UpdateRequest state to Pending")
|
||||
}
|
||||
|
@ -559,7 +559,7 @@ func updateUR(kyvernoClient kyvernoclient.Interface, policyKey string, urList []
|
|||
}
|
||||
}
|
||||
|
||||
func missingAutoGenRules(policy kyverno.PolicyInterface, log logr.Logger) bool {
|
||||
func missingAutoGenRules(policy kyvernov1.PolicyInterface, log logr.Logger) bool {
|
||||
var podRuleName []string
|
||||
ruleCount := 1
|
||||
spec := policy.GetSpec()
|
||||
|
@ -571,7 +571,7 @@ func missingAutoGenRules(policy kyverno.PolicyInterface, log logr.Logger) bool {
|
|||
|
||||
if len(podRuleName) > 0 {
|
||||
annotations := policy.GetAnnotations()
|
||||
val, ok := annotations[kyverno.PodControllersAnnotation]
|
||||
val, ok := annotations[kyvernov1.PodControllersAnnotation]
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
|
|
|
@ -5,8 +5,8 @@ import (
|
|||
"fmt"
|
||||
|
||||
"github.com/gardener/controller-manager-library/pkg/logger"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
urkyverno "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
common "github.com/kyverno/kyverno/pkg/background/common"
|
||||
"github.com/kyverno/kyverno/pkg/config"
|
||||
"github.com/kyverno/kyverno/pkg/engine"
|
||||
|
@ -18,7 +18,7 @@ import (
|
|||
"k8s.io/apimachinery/pkg/labels"
|
||||
)
|
||||
|
||||
func (pc *PolicyController) updateUR(policyKey string, policy kyverno.PolicyInterface) error {
|
||||
func (pc *PolicyController) updateUR(policyKey string, policy kyvernov1.PolicyInterface) error {
|
||||
logger := pc.log.WithName("updateUR").WithName(policyKey)
|
||||
|
||||
if !policy.GetSpec().MutateExistingOnPolicyUpdate && !policy.GetSpec().IsGenerateExistingOnPolicyUpdate() {
|
||||
|
@ -34,10 +34,10 @@ func (pc *PolicyController) updateUR(policyKey string, policy kyverno.PolicyInte
|
|||
updateUR(pc.kyvernoClient, policyKey, append(mutateURs, generateURs...), pc.log.WithName("updateUR"))
|
||||
|
||||
for _, rule := range policy.GetSpec().Rules {
|
||||
var ruleType urkyverno.RequestType
|
||||
var ruleType kyvernov1beta1.RequestType
|
||||
|
||||
if rule.IsMutateExisting() {
|
||||
ruleType = urkyverno.Mutate
|
||||
ruleType = kyvernov1beta1.Mutate
|
||||
|
||||
triggers := generateTriggers(pc.client, rule, pc.log)
|
||||
for _, trigger := range triggers {
|
||||
|
@ -64,7 +64,7 @@ func (pc *PolicyController) updateUR(policyKey string, policy kyverno.PolicyInte
|
|||
}
|
||||
}
|
||||
if policy.GetSpec().IsGenerateExistingOnPolicyUpdate() {
|
||||
ruleType = urkyverno.Generate
|
||||
ruleType = kyvernov1beta1.Generate
|
||||
triggers := generateTriggers(pc.client, rule, pc.log)
|
||||
for _, trigger := range triggers {
|
||||
gurs := pc.listGenerateURs(policyKey, trigger)
|
||||
|
@ -97,7 +97,7 @@ func (pc *PolicyController) updateUR(policyKey string, policy kyverno.PolicyInte
|
|||
return nil
|
||||
}
|
||||
|
||||
func (pc *PolicyController) handleUpdateRequest(ur *urkyverno.UpdateRequest, triggerResource *unstructured.Unstructured, rule kyverno.Rule, policy kyverno.PolicyInterface) (skip bool, err error) {
|
||||
func (pc *PolicyController) handleUpdateRequest(ur *kyvernov1beta1.UpdateRequest, triggerResource *unstructured.Unstructured, rule kyvernov1.Rule, policy kyvernov1.PolicyInterface) (skip bool, err error) {
|
||||
policyContext, _, err := common.NewBackgroundContext(pc.client, ur, policy, triggerResource, pc.configHandler, nil, pc.log)
|
||||
if err != nil {
|
||||
return false, errors.Wrapf(err, "failed to build policy context for rule %s", rule.Name)
|
||||
|
@ -120,7 +120,7 @@ func (pc *PolicyController) handleUpdateRequest(ur *urkyverno.UpdateRequest, tri
|
|||
return false, err
|
||||
}
|
||||
|
||||
new.Status.State = urkyverno.Pending
|
||||
new.Status.State = kyvernov1beta1.Pending
|
||||
if _, err := pc.kyvernoClient.KyvernoV1beta1().UpdateRequests(config.KyvernoNamespace()).UpdateStatus(context.TODO(), new, metav1.UpdateOptions{}); err != nil {
|
||||
pc.log.Error(err, "failed to set UpdateRequest state to Pending")
|
||||
return false, err
|
||||
|
@ -129,7 +129,7 @@ func (pc *PolicyController) handleUpdateRequest(ur *urkyverno.UpdateRequest, tri
|
|||
return false, err
|
||||
}
|
||||
|
||||
func (pc *PolicyController) listMutateURs(policyKey string, trigger *unstructured.Unstructured) []*urkyverno.UpdateRequest {
|
||||
func (pc *PolicyController) listMutateURs(policyKey string, trigger *unstructured.Unstructured) []*kyvernov1beta1.UpdateRequest {
|
||||
selector := createMutateLabels(policyKey, trigger)
|
||||
mutateURs, err := pc.urLister.List(labels.SelectorFromSet(selector))
|
||||
if err != nil {
|
||||
|
@ -139,7 +139,7 @@ func (pc *PolicyController) listMutateURs(policyKey string, trigger *unstructure
|
|||
return mutateURs
|
||||
}
|
||||
|
||||
func (pc *PolicyController) listGenerateURs(policyKey string, trigger *unstructured.Unstructured) []*urkyverno.UpdateRequest {
|
||||
func (pc *PolicyController) listGenerateURs(policyKey string, trigger *unstructured.Unstructured) []*kyvernov1beta1.UpdateRequest {
|
||||
selector := createGenerateLabels(policyKey, trigger)
|
||||
generateURs, err := pc.urLister.List(labels.SelectorFromSet(selector))
|
||||
if err != nil {
|
||||
|
@ -149,7 +149,7 @@ func (pc *PolicyController) listGenerateURs(policyKey string, trigger *unstructu
|
|||
return generateURs
|
||||
}
|
||||
|
||||
func newUR(policy kyverno.PolicyInterface, trigger *unstructured.Unstructured, ruleType urkyverno.RequestType) *urkyverno.UpdateRequest {
|
||||
func newUR(policy kyvernov1.PolicyInterface, trigger *unstructured.Unstructured, ruleType kyvernov1beta1.RequestType) *kyvernov1beta1.UpdateRequest {
|
||||
var policyNameNamespaceKey string
|
||||
|
||||
if policy.IsNamespaced() {
|
||||
|
@ -159,22 +159,22 @@ func newUR(policy kyverno.PolicyInterface, trigger *unstructured.Unstructured, r
|
|||
}
|
||||
|
||||
var label labels.Set
|
||||
if ruleType == urkyverno.Mutate {
|
||||
if ruleType == kyvernov1beta1.Mutate {
|
||||
label = createMutateLabels(policyNameNamespaceKey, trigger)
|
||||
} else {
|
||||
label = createGenerateLabels(policyNameNamespaceKey, trigger)
|
||||
}
|
||||
|
||||
return &urkyverno.UpdateRequest{
|
||||
return &kyvernov1beta1.UpdateRequest{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
GenerateName: "ur-",
|
||||
Namespace: config.KyvernoNamespace(),
|
||||
Labels: label,
|
||||
},
|
||||
Spec: urkyverno.UpdateRequestSpec{
|
||||
Spec: kyvernov1beta1.UpdateRequestSpec{
|
||||
Type: ruleType,
|
||||
Policy: policyNameNamespaceKey,
|
||||
Resource: kyverno.ResourceSpec{
|
||||
Resource: kyvernov1.ResourceSpec{
|
||||
Kind: trigger.GetKind(),
|
||||
Namespace: trigger.GetNamespace(),
|
||||
Name: trigger.GetName(),
|
||||
|
@ -188,18 +188,18 @@ func createMutateLabels(policyKey string, trigger *unstructured.Unstructured) la
|
|||
var selector labels.Set
|
||||
if trigger == nil {
|
||||
selector = labels.Set(map[string]string{
|
||||
urkyverno.URMutatePolicyLabel: policyKey,
|
||||
kyvernov1beta1.URMutatePolicyLabel: policyKey,
|
||||
})
|
||||
} else {
|
||||
selector = labels.Set(map[string]string{
|
||||
urkyverno.URMutatePolicyLabel: policyKey,
|
||||
urkyverno.URMutateTriggerNameLabel: trigger.GetName(),
|
||||
urkyverno.URMutateTriggerNSLabel: trigger.GetNamespace(),
|
||||
urkyverno.URMutatetriggerKindLabel: trigger.GetKind(),
|
||||
kyvernov1beta1.URMutatePolicyLabel: policyKey,
|
||||
kyvernov1beta1.URMutateTriggerNameLabel: trigger.GetName(),
|
||||
kyvernov1beta1.URMutateTriggerNSLabel: trigger.GetNamespace(),
|
||||
kyvernov1beta1.URMutatetriggerKindLabel: trigger.GetKind(),
|
||||
})
|
||||
|
||||
if trigger.GetAPIVersion() != "" {
|
||||
selector[urkyverno.URMutatetriggerAPIVersionLabel] = trigger.GetAPIVersion()
|
||||
selector[kyvernov1beta1.URMutatetriggerAPIVersionLabel] = trigger.GetAPIVersion()
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -210,11 +210,11 @@ func createGenerateLabels(policyKey string, trigger *unstructured.Unstructured)
|
|||
var selector labels.Set
|
||||
if trigger == nil {
|
||||
selector = labels.Set(map[string]string{
|
||||
urkyverno.URGeneratePolicyLabel: policyKey,
|
||||
kyvernov1beta1.URGeneratePolicyLabel: policyKey,
|
||||
})
|
||||
} else {
|
||||
selector = labels.Set(map[string]string{
|
||||
urkyverno.URGeneratePolicyLabel: policyKey,
|
||||
kyvernov1beta1.URGeneratePolicyLabel: policyKey,
|
||||
"generate.kyverno.io/resource-name": trigger.GetName(),
|
||||
"generate.kyverno.io/resource-kind": trigger.GetKind(),
|
||||
"generate.kyverno.io/resource-namespace": trigger.GetNamespace(),
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
package policy
|
||||
|
||||
import (
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
)
|
||||
|
||||
|
@ -16,7 +16,7 @@ func isRunningPod(obj unstructured.Unstructured) bool {
|
|||
}
|
||||
|
||||
// check if all slice elements are same
|
||||
func isMatchResourcesAllValid(rule kyverno.Rule) bool {
|
||||
func isMatchResourcesAllValid(rule kyvernov1.Rule) bool {
|
||||
var kindlist []string
|
||||
for _, all := range rule.MatchResources.All {
|
||||
kindlist = append(kindlist, all.Kinds...)
|
||||
|
@ -34,7 +34,7 @@ func isMatchResourcesAllValid(rule kyverno.Rule) bool {
|
|||
return true
|
||||
}
|
||||
|
||||
func fetchUniqueKinds(rule kyverno.Rule) []string {
|
||||
func fetchUniqueKinds(rule kyvernov1.Rule) []string {
|
||||
var kindlist []string
|
||||
|
||||
kindlist = append(kindlist, rule.MatchResources.Kinds...)
|
||||
|
|
|
@ -11,7 +11,7 @@ import (
|
|||
"github.com/distribution/distribution/reference"
|
||||
jsonpatch "github.com/evanphx/json-patch/v5"
|
||||
"github.com/jmespath/go-jmespath"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/utils/common"
|
||||
"github.com/kyverno/kyverno/pkg/autogen"
|
||||
dclient "github.com/kyverno/kyverno/pkg/dclient"
|
||||
|
@ -77,7 +77,7 @@ func validateJSONPatchPathForForwardSlash(patch string) error {
|
|||
}
|
||||
|
||||
// Validate checks the policy and rules declarations for required configurations
|
||||
func Validate(policy kyverno.PolicyInterface, client dclient.Interface, mock bool, openAPIController *openapi.Controller) (*admissionv1.AdmissionResponse, error) {
|
||||
func Validate(policy kyvernov1.PolicyInterface, client dclient.Interface, mock bool, openAPIController *openapi.Controller) (*admissionv1.AdmissionResponse, error) {
|
||||
namespaced := policy.IsNamespaced()
|
||||
spec := policy.GetSpec()
|
||||
background := spec.BackgroundProcessingEnabled()
|
||||
|
@ -209,7 +209,7 @@ func Validate(policy kyverno.PolicyInterface, client dclient.Interface, mock boo
|
|||
if rule.Validation.Deny != nil {
|
||||
kyvernoConditions, _ := utils.ApiextensionsJsonToKyvernoConditions(rule.Validation.Deny.GetAnyAllConditions())
|
||||
switch typedConditions := kyvernoConditions.(type) {
|
||||
case []kyverno.Condition: // backwards compatibility
|
||||
case []kyvernov1.Condition: // backwards compatibility
|
||||
for _, condition := range typedConditions {
|
||||
key := condition.GetKey()
|
||||
if !strings.Contains(key.(string), "request.object.metadata.") && (!wildCardAllowedVariables.MatchString(key.(string)) || strings.Contains(key.(string), "request.object.spec")) {
|
||||
|
@ -354,7 +354,7 @@ func Validate(policy kyverno.PolicyInterface, client dclient.Interface, mock boo
|
|||
return nil, nil
|
||||
}
|
||||
|
||||
func ValidateVariables(p kyverno.PolicyInterface, backgroundMode bool) error {
|
||||
func ValidateVariables(p kyvernov1.PolicyInterface, backgroundMode bool) error {
|
||||
vars := hasVariables(p)
|
||||
if len(vars) == 0 {
|
||||
return nil
|
||||
|
@ -374,7 +374,7 @@ func ValidateVariables(p kyverno.PolicyInterface, backgroundMode bool) error {
|
|||
}
|
||||
|
||||
// hasInvalidVariables - checks for unexpected variables in the policy
|
||||
func hasInvalidVariables(policy kyverno.PolicyInterface, background bool) error {
|
||||
func hasInvalidVariables(policy kyvernov1.PolicyInterface, background bool) error {
|
||||
for _, r := range autogen.ComputeRules(policy) {
|
||||
ruleCopy := r.DeepCopy()
|
||||
|
||||
|
@ -398,7 +398,7 @@ func hasInvalidVariables(policy kyverno.PolicyInterface, background bool) error
|
|||
return nil
|
||||
}
|
||||
|
||||
func ValidateOnPolicyUpdate(p kyverno.PolicyInterface, onPolicyUpdate bool) error {
|
||||
func ValidateOnPolicyUpdate(p kyvernov1.PolicyInterface, onPolicyUpdate bool) error {
|
||||
vars := hasVariables(p)
|
||||
if len(vars) == 0 {
|
||||
return nil
|
||||
|
@ -416,7 +416,7 @@ func ValidateOnPolicyUpdate(p kyverno.PolicyInterface, onPolicyUpdate bool) erro
|
|||
}
|
||||
|
||||
// for now forbidden sections are match, exclude and
|
||||
func ruleForbiddenSectionsHaveVariables(rule *kyverno.Rule) error {
|
||||
func ruleForbiddenSectionsHaveVariables(rule *kyvernov1.Rule) error {
|
||||
var err error
|
||||
|
||||
err = jsonPatchPathHasVariables(rule.Mutation.PatchesJSON6902)
|
||||
|
@ -438,7 +438,7 @@ func ruleForbiddenSectionsHaveVariables(rule *kyverno.Rule) error {
|
|||
}
|
||||
|
||||
// hasVariables - check for variables in the policy
|
||||
func hasVariables(policy kyverno.PolicyInterface) [][]string {
|
||||
func hasVariables(policy kyvernov1.PolicyInterface) [][]string {
|
||||
policyRaw, _ := json.Marshal(policy)
|
||||
matches := variables.RegexVariables.FindAllStringSubmatch(string(policyRaw), -1)
|
||||
return matches
|
||||
|
@ -484,7 +484,7 @@ func objectHasVariables(object interface{}) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func buildContext(rule *kyverno.Rule, background bool) *context.MockContext {
|
||||
func buildContext(rule *kyvernov1.Rule, background bool) *context.MockContext {
|
||||
re := getAllowedVariables(background)
|
||||
ctx := context.NewMockContext(re)
|
||||
|
||||
|
@ -509,7 +509,7 @@ func getAllowedVariables(background bool) *regexp.Regexp {
|
|||
return allowedVariables
|
||||
}
|
||||
|
||||
func addContextVariables(entries []kyverno.ContextEntry, ctx *context.MockContext) {
|
||||
func addContextVariables(entries []kyvernov1.ContextEntry, ctx *context.MockContext) {
|
||||
for _, contextEntry := range entries {
|
||||
if contextEntry.APICall != nil || contextEntry.ImageRegistry != nil || contextEntry.Variable != nil {
|
||||
ctx.AddVariable(contextEntry.Name + "*")
|
||||
|
@ -551,7 +551,7 @@ func validateElementInForEach(document apiextensions.JSON) error {
|
|||
return err
|
||||
}
|
||||
|
||||
func validateMatchKindHelper(rule kyverno.Rule) error {
|
||||
func validateMatchKindHelper(rule kyvernov1.Rule) error {
|
||||
if !ruleOnlyDealsWithResourceMetaData(rule) {
|
||||
return fmt.Errorf("policy can only deal with the metadata field of the resource if" +
|
||||
" the rule does not match any kind")
|
||||
|
@ -561,7 +561,7 @@ func validateMatchKindHelper(rule kyverno.Rule) error {
|
|||
}
|
||||
|
||||
// isLabelAndAnnotationsString :- Validate if labels and annotations contains only string values
|
||||
func isLabelAndAnnotationsString(rule kyverno.Rule) bool {
|
||||
func isLabelAndAnnotationsString(rule kyvernov1.Rule) bool {
|
||||
// checkMetadata - Verify if the labels and annotations contains string value inside metadata
|
||||
checkMetadata := func(patternMap map[string]interface{}) bool {
|
||||
for k := range patternMap {
|
||||
|
@ -621,7 +621,7 @@ func isLabelAndAnnotationsString(rule kyverno.Rule) bool {
|
|||
return true
|
||||
}
|
||||
|
||||
func ruleOnlyDealsWithResourceMetaData(rule kyverno.Rule) bool {
|
||||
func ruleOnlyDealsWithResourceMetaData(rule kyvernov1.Rule) bool {
|
||||
patches, _ := rule.Mutation.GetPatchStrategicMerge().(map[string]interface{})
|
||||
for k := range patches {
|
||||
if k != "metadata" {
|
||||
|
@ -665,17 +665,17 @@ func ruleOnlyDealsWithResourceMetaData(rule kyverno.Rule) bool {
|
|||
return true
|
||||
}
|
||||
|
||||
func validateResources(path *field.Path, rule kyverno.Rule) (string, error) {
|
||||
func validateResources(path *field.Path, rule kyvernov1.Rule) (string, error) {
|
||||
// validate userInfo in match and exclude
|
||||
if errs := rule.ExcludeResources.UserInfo.Validate(path.Child("exclude")); len(errs) != 0 {
|
||||
return "exclude", errs.ToAggregate()
|
||||
}
|
||||
|
||||
if (len(rule.MatchResources.Any) > 0 || len(rule.MatchResources.All) > 0) && !reflect.DeepEqual(rule.MatchResources.ResourceDescription, kyverno.ResourceDescription{}) {
|
||||
if (len(rule.MatchResources.Any) > 0 || len(rule.MatchResources.All) > 0) && !reflect.DeepEqual(rule.MatchResources.ResourceDescription, kyvernov1.ResourceDescription{}) {
|
||||
return "match.", fmt.Errorf("can't specify any/all together with match resources")
|
||||
}
|
||||
|
||||
if (len(rule.ExcludeResources.Any) > 0 || len(rule.ExcludeResources.All) > 0) && !reflect.DeepEqual(rule.ExcludeResources.ResourceDescription, kyverno.ResourceDescription{}) {
|
||||
if (len(rule.ExcludeResources.Any) > 0 || len(rule.ExcludeResources.All) > 0) && !reflect.DeepEqual(rule.ExcludeResources.ResourceDescription, kyvernov1.ResourceDescription{}) {
|
||||
return "exclude.", fmt.Errorf("can't specify any/all together with exclude resources")
|
||||
}
|
||||
|
||||
|
@ -740,9 +740,9 @@ func validateConditions(conditions apiextensions.JSON, schemaKey string) (string
|
|||
return schemaKey, err
|
||||
}
|
||||
switch typedConditions := kyvernoConditions.(type) {
|
||||
case kyverno.AnyAllConditions:
|
||||
case kyvernov1.AnyAllConditions:
|
||||
// validating the conditions under 'any', if there are any
|
||||
if !reflect.DeepEqual(typedConditions, kyverno.AnyAllConditions{}) && typedConditions.AnyConditions != nil {
|
||||
if !reflect.DeepEqual(typedConditions, kyvernov1.AnyAllConditions{}) && typedConditions.AnyConditions != nil {
|
||||
for i, condition := range typedConditions.AnyConditions {
|
||||
if path, err := validateConditionValues(condition); err != nil {
|
||||
return fmt.Sprintf("%s.any[%d].%s", schemaKey, i, path), err
|
||||
|
@ -750,7 +750,7 @@ func validateConditions(conditions apiextensions.JSON, schemaKey string) (string
|
|||
}
|
||||
}
|
||||
// validating the conditions under 'all', if there are any
|
||||
if !reflect.DeepEqual(typedConditions, kyverno.AnyAllConditions{}) && typedConditions.AllConditions != nil {
|
||||
if !reflect.DeepEqual(typedConditions, kyvernov1.AnyAllConditions{}) && typedConditions.AllConditions != nil {
|
||||
for i, condition := range typedConditions.AllConditions {
|
||||
if path, err := validateConditionValues(condition); err != nil {
|
||||
return fmt.Sprintf("%s.all[%d].%s", schemaKey, i, path), err
|
||||
|
@ -758,7 +758,7 @@ func validateConditions(conditions apiextensions.JSON, schemaKey string) (string
|
|||
}
|
||||
}
|
||||
|
||||
case []kyverno.Condition: // backwards compatibility
|
||||
case []kyvernov1.Condition: // backwards compatibility
|
||||
for i, condition := range typedConditions {
|
||||
if path, err := validateConditionValues(condition); err != nil {
|
||||
return fmt.Sprintf("%s[%d].%s", schemaKey, i, path), err
|
||||
|
@ -770,7 +770,7 @@ func validateConditions(conditions apiextensions.JSON, schemaKey string) (string
|
|||
|
||||
// validateConditionValues validates whether all the values under the 'value' field of a 'conditions' field
|
||||
// are apt with respect to the provided 'condition.key'
|
||||
func validateConditionValues(c kyverno.Condition) (string, error) {
|
||||
func validateConditionValues(c kyvernov1.Condition) (string, error) {
|
||||
k := c.GetKey()
|
||||
v := c.GetValue()
|
||||
if k == nil || v == nil || c.Operator == "" {
|
||||
|
@ -785,7 +785,7 @@ func validateConditionValues(c kyverno.Condition) (string, error) {
|
|||
}
|
||||
}
|
||||
|
||||
func validateValuesKeyRequest(c kyverno.Condition) (string, error) {
|
||||
func validateValuesKeyRequest(c kyvernov1.Condition) (string, error) {
|
||||
k := c.GetKey()
|
||||
switch strings.ReplaceAll(k.(string), " ", "") {
|
||||
case "{{request.operation}}":
|
||||
|
@ -797,7 +797,7 @@ func validateValuesKeyRequest(c kyverno.Condition) (string, error) {
|
|||
|
||||
// validateConditionValuesKeyRequestOperation validates whether all the values under the 'value' field of a 'conditions' field
|
||||
// are one of ["CREATE", "UPDATE", "DELETE", "CONNECT"] when 'condition.key' is {{request.operation}}
|
||||
func validateConditionValuesKeyRequestOperation(c kyverno.Condition) (string, error) {
|
||||
func validateConditionValuesKeyRequestOperation(c kyvernov1.Condition) (string, error) {
|
||||
valuesAllowed := map[string]bool{
|
||||
"CREATE": true,
|
||||
"UPDATE": true,
|
||||
|
@ -830,7 +830,7 @@ func validateConditionValuesKeyRequestOperation(c kyverno.Condition) (string, er
|
|||
return "", nil
|
||||
}
|
||||
|
||||
func validateRuleContext(rule kyverno.Rule) error {
|
||||
func validateRuleContext(rule kyvernov1.Rule) error {
|
||||
if rule.Context == nil || len(rule.Context) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
@ -865,7 +865,7 @@ func validateRuleContext(rule kyverno.Rule) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func validateVariable(entry kyverno.ContextEntry) error {
|
||||
func validateVariable(entry kyvernov1.ContextEntry) error {
|
||||
// If JMESPath contains variables, the validation will fail because it's not possible to infer which value
|
||||
// will be inserted by the variable
|
||||
// Skip validation if a variable is detected
|
||||
|
@ -884,7 +884,7 @@ func validateVariable(entry kyverno.ContextEntry) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func validateConfigMap(entry kyverno.ContextEntry) error {
|
||||
func validateConfigMap(entry kyvernov1.ContextEntry) error {
|
||||
if entry.ConfigMap.Name == "" {
|
||||
return fmt.Errorf("a name is required for configMap context entry")
|
||||
}
|
||||
|
@ -896,7 +896,7 @@ func validateConfigMap(entry kyverno.ContextEntry) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func validateAPICall(entry kyverno.ContextEntry) error {
|
||||
func validateAPICall(entry kyvernov1.ContextEntry) error {
|
||||
// Replace all variables to prevent validation failing on variable keys.
|
||||
urlPath := variables.ReplaceAllVars(entry.APICall.URLPath, func(s string) string { return "kyvernoapicallvariable" })
|
||||
|
||||
|
@ -919,7 +919,7 @@ func validateAPICall(entry kyverno.ContextEntry) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func validateImageRegistry(entry kyverno.ContextEntry) error {
|
||||
func validateImageRegistry(entry kyvernov1.ContextEntry) error {
|
||||
if entry.ImageRegistry.Reference == "" {
|
||||
return fmt.Errorf("a ref is required for imageRegistry context entry")
|
||||
}
|
||||
|
@ -953,8 +953,8 @@ func validateImageRegistry(entry kyverno.ContextEntry) error {
|
|||
// Returns error if
|
||||
// - kinds is empty array in matched resource block, i.e. kinds: []
|
||||
// - selector is invalid
|
||||
func validateMatchedResourceDescription(rd kyverno.ResourceDescription) (string, error) {
|
||||
if reflect.DeepEqual(rd, kyverno.ResourceDescription{}) {
|
||||
func validateMatchedResourceDescription(rd kyvernov1.ResourceDescription) (string, error) {
|
||||
if reflect.DeepEqual(rd, kyvernov1.ResourceDescription{}) {
|
||||
return "", fmt.Errorf("match resources not specified")
|
||||
}
|
||||
|
||||
|
@ -963,7 +963,7 @@ func validateMatchedResourceDescription(rd kyverno.ResourceDescription) (string,
|
|||
|
||||
// checkClusterResourceInMatchAndExclude returns false if namespaced ClusterPolicy contains cluster wide resources in
|
||||
// Match and Exclude block
|
||||
func checkClusterResourceInMatchAndExclude(rule kyverno.Rule, clusterResources sets.String, mock bool, res []*metav1.APIResourceList) error {
|
||||
func checkClusterResourceInMatchAndExclude(rule kyvernov1.Rule, clusterResources sets.String, mock bool, res []*metav1.APIResourceList) error {
|
||||
if !mock {
|
||||
// Check for generate policy
|
||||
// - if resource to be generated is namespaced resource then the namespace field
|
||||
|
@ -994,7 +994,7 @@ func checkClusterResourceInMatchAndExclude(rule kyverno.Rule, clusterResources s
|
|||
}
|
||||
|
||||
// jsonPatchOnPod checks if a rule applies JSON patches to Pod
|
||||
func jsonPatchOnPod(rule kyverno.Rule) bool {
|
||||
func jsonPatchOnPod(rule kyvernov1.Rule) bool {
|
||||
if !rule.HasMutate() {
|
||||
return false
|
||||
}
|
||||
|
@ -1006,9 +1006,9 @@ func jsonPatchOnPod(rule kyverno.Rule) bool {
|
|||
return false
|
||||
}
|
||||
|
||||
func podControllerAutoGenExclusion(policy kyverno.PolicyInterface) bool {
|
||||
func podControllerAutoGenExclusion(policy kyvernov1.PolicyInterface) bool {
|
||||
annotations := policy.GetAnnotations()
|
||||
val, ok := annotations[kyverno.PodControllersAnnotation]
|
||||
val, ok := annotations[kyvernov1.PodControllersAnnotation]
|
||||
if !ok || val == "none" {
|
||||
return false
|
||||
}
|
||||
|
@ -1023,7 +1023,7 @@ func podControllerAutoGenExclusion(policy kyverno.PolicyInterface) bool {
|
|||
|
||||
// validateKinds verifies if an API resource that matches 'kind' is valid kind
|
||||
// and found in the cache, returns error if not found
|
||||
func validateKinds(kinds []string, mock bool, client dclient.Interface, p kyverno.PolicyInterface) error {
|
||||
func validateKinds(kinds []string, mock bool, client dclient.Interface, p kyvernov1.PolicyInterface) error {
|
||||
for _, kind := range kinds {
|
||||
gv, k := kubeutils.GetKindFromGVK(kind)
|
||||
if k == p.GetKind() {
|
||||
|
|
|
@ -4,7 +4,7 @@ import (
|
|||
"fmt"
|
||||
"strings"
|
||||
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
commonAnchors "github.com/kyverno/kyverno/pkg/engine/anchor"
|
||||
"github.com/kyverno/kyverno/pkg/policy/common"
|
||||
)
|
||||
|
@ -12,11 +12,11 @@ import (
|
|||
// Validate validates a 'validate' rule
|
||||
type Validate struct {
|
||||
// rule to hold 'validate' rule specifications
|
||||
rule *kyverno.Validation
|
||||
rule *kyvernov1.Validation
|
||||
}
|
||||
|
||||
// NewValidateFactory returns a new instance of Mutate validation checker
|
||||
func NewValidateFactory(rule *kyverno.Validation) *Validate {
|
||||
func NewValidateFactory(rule *kyvernov1.Validation) *Validate {
|
||||
m := Validate{
|
||||
rule: rule,
|
||||
}
|
||||
|
@ -72,7 +72,7 @@ func (v *Validate) validateElements() error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func validationElemCount(v *kyverno.Validation) int {
|
||||
func validationElemCount(v *kyvernov1.Validation) int {
|
||||
if v == nil {
|
||||
return 0
|
||||
}
|
||||
|
@ -97,7 +97,7 @@ func validationElemCount(v *kyverno.Validation) int {
|
|||
return count
|
||||
}
|
||||
|
||||
func (v *Validate) validateForEach(foreach kyverno.ForEachValidation) error {
|
||||
func (v *Validate) validateForEach(foreach kyvernov1.ForEachValidation) error {
|
||||
if foreach.List == "" {
|
||||
return fmt.Errorf("foreach.list is required")
|
||||
}
|
||||
|
@ -118,7 +118,7 @@ func (v *Validate) validateForEach(foreach kyverno.ForEachValidation) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func foreachElemCount(foreach kyverno.ForEachValidation) int {
|
||||
func foreachElemCount(foreach kyvernov1.ForEachValidation) int {
|
||||
count := 0
|
||||
if foreach.GetPattern() != nil {
|
||||
count++
|
||||
|
|
|
@ -6,7 +6,7 @@ import (
|
|||
"strings"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/autogen"
|
||||
"github.com/kyverno/kyverno/pkg/toggle"
|
||||
jsonutils "github.com/kyverno/kyverno/pkg/utils/json"
|
||||
|
@ -16,7 +16,7 @@ import (
|
|||
// - ValidationFailureAction
|
||||
// - Background
|
||||
// - auto-gen annotation and rules
|
||||
func GenerateJSONPatchesForDefaults(policy kyverno.PolicyInterface, log logr.Logger) ([]byte, []string) {
|
||||
func GenerateJSONPatchesForDefaults(policy kyvernov1.PolicyInterface, log logr.Logger) ([]byte, []string) {
|
||||
var patches [][]byte
|
||||
var updateMsgs []string
|
||||
spec := policy.GetSpec()
|
||||
|
@ -51,7 +51,7 @@ func GenerateJSONPatchesForDefaults(policy kyverno.PolicyInterface, log logr.Log
|
|||
return jsonutils.JoinPatches(patches...), updateMsgs
|
||||
}
|
||||
|
||||
func defaultBackgroundFlag(spec *kyverno.Spec, log logr.Logger) ([]byte, string) {
|
||||
func defaultBackgroundFlag(spec *kyvernov1.Spec, log logr.Logger) ([]byte, string) {
|
||||
// set 'Background' flag to 'true' if not specified
|
||||
if spec.Background == nil {
|
||||
defaultVal := true
|
||||
|
@ -67,10 +67,10 @@ func defaultBackgroundFlag(spec *kyverno.Spec, log logr.Logger) ([]byte, string)
|
|||
return nil, ""
|
||||
}
|
||||
|
||||
func defaultvalidationFailureAction(spec *kyverno.Spec, log logr.Logger) ([]byte, string) {
|
||||
func defaultvalidationFailureAction(spec *kyvernov1.Spec, log logr.Logger) ([]byte, string) {
|
||||
// set ValidationFailureAction to "audit" if not specified
|
||||
if spec.ValidationFailureAction == "" {
|
||||
audit := kyverno.Audit
|
||||
audit := kyvernov1.Audit
|
||||
log.V(4).Info("setting default value", "spec.validationFailureAction", audit)
|
||||
patchByte, err := jsonutils.MarshalPatch("/spec/validationFailureAction", "add", audit)
|
||||
if err != nil {
|
||||
|
@ -83,10 +83,10 @@ func defaultvalidationFailureAction(spec *kyverno.Spec, log logr.Logger) ([]byte
|
|||
return nil, ""
|
||||
}
|
||||
|
||||
func defaultFailurePolicy(spec *kyverno.Spec, log logr.Logger) ([]byte, string) {
|
||||
func defaultFailurePolicy(spec *kyvernov1.Spec, log logr.Logger) ([]byte, string) {
|
||||
// set failurePolicy to Fail if not present
|
||||
if spec.FailurePolicy == nil {
|
||||
failurePolicy := string(kyverno.Fail)
|
||||
failurePolicy := string(kyvernov1.Fail)
|
||||
log.V(4).Info("setting default value", "spec.failurePolicy", failurePolicy)
|
||||
patchByte, err := jsonutils.MarshalPatch("/spec/failurePolicy", "add", failurePolicy)
|
||||
if err != nil {
|
||||
|
@ -109,7 +109,7 @@ func defaultFailurePolicy(spec *kyverno.Spec, log logr.Logger) ([]byte, string)
|
|||
// make sure all fields are applicable to pod controllers
|
||||
|
||||
// GeneratePodControllerRule returns two patches: rulePatches and annotation patch(if necessary)
|
||||
func GeneratePodControllerRule(policy kyverno.PolicyInterface, log logr.Logger) (patches [][]byte, errs []error) {
|
||||
func GeneratePodControllerRule(policy kyvernov1.PolicyInterface, log logr.Logger) (patches [][]byte, errs []error) {
|
||||
spec := policy.GetSpec()
|
||||
applyAutoGen, desiredControllers := autogen.CanAutoGen(spec)
|
||||
|
||||
|
@ -118,7 +118,7 @@ func GeneratePodControllerRule(policy kyverno.PolicyInterface, log logr.Logger)
|
|||
}
|
||||
|
||||
ann := policy.GetAnnotations()
|
||||
actualControllers, ok := ann[kyverno.PodControllersAnnotation]
|
||||
actualControllers, ok := ann[kyvernov1.PodControllersAnnotation]
|
||||
|
||||
// - scenario A
|
||||
// - predefined controllers are invalid, overwrite the value
|
||||
|
@ -154,7 +154,7 @@ func GeneratePodControllerRule(policy kyverno.PolicyInterface, log logr.Logger)
|
|||
func defaultPodControllerAnnotation(ann map[string]string, controllers string) ([]byte, error) {
|
||||
if ann == nil {
|
||||
ann = make(map[string]string)
|
||||
ann[kyverno.PodControllersAnnotation] = controllers
|
||||
ann[kyvernov1.PodControllersAnnotation] = controllers
|
||||
patchByte, err := jsonutils.MarshalPatch("/metadata/annotations", "add", ann)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
|
|
@ -7,9 +7,9 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
request "github.com/kyverno/kyverno/api/kyverno/v1alpha2"
|
||||
report "github.com/kyverno/kyverno/api/policyreport/v1alpha2"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1alpha2 "github.com/kyverno/kyverno/api/kyverno/v1alpha2"
|
||||
policyreportv1alpha2 "github.com/kyverno/kyverno/api/policyreport/v1alpha2"
|
||||
kyvernolister "github.com/kyverno/kyverno/pkg/client/listers/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/config"
|
||||
"github.com/kyverno/kyverno/pkg/engine"
|
||||
|
@ -94,7 +94,7 @@ func NewBuilder(cpolLister kyvernolister.ClusterPolicyLister, polLister kyvernol
|
|||
}
|
||||
|
||||
func (builder *requestBuilder) build(info Info) (req *unstructured.Unstructured, err error) {
|
||||
results := []report.PolicyReportResult{}
|
||||
results := []policyreportv1alpha2.PolicyReportResult{}
|
||||
req = new(unstructured.Unstructured)
|
||||
for _, infoResult := range info.Results {
|
||||
for _, rule := range infoResult.Rules {
|
||||
|
@ -108,12 +108,12 @@ func (builder *requestBuilder) build(info Info) (req *unstructured.Unstructured,
|
|||
}
|
||||
|
||||
if info.Namespace != "" {
|
||||
rr := &request.ReportChangeRequest{
|
||||
rr := &kyvernov1alpha2.ReportChangeRequest{
|
||||
Summary: calculateSummary(results),
|
||||
Results: results,
|
||||
}
|
||||
|
||||
gv := report.SchemeGroupVersion
|
||||
gv := policyreportv1alpha2.SchemeGroupVersion
|
||||
rr.SetGroupVersionKind(schema.GroupVersionKind{Group: gv.Group, Version: gv.Version, Kind: "ReportChangeRequest"})
|
||||
|
||||
rawRcr, err := json.Marshal(rr)
|
||||
|
@ -128,12 +128,12 @@ func (builder *requestBuilder) build(info Info) (req *unstructured.Unstructured,
|
|||
|
||||
set(req, info)
|
||||
} else {
|
||||
rr := &request.ClusterReportChangeRequest{
|
||||
rr := &kyvernov1alpha2.ClusterReportChangeRequest{
|
||||
Summary: calculateSummary(results),
|
||||
Results: results,
|
||||
}
|
||||
|
||||
gv := report.SchemeGroupVersion
|
||||
gv := policyreportv1alpha2.SchemeGroupVersion
|
||||
rr.SetGroupVersionKind(schema.GroupVersionKind{Group: gv.Group, Version: gv.Version, Kind: "ClusterReportChangeRequest"})
|
||||
|
||||
rawRcr, err := json.Marshal(rr)
|
||||
|
@ -160,10 +160,10 @@ func (builder *requestBuilder) build(info Info) (req *unstructured.Unstructured,
|
|||
return req, nil
|
||||
}
|
||||
|
||||
func (builder *requestBuilder) buildRCRResult(policy string, resource response.ResourceSpec, rule kyverno.ViolatedRule) report.PolicyReportResult {
|
||||
func (builder *requestBuilder) buildRCRResult(policy string, resource response.ResourceSpec, rule kyvernov1.ViolatedRule) policyreportv1alpha2.PolicyReportResult {
|
||||
av := builder.fetchAnnotationValues(policy, resource.Namespace)
|
||||
|
||||
result := report.PolicyReportResult{
|
||||
result := policyreportv1alpha2.PolicyReportResult{
|
||||
Policy: policy,
|
||||
Resources: []v1.ObjectReference{
|
||||
{
|
||||
|
@ -181,7 +181,7 @@ func (builder *requestBuilder) buildRCRResult(policy string, resource response.R
|
|||
|
||||
result.Rule = rule.Name
|
||||
result.Message = rule.Message
|
||||
result.Result = report.PolicyResult(rule.Status)
|
||||
result.Result = policyreportv1alpha2.PolicyResult(rule.Status)
|
||||
if result.Result == "fail" && !av.scored {
|
||||
result.Result = "warn"
|
||||
}
|
||||
|
@ -193,7 +193,7 @@ func (builder *requestBuilder) buildRCRResult(policy string, resource response.R
|
|||
}
|
||||
|
||||
func set(obj *unstructured.Unstructured, info Info) {
|
||||
obj.SetAPIVersion(request.SchemeGroupVersion.Group + "/" + request.SchemeGroupVersion.Version)
|
||||
obj.SetAPIVersion(kyvernov1alpha2.SchemeGroupVersion.Group + "/" + kyvernov1alpha2.SchemeGroupVersion.Version)
|
||||
|
||||
if info.Namespace == "" {
|
||||
obj.SetGenerateName("crcr-")
|
||||
|
@ -246,18 +246,18 @@ func setRequestDeletionLabels(req *unstructured.Unstructured, info Info) bool {
|
|||
return false
|
||||
}
|
||||
|
||||
func calculateSummary(results []report.PolicyReportResult) (summary report.PolicyReportSummary) {
|
||||
func calculateSummary(results []policyreportv1alpha2.PolicyReportResult) (summary policyreportv1alpha2.PolicyReportSummary) {
|
||||
for _, res := range results {
|
||||
switch string(res.Result) {
|
||||
case report.StatusPass:
|
||||
case policyreportv1alpha2.StatusPass:
|
||||
summary.Pass++
|
||||
case report.StatusFail:
|
||||
case policyreportv1alpha2.StatusFail:
|
||||
summary.Fail++
|
||||
case report.StatusWarn:
|
||||
case policyreportv1alpha2.StatusWarn:
|
||||
summary.Warn++
|
||||
case report.StatusError:
|
||||
case policyreportv1alpha2.StatusError:
|
||||
summary.Error++
|
||||
case report.StatusSkip:
|
||||
case policyreportv1alpha2.StatusSkip:
|
||||
summary.Skip++
|
||||
}
|
||||
}
|
||||
|
@ -278,10 +278,10 @@ func buildPVInfo(er *response.EngineResponse) Info {
|
|||
return info
|
||||
}
|
||||
|
||||
func buildViolatedRules(er *response.EngineResponse) []kyverno.ViolatedRule {
|
||||
var violatedRules []kyverno.ViolatedRule
|
||||
func buildViolatedRules(er *response.EngineResponse) []kyvernov1.ViolatedRule {
|
||||
var violatedRules []kyvernov1.ViolatedRule
|
||||
for _, rule := range er.PolicyResponse.Rules {
|
||||
vrule := kyverno.ViolatedRule{
|
||||
vrule := kyvernov1.ViolatedRule{
|
||||
Name: rule.Name,
|
||||
Type: string(rule.Type),
|
||||
Message: rule.Message,
|
||||
|
@ -297,15 +297,15 @@ func buildViolatedRules(er *response.EngineResponse) []kyverno.ViolatedRule {
|
|||
func toPolicyResult(status response.RuleStatus) string {
|
||||
switch status {
|
||||
case response.RuleStatusPass:
|
||||
return report.StatusPass
|
||||
return policyreportv1alpha2.StatusPass
|
||||
case response.RuleStatusFail:
|
||||
return report.StatusFail
|
||||
return policyreportv1alpha2.StatusFail
|
||||
case response.RuleStatusError:
|
||||
return report.StatusError
|
||||
return policyreportv1alpha2.StatusError
|
||||
case response.RuleStatusWarn:
|
||||
return report.StatusWarn
|
||||
return policyreportv1alpha2.StatusWarn
|
||||
case response.RuleStatusSkip:
|
||||
return report.StatusSkip
|
||||
return policyreportv1alpha2.StatusSkip
|
||||
}
|
||||
|
||||
return ""
|
||||
|
@ -319,18 +319,18 @@ const (
|
|||
|
||||
type annotationValues struct {
|
||||
category string
|
||||
severity report.PolicySeverity
|
||||
severity policyreportv1alpha2.PolicySeverity
|
||||
scored bool
|
||||
}
|
||||
|
||||
func (av *annotationValues) setSeverityFromString(severity string) {
|
||||
switch severity {
|
||||
case report.SeverityHigh:
|
||||
av.severity = report.SeverityHigh
|
||||
case report.SeverityMedium:
|
||||
av.severity = report.SeverityMedium
|
||||
case report.SeverityLow:
|
||||
av.severity = report.SeverityLow
|
||||
case policyreportv1alpha2.SeverityHigh:
|
||||
av.severity = policyreportv1alpha2.SeverityHigh
|
||||
case policyreportv1alpha2.SeverityMedium:
|
||||
av.severity = policyreportv1alpha2.SeverityMedium
|
||||
case policyreportv1alpha2.SeverityLow:
|
||||
av.severity = policyreportv1alpha2.SeverityLow
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -3,14 +3,14 @@ package policyreport
|
|||
import (
|
||||
"encoding/json"
|
||||
|
||||
typercr "github.com/kyverno/kyverno/api/kyverno/v1alpha2"
|
||||
report "github.com/kyverno/kyverno/api/policyreport/v1alpha2"
|
||||
kyvernov1alpha2 "github.com/kyverno/kyverno/api/kyverno/v1alpha2"
|
||||
policyreportv1alpha2 "github.com/kyverno/kyverno/api/policyreport/v1alpha2"
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
)
|
||||
|
||||
func convertToRCR(request *unstructured.Unstructured) (*typercr.ReportChangeRequest, error) {
|
||||
rcr := typercr.ReportChangeRequest{}
|
||||
func convertToRCR(request *unstructured.Unstructured) (*kyvernov1alpha2.ReportChangeRequest, error) {
|
||||
rcr := kyvernov1alpha2.ReportChangeRequest{}
|
||||
raw, err := request.MarshalJSON()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
@ -18,16 +18,16 @@ func convertToRCR(request *unstructured.Unstructured) (*typercr.ReportChangeRequ
|
|||
|
||||
err = json.Unmarshal(raw, &rcr)
|
||||
rcr.SetGroupVersionKind(schema.GroupVersionKind{
|
||||
Group: typercr.SchemeGroupVersion.Group,
|
||||
Version: typercr.SchemeGroupVersion.Version,
|
||||
Group: kyvernov1alpha2.SchemeGroupVersion.Group,
|
||||
Version: kyvernov1alpha2.SchemeGroupVersion.Version,
|
||||
Kind: "ReportChangeRequest",
|
||||
})
|
||||
|
||||
return &rcr, err
|
||||
}
|
||||
|
||||
func convertToCRCR(request *unstructured.Unstructured) (*typercr.ClusterReportChangeRequest, error) {
|
||||
rcr := typercr.ClusterReportChangeRequest{}
|
||||
func convertToCRCR(request *unstructured.Unstructured) (*kyvernov1alpha2.ClusterReportChangeRequest, error) {
|
||||
rcr := kyvernov1alpha2.ClusterReportChangeRequest{}
|
||||
raw, err := request.MarshalJSON()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
@ -35,16 +35,16 @@ func convertToCRCR(request *unstructured.Unstructured) (*typercr.ClusterReportCh
|
|||
|
||||
err = json.Unmarshal(raw, &rcr)
|
||||
rcr.SetGroupVersionKind(schema.GroupVersionKind{
|
||||
Group: typercr.SchemeGroupVersion.Group,
|
||||
Version: typercr.SchemeGroupVersion.Version,
|
||||
Group: kyvernov1alpha2.SchemeGroupVersion.Group,
|
||||
Version: kyvernov1alpha2.SchemeGroupVersion.Version,
|
||||
Kind: "ClusterReportChangeRequest",
|
||||
})
|
||||
|
||||
return &rcr, err
|
||||
}
|
||||
|
||||
func convertToPolr(request *unstructured.Unstructured) (*report.PolicyReport, error) {
|
||||
polr := report.PolicyReport{}
|
||||
func convertToPolr(request *unstructured.Unstructured) (*policyreportv1alpha2.PolicyReport, error) {
|
||||
polr := policyreportv1alpha2.PolicyReport{}
|
||||
raw, err := request.MarshalJSON()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
@ -52,16 +52,16 @@ func convertToPolr(request *unstructured.Unstructured) (*report.PolicyReport, er
|
|||
|
||||
err = json.Unmarshal(raw, &polr)
|
||||
polr.SetGroupVersionKind(schema.GroupVersionKind{
|
||||
Group: report.SchemeGroupVersion.Group,
|
||||
Version: report.SchemeGroupVersion.Version,
|
||||
Group: policyreportv1alpha2.SchemeGroupVersion.Group,
|
||||
Version: policyreportv1alpha2.SchemeGroupVersion.Version,
|
||||
Kind: "PolicyReport",
|
||||
})
|
||||
|
||||
return &polr, err
|
||||
}
|
||||
|
||||
func convertToCpolr(request *unstructured.Unstructured) (*report.ClusterPolicyReport, error) {
|
||||
cpolr := report.ClusterPolicyReport{}
|
||||
func convertToCpolr(request *unstructured.Unstructured) (*policyreportv1alpha2.ClusterPolicyReport, error) {
|
||||
cpolr := policyreportv1alpha2.ClusterPolicyReport{}
|
||||
raw, err := request.MarshalJSON()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
@ -69,8 +69,8 @@ func convertToCpolr(request *unstructured.Unstructured) (*report.ClusterPolicyRe
|
|||
|
||||
err = json.Unmarshal(raw, &cpolr)
|
||||
cpolr.SetGroupVersionKind(schema.GroupVersionKind{
|
||||
Group: report.SchemeGroupVersion.Group,
|
||||
Version: report.SchemeGroupVersion.Version,
|
||||
Group: policyreportv1alpha2.SchemeGroupVersion.Group,
|
||||
Version: policyreportv1alpha2.SchemeGroupVersion.Version,
|
||||
Kind: "ClusterPolicyReport",
|
||||
})
|
||||
|
||||
|
|
|
@ -7,8 +7,8 @@ import (
|
|||
"strings"
|
||||
|
||||
"github.com/cornelk/hashmap"
|
||||
changerequest "github.com/kyverno/kyverno/api/kyverno/v1alpha2"
|
||||
report "github.com/kyverno/kyverno/api/policyreport/v1alpha2"
|
||||
kyvernov1alpha2 "github.com/kyverno/kyverno/api/kyverno/v1alpha2"
|
||||
policyreportv1alpha2 "github.com/kyverno/kyverno/api/policyreport/v1alpha2"
|
||||
kyvernoclient "github.com/kyverno/kyverno/pkg/client/clientset/versioned"
|
||||
changerequestlister "github.com/kyverno/kyverno/pkg/client/listers/kyverno/v1alpha2"
|
||||
policyreportlister "github.com/kyverno/kyverno/pkg/client/listers/policyreport/v1alpha2"
|
||||
|
@ -57,14 +57,14 @@ func buildLabelForDeletedResource(labels, annotations map[string]string) *delete
|
|||
}
|
||||
|
||||
func getDeletedResources(aggregatedRequests interface{}) (resources []deletedResource) {
|
||||
if requests, ok := aggregatedRequests.([]*changerequest.ClusterReportChangeRequest); ok {
|
||||
if requests, ok := aggregatedRequests.([]*kyvernov1alpha2.ClusterReportChangeRequest); ok {
|
||||
for _, request := range requests {
|
||||
dr := buildLabelForDeletedResource(request.GetLabels(), request.GetAnnotations())
|
||||
if dr != nil {
|
||||
resources = append(resources, *dr)
|
||||
}
|
||||
}
|
||||
} else if requests, ok := aggregatedRequests.([]*changerequest.ReportChangeRequest); ok {
|
||||
} else if requests, ok := aggregatedRequests.([]*kyvernov1alpha2.ReportChangeRequest); ok {
|
||||
for _, request := range requests {
|
||||
dr := buildLabelForDeletedResource(request.GetLabels(), request.GetAnnotations())
|
||||
if dr != nil {
|
||||
|
@ -101,7 +101,7 @@ func updateResults(oldReport, newReport map[string]interface{}, aggregatedReques
|
|||
return nil, hasDuplicate, err
|
||||
}
|
||||
|
||||
summaryResults := []report.PolicyReportResult{}
|
||||
summaryResults := []policyreportv1alpha2.PolicyReportResult{}
|
||||
if err := mapToStruct(results, &summaryResults); err != nil {
|
||||
return nil, hasDuplicate, err
|
||||
}
|
||||
|
@ -178,20 +178,20 @@ func generateHashKey(result map[string]interface{}, dr deletedResource) (string,
|
|||
resource["name"]), true
|
||||
}
|
||||
|
||||
func updateSummary(results []report.PolicyReportResult) report.PolicyReportSummary {
|
||||
summary := report.PolicyReportSummary{}
|
||||
func updateSummary(results []policyreportv1alpha2.PolicyReportResult) policyreportv1alpha2.PolicyReportSummary {
|
||||
summary := policyreportv1alpha2.PolicyReportSummary{}
|
||||
|
||||
for _, result := range results {
|
||||
switch result.Result {
|
||||
case report.StatusPass:
|
||||
case policyreportv1alpha2.StatusPass:
|
||||
summary.Pass++
|
||||
case report.StatusFail:
|
||||
case policyreportv1alpha2.StatusFail:
|
||||
summary.Fail++
|
||||
case report.StatusWarn:
|
||||
case policyreportv1alpha2.StatusWarn:
|
||||
summary.Warn++
|
||||
case report.StatusError:
|
||||
case policyreportv1alpha2.StatusError:
|
||||
summary.Error++
|
||||
case report.StatusSkip:
|
||||
case policyreportv1alpha2.StatusSkip:
|
||||
summary.Skip++
|
||||
}
|
||||
}
|
||||
|
|
|
@ -8,8 +8,8 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
changerequest "github.com/kyverno/kyverno/api/kyverno/v1alpha2"
|
||||
report "github.com/kyverno/kyverno/api/policyreport/v1alpha2"
|
||||
kyvernov1alpha2 "github.com/kyverno/kyverno/api/kyverno/v1alpha2"
|
||||
policyreportv1alpha2 "github.com/kyverno/kyverno/api/policyreport/v1alpha2"
|
||||
kyvernoclient "github.com/kyverno/kyverno/pkg/client/clientset/versioned"
|
||||
requestinformer "github.com/kyverno/kyverno/pkg/client/informers/externalversions/kyverno/v1alpha2"
|
||||
policyreportinformer "github.com/kyverno/kyverno/pkg/client/informers/externalversions/policyreport/v1alpha2"
|
||||
|
@ -112,7 +112,7 @@ const deletedPolicyKey string = "deletedpolicy"
|
|||
// - "" for cluster wide resource
|
||||
// - "deletedpolicy/policyName/ruleName(optional)" for a deleted policy or rule
|
||||
func generateCacheKey(changeRequest interface{}) string {
|
||||
if request, ok := changeRequest.(*changerequest.ReportChangeRequest); ok {
|
||||
if request, ok := changeRequest.(*kyvernov1alpha2.ReportChangeRequest); ok {
|
||||
label := request.GetLabels()
|
||||
policy := label[deletedLabelPolicy]
|
||||
rule := label[deletedLabelRule]
|
||||
|
@ -125,7 +125,7 @@ func generateCacheKey(changeRequest interface{}) string {
|
|||
ns = "default"
|
||||
}
|
||||
return ns
|
||||
} else if request, ok := changeRequest.(*changerequest.ClusterReportChangeRequest); ok {
|
||||
} else if request, ok := changeRequest.(*kyvernov1alpha2.ClusterReportChangeRequest); ok {
|
||||
label := request.GetLabels()
|
||||
policy := label[deletedLabelPolicy]
|
||||
rule := label[deletedLabelRule]
|
||||
|
@ -143,9 +143,9 @@ func generateCacheKey(changeRequest interface{}) string {
|
|||
func managedRequest(changeRequest interface{}) bool {
|
||||
labels := make(map[string]string)
|
||||
|
||||
if request, ok := changeRequest.(*changerequest.ReportChangeRequest); ok {
|
||||
if request, ok := changeRequest.(*kyvernov1alpha2.ReportChangeRequest); ok {
|
||||
labels = request.GetLabels()
|
||||
} else if request, ok := changeRequest.(*changerequest.ClusterReportChangeRequest); ok {
|
||||
} else if request, ok := changeRequest.(*kyvernov1alpha2.ClusterReportChangeRequest); ok {
|
||||
labels = request.GetLabels()
|
||||
}
|
||||
|
||||
|
@ -158,7 +158,7 @@ func managedRequest(changeRequest interface{}) bool {
|
|||
|
||||
func (g *ReportGenerator) addReportChangeRequest(obj interface{}) {
|
||||
if !managedRequest(obj) {
|
||||
g.cleanupReportRequests([]*changerequest.ReportChangeRequest{obj.(*changerequest.ReportChangeRequest)})
|
||||
g.cleanupReportRequests([]*kyvernov1alpha2.ReportChangeRequest{obj.(*kyvernov1alpha2.ReportChangeRequest)})
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -167,14 +167,14 @@ func (g *ReportGenerator) addReportChangeRequest(obj interface{}) {
|
|||
}
|
||||
|
||||
func (g *ReportGenerator) updateReportChangeRequest(old interface{}, cur interface{}) {
|
||||
oldReq := old.(*changerequest.ReportChangeRequest)
|
||||
curReq := cur.(*changerequest.ReportChangeRequest)
|
||||
oldReq := old.(*kyvernov1alpha2.ReportChangeRequest)
|
||||
curReq := cur.(*kyvernov1alpha2.ReportChangeRequest)
|
||||
if reflect.DeepEqual(oldReq.Results, curReq.Results) {
|
||||
return
|
||||
}
|
||||
|
||||
if !managedRequest(curReq) {
|
||||
g.cleanupReportRequests([]*changerequest.ReportChangeRequest{curReq})
|
||||
g.cleanupReportRequests([]*kyvernov1alpha2.ReportChangeRequest{curReq})
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -184,7 +184,7 @@ func (g *ReportGenerator) updateReportChangeRequest(old interface{}, cur interfa
|
|||
|
||||
func (g *ReportGenerator) addClusterReportChangeRequest(obj interface{}) {
|
||||
if !managedRequest(obj) {
|
||||
g.cleanupReportRequests([]*changerequest.ClusterReportChangeRequest{obj.(*changerequest.ClusterReportChangeRequest)})
|
||||
g.cleanupReportRequests([]*kyvernov1alpha2.ClusterReportChangeRequest{obj.(*kyvernov1alpha2.ClusterReportChangeRequest)})
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -193,8 +193,8 @@ func (g *ReportGenerator) addClusterReportChangeRequest(obj interface{}) {
|
|||
}
|
||||
|
||||
func (g *ReportGenerator) updateClusterReportChangeRequest(old interface{}, cur interface{}) {
|
||||
oldReq := old.(*changerequest.ClusterReportChangeRequest)
|
||||
curReq := cur.(*changerequest.ClusterReportChangeRequest)
|
||||
oldReq := old.(*kyvernov1alpha2.ClusterReportChangeRequest)
|
||||
curReq := cur.(*kyvernov1alpha2.ClusterReportChangeRequest)
|
||||
|
||||
if reflect.DeepEqual(oldReq.Results, curReq.Results) {
|
||||
return
|
||||
|
@ -208,7 +208,7 @@ func (g *ReportGenerator) updateClusterReportChangeRequest(old interface{}, cur
|
|||
}
|
||||
|
||||
func (g *ReportGenerator) deletePolicyReport(obj interface{}) {
|
||||
report, ok := kubeutils.GetObjectWithTombstone(obj).(*report.PolicyReport)
|
||||
report, ok := kubeutils.GetObjectWithTombstone(obj).(*policyreportv1alpha2.PolicyReport)
|
||||
if ok {
|
||||
g.log.V(2).Info("PolicyReport deleted", "name", report.GetName())
|
||||
} else {
|
||||
|
@ -443,7 +443,7 @@ func (g *ReportGenerator) removeFromClusterPolicyReport(policyName, ruleName str
|
|||
}
|
||||
|
||||
for _, cpolr := range cpolrs {
|
||||
newRes := []report.PolicyReportResult{}
|
||||
newRes := []policyreportv1alpha2.PolicyReportResult{}
|
||||
for _, result := range cpolr.Results {
|
||||
if ruleName != "" && result.Rule == ruleName && result.Policy == policyName {
|
||||
continue
|
||||
|
@ -454,7 +454,7 @@ func (g *ReportGenerator) removeFromClusterPolicyReport(policyName, ruleName str
|
|||
}
|
||||
cpolr.Results = newRes
|
||||
cpolr.Summary = calculateSummary(newRes)
|
||||
gv := report.SchemeGroupVersion
|
||||
gv := policyreportv1alpha2.SchemeGroupVersion
|
||||
cpolr.SetGroupVersionKind(schema.GroupVersionKind{Group: gv.Group, Version: gv.Version, Kind: "ClusterPolicyReport"})
|
||||
if _, err := g.pclient.Wgpolicyk8sV1alpha2().ClusterPolicyReports().Update(context.TODO(), cpolr, metav1.UpdateOptions{}); err != nil {
|
||||
return fmt.Errorf("failed to update clusterPolicyReport %s %v", cpolr.Name, err)
|
||||
|
@ -474,7 +474,7 @@ func (g *ReportGenerator) removeFromPolicyReport(policyName, ruleName string) er
|
|||
g.log.Error(err, "failed to build labelSelector")
|
||||
}
|
||||
|
||||
policyReports := []*report.PolicyReport{}
|
||||
policyReports := []*policyreportv1alpha2.PolicyReport{}
|
||||
for _, ns := range namespaces.Items {
|
||||
reports, err := g.reportLister.PolicyReports(ns.GetName()).List(selector)
|
||||
if err != nil {
|
||||
|
@ -484,7 +484,7 @@ func (g *ReportGenerator) removeFromPolicyReport(policyName, ruleName string) er
|
|||
}
|
||||
|
||||
for _, r := range policyReports {
|
||||
newRes := []report.PolicyReportResult{}
|
||||
newRes := []policyreportv1alpha2.PolicyReportResult{}
|
||||
for _, result := range r.Results {
|
||||
if ruleName != "" && result.Rule == ruleName && result.Policy == policyName {
|
||||
continue
|
||||
|
@ -496,7 +496,7 @@ func (g *ReportGenerator) removeFromPolicyReport(policyName, ruleName string) er
|
|||
|
||||
r.Results = newRes
|
||||
r.Summary = calculateSummary(newRes)
|
||||
gv := report.SchemeGroupVersion
|
||||
gv := policyreportv1alpha2.SchemeGroupVersion
|
||||
gvk := schema.GroupVersionKind{Group: gv.Group, Version: gv.Version, Kind: "PolicyReport"}
|
||||
r.SetGroupVersionKind(gvk)
|
||||
if _, err := g.pclient.Wgpolicyk8sV1alpha2().PolicyReports(r.GetNamespace()).Update(context.TODO(), r, metav1.UpdateOptions{}); err != nil {
|
||||
|
@ -555,10 +555,10 @@ func (g *ReportGenerator) aggregateReports(namespace string) (
|
|||
}
|
||||
|
||||
func mergeRequests(ns, kyvernoNs *v1.Namespace, requestsGeneral interface{}) (*unstructured.Unstructured, interface{}, error) {
|
||||
results := []report.PolicyReportResult{}
|
||||
results := []policyreportv1alpha2.PolicyReportResult{}
|
||||
|
||||
if requests, ok := requestsGeneral.([]*changerequest.ClusterReportChangeRequest); ok {
|
||||
aggregatedRequests := []*changerequest.ClusterReportChangeRequest{}
|
||||
if requests, ok := requestsGeneral.([]*kyvernov1alpha2.ClusterReportChangeRequest); ok {
|
||||
aggregatedRequests := []*kyvernov1alpha2.ClusterReportChangeRequest{}
|
||||
for _, request := range requests {
|
||||
if request.GetDeletionTimestamp() != nil {
|
||||
continue
|
||||
|
@ -569,7 +569,7 @@ func mergeRequests(ns, kyvernoNs *v1.Namespace, requestsGeneral interface{}) (*u
|
|||
aggregatedRequests = append(aggregatedRequests, request)
|
||||
}
|
||||
|
||||
report := &report.ClusterPolicyReport{
|
||||
report := &policyreportv1alpha2.ClusterPolicyReport{
|
||||
Results: results,
|
||||
Summary: calculateSummary(results),
|
||||
}
|
||||
|
@ -584,8 +584,8 @@ func mergeRequests(ns, kyvernoNs *v1.Namespace, requestsGeneral interface{}) (*u
|
|||
return req, aggregatedRequests, nil
|
||||
}
|
||||
|
||||
if requests, ok := requestsGeneral.([]*changerequest.ReportChangeRequest); ok {
|
||||
aggregatedRequests := []*changerequest.ReportChangeRequest{}
|
||||
if requests, ok := requestsGeneral.([]*kyvernov1alpha2.ReportChangeRequest); ok {
|
||||
aggregatedRequests := []*kyvernov1alpha2.ReportChangeRequest{}
|
||||
for _, request := range requests {
|
||||
if request.GetDeletionTimestamp() != nil {
|
||||
continue
|
||||
|
@ -596,7 +596,7 @@ func mergeRequests(ns, kyvernoNs *v1.Namespace, requestsGeneral interface{}) (*u
|
|||
aggregatedRequests = append(aggregatedRequests, request)
|
||||
}
|
||||
|
||||
report := &report.PolicyReport{
|
||||
report := &policyreportv1alpha2.PolicyReport{
|
||||
Results: results,
|
||||
Summary: calculateSummary(results),
|
||||
}
|
||||
|
@ -616,7 +616,7 @@ func mergeRequests(ns, kyvernoNs *v1.Namespace, requestsGeneral interface{}) (*u
|
|||
}
|
||||
|
||||
func setReport(reportUnstructured *unstructured.Unstructured, ns, kyvernoNs *v1.Namespace) {
|
||||
reportUnstructured.SetAPIVersion(report.SchemeGroupVersion.String())
|
||||
reportUnstructured.SetAPIVersion(policyreportv1alpha2.SchemeGroupVersion.String())
|
||||
reportUnstructured.SetLabels(LabelSelector.MatchLabels)
|
||||
|
||||
if kyvernoNs != nil {
|
||||
|
@ -653,7 +653,7 @@ func (g *ReportGenerator) updateReport(old interface{}, new *unstructured.Unstru
|
|||
|
||||
oldUnstructured := make(map[string]interface{})
|
||||
|
||||
if oldTyped, ok := old.(*report.ClusterPolicyReport); ok {
|
||||
if oldTyped, ok := old.(*policyreportv1alpha2.ClusterPolicyReport); ok {
|
||||
if oldTyped.GetDeletionTimestamp() != nil {
|
||||
return g.pclient.Wgpolicyk8sV1alpha2().ClusterPolicyReports().Delete(context.TODO(), oldTyped.Name, metav1.DeleteOptions{})
|
||||
}
|
||||
|
@ -663,7 +663,7 @@ func (g *ReportGenerator) updateReport(old interface{}, new *unstructured.Unstru
|
|||
}
|
||||
new.SetUID(oldTyped.GetUID())
|
||||
new.SetResourceVersion(oldTyped.GetResourceVersion())
|
||||
} else if oldTyped, ok := old.(*report.PolicyReport); ok {
|
||||
} else if oldTyped, ok := old.(*policyreportv1alpha2.PolicyReport); ok {
|
||||
if oldTyped.GetDeletionTimestamp() != nil {
|
||||
return g.pclient.Wgpolicyk8sV1alpha2().PolicyReports(oldTyped.Namespace).Delete(context.TODO(), oldTyped.Name, metav1.DeleteOptions{})
|
||||
}
|
||||
|
@ -714,7 +714,7 @@ func (g *ReportGenerator) updateReport(old interface{}, new *unstructured.Unstru
|
|||
|
||||
func (g *ReportGenerator) cleanupReportRequests(requestsGeneral interface{}) {
|
||||
defer g.log.V(5).Info("successfully cleaned up report requests")
|
||||
if requests, ok := requestsGeneral.([]*changerequest.ReportChangeRequest); ok {
|
||||
if requests, ok := requestsGeneral.([]*kyvernov1alpha2.ReportChangeRequest); ok {
|
||||
for _, request := range requests {
|
||||
if err := g.pclient.KyvernoV1alpha2().ReportChangeRequests(config.KyvernoNamespace()).Delete(context.TODO(), request.Name, metav1.DeleteOptions{}); err != nil {
|
||||
if !apierrors.IsNotFound(err) {
|
||||
|
@ -724,7 +724,7 @@ func (g *ReportGenerator) cleanupReportRequests(requestsGeneral interface{}) {
|
|||
}
|
||||
}
|
||||
|
||||
if requests, ok := requestsGeneral.([]*changerequest.ClusterReportChangeRequest); ok {
|
||||
if requests, ok := requestsGeneral.([]*kyvernov1alpha2.ClusterReportChangeRequest); ok {
|
||||
for _, request := range requests {
|
||||
if err := g.pclient.KyvernoV1alpha2().ClusterReportChangeRequests().Delete(context.TODO(), request.Name, metav1.DeleteOptions{}); err != nil {
|
||||
if !apierrors.IsNotFound(err) {
|
||||
|
|
|
@ -9,7 +9,7 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
policyreportclient "github.com/kyverno/kyverno/pkg/client/clientset/versioned"
|
||||
kyvernoinformer "github.com/kyverno/kyverno/pkg/client/informers/externalversions/kyverno/v1"
|
||||
requestinformer "github.com/kyverno/kyverno/pkg/client/informers/externalversions/kyverno/v1alpha2"
|
||||
|
@ -115,7 +115,7 @@ type Info struct {
|
|||
|
||||
type EngineResponseResult struct {
|
||||
Resource response.ResourceSpec
|
||||
Rules []kyverno.ViolatedRule
|
||||
Rules []kyvernov1.ViolatedRule
|
||||
}
|
||||
|
||||
func (i Info) ToKey() string {
|
||||
|
|
|
@ -11,7 +11,7 @@ import (
|
|||
"runtime"
|
||||
"testing"
|
||||
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
client "github.com/kyverno/kyverno/pkg/dclient"
|
||||
"github.com/kyverno/kyverno/pkg/engine"
|
||||
"github.com/kyverno/kyverno/pkg/engine/context"
|
||||
|
@ -62,7 +62,7 @@ type Validation struct {
|
|||
|
||||
type Generation struct {
|
||||
// generated resources
|
||||
GeneratedResources []kyverno.ResourceSpec `yaml:"generatedResources"`
|
||||
GeneratedResources []kyvernov1.ResourceSpec `yaml:"generatedResources"`
|
||||
// expected response from the policy engine
|
||||
PolicyResponse response.PolicyResponse `yaml:"policyresponse"`
|
||||
}
|
||||
|
@ -208,7 +208,7 @@ func createNamespace(client client.Interface, ns *unstructured.Unstructured) err
|
|||
return err
|
||||
}
|
||||
|
||||
func validateGeneratedResources(t *testing.T, client client.Interface, policy kyverno.ClusterPolicy, namespace string, expected []kyverno.ResourceSpec) {
|
||||
func validateGeneratedResources(t *testing.T, client client.Interface, policy kyvernov1.ClusterPolicy, namespace string, expected []kyvernov1.ResourceSpec) {
|
||||
t.Helper()
|
||||
t.Log("--validate if resources are generated---")
|
||||
// list of expected generated resources
|
||||
|
@ -442,17 +442,17 @@ func loadObjects(t *testing.T, path string) []k8sRuntime.Object {
|
|||
return resources
|
||||
}
|
||||
|
||||
func loadPolicy(t *testing.T, path string) *kyverno.ClusterPolicy {
|
||||
func loadPolicy(t *testing.T, path string) *kyvernov1.ClusterPolicy {
|
||||
t.Helper()
|
||||
t.Logf("loading policy from %s", path)
|
||||
data, err := loadFile(t, path)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var policies []*kyverno.ClusterPolicy
|
||||
var policies []*kyvernov1.ClusterPolicy
|
||||
pBytes := bytes.Split(data, []byte("---"))
|
||||
for _, p := range pBytes {
|
||||
policy := kyverno.ClusterPolicy{}
|
||||
policy := kyvernov1.ClusterPolicy{}
|
||||
pBytes, err := apiyaml.ToJSON(p)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
|
|
|
@ -4,20 +4,20 @@ import (
|
|||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
admissionv1 "k8s.io/api/admission/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
)
|
||||
|
||||
func UnmarshalPolicy(kind string, raw []byte) (kyverno.PolicyInterface, error) {
|
||||
func UnmarshalPolicy(kind string, raw []byte) (kyvernov1.PolicyInterface, error) {
|
||||
if kind == "ClusterPolicy" {
|
||||
var policy *kyverno.ClusterPolicy
|
||||
var policy *kyvernov1.ClusterPolicy
|
||||
if err := json.Unmarshal(raw, &policy); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return policy, nil
|
||||
} else if kind == "Policy" {
|
||||
var policy *kyverno.Policy
|
||||
var policy *kyvernov1.Policy
|
||||
if err := json.Unmarshal(raw, &policy); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
@ -26,11 +26,11 @@ func UnmarshalPolicy(kind string, raw []byte) (kyverno.PolicyInterface, error) {
|
|||
return nil, fmt.Errorf("admission request does not contain a policy")
|
||||
}
|
||||
|
||||
func GetPolicy(request *admissionv1.AdmissionRequest) (kyverno.PolicyInterface, error) {
|
||||
func GetPolicy(request *admissionv1.AdmissionRequest) (kyvernov1.PolicyInterface, error) {
|
||||
return UnmarshalPolicy(request.Kind.Kind, request.Object.Raw)
|
||||
}
|
||||
|
||||
func GetPolicies(request *admissionv1.AdmissionRequest) (kyverno.PolicyInterface, kyverno.PolicyInterface, error) {
|
||||
func GetPolicies(request *admissionv1.AdmissionRequest) (kyvernov1.PolicyInterface, kyvernov1.PolicyInterface, error) {
|
||||
policy, err := UnmarshalPolicy(request.Kind.Kind, request.Object.Raw)
|
||||
if err != nil {
|
||||
return policy, nil, err
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
package engine
|
||||
|
||||
import (
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/engine/response"
|
||||
)
|
||||
|
||||
|
@ -17,5 +17,5 @@ func IsResponseSuccessful(engineReponses []*response.EngineResponse) bool {
|
|||
|
||||
// CheckEngineResponse return true if engine response is not successful and validation failure action is set to 'enforce'
|
||||
func CheckEngineResponse(er *response.EngineResponse) bool {
|
||||
return !er.IsSuccessful() && er.GetValidationFailureAction() == kyverno.Enforce
|
||||
return !er.IsSuccessful() && er.GetValidationFailureAction() == kyvernov1.Enforce
|
||||
}
|
||||
|
|
|
@ -4,14 +4,14 @@ import (
|
|||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
yamlutils "github.com/kyverno/kyverno/pkg/utils/yaml"
|
||||
"k8s.io/apimachinery/pkg/util/yaml"
|
||||
"sigs.k8s.io/controller-runtime/pkg/log"
|
||||
)
|
||||
|
||||
// GetPolicy - extracts policies from YAML bytes
|
||||
func GetPolicy(bytes []byte) (policies []kyverno.PolicyInterface, err error) {
|
||||
func GetPolicy(bytes []byte) (policies []kyvernov1.PolicyInterface, err error) {
|
||||
documents, err := yamlutils.SplitDocuments(bytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
@ -21,7 +21,7 @@ func GetPolicy(bytes []byte) (policies []kyverno.PolicyInterface, err error) {
|
|||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to convert to JSON: %v", err)
|
||||
}
|
||||
policy := &kyverno.ClusterPolicy{}
|
||||
policy := &kyvernov1.ClusterPolicy{}
|
||||
if err := json.Unmarshal(policyBytes, policy); err != nil {
|
||||
return nil, fmt.Errorf("failed to decode policy: %v", err)
|
||||
}
|
||||
|
|
|
@ -8,7 +8,7 @@ import (
|
|||
|
||||
"github.com/go-logr/logr"
|
||||
wildcard "github.com/kyverno/go-wildcard"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
client "github.com/kyverno/kyverno/pkg/dclient"
|
||||
engineutils "github.com/kyverno/kyverno/pkg/engine/utils"
|
||||
"github.com/pkg/errors"
|
||||
|
@ -308,12 +308,12 @@ func ApiextensionsJsonToKyvernoConditions(original apiextensions.JSON) (interfac
|
|||
return nil, fmt.Errorf("error occurred while marshalling %s: %+v", path, err)
|
||||
}
|
||||
|
||||
var kyvernoOldConditions []kyverno.Condition
|
||||
var kyvernoOldConditions []kyvernov1.Condition
|
||||
if err = json.Unmarshal(jsonByte, &kyvernoOldConditions); err == nil {
|
||||
var validConditionOperator bool
|
||||
|
||||
for _, jsonOp := range kyvernoOldConditions {
|
||||
for _, validOp := range kyverno.ConditionOperators {
|
||||
for _, validOp := range kyvernov1.ConditionOperators {
|
||||
if jsonOp.Operator == validOp {
|
||||
validConditionOperator = true
|
||||
}
|
||||
|
@ -327,7 +327,7 @@ func ApiextensionsJsonToKyvernoConditions(original apiextensions.JSON) (interfac
|
|||
return kyvernoOldConditions, nil
|
||||
}
|
||||
|
||||
var kyvernoAnyAllConditions kyverno.AnyAllConditions
|
||||
var kyvernoAnyAllConditions kyvernov1.AnyAllConditions
|
||||
if err = json.Unmarshal(jsonByte, &kyvernoAnyAllConditions); err == nil {
|
||||
// checking if unknown fields exist or not
|
||||
err = unknownFieldChecker(jsonByte, path)
|
||||
|
|
|
@ -9,7 +9,7 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/autogen"
|
||||
kyvernoclient "github.com/kyverno/kyverno/pkg/client/clientset/versioned"
|
||||
kyvernoinformer "github.com/kyverno/kyverno/pkg/client/informers/externalversions/kyverno/v1"
|
||||
|
@ -131,7 +131,7 @@ func (m *webhookConfigManager) handleErr(err error, key interface{}) {
|
|||
}
|
||||
|
||||
func (m *webhookConfigManager) addClusterPolicy(obj interface{}) {
|
||||
p := obj.(*kyverno.ClusterPolicy)
|
||||
p := obj.(*kyvernov1.ClusterPolicy)
|
||||
if hasWildcard(&p.Spec) {
|
||||
atomic.AddInt64(&m.wildcardPolicy, int64(1))
|
||||
}
|
||||
|
@ -139,7 +139,7 @@ func (m *webhookConfigManager) addClusterPolicy(obj interface{}) {
|
|||
}
|
||||
|
||||
func (m *webhookConfigManager) updateClusterPolicy(old, cur interface{}) {
|
||||
oldP, curP := old.(*kyverno.ClusterPolicy), cur.(*kyverno.ClusterPolicy)
|
||||
oldP, curP := old.(*kyvernov1.ClusterPolicy), cur.(*kyvernov1.ClusterPolicy)
|
||||
if reflect.DeepEqual(oldP.Spec, curP.Spec) {
|
||||
return
|
||||
}
|
||||
|
@ -152,14 +152,14 @@ func (m *webhookConfigManager) updateClusterPolicy(old, cur interface{}) {
|
|||
}
|
||||
|
||||
func (m *webhookConfigManager) deleteClusterPolicy(obj interface{}) {
|
||||
p, ok := obj.(*kyverno.ClusterPolicy)
|
||||
p, ok := obj.(*kyvernov1.ClusterPolicy)
|
||||
if !ok {
|
||||
tombstone, ok := obj.(cache.DeletedFinalStateUnknown)
|
||||
if !ok {
|
||||
utilruntime.HandleError(fmt.Errorf("error decoding object, invalid type"))
|
||||
return
|
||||
}
|
||||
p, ok = tombstone.Obj.(*kyverno.ClusterPolicy)
|
||||
p, ok = tombstone.Obj.(*kyvernov1.ClusterPolicy)
|
||||
if !ok {
|
||||
utilruntime.HandleError(fmt.Errorf("error decoding object tombstone, invalid type"))
|
||||
return
|
||||
|
@ -173,7 +173,7 @@ func (m *webhookConfigManager) deleteClusterPolicy(obj interface{}) {
|
|||
}
|
||||
|
||||
func (m *webhookConfigManager) addPolicy(obj interface{}) {
|
||||
p := obj.(*kyverno.Policy)
|
||||
p := obj.(*kyvernov1.Policy)
|
||||
if hasWildcard(&p.Spec) {
|
||||
atomic.AddInt64(&m.wildcardPolicy, int64(1))
|
||||
}
|
||||
|
@ -181,7 +181,7 @@ func (m *webhookConfigManager) addPolicy(obj interface{}) {
|
|||
}
|
||||
|
||||
func (m *webhookConfigManager) updatePolicy(old, cur interface{}) {
|
||||
oldP, curP := old.(*kyverno.Policy), cur.(*kyverno.Policy)
|
||||
oldP, curP := old.(*kyvernov1.Policy), cur.(*kyvernov1.Policy)
|
||||
if reflect.DeepEqual(oldP.Spec, curP.Spec) {
|
||||
return
|
||||
}
|
||||
|
@ -194,14 +194,14 @@ func (m *webhookConfigManager) updatePolicy(old, cur interface{}) {
|
|||
}
|
||||
|
||||
func (m *webhookConfigManager) deletePolicy(obj interface{}) {
|
||||
p, ok := obj.(*kyverno.Policy)
|
||||
p, ok := obj.(*kyvernov1.Policy)
|
||||
if !ok {
|
||||
tombstone, ok := obj.(cache.DeletedFinalStateUnknown)
|
||||
if !ok {
|
||||
utilruntime.HandleError(fmt.Errorf("error decoding object, invalid type"))
|
||||
return
|
||||
}
|
||||
p, ok = tombstone.Obj.(*kyverno.Policy)
|
||||
p, ok = tombstone.Obj.(*kyvernov1.Policy)
|
||||
if !ok {
|
||||
utilruntime.HandleError(fmt.Errorf("error decoding object tombstone, invalid type"))
|
||||
return
|
||||
|
@ -372,7 +372,7 @@ func (m *webhookConfigManager) reconcileWebhook(namespace, name string) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func (m *webhookConfigManager) getPolicy(namespace, name string) (kyverno.PolicyInterface, error) {
|
||||
func (m *webhookConfigManager) getPolicy(namespace, name string) (kyvernov1.PolicyInterface, error) {
|
||||
if namespace == "" {
|
||||
return m.pLister.Get(name)
|
||||
} else {
|
||||
|
@ -380,8 +380,8 @@ func (m *webhookConfigManager) getPolicy(namespace, name string) (kyverno.Policy
|
|||
}
|
||||
}
|
||||
|
||||
func (m *webhookConfigManager) listAllPolicies() ([]kyverno.PolicyInterface, error) {
|
||||
policies := []kyverno.PolicyInterface{}
|
||||
func (m *webhookConfigManager) listAllPolicies() ([]kyvernov1.PolicyInterface, error) {
|
||||
policies := []kyvernov1.PolicyInterface{}
|
||||
polList, err := m.npLister.Policies(metav1.NamespaceAll).List(labels.Everything())
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(err, "failed to list Policy")
|
||||
|
@ -400,10 +400,10 @@ func (m *webhookConfigManager) listAllPolicies() ([]kyverno.PolicyInterface, err
|
|||
}
|
||||
|
||||
func (m *webhookConfigManager) buildWebhooks(namespace string) (res []*webhook, err error) {
|
||||
mutateIgnore := newWebhook(kindMutating, DefaultWebhookTimeout, kyverno.Ignore)
|
||||
mutateFail := newWebhook(kindMutating, DefaultWebhookTimeout, kyverno.Fail)
|
||||
validateIgnore := newWebhook(kindValidating, DefaultWebhookTimeout, kyverno.Ignore)
|
||||
validateFail := newWebhook(kindValidating, DefaultWebhookTimeout, kyverno.Fail)
|
||||
mutateIgnore := newWebhook(kindMutating, DefaultWebhookTimeout, kyvernov1.Ignore)
|
||||
mutateFail := newWebhook(kindMutating, DefaultWebhookTimeout, kyvernov1.Fail)
|
||||
validateIgnore := newWebhook(kindValidating, DefaultWebhookTimeout, kyvernov1.Ignore)
|
||||
validateFail := newWebhook(kindValidating, DefaultWebhookTimeout, kyvernov1.Fail)
|
||||
|
||||
if atomic.LoadInt64(&m.wildcardPolicy) != 0 {
|
||||
for _, w := range []*webhook{mutateIgnore, mutateFail, validateIgnore, validateFail} {
|
||||
|
@ -422,7 +422,7 @@ func (m *webhookConfigManager) buildWebhooks(namespace string) (res []*webhook,
|
|||
for _, p := range policies {
|
||||
spec := p.GetSpec()
|
||||
if spec.HasValidate() || spec.HasGenerate() || spec.HasMutate() || spec.HasImagesValidationChecks() {
|
||||
if spec.GetFailurePolicy() == kyverno.Ignore {
|
||||
if spec.GetFailurePolicy() == kyvernov1.Ignore {
|
||||
m.mergeWebhook(validateIgnore, p, true)
|
||||
} else {
|
||||
m.mergeWebhook(validateFail, p, true)
|
||||
|
@ -430,7 +430,7 @@ func (m *webhookConfigManager) buildWebhooks(namespace string) (res []*webhook,
|
|||
}
|
||||
|
||||
if spec.HasMutate() || spec.HasVerifyImages() {
|
||||
if spec.GetFailurePolicy() == kyverno.Ignore {
|
||||
if spec.GetFailurePolicy() == kyvernov1.Ignore {
|
||||
m.mergeWebhook(mutateIgnore, p, false)
|
||||
} else {
|
||||
m.mergeWebhook(mutateFail, p, false)
|
||||
|
@ -523,7 +523,7 @@ func (m *webhookConfigManager) updateValidatingWebhookConfiguration(webhookName
|
|||
}
|
||||
|
||||
func (m *webhookConfigManager) updateStatus(namespace, name string, ready bool) error {
|
||||
update := func(meta *metav1.ObjectMeta, p kyverno.PolicyInterface, status *kyverno.PolicyStatus) bool {
|
||||
update := func(meta *metav1.ObjectMeta, p kyvernov1.PolicyInterface, status *kyvernov1.PolicyStatus) bool {
|
||||
copy := status.DeepCopy()
|
||||
status.SetReady(ready)
|
||||
// TODO: finalize status content
|
||||
|
@ -566,7 +566,7 @@ func (m *webhookConfigManager) updateStatus(namespace, name string, ready bool)
|
|||
type webhook struct {
|
||||
kind string
|
||||
maxWebhookTimeout int32
|
||||
failurePolicy kyverno.FailurePolicyType
|
||||
failurePolicy kyvernov1.FailurePolicyType
|
||||
groups sets.String
|
||||
versions sets.String
|
||||
resources sets.String
|
||||
|
@ -588,7 +588,7 @@ func (wh *webhook) isEmpty() bool {
|
|||
}
|
||||
|
||||
// mergeWebhook merges the matching kinds of the policy to webhook.rule
|
||||
func (m *webhookConfigManager) mergeWebhook(dst *webhook, policy kyverno.PolicyInterface, updateValidate bool) {
|
||||
func (m *webhookConfigManager) mergeWebhook(dst *webhook, policy kyvernov1.PolicyInterface, updateValidate bool) {
|
||||
matchedGVK := make([]string, 0)
|
||||
for _, rule := range autogen.ComputeRules(policy) {
|
||||
// matching kinds in generate policies need to be added to both webhook
|
||||
|
@ -666,7 +666,7 @@ func (m *webhookConfigManager) mergeWebhook(dst *webhook, policy kyverno.PolicyI
|
|||
}
|
||||
}
|
||||
|
||||
func newWebhook(kind string, timeout int32, failurePolicy kyverno.FailurePolicyType) *webhook {
|
||||
func newWebhook(kind string, timeout int32, failurePolicy kyvernov1.FailurePolicyType) *webhook {
|
||||
return &webhook{
|
||||
kind: kind,
|
||||
maxWebhookTimeout: timeout,
|
||||
|
@ -681,7 +681,7 @@ func webhookKey(webhookKind, failurePolicy string) string {
|
|||
return strings.Join([]string{webhookKind, failurePolicy}, "/")
|
||||
}
|
||||
|
||||
func hasWildcard(spec *kyverno.Spec) bool {
|
||||
func hasWildcard(spec *kyvernov1.Spec) bool {
|
||||
for _, rule := range spec.Rules {
|
||||
if kinds := rule.MatchResources.GetKinds(); utils.ContainsString(kinds, "*") {
|
||||
return true
|
||||
|
|
|
@ -7,8 +7,8 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
urkyverno "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
"github.com/kyverno/kyverno/pkg/autogen"
|
||||
gencommon "github.com/kyverno/kyverno/pkg/background/common"
|
||||
gen "github.com/kyverno/kyverno/pkg/background/generate"
|
||||
|
@ -28,7 +28,7 @@ import (
|
|||
func (h *handlers) handleGenerate(
|
||||
logger logr.Logger,
|
||||
request *admissionv1.AdmissionRequest,
|
||||
policies []kyverno.PolicyInterface,
|
||||
policies []kyvernov1.PolicyInterface,
|
||||
policyContext *engine.PolicyContext,
|
||||
admissionRequestTimestamp int64,
|
||||
latencySender *chan int64,
|
||||
|
@ -66,7 +66,7 @@ func (h *handlers) handleGenerate(
|
|||
go h.registerPolicyExecutionDurationMetricGenerate(logger, string(request.Operation), policy, *engineResponse)
|
||||
}
|
||||
|
||||
if failedResponse := applyUpdateRequest(request, urkyverno.Generate, h.urGenerator, policyContext.AdmissionInfo, request.Operation, engineResponses...); failedResponse != nil {
|
||||
if failedResponse := applyUpdateRequest(request, kyvernov1beta1.Generate, h.urGenerator, policyContext.AdmissionInfo, request.Operation, engineResponses...); failedResponse != nil {
|
||||
// report failure event
|
||||
for _, failedUR := range failedResponse {
|
||||
err := fmt.Errorf("failed to create Update Request: %v", failedUR.err)
|
||||
|
@ -88,7 +88,7 @@ func (h *handlers) handleGenerate(
|
|||
}
|
||||
|
||||
// handleUpdatesForGenerateRules handles admission-requests for update
|
||||
func (h *handlers) handleUpdatesForGenerateRules(logger logr.Logger, request *admissionv1.AdmissionRequest, policies []kyverno.PolicyInterface) {
|
||||
func (h *handlers) handleUpdatesForGenerateRules(logger logr.Logger, request *admissionv1.AdmissionRequest, policies []kyvernov1.PolicyInterface) {
|
||||
if request.Operation != admissionv1.Update {
|
||||
return
|
||||
}
|
||||
|
@ -122,12 +122,12 @@ func (h *handlers) handleUpdateGenerateSourceResource(resLabels map[string]strin
|
|||
}
|
||||
} else {
|
||||
selector := labels.SelectorFromSet(labels.Set(map[string]string{
|
||||
urkyverno.URGeneratePolicyLabel: policyName,
|
||||
kyvernov1beta1.URGeneratePolicyLabel: policyName,
|
||||
}))
|
||||
|
||||
urList, err := h.urLister.List(selector)
|
||||
if err != nil {
|
||||
logger.Error(err, "failed to get update request for the resource", "label", urkyverno.URGeneratePolicyLabel)
|
||||
logger.Error(err, "failed to get update request for the resource", "label", kyvernov1beta1.URGeneratePolicyLabel)
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -140,7 +140,7 @@ func (h *handlers) handleUpdateGenerateSourceResource(resLabels map[string]strin
|
|||
|
||||
// updateAnnotationInUR - function used to update UR annotation
|
||||
// updating UR will trigger reprocessing of UR and recreation/updation of generated resource
|
||||
func (h *handlers) updateAnnotationInUR(ur *urkyverno.UpdateRequest, logger logr.Logger) {
|
||||
func (h *handlers) updateAnnotationInUR(ur *kyvernov1beta1.UpdateRequest, logger logr.Logger) {
|
||||
urAnnotations := ur.Annotations
|
||||
if len(urAnnotations) == 0 {
|
||||
urAnnotations = make(map[string]string)
|
||||
|
@ -161,14 +161,14 @@ func (h *handlers) updateAnnotationInUR(ur *urkyverno.UpdateRequest, logger logr
|
|||
logger.Error(err, "failed to update update request update-time annotations for the resource", "update request", ur.Name)
|
||||
return
|
||||
}
|
||||
new.Status.State = urkyverno.Pending
|
||||
new.Status.State = kyvernov1beta1.Pending
|
||||
if _, err := h.kyvernoClient.KyvernoV1beta1().UpdateRequests(config.KyvernoNamespace()).UpdateStatus(contextdefault.TODO(), new, metav1.UpdateOptions{}); err != nil {
|
||||
logger.Error(err, "failed to set UpdateRequest state to Pending", "update request", ur.Name)
|
||||
}
|
||||
}
|
||||
|
||||
// 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) {
|
||||
func (h *handlers) handleUpdateGenerateTargetResource(request *admissionv1.AdmissionRequest, policies []kyvernov1.PolicyInterface, resLabels map[string]string, logger logr.Logger) {
|
||||
enqueueBool := false
|
||||
newRes, err := enginutils.ConvertToUnstructured(request.Object.Raw)
|
||||
if err != nil {
|
||||
|
@ -232,7 +232,7 @@ func (h *handlers) handleUpdateGenerateTargetResource(request *admissionv1.Admis
|
|||
func (h *handlers) deleteGR(logger logr.Logger, engineResponse *response.EngineResponse) {
|
||||
logger.V(4).Info("querying all update requests")
|
||||
selector := labels.SelectorFromSet(labels.Set(map[string]string{
|
||||
urkyverno.URGeneratePolicyLabel: engineResponse.PolicyResponse.Policy.Name,
|
||||
kyvernov1beta1.URGeneratePolicyLabel: engineResponse.PolicyResponse.Policy.Name,
|
||||
"generate.kyverno.io/resource-name": engineResponse.PolicyResponse.Resource.Name,
|
||||
"generate.kyverno.io/resource-kind": engineResponse.PolicyResponse.Resource.Kind,
|
||||
"generate.kyverno.io/resource-namespace": engineResponse.PolicyResponse.Resource.Namespace,
|
||||
|
|
|
@ -4,7 +4,7 @@ import (
|
|||
"fmt"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/engine/response"
|
||||
"github.com/kyverno/kyverno/pkg/metrics"
|
||||
admissionRequests "github.com/kyverno/kyverno/pkg/metrics/admissionrequests"
|
||||
|
@ -70,19 +70,19 @@ func registerAdmissionRequestsMetricValidate(logger logr.Logger, promConfig *met
|
|||
|
||||
// POLICY RESULTS
|
||||
|
||||
func (h *handlers) registerPolicyResultsMetricMutation(logger logr.Logger, requestOperation string, policy kyverno.PolicyInterface, engineResponse response.EngineResponse) {
|
||||
func (h *handlers) registerPolicyResultsMetricMutation(logger logr.Logger, requestOperation string, policy kyvernov1.PolicyInterface, engineResponse response.EngineResponse) {
|
||||
registerMetric(logger, "kyverno_policy_results_total", requestOperation, func(op metrics.ResourceRequestOperation) error {
|
||||
return policyResults.ProcessEngineResponse(h.promConfig, policy, engineResponse, metrics.AdmissionRequest, op)
|
||||
})
|
||||
}
|
||||
|
||||
func registerPolicyResultsMetricValidation(logger logr.Logger, promConfig *metrics.PromConfig, requestOperation string, policy kyverno.PolicyInterface, engineResponse response.EngineResponse) {
|
||||
func registerPolicyResultsMetricValidation(logger logr.Logger, promConfig *metrics.PromConfig, requestOperation string, policy kyvernov1.PolicyInterface, engineResponse response.EngineResponse) {
|
||||
registerMetric(logger, "kyverno_policy_results_total", requestOperation, func(op metrics.ResourceRequestOperation) error {
|
||||
return policyResults.ProcessEngineResponse(promConfig, policy, engineResponse, metrics.AdmissionRequest, op)
|
||||
})
|
||||
}
|
||||
|
||||
func (h *handlers) registerPolicyResultsMetricGeneration(logger logr.Logger, requestOperation string, policy kyverno.PolicyInterface, engineResponse response.EngineResponse) {
|
||||
func (h *handlers) registerPolicyResultsMetricGeneration(logger logr.Logger, requestOperation string, policy kyvernov1.PolicyInterface, engineResponse response.EngineResponse) {
|
||||
registerMetric(logger, "kyverno_policy_results_total", requestOperation, func(op metrics.ResourceRequestOperation) error {
|
||||
return policyResults.ProcessEngineResponse(h.promConfig, policy, engineResponse, metrics.AdmissionRequest, op)
|
||||
})
|
||||
|
@ -90,19 +90,19 @@ func (h *handlers) registerPolicyResultsMetricGeneration(logger logr.Logger, req
|
|||
|
||||
// POLICY EXECUTION
|
||||
|
||||
func (h *handlers) registerPolicyExecutionDurationMetricMutate(logger logr.Logger, requestOperation string, policy kyverno.PolicyInterface, engineResponse response.EngineResponse) {
|
||||
func (h *handlers) registerPolicyExecutionDurationMetricMutate(logger logr.Logger, requestOperation string, policy kyvernov1.PolicyInterface, engineResponse response.EngineResponse) {
|
||||
registerMetric(logger, "kyverno_policy_execution_duration_seconds", requestOperation, func(op metrics.ResourceRequestOperation) error {
|
||||
return policyExecutionDuration.ProcessEngineResponse(h.promConfig, policy, engineResponse, metrics.AdmissionRequest, "", op)
|
||||
})
|
||||
}
|
||||
|
||||
func registerPolicyExecutionDurationMetricValidate(logger logr.Logger, promConfig *metrics.PromConfig, requestOperation string, policy kyverno.PolicyInterface, engineResponse response.EngineResponse) {
|
||||
func registerPolicyExecutionDurationMetricValidate(logger logr.Logger, promConfig *metrics.PromConfig, requestOperation string, policy kyvernov1.PolicyInterface, engineResponse response.EngineResponse) {
|
||||
registerMetric(logger, "kyverno_policy_execution_duration_seconds", requestOperation, func(op metrics.ResourceRequestOperation) error {
|
||||
return policyExecutionDuration.ProcessEngineResponse(promConfig, policy, engineResponse, metrics.AdmissionRequest, "", op)
|
||||
})
|
||||
}
|
||||
|
||||
func (h *handlers) registerPolicyExecutionDurationMetricGenerate(logger logr.Logger, requestOperation string, policy kyverno.PolicyInterface, engineResponse response.EngineResponse) {
|
||||
func (h *handlers) registerPolicyExecutionDurationMetricGenerate(logger logr.Logger, requestOperation string, policy kyvernov1.PolicyInterface, engineResponse response.EngineResponse) {
|
||||
registerMetric(logger, "kyverno_policy_execution_duration_seconds", requestOperation, func(op metrics.ResourceRequestOperation) error {
|
||||
return policyExecutionDuration.ProcessEngineResponse(h.promConfig, policy, engineResponse, metrics.AdmissionRequest, "", op)
|
||||
})
|
||||
|
|
|
@ -5,8 +5,8 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
urkyverno "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
"github.com/kyverno/kyverno/pkg/engine"
|
||||
"github.com/kyverno/kyverno/pkg/engine/response"
|
||||
"github.com/kyverno/kyverno/pkg/event"
|
||||
|
@ -14,7 +14,7 @@ import (
|
|||
)
|
||||
|
||||
// createUpdateRequests applies generate and mutateExisting policies, and creates update requests for background reconcile
|
||||
func (h *handlers) createUpdateRequests(logger logr.Logger, request *admissionv1.AdmissionRequest, policyContext *engine.PolicyContext, generatePolicies, mutatePolicies []kyverno.PolicyInterface, ts int64) {
|
||||
func (h *handlers) createUpdateRequests(logger logr.Logger, request *admissionv1.AdmissionRequest, policyContext *engine.PolicyContext, generatePolicies, mutatePolicies []kyvernov1.PolicyInterface, ts int64) {
|
||||
admissionReviewCompletionLatencyChannel := make(chan int64, 1)
|
||||
generateEngineResponsesSenderForAdmissionReviewDurationMetric := make(chan []*response.EngineResponse, 1)
|
||||
generateEngineResponsesSenderForAdmissionRequestsCountMetric := make(chan []*response.EngineResponse, 1)
|
||||
|
@ -26,7 +26,7 @@ func (h *handlers) createUpdateRequests(logger logr.Logger, request *admissionv1
|
|||
go h.registerAdmissionRequestsMetricGenerate(logger, string(request.Operation), &generateEngineResponsesSenderForAdmissionRequestsCountMetric)
|
||||
}
|
||||
|
||||
func (h *handlers) handleMutateExisting(logger logr.Logger, request *admissionv1.AdmissionRequest, policies []kyverno.PolicyInterface, policyContext *engine.PolicyContext, admissionRequestTimestamp int64) {
|
||||
func (h *handlers) handleMutateExisting(logger logr.Logger, request *admissionv1.AdmissionRequest, policies []kyvernov1.PolicyInterface, policyContext *engine.PolicyContext, admissionRequestTimestamp int64) {
|
||||
logger.V(4).Info("update request")
|
||||
|
||||
if request.Operation == admissionv1.Delete {
|
||||
|
@ -65,7 +65,7 @@ func (h *handlers) handleMutateExisting(logger logr.Logger, request *admissionv1
|
|||
go h.registerPolicyExecutionDurationMetricMutate(logger, string(request.Operation), policy, *engineResponse)
|
||||
}
|
||||
|
||||
if failedResponse := applyUpdateRequest(request, urkyverno.Mutate, h.urGenerator, policyContext.AdmissionInfo, request.Operation, engineResponses...); failedResponse != nil {
|
||||
if failedResponse := applyUpdateRequest(request, kyvernov1beta1.Mutate, h.urGenerator, policyContext.AdmissionInfo, request.Operation, engineResponses...); failedResponse != nil {
|
||||
for _, failedUR := range failedResponse {
|
||||
err := fmt.Errorf("failed to create update request: %v", failedUR.err)
|
||||
events := event.NewBackgroundFailedEvent(err, failedUR.ur.Policy, "", event.GeneratePolicyController, &policyContext.NewResource)
|
||||
|
|
|
@ -5,7 +5,7 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
v1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/pkg/engine"
|
||||
"github.com/kyverno/kyverno/pkg/engine/response"
|
||||
"github.com/kyverno/kyverno/pkg/event"
|
||||
|
@ -29,7 +29,7 @@ type validationHandler struct {
|
|||
func (v *validationHandler) handleValidation(
|
||||
promConfig *metrics.PromConfig,
|
||||
request *admissionv1.AdmissionRequest,
|
||||
policies []v1.PolicyInterface,
|
||||
policies []kyvernov1.PolicyInterface,
|
||||
policyContext *engine.PolicyContext,
|
||||
namespaceLabels map[string]string,
|
||||
admissionRequestTimestamp int64,
|
||||
|
|
|
@ -7,7 +7,7 @@ import (
|
|||
backoff "github.com/cenkalti/backoff"
|
||||
"github.com/gardener/controller-manager-library/pkg/logger"
|
||||
"github.com/go-logr/logr"
|
||||
urkyverno "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
kyvernoclient "github.com/kyverno/kyverno/pkg/client/clientset/versioned"
|
||||
urkyvernoinformer "github.com/kyverno/kyverno/pkg/client/informers/externalversions/kyverno/v1beta1"
|
||||
urkyvernolister "github.com/kyverno/kyverno/pkg/client/listers/kyverno/v1beta1"
|
||||
|
@ -21,12 +21,12 @@ import (
|
|||
|
||||
// UpdateRequest provides interface to manage update requests
|
||||
type Interface interface {
|
||||
Apply(gr urkyverno.UpdateRequestSpec, action admissionv1.Operation) error
|
||||
Apply(gr kyvernov1beta1.UpdateRequestSpec, action admissionv1.Operation) error
|
||||
}
|
||||
|
||||
// info object stores message data to create update request
|
||||
type info struct {
|
||||
spec urkyverno.UpdateRequestSpec
|
||||
spec kyvernov1beta1.UpdateRequestSpec
|
||||
action admissionv1.Operation
|
||||
}
|
||||
|
||||
|
@ -51,7 +51,7 @@ func NewGenerator(client kyvernoclient.Interface, urInformer urkyvernoinformer.U
|
|||
}
|
||||
|
||||
// Apply creates update request resource
|
||||
func (g *Generator) Apply(ur urkyverno.UpdateRequestSpec, action admissionv1.Operation) error {
|
||||
func (g *Generator) Apply(ur kyvernov1beta1.UpdateRequestSpec, action admissionv1.Operation) error {
|
||||
logger := g.log
|
||||
logger.V(4).Info("reconcile Update Request", "request", ur)
|
||||
|
||||
|
@ -91,12 +91,12 @@ func (g *Generator) generate(i info) error {
|
|||
|
||||
func retryApplyResource(
|
||||
client kyvernoclient.Interface,
|
||||
urSpec urkyverno.UpdateRequestSpec,
|
||||
urSpec kyvernov1beta1.UpdateRequestSpec,
|
||||
log logr.Logger,
|
||||
action admissionv1.Operation,
|
||||
urLister urkyvernolister.UpdateRequestNamespaceLister,
|
||||
) error {
|
||||
if action == admissionv1.Delete && urSpec.Type == urkyverno.Generate {
|
||||
if action == admissionv1.Delete && urSpec.Type == kyvernov1beta1.Generate {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
@ -109,17 +109,17 @@ func retryApplyResource(
|
|||
}
|
||||
|
||||
applyResource := func() error {
|
||||
ur := urkyverno.UpdateRequest{
|
||||
ur := kyvernov1beta1.UpdateRequest{
|
||||
Spec: urSpec,
|
||||
Status: urkyverno.UpdateRequestStatus{
|
||||
State: urkyverno.Pending,
|
||||
Status: kyvernov1beta1.UpdateRequestStatus{
|
||||
State: kyvernov1beta1.Pending,
|
||||
},
|
||||
}
|
||||
|
||||
queryLabels := make(map[string]string)
|
||||
if ur.Spec.Type == urkyverno.Mutate {
|
||||
if ur.Spec.Type == kyvernov1beta1.Mutate {
|
||||
queryLabels := map[string]string{
|
||||
urkyverno.URMutatePolicyLabel: ur.Spec.Policy,
|
||||
kyvernov1beta1.URMutatePolicyLabel: ur.Spec.Policy,
|
||||
"mutate.updaterequest.kyverno.io/trigger-name": ur.Spec.Resource.Name,
|
||||
"mutate.updaterequest.kyverno.io/trigger-namespace": ur.Spec.Resource.Namespace,
|
||||
"mutate.updaterequest.kyverno.io/trigger-kind": ur.Spec.Resource.Kind,
|
||||
|
@ -128,9 +128,9 @@ func retryApplyResource(
|
|||
if ur.Spec.Resource.APIVersion != "" {
|
||||
queryLabels["mutate.updaterequest.kyverno.io/trigger-apiversion"] = ur.Spec.Resource.APIVersion
|
||||
}
|
||||
} else if ur.Spec.Type == urkyverno.Generate {
|
||||
} else if ur.Spec.Type == kyvernov1beta1.Generate {
|
||||
queryLabels = labels.Set(map[string]string{
|
||||
urkyverno.URGeneratePolicyLabel: policyName,
|
||||
kyvernov1beta1.URGeneratePolicyLabel: policyName,
|
||||
"generate.kyverno.io/resource-name": urSpec.Resource.Name,
|
||||
"generate.kyverno.io/resource-kind": urSpec.Resource.Kind,
|
||||
"generate.kyverno.io/resource-namespace": urSpec.Resource.Namespace,
|
||||
|
@ -164,7 +164,7 @@ func retryApplyResource(
|
|||
log.V(4).Info("successfully updated UpdateRequest", "retryCount", i, "name", ur.GetName(), "namespace", ur.GetNamespace())
|
||||
}
|
||||
|
||||
new.Status.State = urkyverno.Pending
|
||||
new.Status.State = kyvernov1beta1.Pending
|
||||
if _, err := client.KyvernoV1beta1().UpdateRequests(config.KyvernoNamespace()).UpdateStatus(context.TODO(), new, metav1.UpdateOptions{}); err != nil {
|
||||
log.Error(err, "failed to set UpdateRequest state to Pending")
|
||||
return err
|
||||
|
@ -188,7 +188,7 @@ func retryApplyResource(
|
|||
log.V(4).Info("successfully created UpdateRequest", "retryCount", i, "name", new.GetName(), "namespace", ur.GetNamespace())
|
||||
}
|
||||
|
||||
new.Status.State = urkyverno.Pending
|
||||
new.Status.State = kyvernov1beta1.Pending
|
||||
if _, err := client.KyvernoV1beta1().UpdateRequests(config.KyvernoNamespace()).UpdateStatus(context.TODO(), new, metav1.UpdateOptions{}); err != nil {
|
||||
log.Error(err, "failed to set UpdateRequest state to Pending")
|
||||
return err
|
||||
|
|
Loading…
Reference in a new issue