1
0
Fork 0
mirror of https://github.com/kyverno/kyverno.git synced 2025-03-28 02:18:15 +00:00

feat: add toggle package for feature flags (#3419)

Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com>

Co-authored-by: shuting <shuting@nirmata.com>
This commit is contained in:
Charles-Edouard Brétéché 2022-03-18 17:16:42 +01:00 committed by GitHub
parent 0c8e8c1212
commit 4136566bd9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 29 additions and 31 deletions

View file

@ -38,6 +38,7 @@ import (
"github.com/kyverno/kyverno/pkg/resourcecache"
"github.com/kyverno/kyverno/pkg/signal"
ktls "github.com/kyverno/kyverno/pkg/tls"
"github.com/kyverno/kyverno/pkg/toggle"
"github.com/kyverno/kyverno/pkg/utils"
"github.com/kyverno/kyverno/pkg/version"
"github.com/kyverno/kyverno/pkg/webhookconfig"
@ -62,7 +63,6 @@ var (
profile bool
disableMetricsExport bool
autoUpdateWebhooks bool
autogenInternals bool
policyControllerResyncPeriod time.Duration
imagePullSecrets string
imageSignatureRepository string
@ -103,7 +103,7 @@ func main() {
flag.BoolVar(&autoUpdateWebhooks, "autoUpdateWebhooks", true, "Set this flag to 'false' to disable auto-configuration of the webhook.")
flag.Float64Var(&clientRateLimitQPS, "clientRateLimitQPS", 0, "Configure the maximum QPS to the master from Kyverno. Uses the client default if zero.")
flag.IntVar(&clientRateLimitBurst, "clientRateLimitBurst", 0, "Configure the maximum burst for throttle. Uses the client default if zero.")
flag.BoolVar(&autogenInternals, "autogenInternals", false, "Enables autogen internal policies. When this is 'true' policy rules should not be mutated.")
flag.BoolVar(&toggle.AutogenInternals, "autogenInternals", toggle.DefaultAutogenInternals, "Enables autogen internal policies. When this is 'true' policy rules should not be mutated.")
flag.DurationVar(&webhookRegistrationTimeout, "webhookRegistrationTimeout", 120*time.Second, "Timeout for webhook registration, e.g., 30s, 1m, 5m.")
if err := flag.Set("v", "2"); err != nil {
@ -320,7 +320,6 @@ func main() {
log.Log.WithName("PolicyController"),
policyControllerResyncPeriod,
promConfig,
autogenInternals,
)
if err != nil {
@ -478,7 +477,6 @@ func main() {
openAPIController,
grc,
promConfig,
autogenInternals,
)
if err != nil {

View file

@ -15,6 +15,7 @@ import (
"github.com/kyverno/kyverno/pkg/openapi"
policy2 "github.com/kyverno/kyverno/pkg/policy"
"github.com/kyverno/kyverno/pkg/policyreport"
"github.com/kyverno/kyverno/pkg/toggle"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/cli-runtime/pkg/genericclioptions"
@ -107,7 +108,6 @@ func Command() *cobra.Command {
var resourcePaths []string
var cluster, policyReport, stdin, registryAccess bool
var mutateLogPath, variablesString, valuesFile, namespace string
var autogenInternals bool
cmd = &cobra.Command{
Use: "apply",
Short: "applies policies on resources",
@ -122,7 +122,7 @@ func Command() *cobra.Command {
}
}()
rc, resources, skipInvalidPolicies, pvInfos, err := applyCommandHelper(resourcePaths, cluster, policyReport, mutateLogPath, variablesString, valuesFile, namespace, policyPaths, autogenInternals, stdin, registryAccess)
rc, resources, skipInvalidPolicies, pvInfos, err := applyCommandHelper(resourcePaths, cluster, policyReport, mutateLogPath, variablesString, valuesFile, namespace, policyPaths, stdin, registryAccess)
if err != nil {
return err
}
@ -141,13 +141,13 @@ func Command() *cobra.Command {
cmd.Flags().BoolVarP(&policyReport, "policy-report", "", false, "Generates policy report when passed (default policyviolation r")
cmd.Flags().StringVarP(&namespace, "namespace", "n", "", "Optional Policy parameter passed with cluster flag")
cmd.Flags().BoolVarP(&stdin, "stdin", "i", false, "Optional mutate policy parameter to pipe directly through to kubectl")
cmd.Flags().BoolVarP(&autogenInternals, "autogenInternals", "", false, "Use autogen internals")
cmd.Flags().BoolVarP(&toggle.AutogenInternals, "autogenInternals", "", toggle.DefaultAutogenInternals, "Use autogen internals")
cmd.Flags().BoolVarP(&registryAccess, "registry", "", false, "If set to true, access the image registry using local docker credentials to populate external data")
return cmd
}
func applyCommandHelper(resourcePaths []string, cluster bool, policyReport bool, mutateLogPath string,
variablesString string, valuesFile string, namespace string, policyPaths []string, autogenInternals bool, stdin bool, registryAccess bool) (rc *common.ResultCounts, resources []*unstructured.Unstructured, skipInvalidPolicies SkippedInvalidPolicies, pvInfos []policyreport.Info, err error) {
variablesString string, valuesFile string, namespace string, policyPaths []string, stdin bool, registryAccess bool) (rc *common.ResultCounts, resources []*unstructured.Unstructured, skipInvalidPolicies SkippedInvalidPolicies, pvInfos []policyreport.Info, err error) {
store.SetMock(true)
store.SetRegistryAccess(registryAccess)
kubernetesConfig := genericclioptions.NewConfigFlags(true)
@ -224,7 +224,7 @@ func applyCommandHelper(resourcePaths []string, cluster bool, policyReport bool,
}
}
mutatedPolicies, err := common.MutatePolicies(policies, autogenInternals)
mutatedPolicies, err := common.MutatePolicies(policies)
if err != nil {
if !sanitizederror.IsErrorSanitized(err) {
return rc, resources, skipInvalidPolicies, pvInfos, sanitizederror.NewWithError("failed to mutate policy", err)

View file

@ -72,7 +72,7 @@ func Test_Apply(t *testing.T) {
}
for _, tc := range testcases {
_, _, _, info, _ := applyCommandHelper(tc.ResourcePaths, false, true, "", "", "", "", tc.PolicyPaths, false, false, false)
_, _, _, info, _ := applyCommandHelper(tc.ResourcePaths, false, true, "", "", "", "", tc.PolicyPaths, false, false)
resps := buildPolicyReports(info)
for i, resp := range resps {
compareSummary(tc.expectedPolicyReports[i].Summary, resp.UnstructuredContent()["summary"].(map[string]interface{}))

View file

@ -14,6 +14,7 @@ import (
"strings"
"github.com/kyverno/kyverno/pkg/engine/variables"
"github.com/kyverno/kyverno/pkg/toggle"
jsonpatch "github.com/evanphx/json-patch/v5"
"github.com/go-git/go-billy/v5"
@ -438,12 +439,12 @@ func GetVariable(variablesString, valuesFile string, fs billy.Filesystem, isGit
}
// MutatePolicies - function to apply mutation on policies
func MutatePolicies(policies []*v1.ClusterPolicy, autogenInternals bool) ([]*v1.ClusterPolicy, error) {
func MutatePolicies(policies []*v1.ClusterPolicy) ([]*v1.ClusterPolicy, error) {
newPolicies := make([]*v1.ClusterPolicy, 0)
logger := log.Log.WithName("apply")
for _, policy := range policies {
p, err := MutatePolicy(policy, autogenInternals, logger)
p, err := MutatePolicy(policy, toggle.AutogenInternals, logger)
if err != nil {
if !sanitizederror.IsErrorSanitized(err) {
return nil, sanitizederror.NewWithError("failed to mutate policy.", err)

View file

@ -801,7 +801,7 @@ func applyPoliciesFromPath(fs billy.Filesystem, policyBytes []byte, isGit bool,
}
policies = filteredPolicies
mutatedPolicies, err := common.MutatePolicies(policies, false)
mutatedPolicies, err := common.MutatePolicies(policies)
if err != nil {
if !sanitizederror.IsErrorSanitized(err) {
return sanitizederror.NewWithError("failed to mutate policy", err)

View file

@ -13,6 +13,7 @@ import (
sanitizederror "github.com/kyverno/kyverno/pkg/kyverno/sanitizedError"
"github.com/kyverno/kyverno/pkg/openapi"
policy2 "github.com/kyverno/kyverno/pkg/policy"
"github.com/kyverno/kyverno/pkg/toggle"
"github.com/kyverno/kyverno/pkg/utils"
"github.com/spf13/cobra"
"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
@ -27,7 +28,6 @@ import (
func Command() *cobra.Command {
var outputType string
var crdPaths []string
var autogenInternals bool
cmd := &cobra.Command{
Use: "validate",
Short: "Validates kyverno policies",
@ -79,7 +79,7 @@ func Command() *cobra.Command {
}
}
err = validatePolicies(policies, autogenInternals, v1crd, openAPIController, outputType)
err = validatePolicies(policies, v1crd, openAPIController, outputType)
if err != nil {
return sanitizederror.NewWithError("failed to validate policies", err)
}
@ -88,7 +88,7 @@ func Command() *cobra.Command {
}
cmd.Flags().StringVarP(&outputType, "output", "o", "", "Prints the mutated policy in yaml or json format")
cmd.Flags().StringArrayVarP(&crdPaths, "crd", "c", []string{}, "Path to CRD files")
cmd.Flags().BoolVarP(&autogenInternals, "autogenInternals", "", false, "Use autogen internals")
cmd.Flags().BoolVarP(&toggle.AutogenInternals, "autogenInternals", "", toggle.DefaultAutogenInternals, "Use autogen internals")
return cmd
}
@ -155,7 +155,7 @@ func validatePolicyAccordingToPolicyCRD(policy *v1.ClusterPolicy, v1crd apiexten
return
}
func validatePolicies(policies []*v1.ClusterPolicy, autogenInternals bool, v1crd apiextensions.CustomResourceDefinitionSpec, openAPIController *openapi.Controller, outputType string) error {
func validatePolicies(policies []*v1.ClusterPolicy, v1crd apiextensions.CustomResourceDefinitionSpec, openAPIController *openapi.Controller, outputType string) error {
invalidPolicyFound := false
for _, policy := range policies {
err, errorList := validatePolicyAccordingToPolicyCRD(policy, v1crd)
@ -180,7 +180,7 @@ func validatePolicies(policies []*v1.ClusterPolicy, autogenInternals bool, v1crd
fmt.Printf("Policy %s is valid.\n\n", policy.Name)
if outputType != "" {
logger := log.Log.WithName("validate")
p, err := common.MutatePolicy(policy, autogenInternals, logger)
p, err := common.MutatePolicy(policy, toggle.AutogenInternals, logger)
if err != nil {
if !sanitizederror.IsErrorSanitized(err) {
return sanitizederror.NewWithError("failed to mutate policy.", err)

View file

@ -23,6 +23,7 @@ import (
"github.com/kyverno/kyverno/pkg/kyverno/common"
"github.com/kyverno/kyverno/pkg/metrics"
"github.com/kyverno/kyverno/pkg/policyreport"
"github.com/kyverno/kyverno/pkg/toggle"
"github.com/kyverno/kyverno/pkg/utils"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
@ -103,8 +104,6 @@ type PolicyController struct {
log logr.Logger
promConfig *metrics.PromConfig
autogenInternals bool
}
// NewPolicyController create a new PolicyController
@ -123,7 +122,6 @@ func NewPolicyController(
log logr.Logger,
reconcilePeriod time.Duration,
promConfig *metrics.PromConfig,
autogenInternals bool,
) (*PolicyController, error) {
// Event broad caster
@ -149,7 +147,6 @@ func NewPolicyController(
reconcilePeriod: reconcilePeriod,
promConfig: promConfig,
log: log,
autogenInternals: autogenInternals,
}
pc.pLister = pInformer.Lister()
@ -198,7 +195,7 @@ func (pc *PolicyController) addPolicy(obj interface{}) {
go pc.registerPolicyChangesMetricAddPolicy(logger, p)
if p.Spec.Background == nil || p.Spec.ValidationFailureAction == "" || missingAutoGenRules(p, logger) {
pol, _ := common.MutatePolicy(p, pc.autogenInternals, logger)
pol, _ := common.MutatePolicy(p, toggle.AutogenInternals, logger)
pol.SetGroupVersionKind(schema.GroupVersionKind{Group: "kyverno.io", Version: "v1", Kind: "ClusterPolicy"})
_, err := pc.client.UpdateResource("kyverno.io/v1", "ClusterPolicy", "", pol, false)
if err != nil {
@ -225,7 +222,7 @@ func (pc *PolicyController) updatePolicy(old, cur interface{}) {
go pc.registerPolicyChangesMetricUpdatePolicy(logger, oldP, curP)
if curP.Spec.Background == nil || curP.Spec.ValidationFailureAction == "" || missingAutoGenRules(curP, logger) {
pol, _ := common.MutatePolicy(curP, pc.autogenInternals, logger)
pol, _ := common.MutatePolicy(curP, toggle.AutogenInternals, logger)
pol.SetGroupVersionKind(schema.GroupVersionKind{Group: "kyverno.io", Version: "v1", Kind: "ClusterPolicy"})
_, err := pc.client.UpdateResource("kyverno.io/v1", "ClusterPolicy", "", pol, false)
if err != nil {
@ -297,7 +294,7 @@ func (pc *PolicyController) addNsPolicy(obj interface{}) {
pol := ConvertPolicyToClusterPolicy(p)
if pol.Spec.Background == nil || pol.Spec.ValidationFailureAction == "" || missingAutoGenRules(pol, logger) {
nsPol, _ := common.MutatePolicy(pol, pc.autogenInternals, logger)
nsPol, _ := common.MutatePolicy(pol, toggle.AutogenInternals, logger)
nsPol.SetGroupVersionKind(schema.GroupVersionKind{Group: "kyverno.io", Version: "v1", Kind: "Policy"})
_, err := pc.client.UpdateResource("kyverno.io/v1", "Policy", p.Namespace, nsPol, false)
if err != nil {
@ -324,7 +321,7 @@ func (pc *PolicyController) updateNsPolicy(old, cur interface{}) {
ncurP := ConvertPolicyToClusterPolicy(curP)
if ncurP.Spec.Background == nil || ncurP.Spec.ValidationFailureAction == "" || missingAutoGenRules(ncurP, logger) {
nsPol, _ := common.MutatePolicy(ncurP, pc.autogenInternals, logger)
nsPol, _ := common.MutatePolicy(ncurP, toggle.AutogenInternals, logger)
nsPol.SetGroupVersionKind(schema.GroupVersionKind{Group: "kyverno.io", Version: "v1", Kind: "Policy"})
_, err := pc.client.UpdateResource("kyverno.io/v1", "Policy", ncurP.GetNamespace(), nsPol, false)
if err != nil {

5
pkg/toggle/toggle.go Normal file
View file

@ -0,0 +1,5 @@
package toggle
const DefaultAutogenInternals = false
var AutogenInternals = DefaultAutogenInternals

View file

@ -10,6 +10,7 @@ import (
logr "github.com/go-logr/logr"
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
"github.com/kyverno/kyverno/pkg/policymutation"
"github.com/kyverno/kyverno/pkg/toggle"
v1beta1 "k8s.io/api/admission/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
@ -42,7 +43,7 @@ func (ws *WebhookServer) policyMutation(request *v1beta1.AdmissionRequest) *v1be
defer logger.V(3).Info("finished policy change mutation", "time", time.Since(startTime).String())
// Generate JSON Patches for defaults
patches, updateMsgs := policymutation.GenerateJSONPatchesForDefaults(policy, ws.autogenInternals, logger)
patches, updateMsgs := policymutation.GenerateJSONPatchesForDefaults(policy, toggle.AutogenInternals, logger)
if len(patches) != 0 {
patchType := v1beta1.PatchTypeJSONPatch
return &v1beta1.AdmissionResponse{

View file

@ -124,8 +124,6 @@ type WebhookServer struct {
grController *generate.Controller
promConfig *metrics.PromConfig
autogenInternals bool
}
// NewWebhookServer creates new instance of WebhookServer accordingly to given configuration
@ -154,7 +152,6 @@ func NewWebhookServer(
openAPIController *openapi.Controller,
grc *generate.Controller,
promConfig *metrics.PromConfig,
autogenInternals bool,
) (*WebhookServer, error) {
if tlsPair == nil {
@ -199,7 +196,6 @@ func NewWebhookServer(
log: log,
openAPIController: openAPIController,
promConfig: promConfig,
autogenInternals: autogenInternals,
}
mux := httprouter.New()