mirror of
https://github.com/kyverno/kyverno.git
synced 2025-03-05 07:26:55 +00:00
fix: replace fmt.Print calls by fmt.Fprint ones (#8389)
Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com>
This commit is contained in:
parent
5af4d13a0e
commit
b9bc57b201
13 changed files with 138 additions and 109 deletions
|
@ -3,6 +3,7 @@ package apply
|
|||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
@ -75,19 +76,20 @@ func Command() *cobra.Command {
|
|||
Example: command.FormatExamples(examples...),
|
||||
SilenceUsage: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) (err error) {
|
||||
out := cmd.OutOrStdout()
|
||||
color.InitColors(removeColor)
|
||||
applyCommandConfig.PolicyPaths = args
|
||||
rc, _, skipInvalidPolicies, responses, err := applyCommandConfig.applyCommandHelper()
|
||||
rc, _, skipInvalidPolicies, responses, err := applyCommandConfig.applyCommandHelper(out)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
printSkippedAndInvalidPolicies(skipInvalidPolicies)
|
||||
printSkippedAndInvalidPolicies(out, skipInvalidPolicies)
|
||||
if applyCommandConfig.PolicyReport {
|
||||
printReport(responses, applyCommandConfig.AuditWarn)
|
||||
printReport(out, responses, applyCommandConfig.AuditWarn)
|
||||
} else if table {
|
||||
printTable(detailedResults, applyCommandConfig.AuditWarn, responses...)
|
||||
} else {
|
||||
printViolations(rc)
|
||||
printViolations(out, rc)
|
||||
}
|
||||
return exit(rc, applyCommandConfig.warnExitCode, applyCommandConfig.warnNoPassed)
|
||||
},
|
||||
|
@ -115,7 +117,7 @@ func Command() *cobra.Command {
|
|||
return cmd
|
||||
}
|
||||
|
||||
func (c *ApplyCommandConfig) applyCommandHelper() (*processor.ResultCounts, []*unstructured.Unstructured, SkippedInvalidPolicies, []engineapi.EngineResponse, error) {
|
||||
func (c *ApplyCommandConfig) applyCommandHelper(out io.Writer) (*processor.ResultCounts, []*unstructured.Unstructured, SkippedInvalidPolicies, []engineapi.EngineResponse, error) {
|
||||
rc, resources1, skipInvalidPolicies, responses1, err := c.checkArguments()
|
||||
if err != nil {
|
||||
return rc, resources1, skipInvalidPolicies, responses1, err
|
||||
|
@ -151,7 +153,7 @@ func (c *ApplyCommandConfig) applyCommandHelper() (*processor.ResultCounts, []*u
|
|||
if err != nil {
|
||||
return rc, resources1, skipInvalidPolicies, responses1, err
|
||||
}
|
||||
resources, err := c.loadResources(policies, validatingAdmissionPolicies, dClient)
|
||||
resources, err := c.loadResources(out, policies, validatingAdmissionPolicies, dClient)
|
||||
if err != nil {
|
||||
return rc, resources1, skipInvalidPolicies, responses1, err
|
||||
}
|
||||
|
@ -161,9 +163,10 @@ func (c *ApplyCommandConfig) applyCommandHelper() (*processor.ResultCounts, []*u
|
|||
policyRulesCount += len(autogen.ComputeRules(policy))
|
||||
}
|
||||
policyRulesCount += len(validatingAdmissionPolicies)
|
||||
fmt.Printf("\nApplying %d policy rule(s) to %d resource(s)...\n", policyRulesCount, len(resources))
|
||||
fmt.Fprintf(out, "\nApplying %d policy rule(s) to %d resource(s)...\n", policyRulesCount, len(resources))
|
||||
}
|
||||
rc, resources1, responses1, err = c.applyPolicytoResource(
|
||||
out,
|
||||
variables,
|
||||
policies,
|
||||
resources,
|
||||
|
@ -220,6 +223,7 @@ func (c *ApplyCommandConfig) applyValidatingAdmissionPolicytoResource(
|
|||
}
|
||||
|
||||
func (c *ApplyCommandConfig) applyPolicytoResource(
|
||||
out io.Writer,
|
||||
vars *variables.Variables,
|
||||
policies []kyvernov1.PolicyInterface,
|
||||
resources []*unstructured.Unstructured,
|
||||
|
@ -254,7 +258,7 @@ func (c *ApplyCommandConfig) applyPolicytoResource(
|
|||
if !vars.HasVariables() && variables.NeedsVariables(matches...) {
|
||||
// check policy in variable file
|
||||
if !vars.HasPolicyVariables(pol.GetName()) {
|
||||
fmt.Printf("test skipped for policy %v (as required variables are not provided by the users) \n \n", pol.GetName())
|
||||
fmt.Fprintf(out, "test skipped for policy %v (as required variables are not provided by the users) \n \n", pol.GetName())
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
@ -278,6 +282,7 @@ func (c *ApplyCommandConfig) applyPolicytoResource(
|
|||
Client: dClient,
|
||||
AuditWarn: c.AuditWarn,
|
||||
Subresources: vars.Subresources(),
|
||||
Out: out,
|
||||
}
|
||||
ers, err := processor.ApplyPoliciesOnResource()
|
||||
if err != nil {
|
||||
|
@ -288,8 +293,8 @@ func (c *ApplyCommandConfig) applyPolicytoResource(
|
|||
return &rc, resources, responses, nil
|
||||
}
|
||||
|
||||
func (c *ApplyCommandConfig) loadResources(policies []kyvernov1.PolicyInterface, validatingAdmissionPolicies []v1alpha1.ValidatingAdmissionPolicy, dClient dclient.Interface) ([]*unstructured.Unstructured, error) {
|
||||
resources, err := common.GetResourceAccordingToResourcePath(nil, c.ResourcePaths, c.Cluster, policies, validatingAdmissionPolicies, dClient, c.Namespace, c.PolicyReport, "")
|
||||
func (c *ApplyCommandConfig) loadResources(out io.Writer, policies []kyvernov1.PolicyInterface, validatingAdmissionPolicies []v1alpha1.ValidatingAdmissionPolicy, dClient dclient.Interface) ([]*unstructured.Unstructured, error) {
|
||||
resources, err := common.GetResourceAccordingToResourcePath(out, nil, c.ResourcePaths, c.Cluster, policies, validatingAdmissionPolicies, dClient, c.Namespace, c.PolicyReport, "")
|
||||
if err != nil {
|
||||
return resources, fmt.Errorf("failed to load resources (%w)", err)
|
||||
}
|
||||
|
@ -409,42 +414,42 @@ func (c *ApplyCommandConfig) checkArguments() (*processor.ResultCounts, []*unstr
|
|||
return nil, nil, skipInvalidPolicies, nil, nil
|
||||
}
|
||||
|
||||
func printSkippedAndInvalidPolicies(skipInvalidPolicies SkippedInvalidPolicies) {
|
||||
func printSkippedAndInvalidPolicies(out io.Writer, skipInvalidPolicies SkippedInvalidPolicies) {
|
||||
if len(skipInvalidPolicies.skipped) > 0 {
|
||||
fmt.Println(divider)
|
||||
fmt.Println("Policies Skipped (as required variables are not provided by the user):")
|
||||
fmt.Fprintln(out, divider)
|
||||
fmt.Fprintln(out, "Policies Skipped (as required variables are not provided by the user):")
|
||||
for i, policyName := range skipInvalidPolicies.skipped {
|
||||
fmt.Printf("%d. %s\n", i+1, policyName)
|
||||
fmt.Fprintf(out, "%d. %s\n", i+1, policyName)
|
||||
}
|
||||
fmt.Println(divider)
|
||||
fmt.Fprintln(out, divider)
|
||||
}
|
||||
if len(skipInvalidPolicies.invalid) > 0 {
|
||||
fmt.Println(divider)
|
||||
fmt.Println("Invalid Policies:")
|
||||
fmt.Fprintln(out, divider)
|
||||
fmt.Fprintln(out, "Invalid Policies:")
|
||||
for i, policyName := range skipInvalidPolicies.invalid {
|
||||
fmt.Printf("%d. %s\n", i+1, policyName)
|
||||
fmt.Fprintf(out, "%d. %s\n", i+1, policyName)
|
||||
}
|
||||
fmt.Println(divider)
|
||||
fmt.Fprintln(out, divider)
|
||||
}
|
||||
}
|
||||
|
||||
func printReport(engineResponses []engineapi.EngineResponse, auditWarn bool) {
|
||||
func printReport(out io.Writer, engineResponses []engineapi.EngineResponse, auditWarn bool) {
|
||||
clustered, namespaced := report.ComputePolicyReports(auditWarn, engineResponses...)
|
||||
if len(clustered) > 0 || len(namespaced) > 0 {
|
||||
fmt.Println(divider)
|
||||
fmt.Println("POLICY REPORT:")
|
||||
fmt.Println(divider)
|
||||
fmt.Fprintln(out, divider)
|
||||
fmt.Fprintln(out, "POLICY REPORT:")
|
||||
fmt.Fprintln(out, divider)
|
||||
report := report.MergeClusterReports(clustered)
|
||||
yamlReport, _ := yaml.Marshal(report)
|
||||
fmt.Println(string(yamlReport))
|
||||
fmt.Fprintln(out, string(yamlReport))
|
||||
} else {
|
||||
fmt.Println(divider)
|
||||
fmt.Println("POLICY REPORT: skip generating policy report (no validate policy found/resource skipped)")
|
||||
fmt.Fprintln(out, divider)
|
||||
fmt.Fprintln(out, "POLICY REPORT: skip generating policy report (no validate policy found/resource skipped)")
|
||||
}
|
||||
}
|
||||
|
||||
func printViolations(rc *processor.ResultCounts) {
|
||||
fmt.Printf("\npass: %d, fail: %d, warn: %d, error: %d, skip: %d \n", rc.Pass(), rc.Fail(), rc.Warn(), rc.Error(), rc.Skip())
|
||||
func printViolations(out io.Writer, rc *processor.ResultCounts) {
|
||||
fmt.Fprintf(out, "\npass: %d, fail: %d, warn: %d, error: %d, skip: %d \n", rc.Pass(), rc.Fail(), rc.Warn(), rc.Error(), rc.Skip())
|
||||
}
|
||||
|
||||
func exit(rc *processor.ResultCounts, warnExitCode int, warnNoPassed bool) error {
|
||||
|
|
|
@ -334,7 +334,7 @@ func Test_Apply(t *testing.T) {
|
|||
}
|
||||
desc := fmt.Sprintf("Policies: [%s], / Resources: [%s]", strings.Join(tc.config.PolicyPaths, ","), strings.Join(tc.config.ResourcePaths, ","))
|
||||
|
||||
_, _, _, responses, err := tc.config.applyCommandHelper()
|
||||
_, _, _, responses, err := tc.config.applyCommandHelper(os.Stdout)
|
||||
assert.NoError(t, err, desc)
|
||||
|
||||
clustered, _ := report.ComputePolicyReports(tc.config.AuditWarn, responses...)
|
||||
|
|
|
@ -2,6 +2,7 @@ package test
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/go-git/go-billy/v5"
|
||||
|
@ -33,7 +34,7 @@ func Command() *cobra.Command {
|
|||
RunE: func(cmd *cobra.Command, dirPath []string) (err error) {
|
||||
color.InitColors(removeColor)
|
||||
store.SetRegistryAccess(registryAccess)
|
||||
return testCommandExecute(dirPath, fileName, gitBranch, testCase, failOnly, detailedResults)
|
||||
return testCommandExecute(cmd.OutOrStdout(), dirPath, fileName, gitBranch, testCase, failOnly, detailedResults)
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVarP(&fileName, "file-name", "f", "kyverno-test.yaml", "Test filename")
|
||||
|
@ -53,6 +54,7 @@ type resultCounts struct {
|
|||
}
|
||||
|
||||
func testCommandExecute(
|
||||
out io.Writer,
|
||||
dirPath []string,
|
||||
fileName string,
|
||||
gitBranch string,
|
||||
|
@ -67,10 +69,10 @@ func testCommandExecute(
|
|||
// parse filter
|
||||
filter, errors := filter.ParseFilter(testCase)
|
||||
if len(errors) > 0 {
|
||||
fmt.Println()
|
||||
fmt.Println("Filter errors:")
|
||||
fmt.Fprintln(out)
|
||||
fmt.Fprintln(out, "Filter errors:")
|
||||
for _, e := range errors {
|
||||
fmt.Println(" Error:", e)
|
||||
fmt.Fprintln(out, " Error:", e)
|
||||
}
|
||||
}
|
||||
// init openapi manager
|
||||
|
@ -81,20 +83,20 @@ func testCommandExecute(
|
|||
// load tests
|
||||
tests, err := loadTests(dirPath, fileName, gitBranch)
|
||||
if err != nil {
|
||||
fmt.Println()
|
||||
fmt.Println("Error loading tests:", err)
|
||||
fmt.Fprintln(out)
|
||||
fmt.Fprintln(out, "Error loading tests:", err)
|
||||
return err
|
||||
}
|
||||
if len(tests) == 0 {
|
||||
fmt.Println()
|
||||
fmt.Println("No test yamls available")
|
||||
fmt.Fprintln(out)
|
||||
fmt.Fprintln(out, "No test yamls available")
|
||||
}
|
||||
if errs := tests.Errors(); len(errs) > 0 {
|
||||
fmt.Println()
|
||||
fmt.Println("Test errors:")
|
||||
fmt.Fprintln(out)
|
||||
fmt.Fprintln(out, "Test errors:")
|
||||
for _, e := range errs {
|
||||
fmt.Println(" Path:", e.Path)
|
||||
fmt.Println(" Error:", e.Err)
|
||||
fmt.Fprintln(out, " Path:", e.Path)
|
||||
fmt.Fprintln(out, " Error:", e.Err)
|
||||
}
|
||||
}
|
||||
if len(tests) == 0 {
|
||||
|
@ -120,11 +122,11 @@ func testCommandExecute(
|
|||
continue
|
||||
}
|
||||
resourcePath := filepath.Dir(test.Path)
|
||||
responses, err := runTest(openApiManager, test, false)
|
||||
responses, err := runTest(out, openApiManager, test, false)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to run test (%w)", err)
|
||||
}
|
||||
t, err := printTestResult(filteredResults, responses, rc, failOnly, detailedResults, test.Fs, resourcePath)
|
||||
t, err := printTestResult(out, filteredResults, responses, rc, failOnly, detailedResults, test.Fs, resourcePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to print test result (%w)", err)
|
||||
}
|
||||
|
@ -132,14 +134,14 @@ func testCommandExecute(
|
|||
}
|
||||
}
|
||||
if !failOnly {
|
||||
fmt.Printf("\nTest Summary: %d tests passed and %d tests failed\n", rc.Pass+rc.Skip, rc.Fail)
|
||||
fmt.Fprintf(out, "\nTest Summary: %d tests passed and %d tests failed\n", rc.Pass+rc.Skip, rc.Fail)
|
||||
} else {
|
||||
fmt.Printf("\nTest Summary: %d out of %d tests failed\n", rc.Fail, rc.Pass+rc.Skip+rc.Fail)
|
||||
fmt.Fprintf(out, "\nTest Summary: %d out of %d tests failed\n", rc.Fail, rc.Pass+rc.Skip+rc.Fail)
|
||||
}
|
||||
fmt.Println()
|
||||
fmt.Fprintln(out)
|
||||
if rc.Fail > 0 {
|
||||
if !failOnly {
|
||||
printFailedTestResult(table, detailedResults)
|
||||
printFailedTestResult(out, table, detailedResults)
|
||||
}
|
||||
return fmt.Errorf("%d tests failed", rc.Fail)
|
||||
}
|
||||
|
|
|
@ -2,6 +2,7 @@ package test
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/go-git/go-billy/v5"
|
||||
policyreportv1alpha2 "github.com/kyverno/kyverno/api/policyreport/v1alpha2"
|
||||
|
@ -12,6 +13,7 @@ import (
|
|||
)
|
||||
|
||||
func printTestResult(
|
||||
out io.Writer,
|
||||
tests []testapi.TestResult,
|
||||
responses []engineapi.EngineResponse,
|
||||
rc *resultCounts,
|
||||
|
@ -95,17 +97,17 @@ func printTestResult(
|
|||
}
|
||||
}
|
||||
}
|
||||
fmt.Printf("\n")
|
||||
fmt.Fprintln(out)
|
||||
printer.Print(resultsTable.Rows(detailedResults))
|
||||
return resultsTable, nil
|
||||
}
|
||||
|
||||
func printFailedTestResult(resultsTable table.Table, detailedResults bool) {
|
||||
func printFailedTestResult(out io.Writer, resultsTable table.Table, detailedResults bool) {
|
||||
printer := table.NewTablePrinter()
|
||||
for i := range resultsTable.RawRows {
|
||||
resultsTable.RawRows[i].ID = i + 1
|
||||
}
|
||||
fmt.Printf("Aggregated Failed Test Cases : ")
|
||||
fmt.Println()
|
||||
fmt.Fprintf(out, "Aggregated Failed Test Cases : ")
|
||||
fmt.Fprintln(out)
|
||||
printer.Print(resultsTable.Rows(detailedResults))
|
||||
}
|
||||
|
|
|
@ -2,6 +2,7 @@ package test
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
||||
|
@ -26,17 +27,17 @@ import (
|
|||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
)
|
||||
|
||||
func runTest(openApiManager openapi.Manager, testCase test.TestCase, auditWarn bool) ([]engineapi.EngineResponse, error) {
|
||||
func runTest(out io.Writer, openApiManager openapi.Manager, testCase test.TestCase, auditWarn bool) ([]engineapi.EngineResponse, error) {
|
||||
// don't process test case with errors
|
||||
if testCase.Err != nil {
|
||||
return nil, testCase.Err
|
||||
}
|
||||
fmt.Println("Loading test", testCase.Test.Name, "(", testCase.Path, ")", "...")
|
||||
fmt.Fprintln(out, "Loading test", testCase.Test.Name, "(", testCase.Path, ")", "...")
|
||||
isGit := testCase.Fs != nil
|
||||
testDir := testCase.Dir()
|
||||
var dClient dclient.Interface
|
||||
// values/variables
|
||||
fmt.Println(" Loading values/variables", "...")
|
||||
fmt.Fprintln(out, " Loading values/variables", "...")
|
||||
vars, err := variables.New(testCase.Fs, testDir, testCase.Test.Variables, testCase.Test.Values)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("failed to decode yaml (%w)", err)
|
||||
|
@ -45,7 +46,7 @@ func runTest(openApiManager openapi.Manager, testCase test.TestCase, auditWarn b
|
|||
// user info
|
||||
var userInfo *v1beta1.RequestInfo
|
||||
if testCase.Test.UserInfo != "" {
|
||||
fmt.Println(" Loading user infos", "...")
|
||||
fmt.Fprintln(out, " Loading user infos", "...")
|
||||
var err error
|
||||
userInfo, err = userinfo.Load(testCase.Fs, testCase.Test.UserInfo, testDir)
|
||||
if err != nil {
|
||||
|
@ -53,23 +54,23 @@ func runTest(openApiManager openapi.Manager, testCase test.TestCase, auditWarn b
|
|||
}
|
||||
}
|
||||
// policies
|
||||
fmt.Println(" Loading policies", "...")
|
||||
fmt.Fprintln(out, " Loading policies", "...")
|
||||
policyFullPath := path.GetFullPaths(testCase.Test.Policies, testDir, isGit)
|
||||
policies, validatingAdmissionPolicies, err := policy.Load(testCase.Fs, testDir, policyFullPath...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Error: failed to load policies (%s)", err)
|
||||
}
|
||||
// resources
|
||||
fmt.Println(" Loading resources", "...")
|
||||
fmt.Fprintln(out, " Loading resources", "...")
|
||||
resourceFullPath := path.GetFullPaths(testCase.Test.Resources, testDir, isGit)
|
||||
resources, err := common.GetResourceAccordingToResourcePath(testCase.Fs, resourceFullPath, false, policies, validatingAdmissionPolicies, dClient, "", false, testDir)
|
||||
resources, err := common.GetResourceAccordingToResourcePath(out, testCase.Fs, resourceFullPath, false, policies, validatingAdmissionPolicies, dClient, "", false, testDir)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Error: failed to load resources (%s)", err)
|
||||
}
|
||||
uniques, duplicates := resource.RemoveDuplicates(resources)
|
||||
if len(duplicates) > 0 {
|
||||
for dup := range duplicates {
|
||||
fmt.Println(" Warning: found duplicated resource", dup.Kind, dup.Name, dup.Namespace)
|
||||
fmt.Fprintln(out, " Warning: found duplicated resource", dup.Kind, dup.Name, dup.Namespace)
|
||||
}
|
||||
}
|
||||
// init store
|
||||
|
@ -89,12 +90,12 @@ func runTest(openApiManager openapi.Manager, testCase test.TestCase, auditWarn b
|
|||
if rule.HasGenerate() {
|
||||
ruleUnstr, err := generate.GetUnstrRule(rule.Generation.DeepCopy())
|
||||
if err != nil {
|
||||
fmt.Printf("Error: failed to get unstructured rule\nCause: %s\n", err)
|
||||
fmt.Fprintf(out, "Error: failed to get unstructured rule\nCause: %s\n", err)
|
||||
break
|
||||
}
|
||||
genClone, _, err := unstructured.NestedMap(ruleUnstr.Object, "clone")
|
||||
if err != nil {
|
||||
fmt.Printf("Error: failed to read data\nCause: %s\n", err)
|
||||
fmt.Fprintf(out, "Error: failed to read data\nCause: %s\n", err)
|
||||
break
|
||||
}
|
||||
if len(genClone) != 0 {
|
||||
|
@ -127,14 +128,14 @@ func runTest(openApiManager openapi.Manager, testCase test.TestCase, auditWarn b
|
|||
if !vars.HasVariables() && variables.NeedsVariables(matches...) {
|
||||
// check policy in variable file
|
||||
if !vars.HasPolicyVariables(pol.GetName()) {
|
||||
fmt.Printf("test skipped for policy %v (as required variables are not provided by the users) \n \n", pol.GetName())
|
||||
fmt.Fprintf(out, "test skipped for policy %v (as required variables are not provided by the users) \n \n", pol.GetName())
|
||||
// continue
|
||||
}
|
||||
}
|
||||
validPolicies = append(validPolicies, pol)
|
||||
}
|
||||
// execute engine
|
||||
fmt.Println(" Applying", len(policies), pluralize.Pluralize(len(policies), "policy", "policies"), "to", len(uniques), pluralize.Pluralize(len(uniques), "resource", "resources"), "...")
|
||||
fmt.Fprintln(out, " Applying", len(policies), pluralize.Pluralize(len(policies), "policy", "policies"), "to", len(uniques), pluralize.Pluralize(len(uniques), "resource", "resources"), "...")
|
||||
var engineResponses []engineapi.EngineResponse
|
||||
var resultCounts processor.ResultCounts
|
||||
|
||||
|
@ -151,6 +152,7 @@ func runTest(openApiManager openapi.Manager, testCase test.TestCase, auditWarn b
|
|||
RuleToCloneSourceResource: ruleToCloneSourceResource,
|
||||
Client: dClient,
|
||||
Subresources: vars.Subresources(),
|
||||
Out: out,
|
||||
}
|
||||
ers, err := processor.ApplyPoliciesOnResource()
|
||||
if err != nil {
|
||||
|
|
|
@ -2,6 +2,7 @@ package processor
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
|
@ -22,18 +23,18 @@ import (
|
|||
"k8s.io/apimachinery/pkg/util/sets"
|
||||
)
|
||||
|
||||
func handleGeneratePolicy(generateResponse *engineapi.EngineResponse, policyContext engine.PolicyContext, ruleToCloneSourceResource map[string]string) ([]engineapi.RuleResponse, error) {
|
||||
func handleGeneratePolicy(out io.Writer, generateResponse *engineapi.EngineResponse, policyContext engine.PolicyContext, ruleToCloneSourceResource map[string]string) ([]engineapi.RuleResponse, error) {
|
||||
newResource := policyContext.NewResource()
|
||||
objects := []runtime.Object{&newResource}
|
||||
for _, rule := range generateResponse.PolicyResponse.Rules {
|
||||
if path, ok := ruleToCloneSourceResource[rule.Name()]; ok {
|
||||
resourceBytes, err := resource.GetFileBytes(path)
|
||||
if err != nil {
|
||||
fmt.Printf("failed to get resource bytes\n")
|
||||
fmt.Fprintf(out, "failed to get resource bytes\n")
|
||||
} else {
|
||||
r, err := resource.GetUnstructuredResources(resourceBytes)
|
||||
if err != nil {
|
||||
fmt.Printf("failed to convert resource bytes to unstructured format\n")
|
||||
fmt.Fprintf(out, "failed to convert resource bytes to unstructured format\n")
|
||||
}
|
||||
for _, res := range r {
|
||||
objects = append(objects, res)
|
||||
|
@ -42,9 +43,9 @@ func handleGeneratePolicy(generateResponse *engineapi.EngineResponse, policyCont
|
|||
}
|
||||
}
|
||||
|
||||
c, err := initializeMockController(objects)
|
||||
c, err := initializeMockController(out, objects)
|
||||
if err != nil {
|
||||
fmt.Println("error at controller")
|
||||
fmt.Fprintln(out, "error at controller")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
|
@ -81,10 +82,10 @@ func handleGeneratePolicy(generateResponse *engineapi.EngineResponse, policyCont
|
|||
return newRuleResponse, nil
|
||||
}
|
||||
|
||||
func initializeMockController(objects []runtime.Object) (*generate.GenerateController, error) {
|
||||
func initializeMockController(out io.Writer, objects []runtime.Object) (*generate.GenerateController, error) {
|
||||
client, err := dclient.NewFakeClient(runtime.NewScheme(), nil, objects...)
|
||||
if err != nil {
|
||||
fmt.Printf("Failed to mock dynamic client")
|
||||
fmt.Fprintf(out, "Failed to mock dynamic client")
|
||||
return nil, err
|
||||
}
|
||||
gvrs := sets.New[schema.GroupVersionResource]()
|
||||
|
|
|
@ -3,6 +3,7 @@ package processor
|
|||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
@ -49,6 +50,7 @@ type PolicyProcessor struct {
|
|||
Client dclient.Interface
|
||||
AuditWarn bool
|
||||
Subresources []valuesapi.Subresource
|
||||
Out io.Writer
|
||||
}
|
||||
|
||||
func (p *PolicyProcessor) ApplyPoliciesOnResource() ([]engineapi.EngineResponse, error) {
|
||||
|
@ -166,7 +168,7 @@ func (p *PolicyProcessor) ApplyPoliciesOnResource() ([]engineapi.EngineResponse,
|
|||
}
|
||||
generateResponse := eng.ApplyBackgroundChecks(context.TODO(), policyContext)
|
||||
if !generateResponse.IsEmpty() {
|
||||
newRuleResponse, err := handleGeneratePolicy(&generateResponse, *policyContext, p.RuleToCloneSourceResource)
|
||||
newRuleResponse, err := handleGeneratePolicy(p.Out, &generateResponse, *policyContext, p.RuleToCloneSourceResource)
|
||||
if err != nil {
|
||||
log.Log.Error(err, "failed to apply generate policy")
|
||||
} else {
|
||||
|
@ -174,7 +176,7 @@ func (p *PolicyProcessor) ApplyPoliciesOnResource() ([]engineapi.EngineResponse,
|
|||
}
|
||||
responses = append(responses, generateResponse)
|
||||
}
|
||||
p.Rc.addGenerateResponse(p.AuditWarn, resPath, generateResponse)
|
||||
p.Rc.addGenerateResponse(p.Out, p.AuditWarn, resPath, generateResponse)
|
||||
}
|
||||
}
|
||||
p.Rc.addEngineResponses(p.AuditWarn, responses...)
|
||||
|
@ -193,7 +195,7 @@ func (p *PolicyProcessor) makePolicyContext(
|
|||
operation := kyvernov1.Create
|
||||
var resourceValues map[string]interface{}
|
||||
if p.Variables != nil {
|
||||
kindOnwhichPolicyIsApplied := common.GetKindsFromPolicy(policy, p.Variables.Subresources(), p.Client)
|
||||
kindOnwhichPolicyIsApplied := common.GetKindsFromPolicy(p.Out, policy, p.Variables.Subresources(), p.Client)
|
||||
vals, err := p.Variables.ComputeVariables(policy.GetName(), resource.GetName(), resource.GetKind(), kindOnwhichPolicyIsApplied /*matches...*/)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("policy `%s` have variables. pass the values for the variables for resource `%s` using set/values_file flag (%w)",
|
||||
|
@ -305,7 +307,7 @@ func (p *PolicyProcessor) makePolicyContext(
|
|||
}
|
||||
|
||||
func (p *PolicyProcessor) processMutateEngineResponse(response engineapi.EngineResponse, resourcePath string) error {
|
||||
printMutatedRes := p.Rc.addMutateResponse(resourcePath, response)
|
||||
printMutatedRes := p.Rc.addMutateResponse(p.Out, resourcePath, response)
|
||||
if printMutatedRes && p.PrintPatchResource {
|
||||
yamlEncodedResource, err := yamlv2.Marshal(response.PatchedResource.Object)
|
||||
if err != nil {
|
||||
|
@ -316,16 +318,16 @@ func (p *PolicyProcessor) processMutateEngineResponse(response engineapi.EngineR
|
|||
mutatedResource := string(yamlEncodedResource) + string("\n---")
|
||||
if len(strings.TrimSpace(mutatedResource)) > 0 {
|
||||
if !p.Stdin {
|
||||
fmt.Printf("\nmutate policy %s applied to %s:", response.Policy().GetName(), resourcePath)
|
||||
fmt.Fprintf(p.Out, "\nmutate policy %s applied to %s:", response.Policy().GetName(), resourcePath)
|
||||
}
|
||||
fmt.Printf("\n" + mutatedResource + "\n")
|
||||
fmt.Fprintf(p.Out, "\n"+mutatedResource+"\n")
|
||||
}
|
||||
} else {
|
||||
err := p.printMutatedOutput(string(yamlEncodedResource))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to print mutated result (%w)", err)
|
||||
}
|
||||
fmt.Printf("\n\nMutation:\nMutation has been applied successfully. Check the files.")
|
||||
fmt.Fprintf(p.Out, "\n\nMutation:\nMutation has been applied successfully. Check the files.")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
package processor
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/resource"
|
||||
|
@ -112,6 +113,7 @@ func Test_NamespaceSelector(t *testing.T) {
|
|||
UserInfo: nil,
|
||||
NamespaceSelectorMap: tc.namespaceSelectorMap,
|
||||
Rc: rc,
|
||||
Out: os.Stdout,
|
||||
}
|
||||
processor.ApplyPoliciesOnResource()
|
||||
assert.Equal(t, int64(rc.Pass()), int64(tc.result.pass))
|
||||
|
|
|
@ -2,6 +2,7 @@ package processor
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/policy/annotations"
|
||||
|
@ -74,7 +75,7 @@ func (rc *ResultCounts) addEngineResponse(auditWarn bool, response engineapi.Eng
|
|||
}
|
||||
}
|
||||
|
||||
func (rc *ResultCounts) addGenerateResponse(auditWarn bool, resPath string, response engineapi.EngineResponse) {
|
||||
func (rc *ResultCounts) addGenerateResponse(out io.Writer, auditWarn bool, resPath string, response engineapi.EngineResponse) {
|
||||
genericPolicy := response.Policy()
|
||||
if polType := genericPolicy.GetType(); polType == engineapi.ValidatingAdmissionPolicyType {
|
||||
return
|
||||
|
@ -90,10 +91,10 @@ func (rc *ResultCounts) addGenerateResponse(auditWarn bool, resPath string, resp
|
|||
rc.pass++
|
||||
} else {
|
||||
if printCount < 1 {
|
||||
fmt.Println("\ninvalid resource", "policy", policy.GetName(), "resource", resPath)
|
||||
fmt.Fprintln(out, "\ninvalid resource", "policy", policy.GetName(), "resource", resPath)
|
||||
printCount++
|
||||
}
|
||||
fmt.Printf("%d. %s - %s\n", i+1, ruleResponse.Name(), ruleResponse.Message())
|
||||
fmt.Fprintf(out, "%d. %s - %s\n", i+1, ruleResponse.Name(), ruleResponse.Message())
|
||||
if auditWarn && response.GetValidationFailureAction().Audit() {
|
||||
rc.warn++
|
||||
} else {
|
||||
|
@ -109,7 +110,7 @@ func (rc *ResultCounts) addGenerateResponse(auditWarn bool, resPath string, resp
|
|||
}
|
||||
}
|
||||
|
||||
func (rc *ResultCounts) addMutateResponse(resourcePath string, response engineapi.EngineResponse) bool {
|
||||
func (rc *ResultCounts) addMutateResponse(out io.Writer, resourcePath string, response engineapi.EngineResponse) bool {
|
||||
genericPolicy := response.Policy()
|
||||
if polType := genericPolicy.GetType(); polType == engineapi.ValidatingAdmissionPolicyType {
|
||||
return false
|
||||
|
@ -135,17 +136,17 @@ func (rc *ResultCounts) addMutateResponse(resourcePath string, response engineap
|
|||
rc.pass++
|
||||
printMutatedRes = true
|
||||
} else if mutateResponseRule.Status() == engineapi.RuleStatusSkip {
|
||||
fmt.Printf("\nskipped mutate policy %s -> resource %s", policy.GetName(), resourcePath)
|
||||
fmt.Fprintf(out, "\nskipped mutate policy %s -> resource %s", policy.GetName(), resourcePath)
|
||||
rc.skip++
|
||||
} else if mutateResponseRule.Status() == engineapi.RuleStatusError {
|
||||
fmt.Printf("\nerror while applying mutate policy %s -> resource %s\nerror: %s", policy.GetName(), resourcePath, mutateResponseRule.Message())
|
||||
fmt.Fprintf(out, "\nerror while applying mutate policy %s -> resource %s\nerror: %s", policy.GetName(), resourcePath, mutateResponseRule.Message())
|
||||
rc.err++
|
||||
} else {
|
||||
if printCount < 1 {
|
||||
fmt.Printf("\nfailed to apply mutate policy %s -> resource %s", policy.GetName(), resourcePath)
|
||||
fmt.Fprintf(out, "\nfailed to apply mutate policy %s -> resource %s", policy.GetName(), resourcePath)
|
||||
printCount++
|
||||
}
|
||||
fmt.Printf("%d. %s - %s \n", i+1, mutateResponseRule.Name(), mutateResponseRule.Message())
|
||||
fmt.Fprintf(out, "%d. %s - %s \n", i+1, mutateResponseRule.Name(), mutateResponseRule.Message())
|
||||
rc.fail++
|
||||
}
|
||||
continue
|
||||
|
|
|
@ -3,6 +3,7 @@ package common
|
|||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
@ -24,6 +25,7 @@ import (
|
|||
|
||||
// GetResourceAccordingToResourcePath - get resources according to the resource path
|
||||
func GetResourceAccordingToResourcePath(
|
||||
out io.Writer,
|
||||
fs billy.Filesystem,
|
||||
resourcePaths []string,
|
||||
cluster bool,
|
||||
|
@ -35,7 +37,7 @@ func GetResourceAccordingToResourcePath(
|
|||
policyResourcePath string,
|
||||
) (resources []*unstructured.Unstructured, err error) {
|
||||
if fs != nil {
|
||||
resources, err = GetResourcesWithTest(fs, policies, resourcePaths, policyResourcePath)
|
||||
resources, err = GetResourcesWithTest(out, fs, policies, resourcePaths, policyResourcePath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to extract the resources (%w)", err)
|
||||
}
|
||||
|
@ -76,7 +78,7 @@ func GetResourceAccordingToResourcePath(
|
|||
}
|
||||
}
|
||||
|
||||
resources, err = GetResources(policies, validatingAdmissionPolicies, resourcePaths, dClient, cluster, namespace, policyReport)
|
||||
resources, err = GetResources(out, policies, validatingAdmissionPolicies, resourcePaths, dClient, cluster, namespace, policyReport)
|
||||
if err != nil {
|
||||
return resources, err
|
||||
}
|
||||
|
@ -85,13 +87,13 @@ func GetResourceAccordingToResourcePath(
|
|||
return resources, err
|
||||
}
|
||||
|
||||
func GetKindsFromPolicy(policy kyvernov1.PolicyInterface, subresources []valuesapi.Subresource, dClient dclient.Interface) sets.Set[string] {
|
||||
func GetKindsFromPolicy(out io.Writer, policy kyvernov1.PolicyInterface, subresources []valuesapi.Subresource, dClient dclient.Interface) sets.Set[string] {
|
||||
knownkinds := sets.New[string]()
|
||||
for _, rule := range autogen.ComputeRules(policy) {
|
||||
for _, kind := range rule.MatchResources.ResourceDescription.Kinds {
|
||||
k, err := getKind(kind, subresources, dClient)
|
||||
if err != nil {
|
||||
fmt.Printf("Error: %s", err.Error())
|
||||
fmt.Fprintf(out, "Error: %s", err.Error())
|
||||
continue
|
||||
}
|
||||
knownkinds.Insert(k)
|
||||
|
@ -99,7 +101,7 @@ func GetKindsFromPolicy(policy kyvernov1.PolicyInterface, subresources []valuesa
|
|||
for _, kind := range rule.ExcludeResources.ResourceDescription.Kinds {
|
||||
k, err := getKind(kind, subresources, dClient)
|
||||
if err != nil {
|
||||
fmt.Printf("Error: %s", err.Error())
|
||||
fmt.Fprintf(out, "Error: %s", err.Error())
|
||||
continue
|
||||
}
|
||||
knownkinds.Insert(k)
|
||||
|
|
|
@ -27,8 +27,14 @@ import (
|
|||
// - local paths to resources, if given
|
||||
// - the k8s cluster, if given
|
||||
func GetResources(
|
||||
policies []kyvernov1.PolicyInterface, validatingAdmissionPolicies []v1alpha1.ValidatingAdmissionPolicy, resourcePaths []string, dClient dclient.Interface, cluster bool,
|
||||
namespace string, policyReport bool,
|
||||
out io.Writer,
|
||||
policies []kyvernov1.PolicyInterface,
|
||||
validatingAdmissionPolicies []v1alpha1.ValidatingAdmissionPolicy,
|
||||
resourcePaths []string,
|
||||
dClient dclient.Interface,
|
||||
cluster bool,
|
||||
namespace string,
|
||||
policyReport bool,
|
||||
) ([]*unstructured.Unstructured, error) {
|
||||
resources := make([]*unstructured.Unstructured, 0)
|
||||
var err error
|
||||
|
@ -39,7 +45,7 @@ func GetResources(
|
|||
policies: policies,
|
||||
}
|
||||
|
||||
resources, err = matchedResources.FetchResourcesFromPolicy(resourcePaths, dClient, namespace, policyReport)
|
||||
resources, err = matchedResources.FetchResourcesFromPolicy(out, resourcePaths, dClient, namespace, policyReport)
|
||||
if err != nil {
|
||||
return resources, err
|
||||
}
|
||||
|
@ -50,13 +56,13 @@ func GetResources(
|
|||
policies: validatingAdmissionPolicies,
|
||||
}
|
||||
|
||||
resources, err = matchedResources.FetchResourcesFromPolicy(resourcePaths, dClient, namespace, policyReport)
|
||||
resources, err = matchedResources.FetchResourcesFromPolicy(out, resourcePaths, dClient, namespace, policyReport)
|
||||
if err != nil {
|
||||
return resources, err
|
||||
}
|
||||
}
|
||||
} else if len(resourcePaths) > 0 {
|
||||
resources, err = whenClusterIsFalse(resourcePaths, policyReport)
|
||||
resources, err = whenClusterIsFalse(out, resourcePaths, policyReport)
|
||||
if err != nil {
|
||||
return resources, err
|
||||
}
|
||||
|
@ -64,9 +70,9 @@ func GetResources(
|
|||
return resources, err
|
||||
}
|
||||
|
||||
func whenClusterIsTrue(resourceTypes []schema.GroupVersionKind, subresourceMap map[schema.GroupVersionKind]valuesapi.Subresource, dClient dclient.Interface, namespace string, resourcePaths []string, policyReport bool) ([]*unstructured.Unstructured, error) {
|
||||
func whenClusterIsTrue(out io.Writer, resourceTypes []schema.GroupVersionKind, subresourceMap map[schema.GroupVersionKind]valuesapi.Subresource, dClient dclient.Interface, namespace string, resourcePaths []string, policyReport bool) ([]*unstructured.Unstructured, error) {
|
||||
resources := make([]*unstructured.Unstructured, 0)
|
||||
resourceMap, err := getResourcesOfTypeFromCluster(resourceTypes, subresourceMap, dClient, namespace)
|
||||
resourceMap, err := getResourcesOfTypeFromCluster(out, resourceTypes, subresourceMap, dClient, namespace)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
@ -87,7 +93,7 @@ func whenClusterIsTrue(resourceTypes []schema.GroupVersionKind, subresourceMap m
|
|||
if policyReport {
|
||||
log.Log.V(3).Info(fmt.Sprintf("%s not found in cluster", resourcePath))
|
||||
} else {
|
||||
fmt.Printf("\n----------------------------------------------------------------------\nresource %s not found in cluster\n----------------------------------------------------------------------\n", resourcePath)
|
||||
fmt.Fprintf(out, "\n----------------------------------------------------------------------\nresource %s not found in cluster\n----------------------------------------------------------------------\n", resourcePath)
|
||||
}
|
||||
return nil, fmt.Errorf("%s not found in cluster", resourcePath)
|
||||
}
|
||||
|
@ -96,7 +102,7 @@ func whenClusterIsTrue(resourceTypes []schema.GroupVersionKind, subresourceMap m
|
|||
return resources, nil
|
||||
}
|
||||
|
||||
func whenClusterIsFalse(resourcePaths []string, policyReport bool) ([]*unstructured.Unstructured, error) {
|
||||
func whenClusterIsFalse(out io.Writer, resourcePaths []string, policyReport bool) ([]*unstructured.Unstructured, error) {
|
||||
resources := make([]*unstructured.Unstructured, 0)
|
||||
for _, resourcePath := range resourcePaths {
|
||||
resourceBytes, err := resource.GetFileBytes(resourcePath)
|
||||
|
@ -104,7 +110,7 @@ func whenClusterIsFalse(resourcePaths []string, policyReport bool) ([]*unstructu
|
|||
if policyReport {
|
||||
log.Log.V(3).Info(fmt.Sprintf("failed to load resources: %s.", resourcePath), "error", err)
|
||||
} else {
|
||||
fmt.Printf("\n----------------------------------------------------------------------\nfailed to load resources: %s. \nerror: %s\n----------------------------------------------------------------------\n", resourcePath, err)
|
||||
fmt.Fprintf(out, "\n----------------------------------------------------------------------\nfailed to load resources: %s. \nerror: %s\n----------------------------------------------------------------------\n", resourcePath, err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
@ -120,7 +126,7 @@ func whenClusterIsFalse(resourcePaths []string, policyReport bool) ([]*unstructu
|
|||
}
|
||||
|
||||
// GetResourcesWithTest with gets matched resources by the given policies
|
||||
func GetResourcesWithTest(fs billy.Filesystem, policies []kyvernov1.PolicyInterface, resourcePaths []string, policyResourcePath string) ([]*unstructured.Unstructured, error) {
|
||||
func GetResourcesWithTest(out io.Writer, fs billy.Filesystem, policies []kyvernov1.PolicyInterface, resourcePaths []string, policyResourcePath string) ([]*unstructured.Unstructured, error) {
|
||||
resources := make([]*unstructured.Unstructured, 0)
|
||||
resourceTypesMap := make(map[string]bool)
|
||||
for _, policy := range policies {
|
||||
|
@ -137,7 +143,7 @@ func GetResourcesWithTest(fs billy.Filesystem, policies []kyvernov1.PolicyInterf
|
|||
if fs != nil {
|
||||
filep, err := fs.Open(filepath.Join(policyResourcePath, resourcePath))
|
||||
if err != nil {
|
||||
fmt.Printf("Unable to open resource file: %s. error: %s", resourcePath, err)
|
||||
fmt.Fprintf(out, "Unable to open resource file: %s. error: %s", resourcePath, err)
|
||||
continue
|
||||
}
|
||||
resourceBytes, _ = io.ReadAll(filep)
|
||||
|
@ -145,7 +151,7 @@ func GetResourcesWithTest(fs billy.Filesystem, policies []kyvernov1.PolicyInterf
|
|||
resourceBytes, err = resource.GetFileBytes(resourcePath)
|
||||
}
|
||||
if err != nil {
|
||||
fmt.Printf("\n----------------------------------------------------------------------\nfailed to load resources: %s. \nerror: %s\n----------------------------------------------------------------------\n", resourcePath, err)
|
||||
fmt.Fprintf(out, "\n----------------------------------------------------------------------\nfailed to load resources: %s. \nerror: %s\n----------------------------------------------------------------------\n", resourcePath, err)
|
||||
continue
|
||||
}
|
||||
|
||||
|
@ -160,7 +166,7 @@ func GetResourcesWithTest(fs billy.Filesystem, policies []kyvernov1.PolicyInterf
|
|||
return resources, nil
|
||||
}
|
||||
|
||||
func getResourcesOfTypeFromCluster(resourceTypes []schema.GroupVersionKind, subresourceMap map[schema.GroupVersionKind]valuesapi.Subresource, dClient dclient.Interface, namespace string) (map[string]*unstructured.Unstructured, error) {
|
||||
func getResourcesOfTypeFromCluster(out io.Writer, resourceTypes []schema.GroupVersionKind, subresourceMap map[schema.GroupVersionKind]valuesapi.Subresource, dClient dclient.Interface, namespace string) (map[string]*unstructured.Unstructured, error) {
|
||||
r := make(map[string]*unstructured.Unstructured)
|
||||
for _, kind := range resourceTypes {
|
||||
resourceList, err := dClient.ListResource(context.TODO(), kind.GroupVersion().String(), kind.Kind, namespace, nil)
|
||||
|
@ -192,7 +198,7 @@ func getResourcesOfTypeFromCluster(resourceTypes []schema.GroupVersionKind, subr
|
|||
subresourceName := strings.Split(subresource.APIResource.Name, "/")[1]
|
||||
resource, err := dClient.GetResource(context.TODO(), parentGV.String(), subresource.ParentResource.Kind, namespace, parentResourceName, subresourceName)
|
||||
if err != nil {
|
||||
fmt.Printf("Error: %s", err.Error())
|
||||
fmt.Fprintf(out, "Error: %s", err.Error())
|
||||
continue
|
||||
}
|
||||
key := subresource.APIResource.Kind + "-" + resource.GetNamespace() + "-" + resource.GetName()
|
||||
|
|
|
@ -1,6 +1,8 @@
|
|||
package common
|
||||
|
||||
import (
|
||||
"io"
|
||||
|
||||
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
||||
valuesapi "github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/apis/values"
|
||||
"github.com/kyverno/kyverno/pkg/autogen"
|
||||
|
@ -13,7 +15,7 @@ type KyvernoResources struct {
|
|||
policies []kyvernov1.PolicyInterface
|
||||
}
|
||||
|
||||
func (r *KyvernoResources) FetchResourcesFromPolicy(resourcePaths []string, dClient dclient.Interface, namespace string, policyReport bool) ([]*unstructured.Unstructured, error) {
|
||||
func (r *KyvernoResources) FetchResourcesFromPolicy(out io.Writer, resourcePaths []string, dClient dclient.Interface, namespace string, policyReport bool) ([]*unstructured.Unstructured, error) {
|
||||
var resources []*unstructured.Unstructured
|
||||
var err error
|
||||
|
||||
|
@ -35,7 +37,7 @@ func (r *KyvernoResources) FetchResourcesFromPolicy(resourcePaths []string, dCli
|
|||
resourceTypes = append(resourceTypes, kind)
|
||||
}
|
||||
|
||||
resources, err = whenClusterIsTrue(resourceTypes, subresourceMap, dClient, namespace, resourcePaths, policyReport)
|
||||
resources, err = whenClusterIsTrue(out, resourceTypes, subresourceMap, dClient, namespace, resourcePaths, policyReport)
|
||||
|
||||
return resources, err
|
||||
}
|
||||
|
|
|
@ -1,6 +1,8 @@
|
|||
package common
|
||||
|
||||
import (
|
||||
"io"
|
||||
|
||||
valuesapi "github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/apis/values"
|
||||
"github.com/kyverno/kyverno/pkg/clients/dclient"
|
||||
"k8s.io/api/admissionregistration/v1alpha1"
|
||||
|
@ -12,7 +14,7 @@ type ValidatingAdmissionResources struct {
|
|||
policies []v1alpha1.ValidatingAdmissionPolicy
|
||||
}
|
||||
|
||||
func (r *ValidatingAdmissionResources) FetchResourcesFromPolicy(resourcePaths []string, dClient dclient.Interface, namespace string, policyReport bool) ([]*unstructured.Unstructured, error) {
|
||||
func (r *ValidatingAdmissionResources) FetchResourcesFromPolicy(out io.Writer, resourcePaths []string, dClient dclient.Interface, namespace string, policyReport bool) ([]*unstructured.Unstructured, error) {
|
||||
var resources []*unstructured.Unstructured
|
||||
var err error
|
||||
|
||||
|
@ -35,6 +37,6 @@ func (r *ValidatingAdmissionResources) FetchResourcesFromPolicy(resourcePaths []
|
|||
resourceTypes = append(resourceTypes, kind)
|
||||
}
|
||||
|
||||
resources, err = whenClusterIsTrue(resourceTypes, subresourceMap, dClient, namespace, resourcePaths, policyReport)
|
||||
resources, err = whenClusterIsTrue(out, resourceTypes, subresourceMap, dClient, namespace, resourcePaths, policyReport)
|
||||
return resources, err
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue