diff --git a/.golangci.yaml b/.golangci.yaml index 0c613a22763..d98952d7bb1 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -22,14 +22,16 @@ linters: enable: - deadcode - errcheck - - ineffassign - gocritic - goconst + - godot - gofmt + - gofumpt - goimports - gosec - gosimple - govet + - ineffassign - misspell - revive # replacement for golint - staticcheck @@ -37,3 +39,4 @@ linters: - typecheck - unused - varcheck + - whitespace diff --git a/apis/apis.go b/apis/apis.go index 15ccbf9c8a5..dd010023d08 100644 --- a/apis/apis.go +++ b/apis/apis.go @@ -23,10 +23,10 @@ import ( "k8s.io/apimachinery/pkg/runtime" ) -// AddToSchemes may be used to add all resources defined in the project to a Scheme +// AddToSchemes may be used to add all resources defined in the project to a Scheme. var AddToSchemes runtime.SchemeBuilder -// AddToScheme adds all Resources to the Scheme +// AddToScheme adds all Resources to the Scheme. func AddToScheme(s *runtime.Scheme) error { return AddToSchemes.AddToScheme(s) } diff --git a/apis/config/v1alpha1/config_types.go b/apis/config/v1alpha1/config_types.go index a12bae5fa7b..4042068de6c 100644 --- a/apis/config/v1alpha1/config_types.go +++ b/apis/config/v1alpha1/config_types.go @@ -20,7 +20,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) -// ConfigSpec defines the desired state of Config +// ConfigSpec defines the desired state of Config. type ConfigSpec struct { // Important: Run "make" to regenerate code after modifying this file @@ -71,9 +71,8 @@ type ReadinessSpec struct { StatsEnabled bool `json:"statsEnabled,omitempty"` } -// ConfigStatus defines the observed state of Config -type ConfigStatus struct { - // Important: Run "make" to regenerate code after modifying this file +// ConfigStatus defines the observed state of Config. +type ConfigStatus struct { // Important: Run "make" to regenerate code after modifying this file } type GVK struct { @@ -85,7 +84,7 @@ type GVK struct { // +kubebuilder:resource:scope=Namespaced // +kubebuilder:object:root=true -// Config is the Schema for the configs API +// Config is the Schema for the configs API. type Config struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` @@ -96,7 +95,7 @@ type Config struct { // +kubebuilder:object:root=true -// ConfigList contains a list of Config +// ConfigList contains a list of Config. type ConfigList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/apis/config/v1alpha1/groupversion_info.go b/apis/config/v1alpha1/groupversion_info.go index cdbf8977001..2e0dc718578 100644 --- a/apis/config/v1alpha1/groupversion_info.go +++ b/apis/config/v1alpha1/groupversion_info.go @@ -24,10 +24,10 @@ import ( ) var ( - // GroupVersion is group version used to register these objects + // GroupVersion is group version used to register these objects. GroupVersion = schema.GroupVersion{Group: "config.gatekeeper.sh", Version: "v1alpha1"} - // SchemeBuilder is used to add go types to the GroupVersionKind scheme + // SchemeBuilder is used to add go types to the GroupVersionKind scheme. SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion} // AddToScheme adds the types in this group-version to the given scheme. diff --git a/apis/config/v1alpha1/zz_generated.deepcopy.go b/apis/config/v1alpha1/zz_generated.deepcopy.go index c93ae07b908..dbdcebf2efb 100644 --- a/apis/config/v1alpha1/zz_generated.deepcopy.go +++ b/apis/config/v1alpha1/zz_generated.deepcopy.go @@ -141,16 +141,16 @@ func (in *GVK) DeepCopy() *GVK { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MatchEntry) DeepCopyInto(out *MatchEntry) { *out = *in - if in.ExcludedNamespaces != nil { - in, out := &in.ExcludedNamespaces, &out.ExcludedNamespaces - *out = make([]util.PrefixWildcard, len(*in)) - copy(*out, *in) - } if in.Processes != nil { in, out := &in.Processes, &out.Processes *out = make([]string, len(*in)) copy(*out, *in) } + if in.ExcludedNamespaces != nil { + in, out := &in.ExcludedNamespaces, &out.ExcludedNamespaces + *out = make([]util.PrefixWildcard, len(*in)) + copy(*out, *in) + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MatchEntry. diff --git a/apis/mutations/v1alpha1/assign_types.go b/apis/mutations/v1alpha1/assign_types.go index d3d5ab8e7d4..023507fc820 100644 --- a/apis/mutations/v1alpha1/assign_types.go +++ b/apis/mutations/v1alpha1/assign_types.go @@ -28,7 +28,7 @@ import ( // EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! // NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. -// AssignSpec defines the desired state of Assign +// AssignSpec defines the desired state of Assign. type AssignSpec struct { // INSERT ADDITIONAL SPEC FIELDS - desired state of cluster // Important: Run "make" to regenerate code after modifying this file @@ -59,13 +59,13 @@ type Parameters struct { // // Available Tests: // * MustExist - the path must exist or do not mutate -// * MustNotExist - the path must not exist or do not mutate +// * MustNotExist - the path must not exist or do not mutate. type PathTest struct { SubPath string `json:"subPath,omitempty"` Condition tester.Condition `json:"condition,omitempty"` } -// AssignStatus defines the observed state of Assign +// AssignStatus defines the observed state of Assign. type AssignStatus struct { // INSERT ADDITIONAL STATUS FIELD - define observed state of cluster // Important: Run "make" to regenerate code after modifying this file @@ -78,7 +78,7 @@ type AssignStatus struct { // +kubebuilder:resource:scope="Cluster" // +kubebuilder:subresource:status -// Assign is the Schema for the assign API +// Assign is the Schema for the assign API. type Assign struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` @@ -89,7 +89,7 @@ type Assign struct { // +kubebuilder:object:root=true -// AssignList contains a list of Assign +// AssignList contains a list of Assign. type AssignList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` @@ -101,7 +101,7 @@ func init() { } // ValueTests returns tests that the mutator is expected -// to run against the value +// to run against the value. func (a *Assign) ValueTests() (AssignIf, error) { raw := a.Spec.Parameters.AssignIf out := AssignIf{} @@ -117,7 +117,7 @@ func (a *Assign) ValueTests() (AssignIf, error) { // +kubebuilder:object:generate=false // AssignIf describes tests against the pre-existing value. -// The object will be mutated only if assertions pass +// The object will be mutated only if assertions pass. type AssignIf struct { // In Asserts that the value is a member of the provided list before mutating In []interface{} `json:"in,omitempty"` diff --git a/apis/mutations/v1alpha1/assignmetadata_types.go b/apis/mutations/v1alpha1/assignmetadata_types.go index df702894fd3..0343c72277f 100644 --- a/apis/mutations/v1alpha1/assignmetadata_types.go +++ b/apis/mutations/v1alpha1/assignmetadata_types.go @@ -25,7 +25,7 @@ import ( // EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! // NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. -// AssignMetadataSpec defines the desired state of AssignMetadata +// AssignMetadataSpec defines the desired state of AssignMetadata. type AssignMetadataSpec struct { Match match.Match `json:"match,omitempty"` Location string `json:"location,omitempty"` @@ -38,7 +38,7 @@ type MetadataParameters struct { Assign runtime.RawExtension `json:"assign,omitempty"` } -// AssignMetadataStatus defines the observed state of AssignMetadata +// AssignMetadataStatus defines the observed state of AssignMetadata. type AssignMetadataStatus struct { // INSERT ADDITIONAL STATUS FIELD - define observed state of cluster // Important: Run "make" to regenerate code after modifying this file @@ -49,7 +49,7 @@ type AssignMetadataStatus struct { // +kubebuilder:resource:scope="Cluster" // +kubebuilder:subresource:status -// AssignMetadata is the Schema for the assignmetadata API +// AssignMetadata is the Schema for the assignmetadata API. type AssignMetadata struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` @@ -60,7 +60,7 @@ type AssignMetadata struct { // +kubebuilder:object:root=true -// AssignMetadataList contains a list of AssignMetadata +// AssignMetadataList contains a list of AssignMetadata. type AssignMetadataList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/apis/mutations/v1alpha1/groupversion_info.go b/apis/mutations/v1alpha1/groupversion_info.go index 4e74752e736..519991e0645 100644 --- a/apis/mutations/v1alpha1/groupversion_info.go +++ b/apis/mutations/v1alpha1/groupversion_info.go @@ -24,10 +24,10 @@ import ( ) var ( - // GroupVersion is group version used to register these objects + // GroupVersion is group version used to register these objects. GroupVersion = schema.GroupVersion{Group: "mutations.gatekeeper.sh", Version: "v1alpha1"} - // SchemeBuilder is used to add go types to the GroupVersionKind scheme + // SchemeBuilder is used to add go types to the GroupVersionKind scheme. SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion} // AddToScheme adds the types in this group-version to the given scheme. diff --git a/apis/status/v1beta1/constraintpodstatus_types.go b/apis/status/v1beta1/constraintpodstatus_types.go index 44564c941e3..859d568d64b 100644 --- a/apis/status/v1beta1/constraintpodstatus_types.go +++ b/apis/status/v1beta1/constraintpodstatus_types.go @@ -31,7 +31,7 @@ import ( // ConstraintsGroup is the API Group for Gatekeeper Constraints. const ConstraintsGroup = "constraints.gatekeeper.sh" -// ConstraintPodStatusStatus defines the observed state of ConstraintPodStatus +// ConstraintPodStatusStatus defines the observed state of ConstraintPodStatus. type ConstraintPodStatusStatus struct { // Important: Run "make" to regenerate code after modifying this file @@ -46,7 +46,7 @@ type ConstraintPodStatusStatus struct { ObservedGeneration int64 `json:"observedGeneration,omitempty"` } -// Error represents a single error caught while adding a constraint to OPA +// Error represents a single error caught while adding a constraint to OPA. type Error struct { Code string `json:"code"` Message string `json:"message"` @@ -56,7 +56,7 @@ type Error struct { // +kubebuilder:object:root=true // +kubebuilder:resource:scope=Namespaced -// ConstraintPodStatus is the Schema for the constraintpodstatuses API +// ConstraintPodStatus is the Schema for the constraintpodstatuses API. type ConstraintPodStatus struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` @@ -66,7 +66,7 @@ type ConstraintPodStatus struct { // +kubebuilder:object:root=true -// ConstraintPodStatusList contains a list of ConstraintPodStatus +// ConstraintPodStatusList contains a list of ConstraintPodStatus. type ConstraintPodStatusList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` @@ -79,7 +79,7 @@ func init() { // NewConstraintStatusForPod returns a constraint status object // that has been initialized with the bare minimum of fields to make it functional -// with the constraint status controller +// with the constraint status controller. func NewConstraintStatusForPod(pod *corev1.Pod, constraint *unstructured.Unstructured, scheme *runtime.Scheme) (*ConstraintPodStatus, error) { obj := &ConstraintPodStatus{} name, err := KeyForConstraint(pod.Name, constraint) @@ -106,7 +106,7 @@ func NewConstraintStatusForPod(pod *corev1.Pod, constraint *unstructured.Unstruc } // KeyForConstraint returns a unique status object name given the Pod ID and -// a constraint object +// a constraint object. func KeyForConstraint(id string, constraint *unstructured.Unstructured) (string, error) { // We don't need to worry that lower-casing the kind will cause a collision because // the constraint framework requires resource == lower-case kind. We must do this diff --git a/apis/status/v1beta1/constrainttemplatepodstatus_types.go b/apis/status/v1beta1/constrainttemplatepodstatus_types.go index d75b0c89cbc..50b12ea80de 100644 --- a/apis/status/v1beta1/constrainttemplatepodstatus_types.go +++ b/apis/status/v1beta1/constrainttemplatepodstatus_types.go @@ -26,7 +26,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" ) -// ConstraintTemplatePodStatusStatus defines the observed state of ConstraintTemplatePodStatus +// ConstraintTemplatePodStatusStatus defines the observed state of ConstraintTemplatePodStatus. type ConstraintTemplatePodStatusStatus struct { // Important: Run "make" to regenerate code after modifying this file ID string `json:"id,omitempty"` @@ -39,7 +39,7 @@ type ConstraintTemplatePodStatusStatus struct { // +kubebuilder:object:root=true // +kubebuilder:resource:scope=Namespaced -// ConstraintTemplatePodStatus is the Schema for the constrainttemplatepodstatuses API +// ConstraintTemplatePodStatus is the Schema for the constrainttemplatepodstatuses API. type ConstraintTemplatePodStatus struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` @@ -49,7 +49,7 @@ type ConstraintTemplatePodStatus struct { // +kubebuilder:object:root=true -// ConstraintTemplatePodStatusList contains a list of ConstraintTemplatePodStatus +// ConstraintTemplatePodStatusList contains a list of ConstraintTemplatePodStatus. type ConstraintTemplatePodStatusList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` @@ -62,7 +62,7 @@ func init() { // NewConstraintTemplateStatusForPod returns a constraint template status object // that has been initialized with the bare minimum of fields to make it functional -// with the constraint template status controller +// with the constraint template status controller. func NewConstraintTemplateStatusForPod(pod *corev1.Pod, templateName string, scheme *runtime.Scheme) (*ConstraintTemplatePodStatus, error) { obj := &ConstraintTemplatePodStatus{} name, err := KeyForConstraintTemplate(pod.Name, templateName) @@ -86,7 +86,7 @@ func NewConstraintTemplateStatusForPod(pod *corev1.Pod, templateName string, sch } // KeyForConstraintTemplate returns a unique status object name given the Pod ID and -// a template object +// a template object. func KeyForConstraintTemplate(id string, templateName string) (string, error) { return dashPacker(id, templateName) } diff --git a/apis/status/v1beta1/groupversion_info.go b/apis/status/v1beta1/groupversion_info.go index 7fd6a9d7512..75d7ba295ad 100644 --- a/apis/status/v1beta1/groupversion_info.go +++ b/apis/status/v1beta1/groupversion_info.go @@ -24,10 +24,10 @@ import ( ) var ( - // GroupVersion is group version used to register these objects + // GroupVersion is group version used to register these objects. GroupVersion = schema.GroupVersion{Group: "status.gatekeeper.sh", Version: "v1beta1"} - // SchemeBuilder is used to add go types to the GroupVersionKind scheme + // SchemeBuilder is used to add go types to the GroupVersionKind scheme. SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion} // AddToScheme adds the types in this group-version to the given scheme. diff --git a/apis/status/v1beta1/mutatorpodstatus_types.go b/apis/status/v1beta1/mutatorpodstatus_types.go index e6429d90969..2c77e4849c6 100644 --- a/apis/status/v1beta1/mutatorpodstatus_types.go +++ b/apis/status/v1beta1/mutatorpodstatus_types.go @@ -31,7 +31,7 @@ import ( // MutationsGroup is the API Group for Gatekeeper Mutators. const MutationsGroup = "mutations.gatekeeper.sh" -// MutatorPodStatusStatus defines the observed state of MutatorPodStatus +// MutatorPodStatusStatus defines the observed state of MutatorPodStatus. type MutatorPodStatusStatus struct { // Important: Run "make" to regenerate code after modifying this file @@ -46,7 +46,7 @@ type MutatorPodStatusStatus struct { ObservedGeneration int64 `json:"observedGeneration,omitempty"` } -// MutatorError represents a single error caught while adding a mutator to a system +// MutatorError represents a single error caught while adding a mutator to a system. type MutatorError struct { Message string `json:"message"` } @@ -54,7 +54,7 @@ type MutatorError struct { // +kubebuilder:object:root=true // +kubebuilder:resource:scope=Namespaced -// MutatorPodStatus is the Schema for the mutationpodstatuses API +// MutatorPodStatus is the Schema for the mutationpodstatuses API. type MutatorPodStatus struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` @@ -64,7 +64,7 @@ type MutatorPodStatus struct { // +kubebuilder:object:root=true -// MutatorPodStatusList contains a list of MutatorPodStatus +// MutatorPodStatusList contains a list of MutatorPodStatus. type MutatorPodStatusList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` @@ -77,7 +77,7 @@ func init() { // NewMutatorStatusForPod returns a mutator status object // that has been initialized with the bare minimum of fields to make it functional -// with the mutator status controller +// with the mutator status controller. func NewMutatorStatusForPod(pod *corev1.Pod, mutatorID mtypes.ID, scheme *runtime.Scheme) (*MutatorPodStatus, error) { obj := &MutatorPodStatus{} name, err := KeyForMutatorID(pod.Name, mutatorID) @@ -103,7 +103,7 @@ func NewMutatorStatusForPod(pod *corev1.Pod, mutatorID mtypes.ID, scheme *runtim } // KeyForMutatorID returns a unique status object name given the Pod ID and -// a mutator object +// a mutator object. func KeyForMutatorID(id string, mID mtypes.ID) (string, error) { // This adds a requirement that the lowercase of all mutator kinds must be unique. // Though this should already be the case because resource ~= lower(kind) (usually). diff --git a/apis/status/v1beta1/util.go b/apis/status/v1beta1/util.go index 5f4964190f9..d93beee4923 100644 --- a/apis/status/v1beta1/util.go +++ b/apis/status/v1beta1/util.go @@ -12,7 +12,7 @@ var ( ) // DisablePodOwnership disables setting the owner reference for Status resource. -// This should only be used for testing, where a Pod resource may not be available +// This should only be used for testing, where a Pod resource may not be available. func DisablePodOwnership() { ownerMutex.Lock() defer ownerMutex.Unlock() @@ -25,7 +25,7 @@ func PodOwnershipEnabled() bool { return podOwnershipEnabled } -// dashExtractor unpacks the status resource name, unescaping `-` +// dashExtractor unpacks the status resource name, unescaping `-`. func dashExtractor(val string) []string { b := strings.Builder{} var tokens []string diff --git a/cmd/build/helmify/main.go b/cmd/build/helmify/main.go index 95964067116..4f6f40588f4 100644 --- a/cmd/build/helmify/main.go +++ b/cmd/build/helmify/main.go @@ -14,13 +14,11 @@ import ( apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" ) -var ( - outputDir = flag.String("output-dir", "manifest_staging/charts/gatekeeper", "The root directory in which to write the Helm chart") -) +var outputDir = flag.String("output-dir", "manifest_staging/charts/gatekeeper", "The root directory in which to write the Helm chart") var kindRegex = regexp.MustCompile(`(?m)^kind:[\s]+([\S]+)[\s]*$`) -// use exactly two spaces to be sure we are capturing metadata.name +// use exactly two spaces to be sure we are capturing metadata.name. var nameRegex = regexp.MustCompile(`(?m)^ name:[\s]+([\S]+)[\s]*$`) func extractKind(s string) (string, error) { diff --git a/config/crd/bases/config.gatekeeper.sh_configs.yaml b/config/crd/bases/config.gatekeeper.sh_configs.yaml index 9dbcca4df57..21ad7252281 100644 --- a/config/crd/bases/config.gatekeeper.sh_configs.yaml +++ b/config/crd/bases/config.gatekeeper.sh_configs.yaml @@ -19,7 +19,7 @@ spec: - name: v1alpha1 schema: openAPIV3Schema: - description: Config is the Schema for the configs API + description: Config is the Schema for the configs API. properties: apiVersion: description: 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' @@ -30,7 +30,7 @@ spec: metadata: type: object spec: - description: ConfigSpec defines the desired state of Config + description: ConfigSpec defines the desired state of Config. properties: match: description: Configuration for namespace exclusion @@ -98,7 +98,7 @@ spec: type: object type: object status: - description: ConfigStatus defines the observed state of Config + description: ConfigStatus defines the observed state of Config. type: object type: object served: true diff --git a/config/crd/bases/mutations.gatekeeper.sh_assign.yaml b/config/crd/bases/mutations.gatekeeper.sh_assign.yaml index be2cc8a31dd..bce24f80e6e 100644 --- a/config/crd/bases/mutations.gatekeeper.sh_assign.yaml +++ b/config/crd/bases/mutations.gatekeeper.sh_assign.yaml @@ -19,7 +19,7 @@ spec: - name: v1alpha1 schema: openAPIV3Schema: - description: Assign is the Schema for the assign API + description: Assign is the Schema for the assign API. properties: apiVersion: description: 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' @@ -30,7 +30,7 @@ spec: metadata: type: object spec: - description: AssignSpec defines the desired state of Assign + description: AssignSpec defines the desired state of Assign. properties: applyTo: description: 'INSERT ADDITIONAL SPEC FIELDS - desired state of cluster Important: Run "make" to regenerate code after modifying this file' @@ -154,7 +154,7 @@ spec: type: object pathTests: items: - description: "PathTest allows the user to customize how the mutation works if parent paths are missing. It traverses the list in order. All sub paths are tested against the provided condition, if the test fails, the mutation is not applied. All `subPath` entries must be a prefix of `location`. Any glob characters will take on the same value as was used to expand the matching glob in `location`. \n Available Tests: * MustExist - the path must exist or do not mutate * MustNotExist - the path must not exist or do not mutate" + description: "PathTest allows the user to customize how the mutation works if parent paths are missing. It traverses the list in order. All sub paths are tested against the provided condition, if the test fails, the mutation is not applied. All `subPath` entries must be a prefix of `location`. Any glob characters will take on the same value as was used to expand the matching glob in `location`. \n Available Tests: * MustExist - the path must exist or do not mutate * MustNotExist - the path must not exist or do not mutate." properties: condition: description: Condition describes whether the path either MustExist or MustNotExist in the original object @@ -169,17 +169,17 @@ spec: type: object type: object status: - description: AssignStatus defines the observed state of Assign + description: AssignStatus defines the observed state of Assign. properties: byPod: items: - description: MutatorPodStatusStatus defines the observed state of MutatorPodStatus + description: MutatorPodStatusStatus defines the observed state of MutatorPodStatus. properties: enforced: type: boolean errors: items: - description: MutatorError represents a single error caught while adding a mutator to a system + description: MutatorError represents a single error caught while adding a mutator to a system. properties: message: type: string diff --git a/config/crd/bases/mutations.gatekeeper.sh_assignmetadata.yaml b/config/crd/bases/mutations.gatekeeper.sh_assignmetadata.yaml index 480fa4f47cb..e737a2d9c75 100644 --- a/config/crd/bases/mutations.gatekeeper.sh_assignmetadata.yaml +++ b/config/crd/bases/mutations.gatekeeper.sh_assignmetadata.yaml @@ -19,7 +19,7 @@ spec: - name: v1alpha1 schema: openAPIV3Schema: - description: AssignMetadata is the Schema for the assignmetadata API + description: AssignMetadata is the Schema for the assignmetadata API. properties: apiVersion: description: 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' @@ -30,7 +30,7 @@ spec: metadata: type: object spec: - description: AssignMetadataSpec defines the desired state of AssignMetadata + description: AssignMetadataSpec defines the desired state of AssignMetadata. properties: location: type: string @@ -133,18 +133,18 @@ spec: type: object type: object status: - description: AssignMetadataStatus defines the observed state of AssignMetadata + description: AssignMetadataStatus defines the observed state of AssignMetadata. properties: byPod: description: 'INSERT ADDITIONAL STATUS FIELD - define observed state of cluster Important: Run "make" to regenerate code after modifying this file' items: - description: MutatorPodStatusStatus defines the observed state of MutatorPodStatus + description: MutatorPodStatusStatus defines the observed state of MutatorPodStatus. properties: enforced: type: boolean errors: items: - description: MutatorError represents a single error caught while adding a mutator to a system + description: MutatorError represents a single error caught while adding a mutator to a system. properties: message: type: string diff --git a/config/crd/bases/status.gatekeeper.sh_constraintpodstatuses.yaml b/config/crd/bases/status.gatekeeper.sh_constraintpodstatuses.yaml index 7c2cb861f06..c6893bb14c5 100644 --- a/config/crd/bases/status.gatekeeper.sh_constraintpodstatuses.yaml +++ b/config/crd/bases/status.gatekeeper.sh_constraintpodstatuses.yaml @@ -19,7 +19,7 @@ spec: - name: v1beta1 schema: openAPIV3Schema: - description: ConstraintPodStatus is the Schema for the constraintpodstatuses API + description: ConstraintPodStatus is the Schema for the constraintpodstatuses API. properties: apiVersion: description: 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' @@ -30,7 +30,7 @@ spec: metadata: type: object status: - description: ConstraintPodStatusStatus defines the observed state of ConstraintPodStatus + description: ConstraintPodStatusStatus defines the observed state of ConstraintPodStatus. properties: constraintUID: description: Storing the constraint UID allows us to detect drift, such as when a constraint has been recreated after its CRD was deleted out from under it, interrupting the watch @@ -39,7 +39,7 @@ spec: type: boolean errors: items: - description: Error represents a single error caught while adding a constraint to OPA + description: Error represents a single error caught while adding a constraint to OPA. properties: code: type: string diff --git a/config/crd/bases/status.gatekeeper.sh_constrainttemplatepodstatuses.yaml b/config/crd/bases/status.gatekeeper.sh_constrainttemplatepodstatuses.yaml index cb2c0dddc96..2d77a84caee 100644 --- a/config/crd/bases/status.gatekeeper.sh_constrainttemplatepodstatuses.yaml +++ b/config/crd/bases/status.gatekeeper.sh_constrainttemplatepodstatuses.yaml @@ -19,7 +19,7 @@ spec: - name: v1beta1 schema: openAPIV3Schema: - description: ConstraintTemplatePodStatus is the Schema for the constrainttemplatepodstatuses API + description: ConstraintTemplatePodStatus is the Schema for the constrainttemplatepodstatuses API. properties: apiVersion: description: 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' @@ -30,7 +30,7 @@ spec: metadata: type: object status: - description: ConstraintTemplatePodStatusStatus defines the observed state of ConstraintTemplatePodStatus + description: ConstraintTemplatePodStatusStatus defines the observed state of ConstraintTemplatePodStatus. properties: errors: items: diff --git a/config/crd/bases/status.gatekeeper.sh_mutatorpodstatuses.yaml b/config/crd/bases/status.gatekeeper.sh_mutatorpodstatuses.yaml index b4d2b048030..30d53bb1d3f 100644 --- a/config/crd/bases/status.gatekeeper.sh_mutatorpodstatuses.yaml +++ b/config/crd/bases/status.gatekeeper.sh_mutatorpodstatuses.yaml @@ -19,7 +19,7 @@ spec: - name: v1beta1 schema: openAPIV3Schema: - description: MutatorPodStatus is the Schema for the mutationpodstatuses API + description: MutatorPodStatus is the Schema for the mutationpodstatuses API. properties: apiVersion: description: 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' @@ -30,13 +30,13 @@ spec: metadata: type: object status: - description: MutatorPodStatusStatus defines the observed state of MutatorPodStatus + description: MutatorPodStatusStatus defines the observed state of MutatorPodStatus. properties: enforced: type: boolean errors: items: - description: MutatorError represents a single error caught while adding a mutator to a system + description: MutatorError represents a single error caught while adding a mutator to a system. properties: message: type: string diff --git a/config/overlays/mutation_webhook/mutations.gatekeeper.sh_assign.yaml b/config/overlays/mutation_webhook/mutations.gatekeeper.sh_assign.yaml index be2cc8a31dd..bce24f80e6e 100644 --- a/config/overlays/mutation_webhook/mutations.gatekeeper.sh_assign.yaml +++ b/config/overlays/mutation_webhook/mutations.gatekeeper.sh_assign.yaml @@ -19,7 +19,7 @@ spec: - name: v1alpha1 schema: openAPIV3Schema: - description: Assign is the Schema for the assign API + description: Assign is the Schema for the assign API. properties: apiVersion: description: 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' @@ -30,7 +30,7 @@ spec: metadata: type: object spec: - description: AssignSpec defines the desired state of Assign + description: AssignSpec defines the desired state of Assign. properties: applyTo: description: 'INSERT ADDITIONAL SPEC FIELDS - desired state of cluster Important: Run "make" to regenerate code after modifying this file' @@ -154,7 +154,7 @@ spec: type: object pathTests: items: - description: "PathTest allows the user to customize how the mutation works if parent paths are missing. It traverses the list in order. All sub paths are tested against the provided condition, if the test fails, the mutation is not applied. All `subPath` entries must be a prefix of `location`. Any glob characters will take on the same value as was used to expand the matching glob in `location`. \n Available Tests: * MustExist - the path must exist or do not mutate * MustNotExist - the path must not exist or do not mutate" + description: "PathTest allows the user to customize how the mutation works if parent paths are missing. It traverses the list in order. All sub paths are tested against the provided condition, if the test fails, the mutation is not applied. All `subPath` entries must be a prefix of `location`. Any glob characters will take on the same value as was used to expand the matching glob in `location`. \n Available Tests: * MustExist - the path must exist or do not mutate * MustNotExist - the path must not exist or do not mutate." properties: condition: description: Condition describes whether the path either MustExist or MustNotExist in the original object @@ -169,17 +169,17 @@ spec: type: object type: object status: - description: AssignStatus defines the observed state of Assign + description: AssignStatus defines the observed state of Assign. properties: byPod: items: - description: MutatorPodStatusStatus defines the observed state of MutatorPodStatus + description: MutatorPodStatusStatus defines the observed state of MutatorPodStatus. properties: enforced: type: boolean errors: items: - description: MutatorError represents a single error caught while adding a mutator to a system + description: MutatorError represents a single error caught while adding a mutator to a system. properties: message: type: string diff --git a/config/overlays/mutation_webhook/mutations.gatekeeper.sh_assignmetadata.yaml b/config/overlays/mutation_webhook/mutations.gatekeeper.sh_assignmetadata.yaml index 480fa4f47cb..e737a2d9c75 100644 --- a/config/overlays/mutation_webhook/mutations.gatekeeper.sh_assignmetadata.yaml +++ b/config/overlays/mutation_webhook/mutations.gatekeeper.sh_assignmetadata.yaml @@ -19,7 +19,7 @@ spec: - name: v1alpha1 schema: openAPIV3Schema: - description: AssignMetadata is the Schema for the assignmetadata API + description: AssignMetadata is the Schema for the assignmetadata API. properties: apiVersion: description: 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' @@ -30,7 +30,7 @@ spec: metadata: type: object spec: - description: AssignMetadataSpec defines the desired state of AssignMetadata + description: AssignMetadataSpec defines the desired state of AssignMetadata. properties: location: type: string @@ -133,18 +133,18 @@ spec: type: object type: object status: - description: AssignMetadataStatus defines the observed state of AssignMetadata + description: AssignMetadataStatus defines the observed state of AssignMetadata. properties: byPod: description: 'INSERT ADDITIONAL STATUS FIELD - define observed state of cluster Important: Run "make" to regenerate code after modifying this file' items: - description: MutatorPodStatusStatus defines the observed state of MutatorPodStatus + description: MutatorPodStatusStatus defines the observed state of MutatorPodStatus. properties: enforced: type: boolean errors: items: - description: MutatorError represents a single error caught while adding a mutator to a system + description: MutatorError represents a single error caught while adding a mutator to a system. properties: message: type: string diff --git a/config/overlays/mutation_webhook/status.gatekeeper.sh_mutatorpodstatuses.yaml b/config/overlays/mutation_webhook/status.gatekeeper.sh_mutatorpodstatuses.yaml index b4d2b048030..30d53bb1d3f 100644 --- a/config/overlays/mutation_webhook/status.gatekeeper.sh_mutatorpodstatuses.yaml +++ b/config/overlays/mutation_webhook/status.gatekeeper.sh_mutatorpodstatuses.yaml @@ -19,7 +19,7 @@ spec: - name: v1beta1 schema: openAPIV3Schema: - description: MutatorPodStatus is the Schema for the mutationpodstatuses API + description: MutatorPodStatus is the Schema for the mutationpodstatuses API. properties: apiVersion: description: 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' @@ -30,13 +30,13 @@ spec: metadata: type: object status: - description: MutatorPodStatusStatus defines the observed state of MutatorPodStatus + description: MutatorPodStatusStatus defines the observed state of MutatorPodStatus. properties: enforced: type: boolean errors: items: - description: MutatorError represents a single error caught while adding a mutator to a system + description: MutatorError represents a single error caught while adding a mutator to a system. properties: message: type: string diff --git a/main.go b/main.go index 04816b7adfa..0fe2dd621ec 100644 --- a/main.go +++ b/main.go @@ -76,7 +76,7 @@ const ( ) var ( - // DNSName is ..svc + // DNSName is ..svc. dnsName = fmt.Sprintf("%s.%s.svc", serviceName, util.GetNamespace()) scheme = runtime.NewScheme() setupLog = ctrl.Log.WithName("setup") diff --git a/manifest_staging/charts/gatekeeper/crds/assign-customresourcedefinition.yaml b/manifest_staging/charts/gatekeeper/crds/assign-customresourcedefinition.yaml index 19e84b0c1d7..66bae643d11 100644 --- a/manifest_staging/charts/gatekeeper/crds/assign-customresourcedefinition.yaml +++ b/manifest_staging/charts/gatekeeper/crds/assign-customresourcedefinition.yaml @@ -19,7 +19,7 @@ spec: - name: v1alpha1 schema: openAPIV3Schema: - description: Assign is the Schema for the assign API + description: Assign is the Schema for the assign API. properties: apiVersion: description: 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' @@ -30,7 +30,7 @@ spec: metadata: type: object spec: - description: AssignSpec defines the desired state of Assign + description: AssignSpec defines the desired state of Assign. properties: applyTo: description: 'INSERT ADDITIONAL SPEC FIELDS - desired state of cluster Important: Run "make" to regenerate code after modifying this file' @@ -154,7 +154,7 @@ spec: type: object pathTests: items: - description: "PathTest allows the user to customize how the mutation works if parent paths are missing. It traverses the list in order. All sub paths are tested against the provided condition, if the test fails, the mutation is not applied. All `subPath` entries must be a prefix of `location`. Any glob characters will take on the same value as was used to expand the matching glob in `location`. \n Available Tests: * MustExist - the path must exist or do not mutate * MustNotExist - the path must not exist or do not mutate" + description: "PathTest allows the user to customize how the mutation works if parent paths are missing. It traverses the list in order. All sub paths are tested against the provided condition, if the test fails, the mutation is not applied. All `subPath` entries must be a prefix of `location`. Any glob characters will take on the same value as was used to expand the matching glob in `location`. \n Available Tests: * MustExist - the path must exist or do not mutate * MustNotExist - the path must not exist or do not mutate." properties: condition: description: Condition describes whether the path either MustExist or MustNotExist in the original object @@ -169,17 +169,17 @@ spec: type: object type: object status: - description: AssignStatus defines the observed state of Assign + description: AssignStatus defines the observed state of Assign. properties: byPod: items: - description: MutatorPodStatusStatus defines the observed state of MutatorPodStatus + description: MutatorPodStatusStatus defines the observed state of MutatorPodStatus. properties: enforced: type: boolean errors: items: - description: MutatorError represents a single error caught while adding a mutator to a system + description: MutatorError represents a single error caught while adding a mutator to a system. properties: message: type: string diff --git a/manifest_staging/charts/gatekeeper/crds/assignmetadata-customresourcedefinition.yaml b/manifest_staging/charts/gatekeeper/crds/assignmetadata-customresourcedefinition.yaml index 73d53eb2383..43f960d6ef6 100644 --- a/manifest_staging/charts/gatekeeper/crds/assignmetadata-customresourcedefinition.yaml +++ b/manifest_staging/charts/gatekeeper/crds/assignmetadata-customresourcedefinition.yaml @@ -19,7 +19,7 @@ spec: - name: v1alpha1 schema: openAPIV3Schema: - description: AssignMetadata is the Schema for the assignmetadata API + description: AssignMetadata is the Schema for the assignmetadata API. properties: apiVersion: description: 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' @@ -30,7 +30,7 @@ spec: metadata: type: object spec: - description: AssignMetadataSpec defines the desired state of AssignMetadata + description: AssignMetadataSpec defines the desired state of AssignMetadata. properties: location: type: string @@ -133,18 +133,18 @@ spec: type: object type: object status: - description: AssignMetadataStatus defines the observed state of AssignMetadata + description: AssignMetadataStatus defines the observed state of AssignMetadata. properties: byPod: description: 'INSERT ADDITIONAL STATUS FIELD - define observed state of cluster Important: Run "make" to regenerate code after modifying this file' items: - description: MutatorPodStatusStatus defines the observed state of MutatorPodStatus + description: MutatorPodStatusStatus defines the observed state of MutatorPodStatus. properties: enforced: type: boolean errors: items: - description: MutatorError represents a single error caught while adding a mutator to a system + description: MutatorError represents a single error caught while adding a mutator to a system. properties: message: type: string diff --git a/manifest_staging/charts/gatekeeper/crds/config-customresourcedefinition.yaml b/manifest_staging/charts/gatekeeper/crds/config-customresourcedefinition.yaml index 09b86bebdfa..66b0092bf88 100644 --- a/manifest_staging/charts/gatekeeper/crds/config-customresourcedefinition.yaml +++ b/manifest_staging/charts/gatekeeper/crds/config-customresourcedefinition.yaml @@ -19,7 +19,7 @@ spec: - name: v1alpha1 schema: openAPIV3Schema: - description: Config is the Schema for the configs API + description: Config is the Schema for the configs API. properties: apiVersion: description: 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' @@ -30,7 +30,7 @@ spec: metadata: type: object spec: - description: ConfigSpec defines the desired state of Config + description: ConfigSpec defines the desired state of Config. properties: match: description: Configuration for namespace exclusion @@ -98,7 +98,7 @@ spec: type: object type: object status: - description: ConfigStatus defines the observed state of Config + description: ConfigStatus defines the observed state of Config. type: object type: object served: true diff --git a/manifest_staging/charts/gatekeeper/crds/constraintpodstatus-customresourcedefinition.yaml b/manifest_staging/charts/gatekeeper/crds/constraintpodstatus-customresourcedefinition.yaml index d32f683ed8d..d255b81049a 100644 --- a/manifest_staging/charts/gatekeeper/crds/constraintpodstatus-customresourcedefinition.yaml +++ b/manifest_staging/charts/gatekeeper/crds/constraintpodstatus-customresourcedefinition.yaml @@ -19,7 +19,7 @@ spec: - name: v1beta1 schema: openAPIV3Schema: - description: ConstraintPodStatus is the Schema for the constraintpodstatuses API + description: ConstraintPodStatus is the Schema for the constraintpodstatuses API. properties: apiVersion: description: 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' @@ -30,7 +30,7 @@ spec: metadata: type: object status: - description: ConstraintPodStatusStatus defines the observed state of ConstraintPodStatus + description: ConstraintPodStatusStatus defines the observed state of ConstraintPodStatus. properties: constraintUID: description: Storing the constraint UID allows us to detect drift, such as when a constraint has been recreated after its CRD was deleted out from under it, interrupting the watch @@ -39,7 +39,7 @@ spec: type: boolean errors: items: - description: Error represents a single error caught while adding a constraint to OPA + description: Error represents a single error caught while adding a constraint to OPA. properties: code: type: string diff --git a/manifest_staging/charts/gatekeeper/crds/constrainttemplatepodstatus-customresourcedefinition.yaml b/manifest_staging/charts/gatekeeper/crds/constrainttemplatepodstatus-customresourcedefinition.yaml index d01a6bf0307..a5f3ede73c5 100644 --- a/manifest_staging/charts/gatekeeper/crds/constrainttemplatepodstatus-customresourcedefinition.yaml +++ b/manifest_staging/charts/gatekeeper/crds/constrainttemplatepodstatus-customresourcedefinition.yaml @@ -19,7 +19,7 @@ spec: - name: v1beta1 schema: openAPIV3Schema: - description: ConstraintTemplatePodStatus is the Schema for the constrainttemplatepodstatuses API + description: ConstraintTemplatePodStatus is the Schema for the constrainttemplatepodstatuses API. properties: apiVersion: description: 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' @@ -30,7 +30,7 @@ spec: metadata: type: object status: - description: ConstraintTemplatePodStatusStatus defines the observed state of ConstraintTemplatePodStatus + description: ConstraintTemplatePodStatusStatus defines the observed state of ConstraintTemplatePodStatus. properties: errors: items: diff --git a/manifest_staging/charts/gatekeeper/crds/mutatorpodstatus-customresourcedefinition.yaml b/manifest_staging/charts/gatekeeper/crds/mutatorpodstatus-customresourcedefinition.yaml index 8e2eab6898a..ea647580dd8 100644 --- a/manifest_staging/charts/gatekeeper/crds/mutatorpodstatus-customresourcedefinition.yaml +++ b/manifest_staging/charts/gatekeeper/crds/mutatorpodstatus-customresourcedefinition.yaml @@ -19,7 +19,7 @@ spec: - name: v1beta1 schema: openAPIV3Schema: - description: MutatorPodStatus is the Schema for the mutationpodstatuses API + description: MutatorPodStatus is the Schema for the mutationpodstatuses API. properties: apiVersion: description: 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' @@ -30,13 +30,13 @@ spec: metadata: type: object status: - description: MutatorPodStatusStatus defines the observed state of MutatorPodStatus + description: MutatorPodStatusStatus defines the observed state of MutatorPodStatus. properties: enforced: type: boolean errors: items: - description: MutatorError represents a single error caught while adding a mutator to a system + description: MutatorError represents a single error caught while adding a mutator to a system. properties: message: type: string diff --git a/manifest_staging/deploy/gatekeeper.yaml b/manifest_staging/deploy/gatekeeper.yaml index 4764537adca..1811d8c3e75 100644 --- a/manifest_staging/deploy/gatekeeper.yaml +++ b/manifest_staging/deploy/gatekeeper.yaml @@ -45,7 +45,7 @@ spec: - name: v1alpha1 schema: openAPIV3Schema: - description: Config is the Schema for the configs API + description: Config is the Schema for the configs API. properties: apiVersion: description: 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' @@ -56,7 +56,7 @@ spec: metadata: type: object spec: - description: ConfigSpec defines the desired state of Config + description: ConfigSpec defines the desired state of Config. properties: match: description: Configuration for namespace exclusion @@ -124,7 +124,7 @@ spec: type: object type: object status: - description: ConfigStatus defines the observed state of Config + description: ConfigStatus defines the observed state of Config. type: object type: object served: true @@ -157,7 +157,7 @@ spec: - name: v1beta1 schema: openAPIV3Schema: - description: ConstraintPodStatus is the Schema for the constraintpodstatuses API + description: ConstraintPodStatus is the Schema for the constraintpodstatuses API. properties: apiVersion: description: 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' @@ -168,7 +168,7 @@ spec: metadata: type: object status: - description: ConstraintPodStatusStatus defines the observed state of ConstraintPodStatus + description: ConstraintPodStatusStatus defines the observed state of ConstraintPodStatus. properties: constraintUID: description: Storing the constraint UID allows us to detect drift, such as when a constraint has been recreated after its CRD was deleted out from under it, interrupting the watch @@ -177,7 +177,7 @@ spec: type: boolean errors: items: - description: Error represents a single error caught while adding a constraint to OPA + description: Error represents a single error caught while adding a constraint to OPA. properties: code: type: string @@ -231,7 +231,7 @@ spec: - name: v1beta1 schema: openAPIV3Schema: - description: ConstraintTemplatePodStatus is the Schema for the constrainttemplatepodstatuses API + description: ConstraintTemplatePodStatus is the Schema for the constrainttemplatepodstatuses API. properties: apiVersion: description: 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' @@ -242,7 +242,7 @@ spec: metadata: type: object status: - description: ConstraintTemplatePodStatusStatus defines the observed state of ConstraintTemplatePodStatus + description: ConstraintTemplatePodStatusStatus defines the observed state of ConstraintTemplatePodStatus. properties: errors: items: diff --git a/pkg/audit/controller.go b/pkg/audit/controller.go index 2e34e540071..b285e8bf0be 100644 --- a/pkg/audit/controller.go +++ b/pkg/audit/controller.go @@ -20,7 +20,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/manager" ) -// AddToManager adds audit manager to the Manager +// AddToManager adds audit manager to the Manager. func AddToManager(m manager.Manager, opa *opa.Client, processExcluder *process.Excluder) error { if *auditInterval == 0 { log.Info("auditing is disabled") diff --git a/pkg/audit/manager.go b/pkg/audit/manager.go index 2781ada6aff..310be747c2f 100644 --- a/pkg/audit/manager.go +++ b/pkg/audit/manager.go @@ -56,7 +56,7 @@ var ( emptyAuditResults []auditResult ) -// Manager allows us to audit resources periodically +// Manager allows us to audit resources periodically. type Manager struct { client client.Client opa *opa.Client @@ -85,7 +85,7 @@ type auditResult struct { constraint *unstructured.Unstructured } -// StatusViolation represents each violation under status +// StatusViolation represents each violation under status. type StatusViolation struct { Kind string `json:"kind"` Name string `json:"name"` @@ -94,7 +94,7 @@ type StatusViolation struct { EnforcementAction string `json:"enforcementAction"` } -// nsCache is used for caching namespaces and their labels +// nsCache is used for caching namespaces and their labels. type nsCache struct { cache map[string]corev1.Namespace } @@ -116,7 +116,7 @@ func (c *nsCache) Get(ctx context.Context, client client.Client, namespace strin return c.cache[namespace], nil } -// New creates a new manager for audit +// New creates a new manager for audit. func New(ctx context.Context, mgr manager.Manager, opa *opa.Client, processExcluder *process.Excluder) (*Manager, error) { reporter, err := newStatsReporter() if err != nil { @@ -144,7 +144,7 @@ func New(ctx context.Context, mgr manager.Manager, opa *opa.Client, processExclu return am, nil } -// audit performs an audit then updates the status of all constraint resources with the results +// audit performs an audit then updates the status of all constraint resources with the results. func (am *Manager) audit(ctx context.Context) error { startTime := time.Now() timestamp := startTime.UTC().Format(time.RFC3339) @@ -233,7 +233,7 @@ func (am *Manager) audit(ctx context.Context) error { return nil } -// Audits server resources via the discovery client, as an alternative to opa.Client.Audit() +// Audits server resources via the discovery client, as an alternative to opa.Client.Audit(). func (am *Manager) auditResources( ctx context.Context, constraintsGVK []schema.GroupVersionKind, @@ -429,7 +429,7 @@ func (am *Manager) auditManagerLoop(ctx context.Context) { } } -// Start implements controller.Controller +// Start implements controller.Controller. func (am *Manager) Start(ctx context.Context) error { log.Info("Starting Audit Manager") go am.auditManagerLoop(ctx) diff --git a/pkg/audit/stats_reporter.go b/pkg/audit/stats_reporter.go index e740953d169..ccce6528ced 100644 --- a/pkg/audit/stats_reporter.go +++ b/pkg/audit/stats_reporter.go @@ -79,7 +79,7 @@ func (r *reporter) reportRunStart(t time.Time) error { return metrics.Record(r.ctx, lastRunTimeM.M(val)) } -// newStatsReporter creaters a reporter for audit metrics +// newStatsReporter creaters a reporter for audit metrics. func newStatsReporter() (*reporter, error) { ctx, err := tag.New( context.Background(), diff --git a/pkg/controller/assign/assign_controller.go b/pkg/controller/assign/assign_controller.go index 0c642106112..a623d6daed8 100644 --- a/pkg/controller/assign/assign_controller.go +++ b/pkg/controller/assign/assign_controller.go @@ -46,9 +46,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/source" ) -var ( - log = logf.Log.WithName("controller").WithValues(logging.Process, "assign_controller") -) +var log = logf.Log.WithName("controller").WithValues(logging.Process, "assign_controller") var gvkAssign = schema.GroupVersionKind{ Group: mutationsv1alpha1.GroupVersion.Group, @@ -87,7 +85,7 @@ func (a *Adder) InjectMutationCache(mutationCache *mutation.System) { a.MutationCache = mutationCache } -// newReconciler returns a new reconcile.Reconciler +// newReconciler returns a new reconcile.Reconciler. func newReconciler(mgr manager.Manager, mutationCache *mutation.System, tracker *readiness.Tracker, getPod func() (*corev1.Pod, error)) *Reconciler { r := &Reconciler{ system: mutationCache, @@ -102,7 +100,7 @@ func newReconciler(mgr manager.Manager, mutationCache *mutation.System, tracker return r } -// add adds a new Controller to mgr with r as the reconcile.Reconciler +// add adds a new Controller to mgr with r as the reconcile.Reconciler. func add(mgr manager.Manager, r reconcile.Reconciler) error { if !*mutation.MutationEnabled { return nil @@ -132,7 +130,7 @@ func add(mgr manager.Manager, r reconcile.Reconciler) error { return nil } -// Reconciler reconciles a Assign object +// Reconciler reconciles a Assign object. type Reconciler struct { client.Client system *mutation.System @@ -144,7 +142,7 @@ type Reconciler struct { // +kubebuilder:rbac:groups=mutations.gatekeeper.sh,resources=*,verbs=get;list;watch;create;update;patch;delete // Reconcile reads that state of the cluster for a Assign object and makes changes based on the state read -// and what is in the Assign.Spec +// and what is in the Assign.Spec. func (r *Reconciler) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) { log.Info("Reconcile", "request", request) deleted := false diff --git a/pkg/controller/assign/assign_controller_suite_test.go b/pkg/controller/assign/assign_controller_suite_test.go index dec4a81ba0e..0a3f817dda1 100644 --- a/pkg/controller/assign/assign_controller_suite_test.go +++ b/pkg/controller/assign/assign_controller_suite_test.go @@ -76,7 +76,7 @@ func SetupTestReconcile(inner reconcile.Reconciler) (reconcile.Reconciler, chan return fn, requests } -// StartTestManager adds recFn +// StartTestManager adds recFn. func StartTestManager(ctx context.Context, mgr manager.Manager, g *gomega.GomegaWithT) *sync.WaitGroup { wg := &sync.WaitGroup{} wg.Add(1) @@ -87,7 +87,7 @@ func StartTestManager(ctx context.Context, mgr manager.Manager, g *gomega.Gomega return wg } -// Bootstrap the gatekeeper-system namespace for use in tests +// Bootstrap the gatekeeper-system namespace for use in tests. func createGatekeeperNamespace(cfg *rest.Config) error { c, err := client.New(cfg, client.Options{}) if err != nil { diff --git a/pkg/controller/assign/assign_controller_test.go b/pkg/controller/assign/assign_controller_test.go index e8c98839424..9dfe417f752 100644 --- a/pkg/controller/assign/assign_controller_test.go +++ b/pkg/controller/assign/assign_controller_test.go @@ -182,7 +182,6 @@ func TestReconcile(t *testing.T) { } return nil }, timeout).Should(gomega.Succeed()) - }) testMgrStopped() diff --git a/pkg/controller/assignmetadata/assignmetadata_controller.go b/pkg/controller/assignmetadata/assignmetadata_controller.go index f75fc99aad4..efe526ae705 100644 --- a/pkg/controller/assignmetadata/assignmetadata_controller.go +++ b/pkg/controller/assignmetadata/assignmetadata_controller.go @@ -47,9 +47,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/source" ) -var ( - log = logf.Log.WithName("controller").WithValues(logging.Process, "assignmetadata_controller") -) +var log = logf.Log.WithName("controller").WithValues(logging.Process, "assignmetadata_controller") var gvkAssignMetadata = schema.GroupVersionKind{ Group: mutationsv1alpha1.GroupVersion.Group, @@ -104,7 +102,7 @@ func newReconciler(mgr manager.Manager, mutationCache *mutation.System, tracker return r } -// add adds a new Controller to mgr with r as the reconcile.Reconciler +// add adds a new Controller to mgr with r as the reconcile.Reconciler. func add(mgr manager.Manager, r reconcile.Reconciler) error { if !*mutation.MutationEnabled { return nil @@ -134,7 +132,7 @@ func add(mgr manager.Manager, r reconcile.Reconciler) error { return nil } -// Reconciler reconciles a AssignMetadata object +// Reconciler reconciles a AssignMetadata object. type Reconciler struct { client.Client system *mutation.System @@ -146,7 +144,7 @@ type Reconciler struct { // +kubebuilder:rbac:groups=mutations.gatekeeper.sh,resources=*,verbs=get;list;watch;create;update;patch;delete // Reconcile reads that state of the cluster for a AssignMetadata object and makes changes based on the state read -// and what is in the AssignMetadata.Spec +// and what is in the AssignMetadata.Spec. func (r *Reconciler) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) { log.Info("Reconcile", "request", request) deleted := false diff --git a/pkg/controller/assignmetadata/assignmetadata_controller_suite_test.go b/pkg/controller/assignmetadata/assignmetadata_controller_suite_test.go index 25e3dfecd61..24603b3873f 100644 --- a/pkg/controller/assignmetadata/assignmetadata_controller_suite_test.go +++ b/pkg/controller/assignmetadata/assignmetadata_controller_suite_test.go @@ -76,7 +76,7 @@ func SetupTestReconcile(inner reconcile.Reconciler) (reconcile.Reconciler, chan return fn, requests } -// StartTestManager adds recFn +// StartTestManager adds recFn. func StartTestManager(ctx context.Context, mgr manager.Manager, g *gomega.GomegaWithT) *sync.WaitGroup { wg := &sync.WaitGroup{} wg.Add(1) @@ -87,7 +87,7 @@ func StartTestManager(ctx context.Context, mgr manager.Manager, g *gomega.Gomega return wg } -// Bootstrap the gatekeeper-system namespace for use in tests +// Bootstrap the gatekeeper-system namespace for use in tests. func createGatekeeperNamespace(cfg *rest.Config) error { c, err := client.New(cfg, client.Options{}) if err != nil { diff --git a/pkg/controller/assignmetadata/assignmetadata_controller_test.go b/pkg/controller/assignmetadata/assignmetadata_controller_test.go index 74bc48944ea..85fef029aa7 100644 --- a/pkg/controller/assignmetadata/assignmetadata_controller_test.go +++ b/pkg/controller/assignmetadata/assignmetadata_controller_test.go @@ -180,7 +180,6 @@ func TestReconcile(t *testing.T) { } return nil }, timeout).Should(gomega.Succeed()) - }) testMgrStopped() diff --git a/pkg/controller/config/config_controller.go b/pkg/controller/config/config_controller.go index cd5c5299914..7a83dbb533d 100644 --- a/pkg/controller/config/config_controller.go +++ b/pkg/controller/config/config_controller.go @@ -97,7 +97,7 @@ func (a *Adder) InjectMutationCache(mutationCache *mutation.System) {} // newReconciler returns a new reconcile.Reconciler // events is the channel from which sync controller will receive the events // regEvents is the channel registered by Registrar to put the events in -// events and regEvents point to same event channel except for testing +// events and regEvents point to same event channel except for testing. func newReconciler(mgr manager.Manager, opa syncc.OpaDataClient, wm *watch.Manager, cs *watch.ControllerSwitch, tracker *readiness.Tracker, processExcluder *process.Excluder, events <-chan event.GenericEvent, regEvents chan<- event.GenericEvent) (*ReconcileConfig, error) { watchSet := watch.NewSet() filteredOpa := syncc.NewFilteredOpaDataClient(opa, watchSet) @@ -136,7 +136,7 @@ func newReconciler(mgr manager.Manager, opa syncc.OpaDataClient, wm *watch.Manag }, nil } -// add adds a new Controller to mgr with r as the reconcile.Reconciler +// add adds a new Controller to mgr with r as the reconcile.Reconciler. func add(mgr manager.Manager, r reconcile.Reconciler) error { // Create a new controller c, err := controller.New(ctrlName, mgr, controller.Options{Reconciler: r}) @@ -155,7 +155,7 @@ func add(mgr manager.Manager, r reconcile.Reconciler) error { var _ reconcile.Reconciler = &ReconcileConfig{} -// ReconcileConfig reconciles a Config object +// ReconcileConfig reconciles a Config object. type ReconcileConfig struct { reader client.Reader writer client.Writer @@ -181,7 +181,7 @@ type ReconcileConfig struct { // Reconcile reads that state of the cluster for a Config object and makes changes based on the state read // and what is in the Config.Spec // Automatically generate RBAC rules to allow the Controller to read all things (for sync) -// update is needed for finalizers +// update is needed for finalizers. func (r *ReconcileConfig) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) { // Short-circuit if shutting down. if r.cs != nil { diff --git a/pkg/controller/config/config_controller_suite_test.go b/pkg/controller/config/config_controller_suite_test.go index 93132f748ff..d3adf26034e 100644 --- a/pkg/controller/config/config_controller_suite_test.go +++ b/pkg/controller/config/config_controller_suite_test.go @@ -76,7 +76,7 @@ func SetupTestReconcile(inner reconcile.Reconciler) (reconcile.Reconciler, chan return fn, requests } -// StartTestManager adds recFn +// StartTestManager adds recFn. func StartTestManager(ctx context.Context, mgr manager.Manager, g *gomega.GomegaWithT) *sync.WaitGroup { wg := &sync.WaitGroup{} wg.Add(1) @@ -87,7 +87,7 @@ func StartTestManager(ctx context.Context, mgr manager.Manager, g *gomega.Gomega return wg } -// Bootstrap the gatekeeper-system namespace for use in tests +// Bootstrap the gatekeeper-system namespace for use in tests. func createGatekeeperNamespace(cfg *rest.Config) error { c, err := client.New(cfg, client.Options{}) if err != nil { diff --git a/pkg/controller/config/config_controller_test.go b/pkg/controller/config/config_controller_test.go index f1995be841e..79d2389b909 100644 --- a/pkg/controller/config/config_controller_test.go +++ b/pkg/controller/config/config_controller_test.go @@ -129,7 +129,6 @@ func TestReconcile(t *testing.T) { backend, err := opa.NewBackend(opa.Driver(driver)) if err != nil { t.Fatalf("unable to set up OPA backend: %s", err) - } opa, err := backend.NewClient(opa.Targets(&target.K8sValidationTarget{})) if err != nil { @@ -228,7 +227,7 @@ func TestReconcile(t *testing.T) { cs.Stop() } -// tests that expectations for sync only resource gets canceled when it gets deleted +// tests that expectations for sync only resource gets canceled when it gets deleted. func TestConfig_DeleteSyncResources(t *testing.T) { log.Info("Running test: Cancel the expectations when sync only resource gets deleted") @@ -646,7 +645,7 @@ func unstructuredFor(gvk schema.GroupVersionKind, name string) *unstructured.Uns return u } -// This interface is getting used by tests to check the private objects of objectTracker +// This interface is getting used by tests to check the private objects of objectTracker. type testExpectations interface { IsExpecting(gvk schema.GroupVersionKind, nsName types.NamespacedName) bool } diff --git a/pkg/controller/config/fakes_test.go b/pkg/controller/config/fakes_test.go index 0b7fc2de392..aa81bd87db7 100644 --- a/pkg/controller/config/fakes_test.go +++ b/pkg/controller/config/fakes_test.go @@ -56,6 +56,7 @@ func (f *fakeOpa) keyFor(obj interface{}) (opaKey, error) { key: k, }, nil } + func (f *fakeOpa) AddData(ctx context.Context, data interface{}) (*constraintTypes.Responses, error) { f.mu.Lock() defer f.mu.Unlock() diff --git a/pkg/controller/constraint/constraint_controller.go b/pkg/controller/constraint/constraint_controller.go index 5e1be123b7f..370d942602e 100644 --- a/pkg/controller/constraint/constraint_controller.go +++ b/pkg/controller/constraint/constraint_controller.go @@ -48,9 +48,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/source" ) -var ( - log = logf.Log.WithName("controller").WithValues(logging.Process, "constraint_controller") -) +var log = logf.Log.WithName("controller").WithValues(logging.Process, "constraint_controller") const ( finalizerName = "finalizers.gatekeeper.sh/constraint" @@ -111,7 +109,7 @@ type tags struct { status metrics.Status } -// newReconciler returns a new reconcile.Reconciler +// newReconciler returns a new reconcile.Reconciler. func newReconciler( mgr manager.Manager, opa *opa.Client, @@ -137,7 +135,7 @@ func newReconciler( return r } -// add adds a new Controller to mgr with r as the reconcile.Reconciler +// add adds a new Controller to mgr with r as the reconcile.Reconciler. func add(mgr manager.Manager, r reconcile.Reconciler, events <-chan event.GenericEvent) error { // Create a new controller c, err := controller.New("constraint-controller", mgr, controller.Options{Reconciler: r}) @@ -170,7 +168,7 @@ func add(mgr manager.Manager, r reconcile.Reconciler, events <-chan event.Generi var _ reconcile.Reconciler = &ReconcileConstraint{} -// ReconcileConstraint reconciles an arbitrary constraint object described by Kind +// ReconcileConstraint reconciles an arbitrary constraint object described by Kind. type ReconcileConstraint struct { reader client.Reader writer client.Writer @@ -189,7 +187,7 @@ type ReconcileConstraint struct { // +kubebuilder:rbac:groups=constraints.gatekeeper.sh,resources=*,verbs=get;list;watch;create;update;patch;delete // Reconcile reads that state of the cluster for a constraint object and makes changes based on the state read -// and what is in the constraint.Spec +// and what is in the constraint.Spec. func (r *ReconcileConstraint) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) { // Short-circuit if shutting down. if r.cs != nil { diff --git a/pkg/controller/constraint/stats_reporter.go b/pkg/controller/constraint/stats_reporter.go index 1700f1db6aa..e728915ac42 100644 --- a/pkg/controller/constraint/stats_reporter.go +++ b/pkg/controller/constraint/stats_reporter.go @@ -50,12 +50,12 @@ func (r *reporter) reportConstraints(t tags, v int64) error { return r.report(ctx, constraintsM.M(v)) } -// StatsReporter reports audit metrics +// StatsReporter reports audit metrics. type StatsReporter interface { reportConstraints(t tags, v int64) error } -// newStatsReporter creaters a reporter for audit metrics +// newStatsReporter creaters a reporter for audit metrics. func newStatsReporter() (StatsReporter, error) { ctx, err := tag.New( context.Background(), diff --git a/pkg/controller/constraintstatus/constraintstatus_controller.go b/pkg/controller/constraintstatus/constraintstatus_controller.go index 99eb3e864e2..8daf2925fad 100644 --- a/pkg/controller/constraintstatus/constraintstatus_controller.go +++ b/pkg/controller/constraintstatus/constraintstatus_controller.go @@ -41,9 +41,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/source" ) -var ( - log = logf.Log.WithName("controller").WithValues(logging.Process, "constraint_status_controller") -) +var log = logf.Log.WithName("controller").WithValues(logging.Process, "constraint_status_controller") type Adder struct { Opa *opa.Client @@ -59,7 +57,7 @@ func (a *Adder) Add(mgr manager.Manager) error { return add(mgr, r, a.Events) } -// newReconciler returns a new reconcile.Reconciler +// newReconciler returns a new reconcile.Reconciler. func newReconciler( mgr manager.Manager, cs *watch.ControllerSwitch) reconcile.Reconciler { @@ -78,7 +76,7 @@ func newReconciler( type PackerMap func(obj client.Object) []reconcile.Request // PodStatusToConstraintMapper correlates a ConstraintPodStatus with its corresponding constraint -// `selfOnly` tells the mapper to only map statuses corresponding to the current pod +// `selfOnly` tells the mapper to only map statuses corresponding to the current pod. func PodStatusToConstraintMapper(selfOnly bool, packerMap handler.MapFunc) handler.MapFunc { return func(obj client.Object) []reconcile.Request { labels := obj.GetLabels() @@ -109,7 +107,7 @@ func PodStatusToConstraintMapper(selfOnly bool, packerMap handler.MapFunc) handl } } -// add adds a new Controller to mgr with r as the reconcile.Reconciler +// add adds a new Controller to mgr with r as the reconcile.Reconciler. func add(mgr manager.Manager, r reconcile.Reconciler, events <-chan event.GenericEvent) error { // Create a new controller c, err := controller.New("constraint-status-controller", mgr, controller.Options{Reconciler: r}) @@ -138,7 +136,7 @@ func add(mgr manager.Manager, r reconcile.Reconciler, events <-chan event.Generi var _ reconcile.Reconciler = &ReconcileConstraintStatus{} -// ReconcileConstraintStatus reconciles an arbitrary constraint object described by Kind +// ReconcileConstraintStatus reconciles an arbitrary constraint object described by Kind. type ReconcileConstraintStatus struct { reader client.Reader writer client.Writer @@ -153,7 +151,7 @@ type ReconcileConstraintStatus struct { // +kubebuilder:rbac:groups=status.gatekeeper.sh,resources=*,verbs=get;list;watch;create;update;patch;delete // Reconcile reads that state of the cluster for a constraint object and makes changes based on the state read -// and what is in the constraint.Spec +// and what is in the constraint.Spec. func (r *ReconcileConstraintStatus) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) { // Short-circuit if shutting down. if r.cs != nil { diff --git a/pkg/controller/constrainttemplate/constrainttemplate_controller.go b/pkg/controller/constrainttemplate/constrainttemplate_controller.go index 1c6e23692cd..3275156a2a0 100644 --- a/pkg/controller/constrainttemplate/constrainttemplate_controller.go +++ b/pkg/controller/constrainttemplate/constrainttemplate_controller.go @@ -112,7 +112,7 @@ func (a *Adder) InjectMutationCache(mutationCache *mutation.System) {} // newReconciler returns a new reconcile.Reconciler // cstrEvents is the channel from which constraint controller will receive the events // regEvents is the channel registered by Registrar to put the events in -// cstrEvents and regEvents point to same event channel except for testing +// cstrEvents and regEvents point to same event channel except for testing. func newReconciler(mgr manager.Manager, opa *opa.Client, wm *watch.Manager, cs *watch.ControllerSwitch, tracker *readiness.Tracker, cstrEvents <-chan event.GenericEvent, regEvents chan<- event.GenericEvent, getPod func() (*corev1.Pod, error)) (*ReconcileConstraintTemplate, error) { // constraintsCache contains total number of constraints and shared mutex constraintsCache := constraint.NewConstraintsCache() @@ -185,7 +185,7 @@ func newReconciler(mgr manager.Manager, opa *opa.Client, wm *watch.Manager, cs * return reconciler, nil } -// add adds a new Controller to mgr with r as the reconcile.Reconciler +// add adds a new Controller to mgr with r as the reconcile.Reconciler. func add(mgr manager.Manager, r reconcile.Reconciler) error { // Create a new controller c, err := controller.New(ctrlName, mgr, controller.Options{Reconciler: r}) @@ -225,7 +225,7 @@ func add(mgr manager.Manager, r reconcile.Reconciler) error { var _ reconcile.Reconciler = &ReconcileConstraintTemplate{} -// ReconcileConstraintTemplate reconciles a ConstraintTemplate object +// ReconcileConstraintTemplate reconciles a ConstraintTemplate object. type ReconcileConstraintTemplate struct { client.Client scheme *runtime.Scheme @@ -244,7 +244,7 @@ type ReconcileConstraintTemplate struct { // +kubebuilder:rbac:groups=templates.gatekeeper.sh,resources=constrainttemplates/status,verbs=get;update;patch // Reconcile reads that state of the cluster for a ConstraintTemplate object and makes changes based on the state read -// and what is in the ConstraintTemplate.Spec +// and what is in the ConstraintTemplate.Spec. func (r *ReconcileConstraintTemplate) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) { log := log.WithValues("template_name", request.Name) // Short-circuit if shutting down. diff --git a/pkg/controller/constrainttemplate/constrainttemplate_controller_suite_test.go b/pkg/controller/constrainttemplate/constrainttemplate_controller_suite_test.go index d6559824e2e..c9bbff102ac 100644 --- a/pkg/controller/constrainttemplate/constrainttemplate_controller_suite_test.go +++ b/pkg/controller/constrainttemplate/constrainttemplate_controller_suite_test.go @@ -63,7 +63,7 @@ func TestMain(m *testing.M) { os.Exit(code) } -// StartTestManager adds recFn +// StartTestManager adds recFn. func StartTestManager(ctx context.Context, mgr manager.Manager, g *gomega.GomegaWithT) *sync.WaitGroup { wg := &sync.WaitGroup{} wg.Add(1) @@ -74,7 +74,7 @@ func StartTestManager(ctx context.Context, mgr manager.Manager, g *gomega.Gomega return wg } -// Bootstrap the gatekeeper-system namespace for use in tests +// Bootstrap the gatekeeper-system namespace for use in tests. func createGatekeeperNamespace(cfg *rest.Config) error { c, err := client.New(cfg, client.Options{}) if err != nil { diff --git a/pkg/controller/constrainttemplate/constrainttemplate_controller_test.go b/pkg/controller/constrainttemplate/constrainttemplate_controller_test.go index 941921802d8..cf2e2429103 100644 --- a/pkg/controller/constrainttemplate/constrainttemplate_controller_test.go +++ b/pkg/controller/constrainttemplate/constrainttemplate_controller_test.go @@ -116,7 +116,8 @@ package foo violation[{"msg": "denied!"}] { 1 == 1 } -`}, +`, + }, }, }, } @@ -305,7 +306,8 @@ violation[{"msg": "denied!"}] { anyrule[}}}//invalid//rego - `}, + `, + }, }, }, } @@ -425,7 +427,8 @@ package foo violation[{"msg": "denied!"}] { 1 == 1 } -`}, +`, + }, }, }, } @@ -464,7 +467,6 @@ violation[{"msg": "denied!"}] { backend, err := opa.NewBackend(opa.Driver(driver)) if err != nil { t.Fatalf("unable to set up OPA backend: %s", err) - } opa, err := backend.NewClient(opa.Targets(&target.K8sValidationTarget{})) if err != nil { @@ -661,7 +663,7 @@ func ignoreNotFound(err error) error { return err } -// This interface is getting used by tests to check the private objects of objectTracker +// This interface is getting used by tests to check the private objects of objectTracker. type testExpectations interface { IsExpecting(gvk schema.GroupVersionKind, nsName types.NamespacedName) bool } diff --git a/pkg/controller/constrainttemplate/stats_reporter.go b/pkg/controller/constrainttemplate/stats_reporter.go index 3250d621d2a..7e5a8570d0d 100644 --- a/pkg/controller/constrainttemplate/stats_reporter.go +++ b/pkg/controller/constrainttemplate/stats_reporter.go @@ -88,7 +88,7 @@ func (r *reporter) reportIngestDuration(status metrics.Status, d time.Duration) return metrics.Record(ctx, ingestDurationM.M(d.Seconds())) } -// newStatsReporter creates a reporter for watch metrics +// newStatsReporter creates a reporter for watch metrics. func newStatsReporter() (*reporter, error) { ctx, err := tag.New( context.TODO(), diff --git a/pkg/controller/constrainttemplatestatus/constrainttemplatestatus_controller.go b/pkg/controller/constrainttemplatestatus/constrainttemplatestatus_controller.go index be578811a63..65e76822dbf 100644 --- a/pkg/controller/constrainttemplatestatus/constrainttemplatestatus_controller.go +++ b/pkg/controller/constrainttemplatestatus/constrainttemplatestatus_controller.go @@ -41,9 +41,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/source" ) -var ( - log = logf.Log.WithName("controller").WithValues(logging.Process, "constraint_template_status_controller") -) +var log = logf.Log.WithName("controller").WithValues(logging.Process, "constraint_template_status_controller") type Adder struct { Opa *opa.Client @@ -58,7 +56,7 @@ func (a *Adder) Add(mgr manager.Manager) error { return add(mgr, r) } -// newReconciler returns a new reconcile.Reconciler +// newReconciler returns a new reconcile.Reconciler. func newReconciler( mgr manager.Manager, cs *watch.ControllerSwitch) reconcile.Reconciler { @@ -75,7 +73,7 @@ func newReconciler( } // PodStatusToConstraintTemplateMapper correlates a ConstraintTemplatePodStatus with its corresponding constraint template -// `selfOnly` tells the mapper to only map statuses corresponding to the current pod +// `selfOnly` tells the mapper to only map statuses corresponding to the current pod. func PodStatusToConstraintTemplateMapper(selfOnly bool) handler.MapFunc { return func(obj client.Object) []reconcile.Request { labels := obj.GetLabels() @@ -98,7 +96,7 @@ func PodStatusToConstraintTemplateMapper(selfOnly bool) handler.MapFunc { } } -// add adds a new Controller to mgr with r as the reconcile.Reconciler +// add adds a new Controller to mgr with r as the reconcile.Reconciler. func add(mgr manager.Manager, r reconcile.Reconciler) error { // Create a new controller c, err := controller.New("constraint-template-status-controller", mgr, controller.Options{Reconciler: r}) @@ -126,7 +124,7 @@ func add(mgr manager.Manager, r reconcile.Reconciler) error { var _ reconcile.Reconciler = &ReconcileConstraintStatus{} -// ReconcileConstraintStatus reconciles an arbitrary constraint object described by Kind +// ReconcileConstraintStatus reconciles an arbitrary constraint object described by Kind. type ReconcileConstraintStatus struct { reader client.Reader writer client.Writer @@ -141,7 +139,7 @@ type ReconcileConstraintStatus struct { // +kubebuilder:rbac:groups=status.gatekeeper.sh,resources=*,verbs=get;list;watch;create;update;patch;delete // Reconcile reads that state of the cluster for a constraint object and makes changes based on the state read -// and what is in the constraint.Spec +// and what is in the constraint.Spec. func (r *ReconcileConstraintStatus) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) { // Short-circuit if shutting down. if r.cs != nil { diff --git a/pkg/controller/constrainttemplatestatus/constrainttemplatestatus_controller_suite_test.go b/pkg/controller/constrainttemplatestatus/constrainttemplatestatus_controller_suite_test.go index 5807c325012..dead1d3ca28 100644 --- a/pkg/controller/constrainttemplatestatus/constrainttemplatestatus_controller_suite_test.go +++ b/pkg/controller/constrainttemplatestatus/constrainttemplatestatus_controller_suite_test.go @@ -63,7 +63,7 @@ func TestMain(m *testing.M) { os.Exit(code) } -// StartTestManager adds recFn +// StartTestManager adds recFn. func StartTestManager(ctx context.Context, mgr manager.Manager, g *gomega.GomegaWithT) *sync.WaitGroup { wg := &sync.WaitGroup{} wg.Add(1) @@ -74,7 +74,7 @@ func StartTestManager(ctx context.Context, mgr manager.Manager, g *gomega.Gomega return wg } -// Bootstrap the gatekeeper-system namespace for use in tests +// Bootstrap the gatekeeper-system namespace for use in tests. func createGatekeeperNamespace(cfg *rest.Config) error { c, err := client.New(cfg, client.Options{}) if err != nil { diff --git a/pkg/controller/constrainttemplatestatus/constrainttemplatestatus_controller_test.go b/pkg/controller/constrainttemplatestatus/constrainttemplatestatus_controller_test.go index db9ce8ef558..2db47cde1ef 100644 --- a/pkg/controller/constrainttemplatestatus/constrainttemplatestatus_controller_test.go +++ b/pkg/controller/constrainttemplatestatus/constrainttemplatestatus_controller_test.go @@ -88,7 +88,8 @@ package foo violation[{"msg": "denied!"}] { 1 == 1 } -`}, +`, + }, }, }, } @@ -113,7 +114,6 @@ violation[{"msg": "denied!"}] { backend, err := opa.NewBackend(opa.Driver(driver)) if err != nil { t.Fatalf("unable to set up OPA backend: %s", err) - } opa, err := backend.NewClient(opa.Targets(&target.K8sValidationTarget{})) if err != nil { diff --git a/pkg/controller/controller.go b/pkg/controller/controller.go index a6b8a19779f..29500e2b202 100644 --- a/pkg/controller/controller.go +++ b/pkg/controller/controller.go @@ -37,9 +37,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/manager" ) -var ( - debugUseFakePod = flag.Bool("debug-use-fake-pod", false, "Use a fake pod name so the Gatekeeper executable can be run outside of Kubernetes") -) +var debugUseFakePod = flag.Bool("debug-use-fake-pod", false, "Use a fake pod name so the Gatekeeper executable can be run outside of Kubernetes") type Injector interface { InjectOpa(*opa.Client) @@ -59,10 +57,10 @@ type GetProcessExcluderInjector interface { } // Injectors is a list of adder structs that need injection. We can convert this -// to an interface once we create controllers for things like data sync +// to an interface once we create controllers for things like data sync. var Injectors []Injector -// AddToManagerFuncs is a list of functions to add all Controllers to the Manager +// AddToManagerFuncs is a list of functions to add all Controllers to the Manager. var AddToManagerFuncs []func(manager.Manager) error // Dependencies are dependencies that can be injected into controllers. @@ -120,7 +118,7 @@ func (g *defaultPodGetter) GetPod() (*corev1.Pod, error) { return pod.DeepCopy(), nil } -// AddToManager adds all Controllers to the Manager +// AddToManager adds all Controllers to the Manager. func AddToManager(m manager.Manager, deps Dependencies) error { // Reset cache on start - this is to allow for the future possibility that the OPA cache is stored remotely if err := deps.Opa.Reset(context.Background()); err != nil { diff --git a/pkg/controller/mutatorstatus/mutatorstatus_controller.go b/pkg/controller/mutatorstatus/mutatorstatus_controller.go index 39d39cdeeaf..e1200c8bbeb 100644 --- a/pkg/controller/mutatorstatus/mutatorstatus_controller.go +++ b/pkg/controller/mutatorstatus/mutatorstatus_controller.go @@ -44,9 +44,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/source" ) -var ( - log = logf.Log.WithName("controller").WithValues(logging.Process, "mutator_status_controller") -) +var log = logf.Log.WithName("controller").WithValues(logging.Process, "mutator_status_controller") type Adder struct { WatchManager *watch.Manager @@ -73,7 +71,7 @@ func (a *Adder) Add(mgr manager.Manager) error { return add(mgr, r) } -// newReconciler returns a new reconcile.Reconciler +// newReconciler returns a new reconcile.Reconciler. func newReconciler( mgr manager.Manager, cs *watch.ControllerSwitch) reconcile.Reconciler { @@ -91,7 +89,7 @@ func newReconciler( type PackerMap func(obj client.Object) []reconcile.Request -// PodStatusToMutatorMapper correlates a MutatorPodStatus with its corresponding mutator +// PodStatusToMutatorMapper correlates a MutatorPodStatus with its corresponding mutator. func PodStatusToMutatorMapper(selfOnly bool, kindMatch string, packerMap handler.MapFunc) handler.MapFunc { return func(obj client.Object) []reconcile.Request { labels := obj.GetLabels() @@ -125,7 +123,7 @@ func PodStatusToMutatorMapper(selfOnly bool, kindMatch string, packerMap handler } } -// add adds a new Controller to mgr with r as the reconcile.Reconciler +// add adds a new Controller to mgr with r as the reconcile.Reconciler. func add(mgr manager.Manager, r reconcile.Reconciler) error { // Create a new controller c, err := controller.New("mutator-status-controller", mgr, controller.Options{Reconciler: r}) @@ -158,7 +156,7 @@ func add(mgr manager.Manager, r reconcile.Reconciler) error { var _ reconcile.Reconciler = &ReconcileMutatorStatus{} -// ReconcileMutatorStatus reconciles an arbitrary mutator object described by Kind +// ReconcileMutatorStatus reconciles an arbitrary mutator object described by Kind. type ReconcileMutatorStatus struct { reader client.Reader writer client.Writer @@ -173,7 +171,7 @@ type ReconcileMutatorStatus struct { // +kubebuilder:rbac:groups=status.gatekeeper.sh,resources=*,verbs=get;list;watch;create;update;patch;delete // Reconcile reads that state of the cluster for a mutator object and makes changes based on the state read -// and what is in the mutator.Spec +// and what is in the mutator.Spec. func (r *ReconcileMutatorStatus) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) { // Short-circuit if shutting down. if r.cs != nil { diff --git a/pkg/controller/sync/stats_reporter.go b/pkg/controller/sync/stats_reporter.go index 418fa9d511a..a38bbf471a1 100644 --- a/pkg/controller/sync/stats_reporter.go +++ b/pkg/controller/sync/stats_reporter.go @@ -62,7 +62,7 @@ type Reporter struct { now func() float64 } -// NewStatsReporter creates a reporter for sync metrics +// NewStatsReporter creates a reporter for sync metrics. func NewStatsReporter() (*Reporter, error) { ctx, err := tag.New( context.TODO(), @@ -104,7 +104,7 @@ func (r *Reporter) reportSync(t Tags, v int64) error { return r.report(ctx, syncM.M(v)) } -// now returns the timestamp as a second-denominated float +// now returns the timestamp as a second-denominated float. func now() float64 { return float64(time.Now().UnixNano()) / 1e9 } diff --git a/pkg/controller/sync/sync_controller.go b/pkg/controller/sync/sync_controller.go index 56b70c1ae6a..bbde747a1a5 100644 --- a/pkg/controller/sync/sync_controller.go +++ b/pkg/controller/sync/sync_controller.go @@ -66,7 +66,7 @@ func (a *Adder) Add(mgr manager.Manager) error { return add(mgr, r, a.Events) } -// newReconciler returns a new reconcile.Reconciler +// newReconciler returns a new reconcile.Reconciler. func newReconciler( mgr manager.Manager, opa OpaDataClient, @@ -74,7 +74,6 @@ func newReconciler( metricsCache *MetricsCache, tracker *readiness.Tracker, processExcluder *process.Excluder) (reconcile.Reconciler, error) { - return &ReconcileSync{ reader: mgr.GetCache(), scheme: mgr.GetScheme(), @@ -87,7 +86,7 @@ func newReconciler( }, nil } -// add adds a new Controller to mgr with r as the reconcile.Reconciler +// add adds a new Controller to mgr with r as the reconcile.Reconciler. func add(mgr manager.Manager, r reconcile.Reconciler, events <-chan event.GenericEvent) error { // Create a new controller c, err := controller.New("sync-controller", mgr, controller.Options{Reconciler: r}) @@ -118,7 +117,7 @@ type Tags struct { Status metrics.Status } -// ReconcileSync reconciles an arbitrary object described by Kind +// ReconcileSync reconciles an arbitrary object described by Kind. type ReconcileSync struct { reader client.Reader @@ -134,7 +133,7 @@ type ReconcileSync struct { // +kubebuilder:rbac:groups=constraints.gatekeeper.sh,resources=*,verbs=get;list;watch;create;update;patch;delete // Reconcile reads that state of the cluster for an object and makes changes based on the state read -// and what is in the constraint.Spec +// and what is in the constraint.Spec. func (r *ReconcileSync) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) { timeStart := time.Now() @@ -267,7 +266,7 @@ func (c *MetricsCache) GetSyncKey(namespace string, name string) string { // need to know encountered kinds to reset metrics for that kind // this is a known memory leak -// footprint should naturally reset on Pod upgrade b/c the container restarts +// footprint should naturally reset on Pod upgrade b/c the container restarts. func (c *MetricsCache) addKind(key string) { c.mux.Lock() defer c.mux.Unlock() diff --git a/pkg/gktest/filter.go b/pkg/gktest/filter.go index 51d217191de..6b515f9fcc1 100644 --- a/pkg/gktest/filter.go +++ b/pkg/gktest/filter.go @@ -34,7 +34,7 @@ type Filter struct{} // following: // - Test: "forbid-foo-label", Case: "empty-object" // - Test: "forbid-foo-label", Case: "another-empty-object" -// - Test: "require-bar-annotation", Case: "empty-object" +// - Test: "require-bar-annotation", Case: "empty-object". func NewFilter(run string) (Filter, error) { return Filter{}, nil } diff --git a/pkg/gktest/read_suites.go b/pkg/gktest/read_suites.go index eb9cf6dd0e3..35319e0f0db 100644 --- a/pkg/gktest/read_suites.go +++ b/pkg/gktest/read_suites.go @@ -24,7 +24,7 @@ var ( ErrInvalidYAML = errors.New("invalid yaml") // ErrNotADirectory indicates that a user is mistakenly attempting to // perform a directory-only action on a file (for example, recursively - // traversing it) + // traversing it). ErrNotADirectory = errors.New("not a directory") ) @@ -45,7 +45,7 @@ const ( // // Returns an error if: // - path is a file that does not define a Suite -// - any matched files containing Suites are not parseable +// - any matched files containing Suites are not parseable. func ReadSuites(f fs.FS, target string, recursive bool) ([]Suite, error) { if f == nil { return nil, ErrNoFileSystem diff --git a/pkg/gktest/suite.go b/pkg/gktest/suite.go index d0f6bba57aa..08f8d3965ca 100644 --- a/pkg/gktest/suite.go +++ b/pkg/gktest/suite.go @@ -187,7 +187,7 @@ func (t Test) run(ctx context.Context, client Client, f fs.FS, filter Filter) Te return TestResult{CaseResults: results} } -// Case runs Constraint against a YAML object +// Case runs Constraint against a YAML object. type Case struct{} // run executes the Case and returns the Result of the run. diff --git a/pkg/keys/config.go b/pkg/keys/config.go index df73fbb2395..2959ccd5aa3 100644 --- a/pkg/keys/config.go +++ b/pkg/keys/config.go @@ -20,5 +20,5 @@ import ( "k8s.io/apimachinery/pkg/types" ) -// Config resource singleton reference +// Config resource singleton reference. var Config = types.NamespacedName{Namespace: util.GetNamespace(), Name: "config"} diff --git a/pkg/metrics/exporter.go b/pkg/metrics/exporter.go index 937d13b3371..cf1349a1ab8 100644 --- a/pkg/metrics/exporter.go +++ b/pkg/metrics/exporter.go @@ -38,7 +38,7 @@ func new(mgr manager.Manager) (*runner, error) { return mr, nil } -// Start implements the Runnable interface +// Start implements the Runnable interface. func (r *runner) Start(ctx context.Context) error { log.Info("Starting metrics runner") defer log.Info("Stopping metrics runner workers") diff --git a/pkg/metrics/status.go b/pkg/metrics/status.go index 87e589aeac6..0a2ddba4bed 100644 --- a/pkg/metrics/status.go +++ b/pkg/metrics/status.go @@ -11,7 +11,5 @@ const ( ErrorStatus Status = "error" ) -var ( - // AllStatuses is the set of all allowed values of Status. - AllStatuses = []Status{ActiveStatus, ErrorStatus} -) +// AllStatuses is the set of all allowed values of Status. +var AllStatuses = []Status{ActiveStatus, ErrorStatus} diff --git a/pkg/mutation/match/match.go b/pkg/mutation/match/match.go index ce8e457a1df..74982a34365 100644 --- a/pkg/mutation/match/match.go +++ b/pkg/mutation/match/match.go @@ -173,7 +173,7 @@ func Matches(match *Match, obj client.Object, ns *corev1.Namespace) (bool, error // prefixMatch matches checks if the candidate contains the prefix defined in the source. // The source is expected to end with a "*", which acts as a glob. It is removed when -// performing the prefix-based match +// performing the prefix-based match. func prefixMatch(source, candidate string) bool { if !strings.HasSuffix(source, "*") { return false @@ -182,7 +182,7 @@ func prefixMatch(source, candidate string) bool { return strings.HasPrefix(candidate, strings.TrimSuffix(source, "*")) } -// AppliesTo checks if any item the given slice of ApplyTo applies to the given object +// AppliesTo checks if any item the given slice of ApplyTo applies to the given object. func AppliesTo(applyTo []ApplyTo, obj runtime.Object) bool { gvk := obj.GetObjectKind().GroupVersionKind() for _, apply := range applyTo { diff --git a/pkg/mutation/mutation.go b/pkg/mutation/mutation.go index 05f1827f9df..d2bf70c64ea 100644 --- a/pkg/mutation/mutation.go +++ b/pkg/mutation/mutation.go @@ -19,7 +19,7 @@ import ( logf "sigs.k8s.io/controller-runtime/pkg/log" ) -// MutationEnabled indicates if the mutation feature is enabled +// MutationEnabled indicates if the mutation feature is enabled. var ( MutationEnabled *bool MutationLoggingEnabled *bool diff --git a/pkg/mutation/mutators/assign_mutator.go b/pkg/mutation/mutators/assign_mutator.go index 9f7b6755960..68a9b915e48 100644 --- a/pkg/mutation/mutators/assign_mutator.go +++ b/pkg/mutation/mutators/assign_mutator.go @@ -23,9 +23,7 @@ import ( logf "sigs.k8s.io/controller-runtime/pkg/log" ) -var ( - log = logf.Log.WithName("mutation").WithValues(logging.Process, "mutation") -) +var log = logf.Log.WithName("mutation").WithValues(logging.Process, "mutation") // AssignMutator is a mutator object built out of a // Assign instance. @@ -40,7 +38,7 @@ type AssignMutator struct { valueTest *mutationsv1alpha1.AssignIf } -// AssignMutator implements mutatorWithSchema +// AssignMutator implements mutatorWithSchema. var _ schema.MutatorWithSchema = &AssignMutator{} func (m *AssignMutator) Matches(obj client.Object, ns *corev1.Namespace) bool { @@ -59,7 +57,7 @@ func (m *AssignMutator) Mutate(obj *unstructured.Unstructured) (bool, error) { return core.Mutate(m, m.tester, m.testValue, obj) } -// valueTest returns true if it is okay for the mutation func to override the value +// valueTest returns true if it is okay for the mutation func to override the value. func (m *AssignMutator) testValue(v interface{}, exists bool) bool { if len(m.valueTest.In) != 0 { ifInMatched := false @@ -234,7 +232,7 @@ func gatherPathTests(assign *mutationsv1alpha1.Assign) ([]patht.Test, error) { } // IsValidAssign returns an error if the given assign object is not -// semantically valid +// semantically valid. func IsValidAssign(assign *mutationsv1alpha1.Assign) error { if _, err := MutatorForAssign(assign); err != nil { return err @@ -254,7 +252,7 @@ func hasMetadataRoot(path parser.Path) bool { } // checkKeyNotChanged does not allow to change the key field of -// a list element. A path like foo[name: bar].name is rejected +// a list element. A path like foo[name: bar].name is rejected. func checkKeyNotChanged(p parser.Path, assignName string) error { if len(p.Nodes) == 0 { return errors.New("empty path") diff --git a/pkg/mutation/mutators/assign_mutator_test.go b/pkg/mutation/mutators/assign_mutator_test.go index 52c27ae37aa..a87a8990fce 100644 --- a/pkg/mutation/mutators/assign_mutator_test.go +++ b/pkg/mutation/mutators/assign_mutator_test.go @@ -1455,7 +1455,7 @@ func TestValueTests(t *testing.T) { } // TestApplyTo merely tests that ApplyTo is called, its internal -// logic is tested elsewhere +// logic is tested elsewhere. func TestApplyTo(t *testing.T) { tests := []struct { name string diff --git a/pkg/mutation/mutators/assignmeta_mutator.go b/pkg/mutation/mutators/assignmeta_mutator.go index 0b52f3679cf..ddb3b9ddd4a 100644 --- a/pkg/mutation/mutators/assignmeta_mutator.go +++ b/pkg/mutation/mutators/assignmeta_mutator.go @@ -46,7 +46,7 @@ type AssignMetadataMutator struct { path parser.Path } -// assignMetadataMutator implements mutator +// assignMetadataMutator implements mutator. var _ types.Mutator = &AssignMetadataMutator{} func (m *AssignMetadataMutator) Matches(obj client.Object, ns *corev1.Namespace) bool { @@ -67,6 +67,7 @@ func (m *AssignMetadataMutator) Mutate(obj *unstructured.Unstructured) (bool, er } return core.Mutate(m, t, nil, obj) } + func (m *AssignMetadataMutator) ID() types.ID { return m.id } @@ -148,14 +149,13 @@ func MutatorForAssignMetadata(assignMeta *mutationsv1alpha1.AssignMetadata) (*As }, nil } -// Verifies that the given path is valid for metadata +// Verifies that the given path is valid for metadata. func isValidMetadataPath(path parser.Path) bool { // Path must be metadata.annotations.something or metadata.labels.something if len(path.Nodes) != 3 || path.Nodes[0].Type() != parser.ObjectNode || path.Nodes[1].Type() != parser.ObjectNode || path.Nodes[2].Type() != parser.ObjectNode { - return false } @@ -169,7 +169,7 @@ func isValidMetadataPath(path parser.Path) bool { } // IsValidAssignMetadata returns an error if the given assignmetadata object is not -// semantically valid +// semantically valid. func IsValidAssignMetadata(assignMeta *mutationsv1alpha1.AssignMetadata) error { if _, err := MutatorForAssignMetadata(assignMeta); err != nil { return err diff --git a/pkg/mutation/mutators/core/mutation_function.go b/pkg/mutation/mutators/core/mutation_function.go index ab29d972647..af922571886 100644 --- a/pkg/mutation/mutators/core/mutation_function.go +++ b/pkg/mutation/mutators/core/mutation_function.go @@ -12,9 +12,7 @@ import ( logf "sigs.k8s.io/controller-runtime/pkg/log" ) -var ( - log = logf.Log.WithName("mutation").WithValues(logging.Process, "mutation") -) +var log = logf.Log.WithName("mutation").WithValues(logging.Process, "mutation") func Mutate(mutator types.Mutator, tester *path.Tester, valueTest func(interface{}, bool) bool, obj *unstructured.Unstructured) (bool, error) { s := &mutatorState{mutator: mutator, tester: tester, valueTest: valueTest} @@ -37,7 +35,7 @@ type mutatorState struct { } // mutateInternal mutates the resource recursively. It returns false if there has been no change -// to any downstream objects in the tree, indicating that the mutation should not be persisted +// to any downstream objects in the tree, indicating that the mutation should not be persisted. func (s *mutatorState) mutateInternal(current interface{}, depth int) (bool, interface{}, error) { pathEntry := s.mutator.Path().Nodes[depth] switch castPathEntry := pathEntry.(type) { diff --git a/pkg/mutation/mutators/core/mutation_function_test.go b/pkg/mutation/mutators/core/mutation_function_test.go index 06fee5642bd..a291ea4ee62 100644 --- a/pkg/mutation/mutators/core/mutation_function_test.go +++ b/pkg/mutation/mutators/core/mutation_function_test.go @@ -16,8 +16,10 @@ import ( "k8s.io/apimachinery/pkg/runtime" ) -const TestValue = "testValue" -const ParameterTestValue = "\"testValue\"" +const ( + TestValue = "testValue" + ParameterTestValue = "\"testValue\"" +) func prepareTestPod(t *testing.T) *unstructured.Unstructured { pod := &corev1.Pod{ @@ -320,7 +322,6 @@ func testDummyMutation( unstructured *unstructured.Unstructured, testFunc func(*unstructured.Unstructured), t *testing.T) error { - mutator := testhelpers.NewDummyMutator("dummy", location, value) return testMutation(mutator, unstructured, testFunc, t) } @@ -332,7 +333,6 @@ func testAssignMutation( unstructured *unstructured.Unstructured, testFunc func(*unstructured.Unstructured), t *testing.T) error { - assign := mutationsv1alpha1.Assign{ ObjectMeta: metav1.ObjectMeta{}, Spec: mutationsv1alpha1.AssignSpec{ @@ -358,7 +358,6 @@ func testAssignMetadataMutation( unstructured *unstructured.Unstructured, testFunc func(*unstructured.Unstructured), t *testing.T) error { - assignMetadata := mutationsv1alpha1.AssignMetadata{ ObjectMeta: metav1.ObjectMeta{}, Spec: mutationsv1alpha1.AssignMetadataSpec{ diff --git a/pkg/mutation/mutators/testhelpers/dummy_mutator.go b/pkg/mutation/mutators/testhelpers/dummy_mutator.go index 785160e7487..711a6b30099 100644 --- a/pkg/mutation/mutators/testhelpers/dummy_mutator.go +++ b/pkg/mutation/mutators/testhelpers/dummy_mutator.go @@ -15,7 +15,7 @@ import ( var _ types.Mutator = &DummyMutator{} -// DummyMutator is a blank mutator that makes it easier to test the core mutation function +// DummyMutator is a blank mutator that makes it easier to test the core mutation function. type DummyMutator struct { name string value interface{} diff --git a/pkg/mutation/path/parser/errors.go b/pkg/mutation/path/parser/errors.go index 3fa2ffc4190..e4ae81ffce5 100644 --- a/pkg/mutation/path/parser/errors.go +++ b/pkg/mutation/path/parser/errors.go @@ -36,6 +36,7 @@ type invalidIntegerError struct { func (e invalidIntegerError) Error() string { return fmt.Sprintf("invalid integer: %s", e.s) } + func (e invalidIntegerError) Is(target error) bool { _, ok := target.(invalidIntegerError) return ok diff --git a/pkg/mutation/path/parser/node.go b/pkg/mutation/path/parser/node.go index 88c5d7b224b..66f80a61ca1 100644 --- a/pkg/mutation/path/parser/node.go +++ b/pkg/mutation/path/parser/node.go @@ -38,7 +38,7 @@ type Node interface { String() string } -// Path represents an entire parsed path specification +// Path represents an entire parsed path specification. type Path struct { Nodes []Node } diff --git a/pkg/mutation/path/parser/parser.go b/pkg/mutation/path/parser/parser.go index 2a5e1830d58..580fd46d51c 100644 --- a/pkg/mutation/path/parser/parser.go +++ b/pkg/mutation/path/parser/parser.go @@ -140,7 +140,6 @@ func (p *parser) parseList() Node { if err != nil { p.setError(fmt.Errorf("%w: parsing key value for key: %s", err, out.KeyField)) return nil - } out.KeyValue = val default: diff --git a/pkg/mutation/path/tester/tester.go b/pkg/mutation/path/tester/tester.go index 741a29a6c1c..72bb073fbac 100644 --- a/pkg/mutation/path/tester/tester.go +++ b/pkg/mutation/path/tester/tester.go @@ -14,18 +14,16 @@ import ( type Condition string const ( - // MustExist means that an object must exist at the given path entry + // MustExist means that an object must exist at the given path entry. MustExist = Condition("MustExist") - // MustNotExist means that an object must not exist at the given path entry + // MustNotExist means that an object must not exist at the given path entry. MustNotExist = Condition("MustNotExist") ) -var ( - conditions = map[string]Condition{ - "MustExist": MustExist, - "MustNotExist": MustNotExist, - } -) +var conditions = map[string]Condition{ + "MustExist": MustExist, + "MustNotExist": MustNotExist, +} // Base errors for validating path tests. var ( @@ -33,7 +31,7 @@ var ( ErrConflict = errors.New("conflicting path test conditions") ) -// StringToCondition translates a user-provided string into a Test Condition +// StringToCondition translates a user-provided string into a Test Condition. func StringToCondition(s string) (Condition, error) { cond, ok := conditions[s] if !ok { @@ -43,7 +41,7 @@ func StringToCondition(s string) (Condition, error) { return cond, nil } -// Test describes a condition that the object must satisfy +// Test describes a condition that the object must satisfy. type Test struct { SubPath parser.Path Condition Condition @@ -63,7 +61,7 @@ func isPrefix(short, long parser.Path) bool { return true } -// validatePathTests returns whether a set of path tests are valid against the provided location +// validatePathTests returns whether a set of path tests are valid against the provided location. func validatePathTests(location parser.Path, pathTests []Test) error { for _, pathTest := range pathTests { if !isPrefix(pathTest.SubPath, location) { @@ -73,7 +71,7 @@ func validatePathTests(location parser.Path, pathTests []Test) error { return nil } -// New creates a new Tester object +// New creates a new Tester object. func New(location parser.Path, tests []Test) (*Tester, error) { err := validatePathTests(location, tests) if err != nil { @@ -118,12 +116,12 @@ func New(location parser.Path, tests []Test) (*Tester, error) { return idx, nil } -// Tester knows whether it's okay that an object exists at a given path depth +// Tester knows whether it's okay that an object exists at a given path depth. type Tester struct { tests map[int]Condition } -// ExistsOkay returns true if it's okay that an object exists +// ExistsOkay returns true if it's okay that an object exists. func (pt *Tester) ExistsOkay(depth int) bool { c, ok := pt.tests[depth] if !ok { @@ -132,7 +130,7 @@ func (pt *Tester) ExistsOkay(depth int) bool { return c == MustExist } -// MissingOkay returns true if it's okay that an object is missing +// MissingOkay returns true if it's okay that an object is missing. func (pt *Tester) MissingOkay(depth int) bool { c, ok := pt.tests[depth] if !ok { @@ -141,7 +139,7 @@ func (pt *Tester) MissingOkay(depth int) bool { return c == MustNotExist } -// DeepCopy returns a deep copy of the tester +// DeepCopy returns a deep copy of the tester. func (pt *Tester) DeepCopy() *Tester { if pt == nil { return nil diff --git a/pkg/mutation/path/token/scanner.go b/pkg/mutation/path/token/scanner.go index b49590648d5..607960015a9 100644 --- a/pkg/mutation/path/token/scanner.go +++ b/pkg/mutation/path/token/scanner.go @@ -46,7 +46,7 @@ func NewScanner(input string) *Scanner { func (s *Scanner) Next() Token { var err error - var tok = Token{Type: ERROR} + tok := Token{Type: ERROR} s.skipWhitespace() switch { @@ -174,7 +174,6 @@ func isAlphaNum(r rune) bool { default: return false - } return true } @@ -198,7 +197,6 @@ func (e ScanError) Error() string { var innerMsg string if e.Inner != nil { innerMsg = e.Inner.Error() - } return fmt.Sprintf("error at position %d: %s", e.Position, innerMsg) } diff --git a/pkg/mutation/path/token/token.go b/pkg/mutation/path/token/token.go index 1a452d9eb61..dd6614bdedf 100644 --- a/pkg/mutation/path/token/token.go +++ b/pkg/mutation/path/token/token.go @@ -30,11 +30,13 @@ const ( COLON = "COLON" ) -type Type string -type Token struct { - Type Type - Literal string -} +type ( + Type string + Token struct { + Type Type + Literal string + } +) func (t Token) String() string { return fmt.Sprintf("%s: %q", t.Type, t.Literal) diff --git a/pkg/mutation/schema/schema.go b/pkg/mutation/schema/schema.go index 8e0a6693025..50027ebe749 100644 --- a/pkg/mutation/schema/schema.go +++ b/pkg/mutation/schema/schema.go @@ -18,11 +18,9 @@ type MutatorWithSchema interface { SchemaBindings() []schema.GroupVersionKind } -var ( - log = logf.Log.WithName("mutation_schema") -) +var log = logf.Log.WithName("mutation_schema") -// New returns a new schema database +// New returns a new schema database. func New() *DB { return &DB{ cachedMutators: make(map[types.ID]MutatorWithSchema), diff --git a/pkg/mutation/system.go b/pkg/mutation/system.go index 504b68837ea..eff24c8a0ac 100644 --- a/pkg/mutation/system.go +++ b/pkg/mutation/system.go @@ -25,7 +25,7 @@ type System struct { mux sync.RWMutex } -// NewSystem initializes an empty mutation system +// NewSystem initializes an empty mutation system. func NewSystem() *System { return &System{ schemaDB: *schema.New(), @@ -35,7 +35,7 @@ func NewSystem() *System { } // Upsert updates or insert the given object, and returns -// an error in case of conflicts +// an error in case of conflicts. func (s *System) Upsert(m types.Mutator) error { s.mux.Lock() defer s.mux.Unlock() @@ -197,7 +197,7 @@ func logAppliedMutations(message string, mutationUUID uuid.UUID, obj *unstructur } } -// Remove removes the mutator from the mutation system +// Remove removes the mutator from the mutation system. func (s *System) Remove(id types.ID) error { s.mux.Lock() defer s.mux.Unlock() @@ -231,7 +231,7 @@ func (s *System) Remove(id types.ID) error { return nil } -// Get mutator for given id +// Get mutator for given id. func (s *System) Get(id types.ID) types.Mutator { mutator, found := s.mutatorsMap[id] if !found { diff --git a/pkg/mutation/system_test.go b/pkg/mutation/system_test.go index 6ac9be3398b..1457708c0cd 100644 --- a/pkg/mutation/system_test.go +++ b/pkg/mutation/system_test.go @@ -163,14 +163,18 @@ func TestSorting(t *testing.T) { &fakeMutator{MID: types.ID{Group: "aaa", Kind: "aaa", Namespace: "aaa", Name: "aaa"}}, &fakeMutator{MID: types.ID{Group: "aaa", Kind: "aaa", Namespace: "ccc", Name: "ddd"}}, &fakeMutator{MID: types.ID{Group: "aaa", Kind: "bbb", Namespace: "aaa", Name: "aaa"}}, - &fakeMutator{MID: types.ID{Group: "aaa", Kind: "bbb", Namespace: "ccc", Name: "aaa"}, - MPath: mustParse("relevantvalue"), GVKs: []schema.GroupVersionKind{{Kind: "foo"}}}, + &fakeMutator{ + MID: types.ID{Group: "aaa", Kind: "bbb", Namespace: "ccc", Name: "aaa"}, + MPath: mustParse("relevantvalue"), GVKs: []schema.GroupVersionKind{{Kind: "foo"}}, + }, &fakeMutator{MID: types.ID{Group: "aaa", Kind: "bbb", Namespace: "ccc", Name: "ddd"}}, &fakeMutator{MID: types.ID{Group: "bbb", Kind: "aaa", Namespace: "aaa", Name: "aaa"}}, }, action: func(s *System) error { - return s.Upsert(&fakeMutator{MID: types.ID{Group: "aaa", Kind: "bbb", Namespace: "ccc", Name: "aaa"}, - MPath: mustParse("relevantvalue"), GVKs: []schema.GroupVersionKind{{Kind: "foo"}}}) + return s.Upsert(&fakeMutator{ + MID: types.ID{Group: "aaa", Kind: "bbb", Namespace: "ccc", Name: "aaa"}, + MPath: mustParse("relevantvalue"), GVKs: []schema.GroupVersionKind{{Kind: "foo"}}, + }) }, }, } diff --git a/pkg/mutation/types/mutator.go b/pkg/mutation/types/mutator.go index 756f2db0328..2e39349c249 100644 --- a/pkg/mutation/types/mutator.go +++ b/pkg/mutation/types/mutator.go @@ -44,7 +44,7 @@ type Mutator interface { String() string } -// MakeID builds an ID object for the given object +// MakeID builds an ID object for the given object. func MakeID(obj client.Object) ID { return ID{ Group: obj.GetObjectKind().GroupVersionKind().Group, @@ -54,7 +54,7 @@ func MakeID(obj client.Object) ID { } } -// UnmarshalValue unmarshals the value a mutation is meant to assign +// UnmarshalValue unmarshals the value a mutation is meant to assign. func UnmarshalValue(data []byte) (interface{}, error) { value := make(map[string]interface{}) err := json.Unmarshal(data, &value) diff --git a/pkg/operations/operations.go b/pkg/operations/operations.go index eed95eaf7a3..504c67ff88e 100644 --- a/pkg/operations/operations.go +++ b/pkg/operations/operations.go @@ -80,7 +80,7 @@ func init() { flag.Var(operations, "operation", "The operation to be performed by this instance. e.g. audit, webhook. This flag can be declared more than once. Omitting will default to supporting all operations.") } -// AssignedOperations returns a map of operations assigned to the pod +// AssignedOperations returns a map of operations assigned to the pod. func AssignedOperations() map[Operation]bool { ret := make(map[Operation]bool) for k, v := range operations.assignedOperations { @@ -89,13 +89,13 @@ func AssignedOperations() map[Operation]bool { return ret } -// IsAssigned returns true when the provided operation is assigned to the pod +// IsAssigned returns true when the provided operation is assigned to the pod. func IsAssigned(op Operation) bool { return operations.assignedOperations[op] } // AssignedStringList returns a list of all operations assigned to the pod -// as a sorted list of strings +// as a sorted list of strings. func AssignedStringList() []string { if operations.assignedStringList != nil { return operations.assignedStringList diff --git a/pkg/readiness/integration_suite_test.go b/pkg/readiness/integration_suite_test.go index 643c84d8d68..e34d04ed078 100644 --- a/pkg/readiness/integration_suite_test.go +++ b/pkg/readiness/integration_suite_test.go @@ -64,7 +64,7 @@ func TestMain(m *testing.M) { os.Exit(code) } -// StartTestManager adds recFn +// StartTestManager adds recFn. func StartTestManager(ctx context.Context, mgr manager.Manager, g *gomega.GomegaWithT) *sync.WaitGroup { wg := &sync.WaitGroup{} wg.Add(1) @@ -75,7 +75,7 @@ func StartTestManager(ctx context.Context, mgr manager.Manager, g *gomega.Gomega return wg } -// Bootstrap the gatekeeper-system namespace for use in tests +// Bootstrap the gatekeeper-system namespace for use in tests. func createGatekeeperNamespace(cfg *rest.Config) error { c, err := client.New(cfg, client.Options{}) if err != nil { diff --git a/pkg/readiness/list.go b/pkg/readiness/list.go index 32df1db6203..38d754aadb4 100644 --- a/pkg/readiness/list.go +++ b/pkg/readiness/list.go @@ -48,7 +48,6 @@ func retryLister(r Lister, predicate retryPredicate) Lister { backoff.Cap = 5 * time.Second err := syncutil.BackoffWithContext(ctx, backoff, func() (bool, error) { err := r.List(ctx, out, opts...) - if err != nil { if ctx.Err() != nil { // Give up when our parent context is canceled @@ -65,7 +64,6 @@ func retryLister(r Lister, predicate retryPredicate) Lister { // Success return true, nil }) - if err != nil { log.Error(err, "listing", "gvk", gvk, "err", err) return err diff --git a/pkg/readiness/object_tracker.go b/pkg/readiness/object_tracker.go index dc7edaff92e..7a516c479c9 100644 --- a/pkg/readiness/object_tracker.go +++ b/pkg/readiness/object_tracker.go @@ -192,7 +192,7 @@ func (t *objectTracker) ExpectationsDone() { t.populated = true } -// Unsatisfied returns all unsatisfied expectations +// Unsatisfied returns all unsatisfied expectations. func (t *objectTracker) unsatisfied() []objKey { t.mu.RLock() defer t.mu.RUnlock() diff --git a/pkg/readiness/object_tracker_test.go b/pkg/readiness/object_tracker_test.go index 796e43ae041..777141c0550 100644 --- a/pkg/readiness/object_tracker_test.go +++ b/pkg/readiness/object_tracker_test.go @@ -245,7 +245,7 @@ func Test_ObjectTracker_kinds(t *testing.T) { g.Expect(kindsAfter).Should(gomega.Equal(kindsBefore), "expected kinds to match") } -// Verify that TryCancelExpect functions the same as regular CancelExpect if readinessRetries is set to 0 +// Verify that TryCancelExpect functions the same as regular CancelExpect if readinessRetries is set to 0. func Test_ObjectTracker_TryCancelExpect_Default(t *testing.T) { g := gomega.NewWithT(t) ot := newObjTracker(schema.GroupVersionKind{}, func() objData { @@ -274,7 +274,7 @@ func Test_ObjectTracker_TryCancelExpect_Default(t *testing.T) { g.Expect(ot.Satisfied()).To(gomega.BeTrue(), "should be satisfied") } -// Verify that TryCancelExpect must be called multiple times before an expectation is canceled +// Verify that TryCancelExpect must be called multiple times before an expectation is canceled. func Test_ObjectTracker_TryCancelExpect_WithRetries(t *testing.T) { g := gomega.NewWithT(t) ot := newObjTracker(schema.GroupVersionKind{}, func() objData { diff --git a/pkg/readiness/objset.go b/pkg/readiness/objset.go index 61bd9d34797..35347c8b52d 100644 --- a/pkg/readiness/objset.go +++ b/pkg/readiness/objset.go @@ -31,17 +31,17 @@ func (k *objKey) String() string { return fmt.Sprintf("%s [%s]", k.namespacedName.String(), k.gvk.String()) } -// objSet is a set of objKey types with no data +// objSet is a set of objKey types with no data. type objSet map[objKey]struct{} -// retryObjSet holds the allowed retries for a specific object +// retryObjSet holds the allowed retries for a specific object. type objRetrySet map[objKey]objData type objData struct { retries int } -// decrementRetries handles objData retries, and returns `true` if it's time to delete the objData entry +// decrementRetries handles objData retries, and returns `true` if it's time to delete the objData entry. func (o *objData) decrementRetries() bool { // if retries is less than 0, allowed retries are infinite if o.retries < 0 { diff --git a/pkg/readiness/ready_tracker.go b/pkg/readiness/ready_tracker.go index 839279b25dc..eb8111c79ee 100644 --- a/pkg/readiness/ready_tracker.go +++ b/pkg/readiness/ready_tracker.go @@ -70,7 +70,7 @@ type Tracker struct { mutationEnabled bool } -// NewTracker creates a new Tracker and initializes the internal trackers +// NewTracker creates a new Tracker and initializes the internal trackers. func NewTracker(lister Lister, mutationEnabled bool) *Tracker { return newTracker(lister, mutationEnabled, nil) } @@ -290,7 +290,7 @@ func (t *Tracker) Populated() bool { } // collectForObjectTracker identifies objects that are unsatisfied for the provided -// `es`, which must be an objectTracker, and removes those expectations +// `es`, which must be an objectTracker, and removes those expectations. func (t *Tracker) collectForObjectTracker(ctx context.Context, es Expectations, cleanup func(schema.GroupVersionKind)) error { if es == nil { return fmt.Errorf("nil Expectations provided to collectForObjectTracker") diff --git a/pkg/readiness/ready_tracker_test.go b/pkg/readiness/ready_tracker_test.go index 02b1bd19fd7..d177d466e46 100644 --- a/pkg/readiness/ready_tracker_test.go +++ b/pkg/readiness/ready_tracker_test.go @@ -427,7 +427,7 @@ func Test_CollectDeleted(t *testing.T) { } } -// probeIsReady checks whether expectations have been satisfied (via the readiness probe) +// probeIsReady checks whether expectations have been satisfied (via the readiness probe). func probeIsReady(ctx context.Context) (bool, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://127.0.0.1:29090/readyz", http.NoBody) if err != nil { diff --git a/pkg/readiness/ready_tracker_unit_test.go b/pkg/readiness/ready_tracker_unit_test.go index 1a25f4ef201..3ecee7f0def 100644 --- a/pkg/readiness/ready_tracker_unit_test.go +++ b/pkg/readiness/ready_tracker_unit_test.go @@ -27,7 +27,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" ) -// Stub out the lister +// Stub out the lister. type dummyLister struct{} var scheme *runtime.Scheme @@ -66,7 +66,7 @@ func (dl dummyLister) List(ctx context.Context, list client.ObjectList, opts ... return nil } -// Verify that TryCancelTemplate functions the same as regular CancelTemplate if readinessRetries is set to 0 +// Verify that TryCancelTemplate functions the same as regular CancelTemplate if readinessRetries is set to 0. func Test_ReadyTracker_TryCancelTemplate_No_Retries(t *testing.T) { g := gomega.NewWithT(t) @@ -96,7 +96,7 @@ func Test_ReadyTracker_TryCancelTemplate_No_Retries(t *testing.T) { g.Expect(rt.Satisfied(ctx)).To(gomega.BeTrue(), "tracker with 0 retries and cancellation should be satisfied") } -// Verify that TryCancelTemplate must be called enough times to remove all retries before canceling a template +// Verify that TryCancelTemplate must be called enough times to remove all retries before canceling a template. func Test_ReadyTracker_TryCancelTemplate_Retries(t *testing.T) { g := gomega.NewWithT(t) diff --git a/pkg/readiness/testdata_test.go b/pkg/readiness/testdata_test.go index d259bbbe52a..6f18f30dec5 100644 --- a/pkg/readiness/testdata_test.go +++ b/pkg/readiness/testdata_test.go @@ -22,20 +22,22 @@ import ( "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" ) -// Templates and constraints in testdata/ +// Templates and constraints in testdata/. var testTemplates = []*templates.ConstraintTemplate{ makeTemplate("k8sallowedrepos"), makeTemplate("k8srequiredlabels"), } + var testConstraints = []*unstructured.Unstructured{ makeConstraint("ns-must-have-gk", "K8sRequiredLabels"), makeConstraint("prod-repo-is-openpolicyagent", "K8sAllowedRepos"), } -// Templates and constraint in testdata/post/ +// Templates and constraint in testdata/post/. var postTemplates = []*templates.ConstraintTemplate{ makeTemplate("k8shttpsonly"), } + var postConstraints = []*unstructured.Unstructured{ makeConstraint("ingress-https-only", "K8sHttpsOnly"), } diff --git a/pkg/readiness/tracker_map.go b/pkg/readiness/tracker_map.go index 3b9f3ff4921..f18fb86b932 100644 --- a/pkg/readiness/tracker_map.go +++ b/pkg/readiness/tracker_map.go @@ -103,7 +103,7 @@ func (t *trackerMap) Satisfied() bool { return true } -// Populated returns true if all objectTrackers are populated +// Populated returns true if all objectTrackers are populated. func (t *trackerMap) Populated() bool { t.mu.RLock() defer t.mu.RUnlock() diff --git a/pkg/target/target.go b/pkg/target/target.go index 4d61c43fcc5..2ef78f51811 100644 --- a/pkg/target/target.go +++ b/pkg/target/target.go @@ -199,7 +199,7 @@ func getString(m map[string]interface{}, k string) (string, error) { } // nestedMap augments unstructured.NestedMap to interpret a nil-valued field -// as missing +// as missing. func nestedMap(rmap map[string]interface{}, field string) (map[string]interface{}, bool, error) { objMap, found, err := unstructured.NestedMap(rmap, field) if err != nil || !found { diff --git a/pkg/upgrade/controller.go b/pkg/upgrade/controller.go index eb36633f64f..2f41f19970c 100644 --- a/pkg/upgrade/controller.go +++ b/pkg/upgrade/controller.go @@ -18,7 +18,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/manager" ) -// AddToManager adds upgrade manager to the Manager +// AddToManager adds upgrade manager to the Manager. func AddToManager(m manager.Manager) error { am, err := New(context.Background(), m) if err != nil { diff --git a/pkg/upgrade/manager.go b/pkg/upgrade/manager.go index 2faffb77620..3867ebcdf23 100644 --- a/pkg/upgrade/manager.go +++ b/pkg/upgrade/manager.go @@ -28,14 +28,14 @@ const ( crdName = "constrainttemplates.templates.gatekeeper.sh" ) -// Manager allows us to upgrade resources on startup +// Manager allows us to upgrade resources on startup. type Manager struct { client client.Client mgr manager.Manager ctx context.Context } -// New creates a new manager for audit +// New creates a new manager for audit. func New(ctx context.Context, mgr manager.Manager) (*Manager, error) { am := &Manager{ mgr: mgr, @@ -44,7 +44,7 @@ func New(ctx context.Context, mgr manager.Manager) (*Manager, error) { return am, nil } -// Start implements the Runnable interface +// Start implements the Runnable interface. func (um *Manager) Start(ctx context.Context) error { log.Info("Starting Upgrade Manager") defer log.Info("Stopping upgrade manager workers") @@ -89,7 +89,7 @@ func (um *Manager) upgrade(ctx context.Context) error { return nil } -// upgradeGroupVersion touches each resource in a given groupVersion, incrementing its storage version +// upgradeGroupVersion touches each resource in a given groupVersion, incrementing its storage version. func (um *Manager) upgradeGroupVersion(ctx context.Context, groupVersion string) error { // new client to get updated restmapper c, err := client.New(um.mgr.GetConfig(), client.Options{Scheme: um.mgr.GetScheme(), Mapper: nil}) diff --git a/pkg/util/pack.go b/pkg/util/pack.go index 09c1f67f23d..fdb7ba85747 100644 --- a/pkg/util/pack.go +++ b/pkg/util/pack.go @@ -19,7 +19,7 @@ var ErrInvalidPackedName = errors.New("invalid packed name, want request.Name to // UnpackRequest unpacks the GVK from a reconcile.Request and returns the separated components. // GVK is encoded as "Kind.Version.Group". -// Requests are expected to be in the format: {Name: "gvk:EncodedGVK:Name", Namespace: Namespace} +// Requests are expected to be in the format: {Name: "gvk:EncodedGVK:Name", Namespace: Namespace}. func UnpackRequest(r reconcile.Request) (schema.GroupVersionKind, reconcile.Request, error) { fields := strings.SplitN(r.Name, ":", 3) if len(fields) != 3 || fields[0] != "gvk" { @@ -57,13 +57,14 @@ func EventPackerMapFunc() handler.MapFunc { NamespacedName: types.NamespacedName{ Namespace: obj.GetNamespace(), Name: packed, - }}, + }, + }, } } } // EventPackerMapFuncHardcodeGVK accounts for the fact that typed K8s objects have -// no GVK associated with them by allowing the caller to set the expected GVK +// no GVK associated with them by allowing the caller to set the expected GVK. func EventPackerMapFuncHardcodeGVK(gvk schema.GroupVersionKind) handler.MapFunc { mf := EventPackerMapFunc() return func(obj client.Object) []reconcile.Request { diff --git a/pkg/util/pod_info.go b/pkg/util/pod_info.go index 4287317de53..475c81fe942 100644 --- a/pkg/util/pod_info.go +++ b/pkg/util/pod_info.go @@ -2,12 +2,12 @@ package util import "os" -// GetPodName returns the name of the Gatekeeper pod +// GetPodName returns the name of the Gatekeeper pod. func GetPodName() string { return os.Getenv("POD_NAME") } -// GetID returns a unique name for the Gatekeeper pod +// GetID returns a unique name for the Gatekeeper pod. func GetID() string { return GetPodName() } diff --git a/pkg/version/version.go b/pkg/version/version.go index 7b09dad25a3..52531b3049d 100644 --- a/pkg/version/version.go +++ b/pkg/version/version.go @@ -5,16 +5,16 @@ import ( "runtime" ) -// Vcs is is the commit hash for the binary build +// Vcs is is the commit hash for the binary build. var Vcs string -// Timestamp is the date for the binary build +// Timestamp is the date for the binary build. var Timestamp string -// Version is the gatekeeper version +// Version is the gatekeeper version. var Version string -// GetUserAgent returns a user agent of the format: gatekeeper/ (/) / +// GetUserAgent returns a user agent of the format: gatekeeper/ (/) /. func GetUserAgent() string { return fmt.Sprintf("gatekeeper/%s (%s/%s) %s/%s", Version, runtime.GOOS, runtime.GOARCH, Vcs, Timestamp) } diff --git a/pkg/watch/manager.go b/pkg/watch/manager.go index 94d49184104..e1fd241f05a 100644 --- a/pkg/watch/manager.go +++ b/pkg/watch/manager.go @@ -33,7 +33,7 @@ import ( var log = logf.Log.WithName("watch-manager") -// Manager allows us to dynamically configure what kinds are watched +// Manager allows us to dynamically configure what kinds are watched. type Manager struct { cache RemovableCache startedMux sync.Mutex diff --git a/pkg/watch/manager_test.go b/pkg/watch/manager_test.go index f43e07c76ab..6f63937c9c7 100644 --- a/pkg/watch/manager_test.go +++ b/pkg/watch/manager_test.go @@ -363,7 +363,7 @@ func TestRegistrar_Replay(t *testing.T) { } } -// Verify that event replay can retry upon error +// Verify that event replay can retry upon error. func TestRegistrar_Replay_Retry(t *testing.T) { g := gomega.NewWithT(t) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) diff --git a/pkg/watch/registrar.go b/pkg/watch/registrar.go index 51f44f14974..8622da12c4a 100644 --- a/pkg/watch/registrar.go +++ b/pkg/watch/registrar.go @@ -48,7 +48,7 @@ func (w *vitals) merge(wv vitals) vitals { } // recordKeeper holds the source of truth for the intended state of the manager -// This is essentially a read/write lock on the wrapped map (the `intent` variable) +// This is essentially a read/write lock on the wrapped map (the `intent` variable). type recordKeeper struct { // map[registrarName][kind] intent map[string]vitalsByGVK @@ -120,7 +120,6 @@ func (r *recordKeeper) ReplaceRegistrarRoster(reg *Registrar, roster map[schema. if err := r.metrics.reportGvkIntentCount(int64(r.count())); err != nil { log.Error(err, "while reporting gvk intent count metric") } - }() r.intent[reg.parentName] = roster @@ -164,7 +163,7 @@ func (r *recordKeeper) Get() vitalsByGVK { return managedKinds } -// count returns total gvk count across all registrars +// count returns total gvk count across all registrars. func (r *recordKeeper) count() int { managedKinds := make(map[schema.GroupVersionKind]bool) for _, registrar := range r.intent { @@ -198,7 +197,7 @@ func newRecordKeeper() (*recordKeeper, error) { }, nil } -// A Registrar allows a parent to add/remove child watches +// A Registrar allows a parent to add/remove child watches. type Registrar struct { parentName string mgr *Manager diff --git a/pkg/watch/stats_reporter.go b/pkg/watch/stats_reporter.go index 4985e9e08ec..c9593218136 100644 --- a/pkg/watch/stats_reporter.go +++ b/pkg/watch/stats_reporter.go @@ -52,7 +52,7 @@ func (r *reporter) reportGvkIntentCount(count int64) error { return metrics.Record(r.ctx, gvkIntentCountM.M(count)) } -// newStatsReporter creates a reporter for watch metrics +// newStatsReporter creates a reporter for watch metrics. func newStatsReporter() (*reporter, error) { ctx, err := tag.New( context.TODO(), diff --git a/pkg/webhook/common.go b/pkg/webhook/common.go index 409a7330508..907aa4e1b63 100644 --- a/pkg/webhook/common.go +++ b/pkg/webhook/common.go @@ -57,7 +57,7 @@ var ( logDenies = flag.Bool("log-denies", false, "log detailed info on each deny") emitAdmissionEvents = flag.Bool("emit-admission-events", false, "(alpha) emit Kubernetes events in gatekeeper namespace for each admission violation") serviceaccount = fmt.Sprintf("system:serviceaccount:%s:%s", util.GetNamespace(), serviceAccountName) - // webhookName is deprecated, set this on the manifest YAML if needed" + // webhookName is deprecated, set this on the manifest YAML if needed". ) func init() { @@ -92,7 +92,7 @@ func (h *webhookHandler) getConfig(ctx context.Context) (*v1alpha1.Config, error return cfg, h.client.Get(ctx, keys.Config, cfg) } -// isGatekeeperResource returns true if the request relates to a gatekeeper resource +// isGatekeeperResource returns true if the request relates to a gatekeeper resource. func (h *webhookHandler) isGatekeeperResource(ctx context.Context, req *admission.Request) bool { if req.AdmissionRequest.Kind.Group == "templates.gatekeeper.sh" || req.AdmissionRequest.Kind.Group == "constraints.gatekeeper.sh" || diff --git a/pkg/webhook/mutation.go b/pkg/webhook/mutation.go index 3448004b9d5..874d4512168 100644 --- a/pkg/webhook/mutation.go +++ b/pkg/webhook/mutation.go @@ -50,7 +50,7 @@ func init() { // TODO enable this once mutation is beta +kubebuilder:webhook:verbs=create;update,path=/v1/mutate,mutating=true,failurePolicy=ignore,groups=*,resources=*,versions=*,name=mutation.gatekeeper.sh,sideEffects=None,admissionReviewVersions=v1;v1beta1,matchPolicy=Exact // TODO enable this once mutation is beta +kubebuilder:rbac:groups=*,resources=*,verbs=get;list;watch;update -// AddMutatingWebhook registers the mutating webhook server with the manager +// AddMutatingWebhook registers the mutating webhook server with the manager. func AddMutatingWebhook(mgr manager.Manager, client *opa.Client, processExcluder *process.Excluder, mutationSystem *mutation.System) error { if !*mutation.MutationEnabled { return nil @@ -104,7 +104,7 @@ type mutationHandler struct { // nolint: gocritic // Must accept admission.Request to satisfy interface. func (h *mutationHandler) Handle(ctx context.Context, req admission.Request) admission.Response { log := log.WithValues("hookType", "mutation") - var timeStart = time.Now() + timeStart := time.Now() if isGkServiceAccount(req.AdmissionRequest.UserInfo) { return admission.ValidationResponse(true, "Gatekeeper does not self-manage") @@ -140,7 +140,6 @@ func (h *mutationHandler) Handle(ctx context.Context, req admission.Request) adm } resp, err := h.mutateRequest(ctx, &req) - if err != nil { requestResponse = errorResponse return admission.Errored(int32(http.StatusInternalServerError), err) @@ -150,7 +149,6 @@ func (h *mutationHandler) Handle(ctx context.Context, req admission.Request) adm } func (h *mutationHandler) mutateRequest(ctx context.Context, req *admission.Request) (admission.Response, error) { - ns := &corev1.Namespace{} // if the object being mutated is a namespace itself, we use it as namespace diff --git a/pkg/webhook/namespacelabel.go b/pkg/webhook/namespacelabel.go index 3771dc8c2b3..a40a3c49583 100644 --- a/pkg/webhook/namespacelabel.go +++ b/pkg/webhook/namespacelabel.go @@ -34,7 +34,7 @@ const ignoreLabel = "admission.gatekeeper.sh/ignore" // +kubebuilder:webhook:verbs=CREATE;UPDATE,path=/v1/admitlabel,mutating=false,failurePolicy=fail,groups="",resources=namespaces,versions=*,name=check-ignore-label.gatekeeper.sh,sideEffects=None,admissionReviewVersions=v1;v1beta1,matchPolicy=Exact -// AddLabelWebhook registers the label webhook server with the manager +// AddLabelWebhook registers the label webhook server with the manager. func AddLabelWebhook(mgr manager.Manager, _ *opa.Client, _ *process.Excluder, mutationCache *mutation.System) error { wh := &admission.Webhook{Handler: &namespaceLabelHandler{}} // TODO(https://github.com/open-policy-agent/gatekeeper/issues/661): remove log injection if the race condition in the cited bug is eliminated. diff --git a/pkg/webhook/policy.go b/pkg/webhook/policy.go index f5ac204194f..f3ac364acfe 100644 --- a/pkg/webhook/policy.go +++ b/pkg/webhook/policy.go @@ -54,9 +54,7 @@ import ( // https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/#response const httpStatusWarning = 299 -var ( - maxServingThreads = flag.Int("max-serving-threads", -1, "(alpha) cap the number of threads handling non-trivial requests, -1 means an infinite number of threads") -) +var maxServingThreads = flag.Int("max-serving-threads", -1, "(alpha) cap the number of threads handling non-trivial requests, -1 means an infinite number of threads") func init() { AddToManagerFuncs = append(AddToManagerFuncs, AddPolicyWebhook) @@ -69,7 +67,7 @@ func init() { // +kubebuilder:webhook:verbs=create;update,path=/v1/admit,mutating=false,failurePolicy=ignore,groups=*,resources=*,versions=*,name=validation.gatekeeper.sh,sideEffects=None,admissionReviewVersions=v1;v1beta1,matchPolicy=Exact // +kubebuilder:rbac:groups=*,resources=*,verbs=get;list;watch -// AddPolicyWebhook registers the policy webhook server with the manager +// AddPolicyWebhook registers the policy webhook server with the manager. func AddPolicyWebhook(mgr manager.Manager, opa *opa.Client, processExcluder *process.Excluder, mutationCache *mutation.System) error { reporter, err := newStatsReporter() if err != nil { @@ -118,7 +116,7 @@ type validationHandler struct { func (h *validationHandler) Handle(ctx context.Context, req admission.Request) admission.Response { log := log.WithValues("hookType", "validation") - var timeStart = time.Now() + timeStart := time.Now() if isGkServiceAccount(req.AdmissionRequest.UserInfo) { return admission.ValidationResponse(true, "Gatekeeper does not self-manage") @@ -309,7 +307,7 @@ func (h *validationHandler) getValidationMessages(res []*rtypes.Result, req *adm } // validateGatekeeperResources returns whether an issue is user error (vs internal) and any errors -// validating internal resources +// validating internal resources. func (h *validationHandler) validateGatekeeperResources(ctx context.Context, req *admission.Request) (bool, error) { gvk := req.AdmissionRequest.Kind @@ -415,7 +413,7 @@ func (h *validationHandler) validateAssign(ctx context.Context, req *admission.R return false, nil } -// traceSwitch returns true if a request should be traced +// traceSwitch returns true if a request should be traced. func (h *validationHandler) reviewRequest(ctx context.Context, req *admission.Request) (*rtypes.Responses, error) { // if we have a maximum number of concurrent serving goroutines, try to acquire // a lock and block until we succeed diff --git a/pkg/webhook/policy_benchmark_test.go b/pkg/webhook/policy_benchmark_test.go index 641131f342f..38b278926b6 100644 --- a/pkg/webhook/policy_benchmark_test.go +++ b/pkg/webhook/policy_benchmark_test.go @@ -63,7 +63,7 @@ func (f *fakeNsGetter) Get(ctx context.Context, key client.ObjectKey, obj client } // getFiles reads a directory and returns a list of files ending with .yaml/.yml -// returns an error if directory does not exist +// returns an error if directory does not exist. func getFiles(dir string) ([]string, error) { var filePaths []string var err error @@ -89,7 +89,7 @@ func getFiles(dir string) ([]string, error) { // all files ending with .yaml are loaded. One resource per .yaml file // does not support recursive directory search // fails if directory is not a valid path -// fails if any of the files is not a valid constraint template +// fails if any of the files is not a valid constraint template. func readTemplates(dir string) ([]templates.ConstraintTemplate, error) { fileList, err := getFiles(dir) if err != nil { @@ -117,7 +117,7 @@ func readTemplates(dir string) ([]templates.ConstraintTemplate, error) { // readConstraints reads constraints from a directory // all files ending with .yaml are loaded. One resource per .yaml file // does not support recursive directory search -// fails if directory is not a valid path +// fails if directory is not a valid path. func readConstraints(dir string) ([]unstructured.Unstructured, error) { return readDirHelper(dir) } @@ -126,12 +126,12 @@ func readConstraints(dir string) ([]unstructured.Unstructured, error) { // these resources would be transformed into admission requests ex: Pods, Deployments // all files ending with .yaml are loaded. One resource per .yaml file // does not support recursive directory search -// fails if directory is not a valid path +// fails if directory is not a valid path. func readResources(dir string) ([]unstructured.Unstructured, error) { return readDirHelper(dir) } -// readDirHelper is a helper method to read YAML files and unmarshal them into unstructured +// readDirHelper is a helper method to read YAML files and unmarshal them into unstructured. func readDirHelper(dir string) ([]unstructured.Unstructured, error) { fileList, err := getFiles(dir) if err != nil { @@ -172,7 +172,7 @@ func addConstraints(opa *opa.Client, list []unstructured.Unstructured) error { return nil } -// generateConstraints generates m constraints based on representative constraint in crList +// generateConstraints generates m constraints based on representative constraint in crList. func generateConstraints(m int, crList []unstructured.Unstructured) []unstructured.Unstructured { result := make([]unstructured.Unstructured, m) for i := 0; i < m; i++ { @@ -219,7 +219,8 @@ func createAdmissionRequests(resList []unstructured.Unstructured, n int) atypes. Username: "res-creator", UID: "uid", Groups: []string{"res-creator-group"}, - Extra: map[string]authenticationv1.ExtraValue{"extraKey": {"value1", "value2"}}}, + Extra: map[string]authenticationv1.ExtraValue{"extraKey": {"value1", "value2"}}, + }, Object: runtime.RawExtension{Object: &resList[n%len(resList)]}, OldObject: runtime.RawExtension{Object: oldRes}, DryRun: &dryRun, diff --git a/pkg/webhook/policy_test.go b/pkg/webhook/policy_test.go index 0a38dee44f0..a707b908673 100644 --- a/pkg/webhook/policy_test.go +++ b/pkg/webhook/policy_test.go @@ -321,7 +321,6 @@ func TestReviewRequest(t *testing.T) { maxThreads = 1 t.Run(tt.Name+" with max threads", testFn) } - } func TestConstraintValidation(t *testing.T) { diff --git a/pkg/webhook/stats_reporter.go b/pkg/webhook/stats_reporter.go index 71d4450ae08..868c4f6478d 100644 --- a/pkg/webhook/stats_reporter.go +++ b/pkg/webhook/stats_reporter.go @@ -39,18 +39,18 @@ func init() { } } -// StatsReporter reports webhook metrics +// StatsReporter reports webhook metrics. type StatsReporter interface { ReportValidationRequest(response requestResponse, d time.Duration) error ReportMutationRequest(response requestResponse, d time.Duration) error } -// reporter implements StatsReporter interface +// reporter implements StatsReporter interface. type reporter struct { ctx context.Context } -// newStatsReporter creaters a reporter for webhook metrics +// newStatsReporter creaters a reporter for webhook metrics. func newStatsReporter() (StatsReporter, error) { ctx, err := tag.New( context.Background(), @@ -70,7 +70,7 @@ func (r *reporter) ReportMutationRequest(response requestResponse, d time.Durati return r.reportRequest(response, mutationStatusKey, mutationResponseTimeInSecM.M(d.Seconds())) } -// Captures req count metric, recording the count and the duration +// Captures req count metric, recording the count and the duration. func (r *reporter) reportRequest(response requestResponse, statusKey tag.Key, m stats.Measurement) error { ctx, err := tag.New( r.ctx, diff --git a/pkg/webhook/stats_reporter_test.go b/pkg/webhook/stats_reporter_test.go index 42f7172a61d..d6ae42d8f1a 100644 --- a/pkg/webhook/stats_reporter_test.go +++ b/pkg/webhook/stats_reporter_test.go @@ -7,12 +7,14 @@ import ( "go.opencensus.io/stats/view" ) -const expectedDurationValueMin = time.Duration(1 * time.Second) -const expectedDurationValueMax = time.Duration(5 * time.Second) -const expectedDurationMin float64 = 1 -const expectedDurationMax float64 = 5 -const expectedCount int64 = 2 -const expectedRowLength = 1 +const ( + expectedDurationValueMin = time.Duration(1 * time.Second) + expectedDurationValueMax = time.Duration(5 * time.Second) + expectedDurationMin float64 = 1 + expectedDurationMax float64 = 5 + expectedCount int64 = 2 + expectedRowLength = 1 +) func TestValidationReportRequest(t *testing.T) { expectedTags := map[string]string{ @@ -40,7 +42,6 @@ func TestMutationReportRequest(t *testing.T) { } r, err := newStatsReporter() - if err != nil { t.Errorf("newStatsReporter() error %v", err) } @@ -57,7 +58,6 @@ func TestMutationReportRequest(t *testing.T) { } func check(t *testing.T, expectedTags map[string]string, requestCountMetricName string, requestDurationMetricName string) { - // count test row := checkData(t, requestCountMetricName, expectedRowLength) diff --git a/pkg/webhook/webhook.go b/pkg/webhook/webhook.go index 276d4a661e7..e158b906cc7 100644 --- a/pkg/webhook/webhook.go +++ b/pkg/webhook/webhook.go @@ -22,7 +22,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/manager" ) -// AddToManagerFuncs is a list of functions to add all Controllers to the Manager +// AddToManagerFuncs is a list of functions to add all Controllers to the Manager. var AddToManagerFuncs []func(manager.Manager, *client.Client, *process.Excluder, *mutation.System) error // The below autogen directive is currently disabled because controller-gen has @@ -32,7 +32,7 @@ var AddToManagerFuncs []func(manager.Manager, *client.Client, *process.Excluder, // +kubebuilder:rbac:groups="",namespace=gatekeeper-system,resources=secrets,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups="",namespace=gatekeeper-system,resources=events,verbs=create;patch -// AddToManager adds all Controllers to the Manager +// AddToManager adds all Controllers to the Manager. func AddToManager(m manager.Manager, opa *client.Client, processExcluder *process.Excluder, mutationCache *mutation.System) error { for _, f := range AddToManagerFuncs { if err := f(m, opa, processExcluder, mutationCache); err != nil {